Skip to main content

annotate_snippets/renderer/
mod.rs

1//! The [Renderer] and its settings
2//!
3//! # Example
4//!
5//! ```
6//! # use annotate_snippets::*;
7//! # use annotate_snippets::renderer::*;
8//! # use annotate_snippets::Level;
9//! let report = // ...
10//! # &[Group::with_title(
11//! #     Level::ERROR
12//! #         .primary_title("unresolved import `baz::zed`")
13//! #         .id("E0432")
14//! # )];
15//!
16//! let renderer = Renderer::styled().decor_style(DecorStyle::Unicode);
17//! let output = renderer.render(report);
18//! anstream::println!("{output}");
19//! ```
20
21pub(crate) mod graphics;
22pub(crate) mod no_graphics;
23pub(crate) mod source_map;
24pub(crate) mod stylesheet;
25
26mod margin;
27mod preprocess;
28mod styled_buffer;
29
30use alloc::string::String;
31
32use crate::Report;
33
34pub(crate) use graphics::ElementStyle;
35pub(crate) use graphics::UnderlineParts;
36pub(crate) use graphics::normalize_whitespace;
37pub(crate) use graphics::{LineAnnotation, LineAnnotationType, char_width, num_overlap};
38pub(crate) use stylesheet::Stylesheet;
39
40pub use anstyle::*;
41
42/// See [`Renderer::term_width`]
43pub const DEFAULT_TERM_WIDTH: usize = 140;
44
45/// [`Renderer::error`] applied by [`Renderer::styled`]
46pub const DEFAULT_ERROR_STYLE: Style = AnsiColor::BrightRed.on_default().effects(Effects::BOLD);
47/// [`Renderer::warning`] applied by [`Renderer::styled`]
48pub const DEFAULT_WARNING_STYLE: Style = AnsiColor::Yellow.on_default().effects(Effects::BOLD);
49/// [`Renderer::info`] applied by [`Renderer::styled`]
50pub const DEFAULT_INFO_STYLE: Style = AnsiColor::BrightBlue.on_default().effects(Effects::BOLD);
51/// [`Renderer::note`] applied by [`Renderer::styled`]
52pub const DEFAULT_NOTE_STYLE: Style = AnsiColor::BrightGreen.on_default().effects(Effects::BOLD);
53/// [`Renderer::help`] applied by [`Renderer::styled`]
54pub const DEFAULT_HELP_STYLE: Style = AnsiColor::BrightCyan.on_default().effects(Effects::BOLD);
55/// [`Renderer::line_num`] applied by [`Renderer::styled`]
56pub const DEFAULT_LINE_NUM_STYLE: Style = AnsiColor::BrightBlue.on_default().effects(Effects::BOLD);
57/// [`Renderer::emphasis`] applied by [`Renderer::styled`]
58pub const DEFAULT_EMPHASIS_STYLE: Style = Style::new().effects(Effects::BOLD);
59/// [`Renderer::none`] applied by [`Renderer::styled`]
60pub const DEFAULT_NONE_STYLE: Style = Style::new();
61/// [`Renderer::context`] applied by [`Renderer::styled`]
62pub const DEFAULT_CONTEXT_STYLE: Style = AnsiColor::BrightBlue.on_default().effects(Effects::BOLD);
63/// [`Renderer::addition`] applied by [`Renderer::styled`]
64pub const DEFAULT_ADDITION_STYLE: Style = AnsiColor::BrightGreen.on_default();
65/// [`Renderer::removal`] applied by [`Renderer::styled`]
66pub const DEFAULT_REMOVAL_STYLE: Style = AnsiColor::BrightRed.on_default();
67
68/// The [Renderer] for a [`Report`]
69///
70/// The caller is expected to detect any relevant terminal features and configure the renderer,
71/// including
72/// - ANSI Escape code support (always outputted with [`Renderer::styled`])
73/// - Terminal width ([`Renderer::term_width`])
74/// - Unicode support ([`Renderer::decor_style`])
75///
76/// # Example
77///
78/// ```
79/// # use annotate_snippets::*;
80/// # use annotate_snippets::renderer::*;
81/// # use annotate_snippets::Level;
82/// let report = // ...
83/// # &[Group::with_title(
84/// #     Level::ERROR
85/// #         .primary_title("unresolved import `baz::zed`")
86/// #         .id("E0432")
87/// # )];
88///
89/// let renderer = Renderer::styled();
90/// let output = renderer.render(report);
91/// anstream::println!("{output}");
92/// ```
93#[derive(Clone, Debug)]
94pub struct Renderer {
95    anonymized_origin_line_numbers: bool,
96    anonymized_snippet_line_numbers: bool,
97    term_width: usize,
98    decor_style: DecorStyle,
99    stylesheet: Stylesheet,
100    hyperlink: bool,
101    short_message: bool,
102    no_graphics: bool,
103}
104
105impl Renderer {
106    /// No terminal styling
107    pub const fn plain() -> Self {
108        Self {
109            anonymized_origin_line_numbers: false,
110            anonymized_snippet_line_numbers: false,
111            term_width: DEFAULT_TERM_WIDTH,
112            decor_style: DecorStyle::Ascii,
113            stylesheet: Stylesheet::plain(),
114            hyperlink: false,
115            short_message: false,
116            no_graphics: false,
117        }
118    }
119
120    /// Default terminal styling
121    ///
122    /// If ANSI escape codes are not supported, either
123    /// - Call [`Renderer::plain`] instead
124    /// - Strip them after the fact, like with [`anstream`](https://docs.rs/anstream/latest/anstream/)
125    pub const fn styled() -> Self {
126        Self {
127            stylesheet: Stylesheet {
128                error: DEFAULT_ERROR_STYLE,
129                warning: DEFAULT_WARNING_STYLE,
130                info: DEFAULT_INFO_STYLE,
131                note: DEFAULT_NOTE_STYLE,
132                help: DEFAULT_HELP_STYLE,
133                line_num: DEFAULT_LINE_NUM_STYLE,
134                emphasis: DEFAULT_EMPHASIS_STYLE,
135                none: DEFAULT_NONE_STYLE,
136                context: DEFAULT_CONTEXT_STYLE,
137                addition: DEFAULT_ADDITION_STYLE,
138                removal: DEFAULT_REMOVAL_STYLE,
139            },
140            hyperlink: true,
141            ..Self::plain()
142        }
143    }
144
145    /// Render a `Report` without source snippets or graphical decorations
146    ///
147    /// The output is primarily designed for Text-To-Speech and Braille
148    /// displays. It also provides a more detailed alternative to
149    /// [`Renderer::short_message`].
150    ///
151    /// We recommend that applications enable this format when `NO_GRAPHICS=1`
152    /// is set in the environment.
153    ///
154    /// <div class="warning">
155    ///
156    /// This format supports colors and hyperlinks.
157    ///
158    /// [`Renderer::plain`] can be used to disable colors and hyperlinks.
159    ///
160    /// </div>
161    ///
162    /// # Example output
163    ///
164    /// ```text
165    #[doc = include_str!("../../examples/no_graphics.txt")]
166    /// ```
167    pub const fn no_graphics(mut self, no_graphics: bool) -> Self {
168        self.no_graphics = no_graphics;
169        self
170    }
171
172    /// Abbreviate the message
173    pub const fn short_message(mut self, short_message: bool) -> Self {
174        self.short_message = short_message;
175        self
176    }
177
178    /// Set the width to render within
179    ///
180    /// Affects the rendering of [`Snippet`][crate::Snippet]s
181    pub const fn term_width(mut self, term_width: usize) -> Self {
182        self.term_width = term_width;
183        self
184    }
185
186    /// Set the character set used for rendering decor
187    pub const fn decor_style(mut self, decor_style: DecorStyle) -> Self {
188        self.decor_style = decor_style;
189        self
190    }
191
192    /// Anonymize snippet line numbers
193    ///
194    /// When enabled, line numbers are replaced with `LL` which is useful for tests.
195    ///
196    /// # Example
197    ///
198    /// ```text
199    ///   --> $DIR/whitespace-trimming.rs:4:193
200    ///    |
201    /// LL | ...                   let _: () = 42;
202    ///    |                                   ^^ expected (), found integer
203    ///    |
204    /// ```
205    pub const fn anonymized_snippet_line_numbers(mut self, yes: bool) -> Self {
206        self.anonymized_snippet_line_numbers = yes;
207        self
208    }
209
210    /// Deprecated, replaced with [`Self::anonymized_snippet_line_numbers`]
211    #[deprecated(
212        since = "0.12.17",
213        note = "replaced with `Renderer::anonymized_snippet_line_numbers`"
214    )]
215    pub const fn anonymized_line_numbers(mut self, yes: bool) -> Self {
216        self.anonymized_snippet_line_numbers = yes;
217        self
218    }
219
220    /// Anonymize origin line numbers
221    ///
222    /// When enabled, line numbers are replaced with `LL` which is useful for tests.
223    ///
224    /// # Example
225    ///
226    /// ```text
227    ///   --> $DIR/whitespace-trimming.rs:LL:193
228    ///   |
229    /// 4 | ...                   let _: () = 42;
230    ///   |                                   ^^ expected (), found integer
231    ///   |
232    /// ```
233    pub const fn anonymized_origin_line_numbers(mut self, yes: bool) -> Self {
234        self.anonymized_origin_line_numbers = yes;
235        self
236    }
237}
238
239impl Renderer {
240    /// Render a diagnostic [`Report`]
241    pub fn render(&self, groups: Report<'_>) -> String {
242        if self.no_graphics {
243            no_graphics::render_no_graphics(self, groups).unwrap()
244        } else {
245            graphics::render(self, groups)
246        }
247    }
248}
249
250/// Customize [`Renderer::styled`]
251impl Renderer {
252    /// Override the output style for [error][crate::Level::ERROR]
253    pub const fn error(mut self, style: Style) -> Self {
254        self.stylesheet.error = style;
255        self
256    }
257
258    /// Override the output style for [warnings][crate::Level::WARNING]
259    pub const fn warning(mut self, style: Style) -> Self {
260        self.stylesheet.warning = style;
261        self
262    }
263
264    /// Override the output style for [info][crate::Level::INFO]
265    pub const fn info(mut self, style: Style) -> Self {
266        self.stylesheet.info = style;
267        self
268    }
269
270    /// Override the output style for [notes][crate::Level::NOTE]
271    pub const fn note(mut self, style: Style) -> Self {
272        self.stylesheet.note = style;
273        self
274    }
275
276    /// Override the output style for [help][crate::Level::HELP]
277    pub const fn help(mut self, style: Style) -> Self {
278        self.stylesheet.help = style;
279        self
280    }
281
282    /// Override the output style for line numbers in the [`Snippet`][crate::Snippet] gutter
283    pub const fn line_num(mut self, style: Style) -> Self {
284        self.stylesheet.line_num = style;
285        self
286    }
287
288    /// Override the output style for emphasis for the
289    /// [`primary_title`][crate::Level::primary_title]
290    pub const fn emphasis(mut self, style: Style) -> Self {
291        self.stylesheet.emphasis = style;
292        self
293    }
294
295    /// Override the output style for [`AnnotationKind::Context`][crate::AnnotationKind::Context]
296    pub const fn context(mut self, style: Style) -> Self {
297        self.stylesheet.context = style;
298        self
299    }
300
301    /// Override the output style for [`Patch`][crate::Patch] additions
302    pub const fn addition(mut self, style: Style) -> Self {
303        self.stylesheet.addition = style;
304        self
305    }
306
307    /// Override the output style for [`Patch`][crate::Patch] removals
308    pub const fn removal(mut self, style: Style) -> Self {
309        self.stylesheet.removal = style;
310        self
311    }
312
313    /// Override the output style for all other text
314    pub const fn none(mut self, style: Style) -> Self {
315        self.stylesheet.none = style;
316        self
317    }
318
319    /// Override whether hyperlinks should be emitted
320    pub const fn hyperlink(mut self, hyperlink: bool) -> Self {
321        self.hyperlink = hyperlink;
322        self
323    }
324}
325
326/// The character set for rendering for decor
327#[derive(Debug, Clone, Copy, PartialEq, Eq)]
328pub enum DecorStyle {
329    Ascii,
330    Unicode,
331}
332
333impl DecorStyle {
334    fn col_separator(&self) -> char {
335        match self {
336            Self::Ascii => '|',
337            Self::Unicode => '│',
338        }
339    }
340
341    fn note_separator(&self, is_cont: bool) -> &str {
342        match self {
343            Self::Ascii => "= ",
344            Self::Unicode if is_cont => "├ ",
345            Self::Unicode => "╰ ",
346        }
347    }
348
349    fn multi_suggestion_separator(&self) -> &'static str {
350        match self {
351            Self::Ascii => "|",
352            Self::Unicode => "├╴",
353        }
354    }
355
356    fn file_start(&self, is_first: bool, alone: bool) -> &'static str {
357        match self {
358            Self::Ascii => "--> ",
359            Self::Unicode if is_first && alone => " ─▸ ",
360            Self::Unicode if is_first => " ╭▸ ",
361            Self::Unicode => " ├▸ ",
362        }
363    }
364
365    fn secondary_file_start(&self) -> &'static str {
366        match self {
367            Self::Ascii => "::: ",
368            Self::Unicode => " ⸬  ",
369        }
370    }
371
372    fn diff(&self) -> char {
373        match self {
374            Self::Ascii => '~',
375            Self::Unicode => '±',
376        }
377    }
378
379    fn margin(&self) -> &'static str {
380        match self {
381            Self::Ascii => "...",
382            Self::Unicode => "…",
383        }
384    }
385
386    fn underline(&self, is_primary: bool) -> UnderlineParts {
387        //               X0 Y0
388        // label_start > ┯━━━━ < underline
389        //               │ < vertical_text_line
390        //               text
391
392        //    multiline_start_down ⤷ X0 Y0
393        //            top_left > ┌───╿──┘ < top_right_flat
394        //           top_left > ┏│━━━┙ < top_right
395        // multiline_vertical > ┃│
396        //                      ┃│   X1 Y1
397        //                      ┃│   X2 Y2
398        //                      ┃└────╿──┘ < multiline_end_same_line
399        //        bottom_left > ┗━━━━━┥ < bottom_right_with_text
400        //   multiline_horizontal ^   `X` is a good letter
401
402        // multiline_whole_line > ┏ X0 Y0
403        //                        ┃   X1 Y1
404        //                        ┗━━━━┛ < multiline_end_same_line
405
406        // multiline_whole_line > ┏ X0 Y0
407        //                        ┃ X1 Y1
408        //                        ┃  ╿ < multiline_end_up
409        //                        ┗━━┛ < bottom_right
410
411        match (self, is_primary) {
412            (Self::Ascii, true) => UnderlineParts {
413                style: ElementStyle::UnderlinePrimary,
414                underline: '^',
415                label_start: '^',
416                vertical_text_line: '|',
417                multiline_vertical: '|',
418                multiline_horizontal: '_',
419                multiline_whole_line: '/',
420                multiline_start_down: '^',
421                bottom_right: '|',
422                top_left: ' ',
423                top_right_flat: '^',
424                bottom_left: '|',
425                multiline_end_up: '^',
426                multiline_end_same_line: '^',
427                multiline_bottom_right_with_text: '|',
428            },
429            (Self::Ascii, false) => UnderlineParts {
430                style: ElementStyle::UnderlineSecondary,
431                underline: '-',
432                label_start: '-',
433                vertical_text_line: '|',
434                multiline_vertical: '|',
435                multiline_horizontal: '_',
436                multiline_whole_line: '/',
437                multiline_start_down: '-',
438                bottom_right: '|',
439                top_left: ' ',
440                top_right_flat: '-',
441                bottom_left: '|',
442                multiline_end_up: '-',
443                multiline_end_same_line: '-',
444                multiline_bottom_right_with_text: '|',
445            },
446            (Self::Unicode, true) => UnderlineParts {
447                style: ElementStyle::UnderlinePrimary,
448                underline: '━',
449                label_start: '┯',
450                vertical_text_line: '│',
451                multiline_vertical: '┃',
452                multiline_horizontal: '━',
453                multiline_whole_line: '┏',
454                multiline_start_down: '╿',
455                bottom_right: '┙',
456                top_left: '┏',
457                top_right_flat: '┛',
458                bottom_left: '┗',
459                multiline_end_up: '╿',
460                multiline_end_same_line: '┛',
461                multiline_bottom_right_with_text: '┥',
462            },
463            (Self::Unicode, false) => UnderlineParts {
464                style: ElementStyle::UnderlineSecondary,
465                underline: '─',
466                label_start: '┬',
467                vertical_text_line: '│',
468                multiline_vertical: '│',
469                multiline_horizontal: '─',
470                multiline_whole_line: '┌',
471                multiline_start_down: '│',
472                bottom_right: '┘',
473                top_left: '┌',
474                top_right_flat: '┘',
475                bottom_left: '└',
476                multiline_end_up: '│',
477                multiline_end_same_line: '┘',
478                multiline_bottom_right_with_text: '┤',
479            },
480        }
481    }
482}