annotate-snippets 0.12.17

Format diagnostic reports, including highlighting snippets of text
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! The [Renderer] and its settings
//!
//! # Example
//!
//! ```
//! # use annotate_snippets::*;
//! # use annotate_snippets::renderer::*;
//! # use annotate_snippets::Level;
//! let report = // ...
//! # &[Group::with_title(
//! #     Level::ERROR
//! #         .primary_title("unresolved import `baz::zed`")
//! #         .id("E0432")
//! # )];
//!
//! let renderer = Renderer::styled().decor_style(DecorStyle::Unicode);
//! let output = renderer.render(report);
//! anstream::println!("{output}");
//! ```

pub(crate) mod graphics;
pub(crate) mod no_graphics;
pub(crate) mod source_map;
pub(crate) mod stylesheet;

mod margin;
mod preprocess;
mod styled_buffer;

use alloc::string::String;

use crate::Report;

pub(crate) use graphics::ElementStyle;
pub(crate) use graphics::UnderlineParts;
pub(crate) use graphics::normalize_whitespace;
pub(crate) use graphics::{LineAnnotation, LineAnnotationType, char_width, num_overlap};
pub(crate) use stylesheet::Stylesheet;

pub use anstyle::*;

/// See [`Renderer::term_width`]
pub const DEFAULT_TERM_WIDTH: usize = 140;

const USE_WINDOWS_COLORS: bool = cfg!(windows) && !cfg!(feature = "testing-colors");
const BRIGHT_BLUE: Style = if USE_WINDOWS_COLORS {
    AnsiColor::BrightCyan.on_default()
} else {
    AnsiColor::BrightBlue.on_default()
};
/// [`Renderer::error`] applied by [`Renderer::styled`]
pub const DEFAULT_ERROR_STYLE: Style = AnsiColor::BrightRed.on_default().effects(Effects::BOLD);
/// [`Renderer::warning`] applied by [`Renderer::styled`]
pub const DEFAULT_WARNING_STYLE: Style = if USE_WINDOWS_COLORS {
    AnsiColor::BrightYellow.on_default()
} else {
    AnsiColor::Yellow.on_default()
}
.effects(Effects::BOLD);
/// [`Renderer::info`] applied by [`Renderer::styled`]
pub const DEFAULT_INFO_STYLE: Style = BRIGHT_BLUE.effects(Effects::BOLD);
/// [`Renderer::note`] applied by [`Renderer::styled`]
pub const DEFAULT_NOTE_STYLE: Style = AnsiColor::BrightGreen.on_default().effects(Effects::BOLD);
/// [`Renderer::help`] applied by [`Renderer::styled`]
pub const DEFAULT_HELP_STYLE: Style = AnsiColor::BrightCyan.on_default().effects(Effects::BOLD);
/// [`Renderer::line_num`] applied by [`Renderer::styled`]
pub const DEFAULT_LINE_NUM_STYLE: Style = BRIGHT_BLUE.effects(Effects::BOLD);
/// [`Renderer::emphasis`] applied by [`Renderer::styled`]
pub const DEFAULT_EMPHASIS_STYLE: Style = if USE_WINDOWS_COLORS {
    AnsiColor::BrightWhite.on_default()
} else {
    Style::new()
}
.effects(Effects::BOLD);
/// [`Renderer::none`] applied by [`Renderer::styled`]
pub const DEFAULT_NONE_STYLE: Style = Style::new();
/// [`Renderer::context`] applied by [`Renderer::styled`]
pub const DEFAULT_CONTEXT_STYLE: Style = BRIGHT_BLUE.effects(Effects::BOLD);
/// [`Renderer::addition`] applied by [`Renderer::styled`]
pub const DEFAULT_ADDITION_STYLE: Style = AnsiColor::BrightGreen.on_default();
/// [`Renderer::removal`] applied by [`Renderer::styled`]
pub const DEFAULT_REMOVAL_STYLE: Style = AnsiColor::BrightRed.on_default();

