#annotations #report #error #code

sourceannot

一个用于渲染带注释的源代码片段的库

4 个版本

新版本 0.2.1 2024年8月13日
0.2.0 2024年4月21日
0.1.1 2024年3月30日
0.1.0 2024年3月26日

#334 in 文本处理

Download history 22/week @ 2024-04-28 2/week @ 2024-05-05 18/week @ 2024-05-19 46/week @ 2024-05-26 41/week @ 2024-06-02 8/week @ 2024-06-09 8/week @ 2024-06-16 57/week @ 2024-06-23 2/week @ 2024-06-30 5/week @ 2024-07-07 212/week @ 2024-07-14 192/week @ 2024-07-21 306/week @ 2024-07-28 199/week @ 2024-08-04 388/week @ 2024-08-11

1,254 每月下载量
2 个Crate中使用 (通过 rsjsonnet-front)

MIT/Apache

82KB
2K SLoC

sourceannot

GitHub Actions Status crates.io Documentation MSRV License

一个用于渲染带注释的源代码片段的库。

许可

根据以下任一许可发布:

由您选择。


lib.rs:

一个用于渲染带注释的源代码片段的库。它旨在用作编译器诊断的构建块。

此Crate是 #![no_std],但它依赖于 alloc

示例

// Some source code
let source = indoc::indoc! {r#"
    fn main() {
        println!("Hello, world!");
    }
"#};

// Create the snippet
let snippet = sourceannot::SourceSnippet::build_from_utf8(1, source.as_bytes(), 4);

// Styles are generic over the type of the metadata that accompanies each
// chunk of rendered text. In this example, we will use the following enum:
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Color {
    Default,
    Red,
    Green,
    Blue,
}
// If do not you need this per-chunk metadata, you can use `()` instead.

// Define the styles
// Use Unicode box drawing characters
let main_style = sourceannot::MainStyle {
    margin: Some(sourceannot::MarginStyle {
        line_char: '',
        dot_char: '·',
        meta: Color::Blue,
    }),
    horizontal_char: '',
    vertical_char: '',
    top_vertical_char: '',
    top_corner_char: '',
    bottom_corner_char: '',
    spaces_meta: Color::Default,
    text_normal_meta: Color::Default,
    text_alt_meta: Color::Default,
};

// You can use a different style for each annotation, but in
// this example we will use the same style for all of them.
let annot_style = sourceannot::AnnotStyle {
    caret: '^',
    text_normal_meta: Color::Red,
    text_alt_meta: Color::Red,
    line_meta: Color::Red,
};

// Create the annotations
let mut annotations = sourceannot::Annotations::new(&snippet, main_style);

annotations.add_annotation(
    0..44,
    annot_style,
    vec![("this is the `main` function".into(), Color::Red)],
);
annotations.add_annotation(
    16..24,
    annot_style,
    vec![("this is a macro invocation".into(), Color::Red)],
);

// Render the snippet with annotations
let max_line_no_width = annotations.max_line_no_width();
let rendered = annotations.render(max_line_no_width, 0, 0);

// `rendered` is a `Vec<(String, Color)>`, which you could print with
// your favorite terminal coloring library. In this example, we will
// ignore the colors.

for (chunk, _) in rendered.iter() {
    eprint!("{chunk}");
}

输出将如下所示

1 │ ╭ fn main() {
2 │ │     println!(\"Hello, world!\");
  │ │     ^^^^^^^^ this is a macro invocation
3 │ │ }
  │ ╰─^ this is the `main` function

依赖项

~375KB