/// The [Renderer] for a [`Report`]
///
/// The caller is expected to detect any relevant terminal features and configure the renderer,
/// including
/// - ANSI Escape code support (always outputted with [`Renderer::styled`])
/// - Terminal width ([`Renderer::term_width`])
/// - Unicode support ([`Renderer::decor_style`])
///
/// # Example
///
/// ```
/// # use annotate_snippets::*;
/// # use annotate_snippets::renderer::*;
/// # use annotate_snippets::Level;
/// let report = // ...
/// # &[Group::with_title(
/// #     Level::ERROR
/// #         .primary_title("unresolved import `baz::zed`")
/// #         .id("E0432")
/// # )];
///
/// let renderer = Renderer::styled();
/// let output = renderer.render(report);
/// anstream::println!("{output}");
/// ```
#[derive(Clone, Debug)]
pub struct Renderer {
    anonymized_origin_line_numbers: bool,
    anonymized_snippet_line_numbers: bool,
    term_width: usize,
    decor_style: DecorStyle,
    stylesheet: Stylesheet,
    hyperlink: bool,
    short_message: bool,
    no_graphics: bool,
}

impl Renderer {
    /// No terminal styling
    pub const fn plain() -> Self {
        Self {
            anonymized_origin_line_numbers: false,
            anonymized_snippet_line_numbers: false,
            term_width: DEFAULT_TERM_WIDTH,
            decor_style: DecorStyle::Ascii,
            stylesheet: Stylesheet::plain(),
            hyperlink: false,
            short_message: false,
            no_graphics: false,
        }
    }

    /// Default terminal styling
    ///
    /// If ANSI escape codes are not supported, either
    /// - Call [`Renderer::plain`] instead
    /// - Strip them after the fact, like with [`anstream`](https://docs.rs/anstream/latest/anstream/)
    ///
    /// # Note
    ///
    /// When testing styled terminal output, see the [`testing-colors` feature](crate#features)
    pub const fn styled() -> Self {
        Self {
            stylesheet: Stylesheet {
                error: DEFAULT_ERROR_STYLE,
                warning: DEFAULT_WARNING_STYLE,
                info: DEFAULT_INFO_STYLE,
                note: DEFAULT_NOTE_STYLE,
                help: DEFAULT_HELP_STYLE,
                line_num: DEFAULT_LINE_NUM_STYLE,
                emphasis: DEFAULT_EMPHASIS_STYLE,
                none: DEFAULT_NONE_STYLE,
                context: DEFAULT_CONTEXT_STYLE,
                addition: DEFAULT_ADDITION_STYLE,
                removal: DEFAULT_REMOVAL_STYLE,
            },
            hyperlink: true,
            ..Self::plain()
        }
    }

    /// Render a `Report` without source snippets or graphical decorations
    ///
    /// The output is primarily designed for Text-To-Speech and Braille
    /// displays. It also provides a more detailed alternative to
    /// [`Renderer::short_message`].
    ///
    /// We recommend that applications enable this format when `NO_GRAPHICS=1`
    /// is set in the environment.
    ///
    /// <div class="warning">
    ///
    /// This format supports colors and hyperlinks.
    ///
    /// [`Renderer::plain`] can be used to disable colors and hyperlinks.
    ///
    /// </div>
    ///
    /// # Example output
    ///
    /// ```text
    #[doc = include_str!("../../examples/no_graphics.txt")]
    /// ```
    pub const fn no_graphics(mut self, no_graphics: bool) -> Self {
        self.no_graphics = no_graphics;
        self
    }

    /// Abbreviate the message
    pub const fn short_message(mut self, short_message: bool) -> Self {
        self.short_message = short_message;
        self
    }

    /// Set the width to render within
    ///
    /// Affects the rendering of [`Snippet`][crate::Snippet]s
    pub const fn term_width(mut self, term_width: usize) -> Self {
        self.term_width = term_width;
        self
    }

    /// Set the character set used for rendering decor
    pub const fn decor_style(mut self, decor_style: DecorStyle) -> Self {
        self.decor_style = decor_style;
        self
    }

    /// Anonymize snippet line numbers
    ///
    /// When enabled, line numbers are replaced with `LL` which is useful for tests.
    ///
    /// # Example
    ///
    /// ```text
    ///   --> $DIR/whitespace-trimming.rs:4:193
    ///    |
    /// LL | ...                   let _: () = 42;
    ///    |                                   ^^ expected (), found integer
    ///    |
    /// ```
    pub const fn anonymized_snippet_line_numbers(mut self, yes: bool) -> Self {
        self.anonymized_snippet_line_numbers = yes;
        self
    }

    /// Deprecated, replaced with [`Self::anonymized_snippet_line_numbers`]
    #[deprecated(
        since = "0.12.17",
        note = "replaced with `Renderer::anonymized_snippet_line_numbers`"
    )]
    pub const fn anonymized_line_numbers(mut self, yes: bool) -> Self {
        self.anonymized_snippet_line_numbers = yes;
        self
    }

    /// Anonymize origin line numbers
    ///
    /// When enabled, line numbers are replaced with `LL` which is useful for tests.
    ///
    /// # Example
    ///
    /// ```text
    ///   --> $DIR/whitespace-trimming.rs:LL:193
    ///   |
    /// 4 | ...                   let _: () = 42;
    ///   |                                   ^^ expected (), found integer
    ///   |
    /// ```
    pub const fn anonymized_origin_line_numbers(mut self, yes: bool) -> Self {
        self.anonymized_origin_line_numbers = yes;
        self
    }
}

impl Renderer {
    /// Render a diagnostic [`Report`]
    pub fn render(&self, groups: Report<'_>) -> String {
        if self.no_graphics {
            no_graphics::render_no_graphics(self, groups).unwrap()
        } else {
            graphics::render(self, groups)
        }
    }
}

/// Customize [`Renderer::styled`]
impl Renderer {
    /// Override the output style for [error][crate::Level::ERROR]
    pub const fn error(mut self, style: Style) -> Self {
        self.stylesheet.error = style;
        self
    }

    /// Override the output style for [warnings][crate::Level::WARNING]
    pub const fn warning(mut self, style: Style) -> Self {
        self.stylesheet.warning = style;
        self
    }

    /// Override the output style for [info][crate::Level::INFO]
    pub const fn info(mut self, style: Style) -> Self {
        self.stylesheet.info = style;
        self
    }

    /// Override the output style for [notes][crate::Level::NOTE]
    pub const fn note(mut self, style: Style) -> Self {
        self.stylesheet.note = style;
        self
    }

    /// Override the output style for [help][crate::Level::HELP]
    pub const fn help(mut self, style: Style) -> Self {
        self.stylesheet.help = style;
        self
    }

    /// Override the output style for line numbers in the [`Snippet`][crate::Snippet] gutter
    pub const fn line_num(mut self, style: Style) -> Self {
        self.stylesheet.line_num = style;
        self
    }

    /// Override the output style for emphasis for the
    /// [`primary_title`][crate::Level::primary_title]
    pub const fn emphasis(mut self, style: Style) -> Self {
        self.stylesheet.emphasis = style;
        self
    }

    /// Override the output style for [`AnnotationKind::Context`][crate::AnnotationKind::Context]
    pub const fn context(mut self, style: Style) -> Self {
        self.stylesheet.context = style;
        self
    }

    /// Override the output style for [`Patch`][crate::Patch] additions
    pub const fn addition(mut self, style: Style) -> Self {
        self.stylesheet.addition = style;
        self
    }

    /// Override the output style for [`Patch`][crate::Patch] removals
    pub const fn removal(mut self, style: Style) -> Self {
        self.stylesheet.removal = style;
        self
    }

    /// Override the output style for all other text
    pub const fn none(mut self, style: Style) -> Self {
        self.stylesheet.none = style;
        self
    }

    /// Override whether hyperlinks should be emitted
    pub const fn hyperlink(mut self, hyperlink: bool) -> Self {
        self.hyperlink = hyperlink;
        self
    }
}

/// The character set for rendering for decor
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecorStyle {
    Ascii,
    Unicode,
}

impl DecorStyle {
    fn col_separator(&self) -> char {
        match self {
            Self::Ascii => '|',
            Self::Unicode => '│',
        }
    }

    fn note_separator(&self, is_cont: bool) -> &str {
        match self {
            Self::Ascii => "= ",
            Self::Unicode if is_cont => "├ ",
            Self::Unicode => "╰ ",
        }
    }

    fn multi_suggestion_separator(&self) -> &'static str {
        match self {
            Self::Ascii => "|",
            Self::Unicode => "├╴",
        }
    }

    fn file_start(&self, is_first: bool, alone: bool) -> &'static str {
        match self {
            Self::Ascii => "--> ",
            Self::Unicode if is_first && alone => " ─▸ ",
            Self::Unicode if is_first => " ╭▸ ",
            Self::Unicode => " ├▸ ",
        }
    }

    fn secondary_file_start(&self) -> &'static str {
        match self {
            Self::Ascii => "::: ",
            Self::Unicode => " ⸬  ",
        }
    }

    fn diff(&self) -> char {
        match self {
            Self::Ascii => '~',
            Self::Unicode => '±',
        }
    }

    fn margin(&self) -> &'static str {
        match self {
            Self::Ascii => "...",
            Self::Unicode => "…",
        }
    }

    fn underline(&self, is_primary: bool) -> UnderlineParts {
        //               X0 Y0
        // label_start > ┯━━━━ < underline
        //               │ < vertical_text_line
        //               text

        //    multiline_start_down ⤷ X0 Y0
        //            top_left > ┌───╿──┘ < top_right_flat
        //           top_left > ┏│━━━┙ < top_right
        // multiline_vertical > ┃│
        //                      ┃│   X1 Y1
        //                      ┃│   X2 Y2
        //                      ┃└────╿──┘ < multiline_end_same_line
        //        bottom_left > ┗━━━━━┥ < bottom_right_with_text
        //   multiline_horizontal ^   `X` is a good letter

        // multiline_whole_line > ┏ X0 Y0
        //                        ┃   X1 Y1
        //                        ┗━━━━┛ < multiline_end_same_line

        // multiline_whole_line > ┏ X0 Y0
        //                        ┃ X1 Y1
        //                        ┃  ╿ < multiline_end_up
        //                        ┗━━┛ < bottom_right

        match (self, is_primary) {
            (Self::Ascii, true) => UnderlineParts {
                style: ElementStyle::UnderlinePrimary,
                underline: '^',
                label_start: '^',
                vertical_text_line: '|',
                multiline_vertical: '|',
                multiline_horizontal: '_',
                multiline_whole_line: '/',
                multiline_start_down: '^',
                bottom_right: '|',
                top_left: ' ',
                top_right_flat: '^',
                bottom_left: '|',
                multiline_end_up: '^',
                multiline_end_same_line: '^',
                multiline_bottom_right_with_text: '|',
            },
            (Self::Ascii, false) => UnderlineParts {
                style: ElementStyle::UnderlineSecondary,
                underline: '-',
                label_start: '-',
                vertical_text_line: '|',
                multiline_vertical: '|',
                multiline_horizontal: '_',
                multiline_whole_line: '/',
                multiline_start_down: '-',
                bottom_right: '|',
                top_left: ' ',
                top_right_flat: '-',
                bottom_left: '|',
                multiline_end_up: '-',
                multiline_end_same_line: '-',
                multiline_bottom_right_with_text: '|',
            },
            (Self::Unicode, true) => UnderlineParts {
                style: ElementStyle::UnderlinePrimary,
                underline: '━',
                label_start: '┯',
                vertical_text_line: '│',
                multiline_vertical: '┃',
                multiline_horizontal: '━',
                multiline_whole_line: '┏',
                multiline_start_down: '╿',
                bottom_right: '┙',
                top_left: '┏',
                top_right_flat: '┛',
                bottom_left: '┗',
                multiline_end_up: '╿',
                multiline_end_same_line: '┛',
                multiline_bottom_right_with_text: '┥',
            },
            (Self::Unicode, false) => UnderlineParts {
                style: ElementStyle::UnderlineSecondary,
                underline: '─',
                label_start: '┬',
                vertical_text_line: '│',
                multiline_vertical: '│',
                multiline_horizontal: '─',
                multiline_whole_line: '┌',
                multiline_start_down: '│',
                bottom_right: '┘',
                top_left: '┌',
                top_right_flat: '┘',
                bottom_left: '└',
                multiline_end_up: '│',
                multiline_end_same_line: '┘',
                multiline_bottom_right_with_text: '┤',
            },
        }
    }
}