annotate_snippets/renderer/
mod.rs

1// Most of this file is adapted from https://github.com/rust-lang/rust/blob/160905b6253f42967ed4aef4b98002944c7df24c/compiler/rustc_errors/src/emitter.rs
2
3//! The [Renderer] and its settings
4//!
5//! # Example
6//!
7//! ```
8//! # use annotate_snippets::*;
9//! # use annotate_snippets::renderer::*;
10//! # use annotate_snippets::Level;
11//! let report = // ...
12//! # &[Group::with_title(
13//! #     Level::ERROR
14//! #         .primary_title("unresolved import `baz::zed`")
15//! #         .id("E0432")
16//! # )];
17//!
18//! let renderer = Renderer::styled().decor_style(DecorStyle::Unicode);
19//! let output = renderer.render(report);
20//! anstream::println!("{output}");
21//! ```
22
23mod margin;
24pub(crate) mod source_map;
25mod styled_buffer;
26pub(crate) mod stylesheet;
27
28use crate::level::{Level, LevelInner};
29use crate::renderer::source_map::{
30    AnnotatedLineInfo, LineInfo, Loc, SourceMap, SubstitutionHighlight,
31};
32use crate::renderer::styled_buffer::StyledBuffer;
33use crate::snippet::Id;
34use crate::{
35    Annotation, AnnotationKind, Element, Group, Message, Origin, Patch, Report, Snippet, Title,
36};
37pub use anstyle::*;
38use margin::Margin;
39use std::borrow::Cow;
40use std::cmp::{max, min, Ordering, Reverse};
41use std::collections::{HashMap, VecDeque};
42use std::fmt;
43use stylesheet::Stylesheet;
44
45const ANONYMIZED_LINE_NUM: &str = "LL";
46
47/// See [`Renderer::term_width`]
48pub const DEFAULT_TERM_WIDTH: usize = 140;
49
50/// The [Renderer] for a [`Report`]
51///
52/// The caller is expected to detect any relevant terminal features and configure the renderer,
53/// including
54/// - ANSI Escape code support (always outputted with [`Renderer::styled`])
55/// - Terminal width ([`Renderer::term_width`])
56/// - Unicode support ([`Renderer::decor_style`])
57///
58/// # Example
59///
60/// ```
61/// # use annotate_snippets::*;
62/// # use annotate_snippets::renderer::*;
63/// # use annotate_snippets::Level;
64/// let report = // ...
65/// # &[Group::with_title(
66/// #     Level::ERROR
67/// #         .primary_title("unresolved import `baz::zed`")
68/// #         .id("E0432")
69/// # )];
70///
71/// let renderer = Renderer::styled();
72/// let output = renderer.render(report);
73/// anstream::println!("{output}");
74/// ```
75#[derive(Clone, Debug)]
76pub struct Renderer {
77    anonymized_line_numbers: bool,
78    term_width: usize,
79    decor_style: DecorStyle,
80    stylesheet: Stylesheet,
81    short_message: bool,
82}
83
84impl Renderer {
85    /// No terminal styling
86    pub const fn plain() -> Self {
87        Self {
88            anonymized_line_numbers: false,
89            term_width: DEFAULT_TERM_WIDTH,
90            decor_style: DecorStyle::Ascii,
91            stylesheet: Stylesheet::plain(),
92            short_message: false,
93        }
94    }
95
96    /// Default terminal styling
97    ///
98    /// If ANSI escape codes are not supported, either
99    /// - Call [`Renderer::plain`] instead
100    /// - Strip them after the fact, like with [`anstream`](https://docs.rs/anstream/latest/anstream/)
101    ///
102    /// # Note
103    ///
104    /// When testing styled terminal output, see the [`testing-colors` feature](crate#features)
105    pub const fn styled() -> Self {
106        const USE_WINDOWS_COLORS: bool = cfg!(windows) && !cfg!(feature = "testing-colors");
107        const BRIGHT_BLUE: Style = if USE_WINDOWS_COLORS {
108            AnsiColor::BrightCyan.on_default()
109        } else {
110            AnsiColor::BrightBlue.on_default()
111        };
112        Self {
113            stylesheet: Stylesheet {
114                error: AnsiColor::BrightRed.on_default().effects(Effects::BOLD),
115                warning: if USE_WINDOWS_COLORS {
116                    AnsiColor::BrightYellow.on_default()
117                } else {
118                    AnsiColor::Yellow.on_default()
119                }
120                .effects(Effects::BOLD),
121                info: BRIGHT_BLUE.effects(Effects::BOLD),
122                note: AnsiColor::BrightGreen.on_default().effects(Effects::BOLD),
123                help: AnsiColor::BrightCyan.on_default().effects(Effects::BOLD),
124                line_num: BRIGHT_BLUE.effects(Effects::BOLD),
125                emphasis: if USE_WINDOWS_COLORS {
126                    AnsiColor::BrightWhite.on_default()
127                } else {
128                    Style::new()
129                }
130                .effects(Effects::BOLD),
131                none: Style::new(),
132                context: BRIGHT_BLUE.effects(Effects::BOLD),
133                addition: AnsiColor::BrightGreen.on_default(),
134                removal: AnsiColor::BrightRed.on_default(),
135            },
136            ..Self::plain()
137        }
138    }
139
140    /// Abbreviate the message
141    pub const fn short_message(mut self, short_message: bool) -> Self {
142        self.short_message = short_message;
143        self
144    }
145
146    /// Set the width to render within
147    ///
148    /// Affects the rendering of [`Snippet`]s
149    pub const fn term_width(mut self, term_width: usize) -> Self {
150        self.term_width = term_width;
151        self
152    }
153
154    /// Set the character set used for rendering decor
155    pub const fn decor_style(mut self, decor_style: DecorStyle) -> Self {
156        self.decor_style = decor_style;
157        self
158    }
159
160    /// Anonymize line numbers
161    ///
162    /// When enabled, line numbers are replaced with `LL` which is useful for tests.
163    ///
164    /// # Example
165    ///
166    /// ```text
167    ///   --> $DIR/whitespace-trimming.rs:4:193
168    ///    |
169    /// LL | ...                   let _: () = 42;
170    ///    |                                   ^^ expected (), found integer
171    ///    |
172    /// ```
173    pub const fn anonymized_line_numbers(mut self, anonymized_line_numbers: bool) -> Self {
174        self.anonymized_line_numbers = anonymized_line_numbers;
175        self
176    }
177}
178
179impl Renderer {
180    /// Render a diagnostic [`Report`]
181    pub fn render(&self, groups: Report<'_>) -> String {
182        if self.short_message {
183            self.render_short_message(groups).unwrap()
184        } else {
185            let max_line_num_len = if self.anonymized_line_numbers {
186                ANONYMIZED_LINE_NUM.len()
187            } else {
188                num_decimal_digits(max_line_number(groups))
189            };
190            let mut out_string = String::new();
191            let group_len = groups.len();
192            let mut og_primary_path = None;
193            for (g, group) in groups.iter().enumerate() {
194                let mut buffer = StyledBuffer::new();
195                let primary_path = group
196                    .elements
197                    .iter()
198                    .find_map(|s| match &s {
199                        Element::Cause(cause) => Some(cause.path.as_ref()),
200                        Element::Origin(origin) => Some(Some(&origin.path)),
201                        _ => None,
202                    })
203                    .unwrap_or_default();
204                if og_primary_path.is_none() && primary_path.is_some() {
205                    og_primary_path = primary_path;
206                }
207                let level = group.primary_level.clone();
208                let mut source_map_annotated_lines = VecDeque::new();
209                let mut max_depth = 0;
210                for e in &group.elements {
211                    if let Element::Cause(cause) = e {
212                        let source_map = SourceMap::new(&cause.source, cause.line_start);
213                        let (depth, annotated_lines) =
214                            source_map.annotated_lines(cause.markers.clone(), cause.fold);
215                        max_depth = max(max_depth, depth);
216                        source_map_annotated_lines.push_back((source_map, annotated_lines));
217                    }
218                }
219                let mut message_iter = group.elements.iter().enumerate().peekable();
220                if let Some(title) = &group.title {
221                    let peek = message_iter.peek().map(|(_, s)| s).copied();
222                    let title_style = if title.allows_styling {
223                        TitleStyle::Header
224                    } else {
225                        TitleStyle::MainHeader
226                    };
227                    let buffer_msg_line_offset = buffer.num_lines();
228                    self.render_title(
229                        &mut buffer,
230                        title,
231                        max_line_num_len,
232                        title_style,
233                        matches!(peek, Some(Element::Message(_))),
234                        buffer_msg_line_offset,
235                    );
236                    let buffer_msg_line_offset = buffer.num_lines();
237
238                    if matches!(peek, Some(Element::Message(_))) {
239                        self.draw_col_separator_no_space(
240                            &mut buffer,
241                            buffer_msg_line_offset,
242                            max_line_num_len + 1,
243                        );
244                    }
245                    if peek.is_none() && g == 0 && group_len > 1 {
246                        self.draw_col_separator_end(
247                            &mut buffer,
248                            buffer_msg_line_offset,
249                            max_line_num_len + 1,
250                        );
251                    }
252                }
253                let mut seen_primary = false;
254                let mut last_suggestion_path = None;
255                while let Some((i, section)) = message_iter.next() {
256                    let peek = message_iter.peek().map(|(_, s)| s).copied();
257                    let is_first = i == 0;
258                    match &section {
259                        Element::Message(title) => {
260                            let title_style = TitleStyle::Secondary;
261                            let buffer_msg_line_offset = buffer.num_lines();
262                            self.render_title(
263                                &mut buffer,
264                                title,
265                                max_line_num_len,
266                                title_style,
267                                peek.is_some(),
268                                buffer_msg_line_offset,
269                            );
270                        }
271                        Element::Cause(cause) => {
272                            if let Some((source_map, annotated_lines)) =
273                                source_map_annotated_lines.pop_front()
274                            {
275                                let is_primary =
276                                    primary_path == cause.path.as_ref() && !seen_primary;
277                                seen_primary |= is_primary;
278                                self.render_snippet_annotations(
279                                    &mut buffer,
280                                    max_line_num_len,
281                                    cause,
282                                    is_primary,
283                                    &source_map,
284                                    &annotated_lines,
285                                    max_depth,
286                                    peek.is_some() || (g == 0 && group_len > 1),
287                                    is_first,
288                                );
289
290                                if g == 0 {
291                                    let current_line = buffer.num_lines();
292                                    match peek {
293                                        Some(Element::Message(_)) => {
294                                            self.draw_col_separator_no_space(
295                                                &mut buffer,
296                                                current_line,
297                                                max_line_num_len + 1,
298                                            );
299                                        }
300                                        None if group_len > 1 => self.draw_col_separator_end(
301                                            &mut buffer,
302                                            current_line,
303                                            max_line_num_len + 1,
304                                        ),
305                                        _ => {}
306                                    }
307                                }
308                            }
309                        }
310                        Element::Suggestion(suggestion) => {
311                            let source_map =
312                                SourceMap::new(&suggestion.source, suggestion.line_start);
313                            let matches_previous_suggestion =
314                                last_suggestion_path == Some(suggestion.path.as_ref());
315                            self.emit_suggestion_default(
316                                &mut buffer,
317                                suggestion,
318                                max_line_num_len,
319                                &source_map,
320                                primary_path.or(og_primary_path),
321                                matches_previous_suggestion,
322                                is_first,
323                                //matches!(peek, Some(Element::Message(_) | Element::Padding(_))),
324                                peek.is_some(),
325                            );
326
327                            if matches!(peek, Some(Element::Suggestion(_))) {
328                                last_suggestion_path = Some(suggestion.path.as_ref());
329                            } else {
330                                last_suggestion_path = None;
331                            }
332                        }
333
334                        Element::Origin(origin) => {
335                            let buffer_msg_line_offset = buffer.num_lines();
336                            let is_primary = primary_path == Some(&origin.path) && !seen_primary;
337                            seen_primary |= is_primary;
338                            self.render_origin(
339                                &mut buffer,
340                                max_line_num_len,
341                                origin,
342                                is_primary,
343                                is_first,
344                                buffer_msg_line_offset,
345                            );
346                            let current_line = buffer.num_lines();
347                            if g == 0 && peek.is_none() && group_len > 1 {
348                                self.draw_col_separator_end(
349                                    &mut buffer,
350                                    current_line,
351                                    max_line_num_len + 1,
352                                );
353                            }
354                        }
355                        Element::Padding(_) => {
356                            let current_line = buffer.num_lines();
357                            if peek.is_none() {
358                                self.draw_col_separator_end(
359                                    &mut buffer,
360                                    current_line,
361                                    max_line_num_len + 1,
362                                );
363                            } else {
364                                self.draw_col_separator_no_space(
365                                    &mut buffer,
366                                    current_line,
367                                    max_line_num_len + 1,
368                                );
369                            }
370                        }
371                    }
372                }
373                buffer
374                    .render(&level, &self.stylesheet, &mut out_string)
375                    .unwrap();
376                if g != group_len - 1 {
377                    use std::fmt::Write;
378
379                    writeln!(out_string).unwrap();
380                }
381            }
382            out_string
383        }
384    }
385
386    fn render_short_message(&self, groups: &[Group<'_>]) -> Result<String, fmt::Error> {
387        let mut buffer = StyledBuffer::new();
388        let mut labels = None;
389        let group = groups.first().expect("Expected at least one group");
390
391        let Some(title) = &group.title else {
392            panic!("Expected a Title");
393        };
394
395        if let Some(Element::Cause(cause)) = group
396            .elements
397            .iter()
398            .find(|e| matches!(e, Element::Cause(_)))
399        {
400            let labels_inner = cause
401                .markers
402                .iter()
403                .filter_map(|ann| match &ann.label {
404                    Some(msg) if ann.kind.is_primary() => {
405                        if !msg.trim().is_empty() {
406                            Some(msg.to_string())
407                        } else {
408                            None
409                        }
410                    }
411                    _ => None,
412                })
413                .collect::<Vec<_>>()
414                .join(", ");
415            if !labels_inner.is_empty() {
416                labels = Some(labels_inner);
417            }
418
419            if let Some(path) = &cause.path {
420                let mut origin = Origin::path(path.as_ref());
421
422                let source_map = SourceMap::new(&cause.source, cause.line_start);
423                let (_depth, annotated_lines) =
424                    source_map.annotated_lines(cause.markers.clone(), cause.fold);
425
426                if let Some(primary_line) = annotated_lines
427                    .iter()
428                    .find(|l| l.annotations.iter().any(LineAnnotation::is_primary))
429                    .or(annotated_lines.iter().find(|l| !l.annotations.is_empty()))
430                {
431                    origin.line = Some(primary_line.line_index);
432                    if let Some(first_annotation) = primary_line
433                        .annotations
434                        .iter()
435                        .min_by_key(|a| (Reverse(a.is_primary()), a.start.char))
436                    {
437                        origin.char_column = Some(first_annotation.start.char + 1);
438                    }
439                }
440
441                self.render_origin(&mut buffer, 0, &origin, true, true, 0);
442                buffer.append(0, ": ", ElementStyle::LineAndColumn);
443            }
444        }
445
446        self.render_title(
447            &mut buffer,
448            title,
449            0, // No line numbers in short messages
450            TitleStyle::MainHeader,
451            false,
452            0,
453        );
454
455        if let Some(labels) = labels {
456            buffer.append(0, &format!(": {labels}"), ElementStyle::NoStyle);
457        }
458
459        let mut out_string = String::new();
460        buffer.render(&title.level, &self.stylesheet, &mut out_string)?;
461
462        Ok(out_string)
463    }
464
465    #[allow(clippy::too_many_arguments)]
466    fn render_title(
467        &self,
468        buffer: &mut StyledBuffer,
469        title: &dyn MessageOrTitle,
470        max_line_num_len: usize,
471        title_style: TitleStyle,
472        is_cont: bool,
473        buffer_msg_line_offset: usize,
474    ) {
475        let (label_style, title_element_style) = match title_style {
476            TitleStyle::MainHeader => (
477                ElementStyle::Level(title.level().level),
478                if self.short_message {
479                    ElementStyle::NoStyle
480                } else {
481                    ElementStyle::MainHeaderMsg
482                },
483            ),
484            TitleStyle::Header => (
485                ElementStyle::Level(title.level().level),
486                ElementStyle::HeaderMsg,
487            ),
488            TitleStyle::Secondary => {
489                for _ in 0..max_line_num_len {
490                    buffer.prepend(buffer_msg_line_offset, " ", ElementStyle::NoStyle);
491                }
492
493                self.draw_note_separator(
494                    buffer,
495                    buffer_msg_line_offset,
496                    max_line_num_len + 1,
497                    is_cont,
498                );
499                (ElementStyle::MainHeaderMsg, ElementStyle::NoStyle)
500            }
501        };
502        let mut label_width = 0;
503
504        if title.level().name != Some(None) {
505            buffer.append(buffer_msg_line_offset, title.level().as_str(), label_style);
506            label_width += title.level().as_str().len();
507            if let Some(Id { id: Some(id), url }) = &title.id() {
508                buffer.append(buffer_msg_line_offset, "[", label_style);
509                if let Some(url) = url.as_ref() {
510                    buffer.append(
511                        buffer_msg_line_offset,
512                        &format!("\x1B]8;;{url}\x1B\\"),
513                        label_style,
514                    );
515                }
516                buffer.append(buffer_msg_line_offset, id, label_style);
517                if url.is_some() {
518                    buffer.append(buffer_msg_line_offset, "\x1B]8;;\x1B\\", label_style);
519                }
520                buffer.append(buffer_msg_line_offset, "]", label_style);
521                label_width += 2 + id.len();
522            }
523            buffer.append(buffer_msg_line_offset, ": ", title_element_style);
524            label_width += 2;
525        }
526
527        let padding = " ".repeat(if title_style == TitleStyle::Secondary {
528            // The extra 3 ` ` is padding that's always needed to align to the
529            // label i.e. `note: `:
530            //
531            //   error: message
532            //     --> file.rs:13:20
533            //      |
534            //   13 |     <CODE>
535            //      |      ^^^^
536            //      |
537            //      = note: multiline
538            //              message
539            //   ++^^^------
540            //    |  |     |
541            //    |  |     |
542            //    |  |     width of label
543            //    |  magic `3`
544            //    `max_line_num_len`
545            max_line_num_len + 3 + label_width
546        } else {
547            label_width
548        });
549
550        let (title_str, style) = if title.allows_styling() {
551            (title.text().to_owned(), ElementStyle::NoStyle)
552        } else {
553            (normalize_whitespace(title.text()), title_element_style)
554        };
555        for (i, text) in title_str.split('\n').enumerate() {
556            if i != 0 {
557                buffer.append(buffer_msg_line_offset + i, &padding, ElementStyle::NoStyle);
558                if title_style == TitleStyle::Secondary
559                    && is_cont
560                    && matches!(self.decor_style, DecorStyle::Unicode)
561                {
562                    // There's another note after this one, associated to the subwindow above.
563                    // We write additional vertical lines to join them:
564                    //   ╭▸ test.rs:3:3
565                    //   │
566                    // 3 │   code
567                    //   │   ━━━━
568                    //   │
569                    //   ├ note: foo
570                    //   │       bar
571                    //   ╰ note: foo
572                    //           bar
573                    self.draw_col_separator_no_space(
574                        buffer,
575                        buffer_msg_line_offset + i,
576                        max_line_num_len + 1,
577                    );
578                }
579            }
580            buffer.append(buffer_msg_line_offset + i, text, style);
581        }
582    }
583
584    fn render_origin(
585        &self,
586        buffer: &mut StyledBuffer,
587        max_line_num_len: usize,
588        origin: &Origin<'_>,
589        is_primary: bool,
590        is_first: bool,
591        buffer_msg_line_offset: usize,
592    ) {
593        if is_primary && !self.short_message {
594            buffer.prepend(
595                buffer_msg_line_offset,
596                self.file_start(is_first),
597                ElementStyle::LineNumber,
598            );
599        } else if !self.short_message {
600            // if !origin.standalone {
601            //     // Add spacing line, as shown:
602            //     //   --> $DIR/file:54:15
603            //     //    |
604            //     // LL |         code
605            //     //    |         ^^^^
606            //     //    | (<- It prints *this* line)
607            //     //   ::: $DIR/other_file.rs:15:5
608            //     //    |
609            //     // LL |     code
610            //     //    |     ----
611            //     self.draw_col_separator_no_space(
612            //         buffer,
613            //         buffer_msg_line_offset,
614            //         max_line_num_len + 1,
615            //     );
616            //
617            //     buffer_msg_line_offset += 1;
618            // }
619            // Then, the secondary file indicator
620            buffer.prepend(
621                buffer_msg_line_offset,
622                self.secondary_file_start(),
623                ElementStyle::LineNumber,
624            );
625        }
626
627        let str = match (&origin.line, &origin.char_column) {
628            (Some(line), Some(col)) => {
629                format!("{}:{}:{}", origin.path, line, col)
630            }
631            (Some(line), None) => format!("{}:{}", origin.path, line),
632            _ => origin.path.to_string(),
633        };
634
635        buffer.append(buffer_msg_line_offset, &str, ElementStyle::LineAndColumn);
636        if !self.short_message {
637            for _ in 0..max_line_num_len {
638                buffer.prepend(buffer_msg_line_offset, " ", ElementStyle::NoStyle);
639            }
640        }
641    }
642
643    #[allow(clippy::too_many_arguments)]
644    fn render_snippet_annotations(
645        &self,
646        buffer: &mut StyledBuffer,
647        max_line_num_len: usize,
648        snippet: &Snippet<'_, Annotation<'_>>,
649        is_primary: bool,
650        sm: &SourceMap<'_>,
651        annotated_lines: &[AnnotatedLineInfo<'_>],
652        multiline_depth: usize,
653        is_cont: bool,
654        is_first: bool,
655    ) {
656        if let Some(path) = &snippet.path {
657            let mut origin = Origin::path(path.as_ref());
658            // print out the span location and spacer before we print the annotated source
659            // to do this, we need to know if this span will be primary
660            //let is_primary = primary_path == Some(&origin.path);
661
662            if is_primary {
663                if let Some(primary_line) = annotated_lines
664                    .iter()
665                    .find(|l| l.annotations.iter().any(LineAnnotation::is_primary))
666                    .or(annotated_lines.iter().find(|l| !l.annotations.is_empty()))
667                {
668                    origin.line = Some(primary_line.line_index);
669                    if let Some(first_annotation) = primary_line
670                        .annotations
671                        .iter()
672                        .min_by_key(|a| (Reverse(a.is_primary()), a.start.char))
673                    {
674                        origin.char_column = Some(first_annotation.start.char + 1);
675                    }
676                }
677            } else {
678                let buffer_msg_line_offset = buffer.num_lines();
679                // Add spacing line, as shown:
680                //   --> $DIR/file:54:15
681                //    |
682                // LL |         code
683                //    |         ^^^^
684                //    | (<- It prints *this* line)
685                //   ::: $DIR/other_file.rs:15:5
686                //    |
687                // LL |     code
688                //    |     ----
689                self.draw_col_separator_no_space(
690                    buffer,
691                    buffer_msg_line_offset,
692                    max_line_num_len + 1,
693                );
694                if let Some(first_line) = annotated_lines.first() {
695                    origin.line = Some(first_line.line_index);
696                    if let Some(first_annotation) = first_line.annotations.first() {
697                        origin.char_column = Some(first_annotation.start.char + 1);
698                    }
699                }
700            }
701            let buffer_msg_line_offset = buffer.num_lines();
702            self.render_origin(
703                buffer,
704                max_line_num_len,
705                &origin,
706                is_primary,
707                is_first,
708                buffer_msg_line_offset,
709            );
710            // Put in the spacer between the location and annotated source
711            self.draw_col_separator_no_space(
712                buffer,
713                buffer_msg_line_offset + 1,
714                max_line_num_len + 1,
715            );
716        } else {
717            let buffer_msg_line_offset = buffer.num_lines();
718            if is_primary {
719                if self.decor_style == DecorStyle::Unicode {
720                    buffer.puts(
721                        buffer_msg_line_offset,
722                        max_line_num_len,
723                        self.file_start(is_first),
724                        ElementStyle::LineNumber,
725                    );
726                } else {
727                    self.draw_col_separator_no_space(
728                        buffer,
729                        buffer_msg_line_offset,
730                        max_line_num_len + 1,
731                    );
732                }
733            } else {
734                // Add spacing line, as shown:
735                //   --> $DIR/file:54:15
736                //    |
737                // LL |         code
738                //    |         ^^^^
739                //    | (<- It prints *this* line)
740                //   ::: $DIR/other_file.rs:15:5
741                //    |
742                // LL |     code
743                //    |     ----
744                self.draw_col_separator_no_space(
745                    buffer,
746                    buffer_msg_line_offset,
747                    max_line_num_len + 1,
748                );
749
750                buffer.puts(
751                    buffer_msg_line_offset + 1,
752                    max_line_num_len,
753                    self.secondary_file_start(),
754                    ElementStyle::LineNumber,
755                );
756            }
757        }
758
759        // Contains the vertical lines' positions for active multiline annotations
760        let mut multilines = Vec::new();
761
762        // Get the left-side margin to remove it
763        let mut whitespace_margin = usize::MAX;
764        for line_info in annotated_lines {
765            // Whitespace can only be removed (aka considered leading)
766            // if the lexer considers it whitespace.
767            // non-rustc_lexer::is_whitespace() chars are reported as an
768            // error (ex. no-break-spaces \u{a0}), and thus can't be considered
769            // for removal during error reporting.
770            let leading_whitespace = line_info
771                .line
772                .chars()
773                .take_while(|c| c.is_whitespace())
774                .map(|c| {
775                    match c {
776                        // Tabs are displayed as 4 spaces
777                        '\t' => 4,
778                        _ => 1,
779                    }
780                })
781                .sum();
782            if line_info.line.chars().any(|c| !c.is_whitespace()) {
783                whitespace_margin = min(whitespace_margin, leading_whitespace);
784            }
785        }
786        if whitespace_margin == usize::MAX {
787            whitespace_margin = 0;
788        }
789
790        // Left-most column any visible span points at.
791        let mut span_left_margin = usize::MAX;
792        for line_info in annotated_lines {
793            for ann in &line_info.annotations {
794                span_left_margin = min(span_left_margin, ann.start.display);
795                span_left_margin = min(span_left_margin, ann.end.display);
796            }
797        }
798        if span_left_margin == usize::MAX {
799            span_left_margin = 0;
800        }
801
802        // Right-most column any visible span points at.
803        let mut span_right_margin = 0;
804        let mut label_right_margin = 0;
805        let mut max_line_len = 0;
806        for line_info in annotated_lines {
807            max_line_len = max(max_line_len, line_info.line.len());
808            for ann in &line_info.annotations {
809                span_right_margin = max(span_right_margin, ann.start.display);
810                span_right_margin = max(span_right_margin, ann.end.display);
811                // FIXME: account for labels not in the same line
812                let label_right = ann.label.as_ref().map_or(0, |l| l.len() + 1);
813                label_right_margin = max(label_right_margin, ann.end.display + label_right);
814            }
815        }
816        let width_offset = 3 + max_line_num_len;
817        let code_offset = if multiline_depth == 0 {
818            width_offset
819        } else {
820            width_offset + multiline_depth + 1
821        };
822
823        let column_width = self.term_width.saturating_sub(code_offset);
824
825        let margin = Margin::new(
826            whitespace_margin,
827            span_left_margin,
828            span_right_margin,
829            label_right_margin,
830            column_width,
831            max_line_len,
832        );
833
834        // Next, output the annotate source for this file
835        for annotated_line_idx in 0..annotated_lines.len() {
836            let previous_buffer_line = buffer.num_lines();
837
838            let depths = self.render_source_line(
839                &annotated_lines[annotated_line_idx],
840                buffer,
841                width_offset,
842                code_offset,
843                max_line_num_len,
844                margin,
845                !is_cont && annotated_line_idx + 1 == annotated_lines.len(),
846            );
847
848            let mut to_add = HashMap::new();
849
850            for (depth, style) in depths {
851                if let Some(index) = multilines.iter().position(|(d, _)| d == &depth) {
852                    multilines.swap_remove(index);
853                } else {
854                    to_add.insert(depth, style);
855                }
856            }
857
858            // Set the multiline annotation vertical lines to the left of
859            // the code in this line.
860            for (depth, style) in &multilines {
861                for line in previous_buffer_line..buffer.num_lines() {
862                    self.draw_multiline_line(buffer, line, width_offset, *depth, *style);
863                }
864            }
865            // check to see if we need to print out or elide lines that come between
866            // this annotated line and the next one.
867            if annotated_line_idx < (annotated_lines.len() - 1) {
868                let line_idx_delta = annotated_lines[annotated_line_idx + 1].line_index
869                    - annotated_lines[annotated_line_idx].line_index;
870                match line_idx_delta.cmp(&2) {
871                    Ordering::Greater => {
872                        let last_buffer_line_num = buffer.num_lines();
873
874                        self.draw_line_separator(buffer, last_buffer_line_num, width_offset);
875
876                        // Set the multiline annotation vertical lines on `...` bridging line.
877                        for (depth, style) in &multilines {
878                            self.draw_multiline_line(
879                                buffer,
880                                last_buffer_line_num,
881                                width_offset,
882                                *depth,
883                                *style,
884                            );
885                        }
886                        if let Some(line) = annotated_lines.get(annotated_line_idx) {
887                            for ann in &line.annotations {
888                                if let LineAnnotationType::MultilineStart(pos) = ann.annotation_type
889                                {
890                                    // In the case where we have elided the entire start of the
891                                    // multispan because those lines were empty, we still need
892                                    // to draw the `|`s across the `...`.
893                                    self.draw_multiline_line(
894                                        buffer,
895                                        last_buffer_line_num,
896                                        width_offset,
897                                        pos,
898                                        if ann.is_primary() {
899                                            ElementStyle::UnderlinePrimary
900                                        } else {
901                                            ElementStyle::UnderlineSecondary
902                                        },
903                                    );
904                                }
905                            }
906                        }
907                    }
908
909                    Ordering::Equal => {
910                        let unannotated_line = sm
911                            .get_line(annotated_lines[annotated_line_idx].line_index + 1)
912                            .unwrap_or("");
913
914                        let last_buffer_line_num = buffer.num_lines();
915
916                        self.draw_line(
917                            buffer,
918                            &normalize_whitespace(unannotated_line),
919                            annotated_lines[annotated_line_idx + 1].line_index - 1,
920                            last_buffer_line_num,
921                            width_offset,
922                            code_offset,
923                            max_line_num_len,
924                            margin,
925                        );
926
927                        for (depth, style) in &multilines {
928                            self.draw_multiline_line(
929                                buffer,
930                                last_buffer_line_num,
931                                width_offset,
932                                *depth,
933                                *style,
934                            );
935                        }
936                        if let Some(line) = annotated_lines.get(annotated_line_idx) {
937                            for ann in &line.annotations {
938                                if let LineAnnotationType::MultilineStart(pos) = ann.annotation_type
939                                {
940                                    self.draw_multiline_line(
941                                        buffer,
942                                        last_buffer_line_num,
943                                        width_offset,
944                                        pos,
945                                        if ann.is_primary() {
946                                            ElementStyle::UnderlinePrimary
947                                        } else {
948                                            ElementStyle::UnderlineSecondary
949                                        },
950                                    );
951                                }
952                            }
953                        }
954                    }
955                    Ordering::Less => {}
956                }
957            }
958
959            multilines.extend(to_add);
960        }
961    }
962
963    #[allow(clippy::too_many_arguments)]
964    fn render_source_line(
965        &self,
966        line_info: &AnnotatedLineInfo<'_>,
967        buffer: &mut StyledBuffer,
968        width_offset: usize,
969        code_offset: usize,
970        max_line_num_len: usize,
971        margin: Margin,
972        close_window: bool,
973    ) -> Vec<(usize, ElementStyle)> {
974        // Draw:
975        //
976        //   LL | ... code ...
977        //      |     ^^-^ span label
978        //      |       |
979        //      |       secondary span label
980        //
981        //   ^^ ^ ^^^ ^^^^ ^^^ we don't care about code too far to the right of a span, we trim it
982        //   |  | |   |
983        //   |  | |   actual code found in your source code and the spans we use to mark it
984        //   |  | when there's too much wasted space to the left, trim it
985        //   |  vertical divider between the column number and the code
986        //   column number
987
988        if line_info.line_index == 0 {
989            return Vec::new();
990        }
991
992        let source_string = normalize_whitespace(line_info.line);
993
994        let line_offset = buffer.num_lines();
995
996        let left = self.draw_line(
997            buffer,
998            &source_string,
999            line_info.line_index,
1000            line_offset,
1001            width_offset,
1002            code_offset,
1003            max_line_num_len,
1004            margin,
1005        );
1006
1007        // Special case when there's only one annotation involved, it is the start of a multiline
1008        // span and there's no text at the beginning of the code line. Instead of doing the whole
1009        // graph:
1010        //
1011        // 2 |   fn foo() {
1012        //   |  _^
1013        // 3 | |
1014        // 4 | | }
1015        //   | |_^ test
1016        //
1017        // we simplify the output to:
1018        //
1019        // 2 | / fn foo() {
1020        // 3 | |
1021        // 4 | | }
1022        //   | |_^ test
1023        let mut buffer_ops = vec![];
1024        let mut annotations = vec![];
1025        let mut short_start = true;
1026        for ann in &line_info.annotations {
1027            if let LineAnnotationType::MultilineStart(depth) = ann.annotation_type {
1028                if source_string
1029                    .chars()
1030                    .take(ann.start.display)
1031                    .all(char::is_whitespace)
1032                {
1033                    let uline = self.underline(ann.is_primary());
1034                    let chr = uline.multiline_whole_line;
1035                    annotations.push((depth, uline.style));
1036                    buffer_ops.push((line_offset, width_offset + depth - 1, chr, uline.style));
1037                } else {
1038                    short_start = false;
1039                    break;
1040                }
1041            } else if let LineAnnotationType::MultilineLine(_) = ann.annotation_type {
1042            } else {
1043                short_start = false;
1044                break;
1045            }
1046        }
1047        if short_start {
1048            for (y, x, c, s) in buffer_ops {
1049                buffer.putc(y, x, c, s);
1050            }
1051            return annotations;
1052        }
1053
1054        // We want to display like this:
1055        //
1056        //      vec.push(vec.pop().unwrap());
1057        //      ---      ^^^               - previous borrow ends here
1058        //      |        |
1059        //      |        error occurs here
1060        //      previous borrow of `vec` occurs here
1061        //
1062        // But there are some weird edge cases to be aware of:
1063        //
1064        //      vec.push(vec.pop().unwrap());
1065        //      --------                    - previous borrow ends here
1066        //      ||
1067        //      |this makes no sense
1068        //      previous borrow of `vec` occurs here
1069        //
1070        // For this reason, we group the lines into "highlight lines"
1071        // and "annotations lines", where the highlight lines have the `^`.
1072
1073        // Sort the annotations by (start, end col)
1074        // The labels are reversed, sort and then reversed again.
1075        // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
1076        // the letter signifies the span. Here we are only sorting by the
1077        // span and hence, the order of the elements with the same span will
1078        // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
1079        // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
1080        // still ordered first to last, but all the elements with different
1081        // spans are ordered by their spans in last to first order. Last to
1082        // first order is important, because the jiggly lines and | are on
1083        // the left, so the rightmost span needs to be rendered first,
1084        // otherwise the lines would end up needing to go over a message.
1085
1086        let mut annotations = line_info.annotations.clone();
1087        annotations.sort_by_key(|a| Reverse((a.start.display, a.start.char)));
1088
1089        // First, figure out where each label will be positioned.
1090        //
1091        // In the case where you have the following annotations:
1092        //
1093        //      vec.push(vec.pop().unwrap());
1094        //      --------                    - previous borrow ends here [C]
1095        //      ||
1096        //      |this makes no sense [B]
1097        //      previous borrow of `vec` occurs here [A]
1098        //
1099        // `annotations_position` will hold [(2, A), (1, B), (0, C)].
1100        //
1101        // We try, when possible, to stick the rightmost annotation at the end
1102        // of the highlight line:
1103        //
1104        //      vec.push(vec.pop().unwrap());
1105        //      ---      ---               - previous borrow ends here
1106        //
1107        // But sometimes that's not possible because one of the other
1108        // annotations overlaps it. For example, from the test
1109        // `span_overlap_label`, we have the following annotations
1110        // (written on distinct lines for clarity):
1111        //
1112        //      fn foo(x: u32) {
1113        //      --------------
1114        //             -
1115        //
1116        // In this case, we can't stick the rightmost-most label on
1117        // the highlight line, or we would get:
1118        //
1119        //      fn foo(x: u32) {
1120        //      -------- x_span
1121        //      |
1122        //      fn_span
1123        //
1124        // which is totally weird. Instead we want:
1125        //
1126        //      fn foo(x: u32) {
1127        //      --------------
1128        //      |      |
1129        //      |      x_span
1130        //      fn_span
1131        //
1132        // which is...less weird, at least. In fact, in general, if
1133        // the rightmost span overlaps with any other span, we should
1134        // use the "hang below" version, so we can at least make it
1135        // clear where the span *starts*. There's an exception for this
1136        // logic, when the labels do not have a message:
1137        //
1138        //      fn foo(x: u32) {
1139        //      --------------
1140        //             |
1141        //             x_span
1142        //
1143        // instead of:
1144        //
1145        //      fn foo(x: u32) {
1146        //      --------------
1147        //      |      |
1148        //      |      x_span
1149        //      <EMPTY LINE>
1150        //
1151        let mut overlap = vec![false; annotations.len()];
1152        let mut annotations_position = vec![];
1153        let mut line_len: usize = 0;
1154        let mut p = 0;
1155        for (i, annotation) in annotations.iter().enumerate() {
1156            for (j, next) in annotations.iter().enumerate() {
1157                if overlaps(next, annotation, 0) && j > 1 {
1158                    overlap[i] = true;
1159                    overlap[j] = true;
1160                }
1161                if overlaps(next, annotation, 0)  // This label overlaps with another one and both
1162                    && annotation.has_label()     // take space (they have text and are not
1163                    && j > i                      // multiline lines).
1164                    && p == 0
1165                // We're currently on the first line, move the label one line down
1166                {
1167                    // If we're overlapping with an un-labelled annotation with the same span
1168                    // we can just merge them in the output
1169                    if next.start.display == annotation.start.display
1170                        && next.start.char == annotation.start.char
1171                        && next.end.display == annotation.end.display
1172                        && next.end.char == annotation.end.char
1173                        && !next.has_label()
1174                    {
1175                        continue;
1176                    }
1177
1178                    // This annotation needs a new line in the output.
1179                    p += 1;
1180                    break;
1181                }
1182            }
1183            annotations_position.push((p, annotation));
1184            for (j, next) in annotations.iter().enumerate() {
1185                if j > i {
1186                    let l = next.label.as_ref().map_or(0, |label| label.len() + 2);
1187                    if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
1188                        // line if they overlap including padding, to
1189                        // avoid situations like:
1190                        //
1191                        //      fn foo(x: u32) {
1192                        //      -------^------
1193                        //      |      |
1194                        //      fn_spanx_span
1195                        //
1196                        && annotation.has_label()    // Both labels must have some text, otherwise
1197                        && next.has_label())         // they are not overlapping.
1198                        // Do not add a new line if this annotation
1199                        // or the next are vertical line placeholders.
1200                        || (annotation.takes_space() // If either this or the next annotation is
1201                        && next.has_label())     // multiline start/end, move it to a new line
1202                        || (annotation.has_label()   // so as not to overlap the horizontal lines.
1203                        && next.takes_space())
1204                        || (annotation.takes_space() && next.takes_space())
1205                        || (overlaps(next, annotation, l)
1206                        && (next.end.display, next.end.char) <= (annotation.end.display, annotation.end.char)
1207                        && next.has_label()
1208                        && p == 0)
1209                    // Avoid #42595.
1210                    {
1211                        // This annotation needs a new line in the output.
1212                        p += 1;
1213                        break;
1214                    }
1215                }
1216            }
1217            line_len = max(line_len, p);
1218        }
1219
1220        if line_len != 0 {
1221            line_len += 1;
1222        }
1223
1224        // If there are no annotations or the only annotations on this line are
1225        // MultilineLine, then there's only code being shown, stop processing.
1226        if line_info.annotations.iter().all(LineAnnotation::is_line) {
1227            return vec![];
1228        }
1229
1230        if annotations_position
1231            .iter()
1232            .all(|(_, ann)| matches!(ann.annotation_type, LineAnnotationType::MultilineStart(_)))
1233        {
1234            if let Some(max_pos) = annotations_position.iter().map(|(pos, _)| *pos).max() {
1235                // Special case the following, so that we minimize overlapping multiline spans.
1236                //
1237                // 3 │       X0 Y0 Z0
1238                //   │ ┏━━━━━┛  │  │     < We are writing these lines
1239                //   │ ┃┌───────┘  │     < by reverting the "depth" of
1240                //   │ ┃│┌─────────┘     < their multiline spans.
1241                // 4 │ ┃││   X1 Y1 Z1
1242                // 5 │ ┃││   X2 Y2 Z2
1243                //   │ ┃│└────╿──│──┘ `Z` label
1244                //   │ ┃└─────│──┤
1245                //   │ ┗━━━━━━┥  `Y` is a good letter too
1246                //   ╰╴       `X` is a good letter
1247                for (pos, _) in &mut annotations_position {
1248                    *pos = max_pos - *pos;
1249                }
1250                // We know then that we don't need an additional line for the span label, saving us
1251                // one line of vertical space.
1252                line_len = line_len.saturating_sub(1);
1253            }
1254        }
1255
1256        // Write the column separator.
1257        //
1258        // After this we will have:
1259        //
1260        // 2 |   fn foo() {
1261        //   |
1262        //   |
1263        //   |
1264        // 3 |
1265        // 4 |   }
1266        //   |
1267        for pos in 0..=line_len {
1268            self.draw_col_separator_no_space(buffer, line_offset + pos + 1, width_offset - 2);
1269        }
1270        if close_window {
1271            self.draw_col_separator_end(buffer, line_offset + line_len + 1, width_offset - 2);
1272        }
1273        // Write the horizontal lines for multiline annotations
1274        // (only the first and last lines need this).
1275        //
1276        // After this we will have:
1277        //
1278        // 2 |   fn foo() {
1279        //   |  __________
1280        //   |
1281        //   |
1282        // 3 |
1283        // 4 |   }
1284        //   |  _
1285        for &(pos, annotation) in &annotations_position {
1286            let underline = self.underline(annotation.is_primary());
1287            let pos = pos + 1;
1288            match annotation.annotation_type {
1289                LineAnnotationType::MultilineStart(depth)
1290                | LineAnnotationType::MultilineEnd(depth) => {
1291                    self.draw_range(
1292                        buffer,
1293                        underline.multiline_horizontal,
1294                        line_offset + pos,
1295                        width_offset + depth,
1296                        (code_offset + annotation.start.display).saturating_sub(left),
1297                        underline.style,
1298                    );
1299                }
1300                _ if annotation.highlight_source => {
1301                    buffer.set_style_range(
1302                        line_offset,
1303                        (code_offset + annotation.start.display).saturating_sub(left),
1304                        (code_offset + annotation.end.display).saturating_sub(left),
1305                        underline.style,
1306                        annotation.is_primary(),
1307                    );
1308                }
1309                _ => {}
1310            }
1311        }
1312
1313        // Write the vertical lines for labels that are on a different line as the underline.
1314        //
1315        // After this we will have:
1316        //
1317        // 2 |   fn foo() {
1318        //   |  __________
1319        //   | |    |
1320        //   | |
1321        // 3 | |
1322        // 4 | | }
1323        //   | |_
1324        for &(pos, annotation) in &annotations_position {
1325            let underline = self.underline(annotation.is_primary());
1326            let pos = pos + 1;
1327
1328            if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
1329                for p in line_offset + 1..=line_offset + pos {
1330                    buffer.putc(
1331                        p,
1332                        (code_offset + annotation.start.display).saturating_sub(left),
1333                        match annotation.annotation_type {
1334                            LineAnnotationType::MultilineLine(_) => underline.multiline_vertical,
1335                            _ => underline.vertical_text_line,
1336                        },
1337                        underline.style,
1338                    );
1339                }
1340                if let LineAnnotationType::MultilineStart(_) = annotation.annotation_type {
1341                    buffer.putc(
1342                        line_offset + pos,
1343                        (code_offset + annotation.start.display).saturating_sub(left),
1344                        underline.bottom_right,
1345                        underline.style,
1346                    );
1347                }
1348                if matches!(
1349                    annotation.annotation_type,
1350                    LineAnnotationType::MultilineEnd(_)
1351                ) && annotation.has_label()
1352                {
1353                    buffer.putc(
1354                        line_offset + pos,
1355                        (code_offset + annotation.start.display).saturating_sub(left),
1356                        underline.multiline_bottom_right_with_text,
1357                        underline.style,
1358                    );
1359                }
1360            }
1361            match annotation.annotation_type {
1362                LineAnnotationType::MultilineStart(depth) => {
1363                    buffer.putc(
1364                        line_offset + pos,
1365                        width_offset + depth - 1,
1366                        underline.top_left,
1367                        underline.style,
1368                    );
1369                    for p in line_offset + pos + 1..line_offset + line_len + 2 {
1370                        buffer.putc(
1371                            p,
1372                            width_offset + depth - 1,
1373                            underline.multiline_vertical,
1374                            underline.style,
1375                        );
1376                    }
1377                }
1378                LineAnnotationType::MultilineEnd(depth) => {
1379                    for p in line_offset..line_offset + pos {
1380                        buffer.putc(
1381                            p,
1382                            width_offset + depth - 1,
1383                            underline.multiline_vertical,
1384                            underline.style,
1385                        );
1386                    }
1387                    buffer.putc(
1388                        line_offset + pos,
1389                        width_offset + depth - 1,
1390                        underline.bottom_left,
1391                        underline.style,
1392                    );
1393                }
1394                _ => (),
1395            }
1396        }
1397
1398        // Write the labels on the annotations that actually have a label.
1399        //
1400        // After this we will have:
1401        //
1402        // 2 |   fn foo() {
1403        //   |  __________
1404        //   |      |
1405        //   |      something about `foo`
1406        // 3 |
1407        // 4 |   }
1408        //   |  _  test
1409        for &(pos, annotation) in &annotations_position {
1410            let style = if annotation.is_primary() {
1411                ElementStyle::LabelPrimary
1412            } else {
1413                ElementStyle::LabelSecondary
1414            };
1415            let (pos, col) = if pos == 0 {
1416                if annotation.end.display == 0 {
1417                    (pos + 1, (annotation.end.display + 2).saturating_sub(left))
1418                } else {
1419                    (pos + 1, (annotation.end.display + 1).saturating_sub(left))
1420                }
1421            } else {
1422                (pos + 2, annotation.start.display.saturating_sub(left))
1423            };
1424            if let Some(label) = &annotation.label {
1425                buffer.puts(line_offset + pos, code_offset + col, label, style);
1426            }
1427        }
1428
1429        // Sort from biggest span to smallest span so that smaller spans are
1430        // represented in the output:
1431        //
1432        // x | fn foo()
1433        //   | ^^^---^^
1434        //   | |  |
1435        //   | |  something about `foo`
1436        //   | something about `fn foo()`
1437        annotations_position.sort_by_key(|(_, ann)| {
1438            // Decreasing order. When annotations share the same length, prefer `Primary`.
1439            (Reverse(ann.len()), ann.is_primary())
1440        });
1441
1442        // Write the underlines.
1443        //
1444        // After this we will have:
1445        //
1446        // 2 |   fn foo() {
1447        //   |  ____-_____^
1448        //   |      |
1449        //   |      something about `foo`
1450        // 3 |
1451        // 4 |   }
1452        //   |  _^  test
1453        for &(pos, annotation) in &annotations_position {
1454            let uline = self.underline(annotation.is_primary());
1455            for p in annotation.start.display..annotation.end.display {
1456                // The default span label underline.
1457                buffer.putc(
1458                    line_offset + 1,
1459                    (code_offset + p).saturating_sub(left),
1460                    uline.underline,
1461                    uline.style,
1462                );
1463            }
1464
1465            if pos == 0
1466                && matches!(
1467                    annotation.annotation_type,
1468                    LineAnnotationType::MultilineStart(_) | LineAnnotationType::MultilineEnd(_)
1469                )
1470            {
1471                // The beginning of a multiline span with its leftward moving line on the same line.
1472                buffer.putc(
1473                    line_offset + 1,
1474                    (code_offset + annotation.start.display).saturating_sub(left),
1475                    match annotation.annotation_type {
1476                        LineAnnotationType::MultilineStart(_) => uline.top_right_flat,
1477                        LineAnnotationType::MultilineEnd(_) => uline.multiline_end_same_line,
1478                        _ => panic!("unexpected annotation type: {annotation:?}"),
1479                    },
1480                    uline.style,
1481                );
1482            } else if pos != 0
1483                && matches!(
1484                    annotation.annotation_type,
1485                    LineAnnotationType::MultilineStart(_) | LineAnnotationType::MultilineEnd(_)
1486                )
1487            {
1488                // The beginning of a multiline span with its leftward moving line on another line,
1489                // so we start going down first.
1490                buffer.putc(
1491                    line_offset + 1,
1492                    (code_offset + annotation.start.display).saturating_sub(left),
1493                    match annotation.annotation_type {
1494                        LineAnnotationType::MultilineStart(_) => uline.multiline_start_down,
1495                        LineAnnotationType::MultilineEnd(_) => uline.multiline_end_up,
1496                        _ => panic!("unexpected annotation type: {annotation:?}"),
1497                    },
1498                    uline.style,
1499                );
1500            } else if pos != 0 && annotation.has_label() {
1501                // The beginning of a span label with an actual label, we'll point down.
1502                buffer.putc(
1503                    line_offset + 1,
1504                    (code_offset + annotation.start.display).saturating_sub(left),
1505                    uline.label_start,
1506                    uline.style,
1507                );
1508            }
1509        }
1510
1511        // We look for individual *long* spans, and we trim the *middle*, so that we render
1512        // LL | ...= [0, 0, 0, ..., 0, 0];
1513        //    |      ^^^^^^^^^^...^^^^^^^ expected `&[u8]`, found `[{integer}; 1680]`
1514        for (i, (_pos, annotation)) in annotations_position.iter().enumerate() {
1515            // Skip cases where multiple spans overlap eachother.
1516            if overlap[i] {
1517                continue;
1518            };
1519            let LineAnnotationType::Singleline = annotation.annotation_type else {
1520                continue;
1521            };
1522            let width = annotation.end.display - annotation.start.display;
1523            if width > margin.term_width * 2 && width > 10 {
1524                // If the terminal is *too* small, we keep at least a tiny bit of the span for
1525                // display.
1526                let pad = max(margin.term_width / 3, 5);
1527                // Code line
1528                buffer.replace(
1529                    line_offset,
1530                    annotation.start.display + pad,
1531                    annotation.end.display - pad,
1532                    self.margin(),
1533                );
1534                // Underline line
1535                buffer.replace(
1536                    line_offset + 1,
1537                    annotation.start.display + pad,
1538                    annotation.end.display - pad,
1539                    self.margin(),
1540                );
1541            }
1542        }
1543        annotations_position
1544            .iter()
1545            .filter_map(|&(_, annotation)| match annotation.annotation_type {
1546                LineAnnotationType::MultilineStart(p) | LineAnnotationType::MultilineEnd(p) => {
1547                    let style = if annotation.is_primary() {
1548                        ElementStyle::LabelPrimary
1549                    } else {
1550                        ElementStyle::LabelSecondary
1551                    };
1552                    Some((p, style))
1553                }
1554                _ => None,
1555            })
1556            .collect::<Vec<_>>()
1557    }
1558
1559    #[allow(clippy::too_many_arguments)]
1560    fn emit_suggestion_default(
1561        &self,
1562        buffer: &mut StyledBuffer,
1563        suggestion: &Snippet<'_, Patch<'_>>,
1564        max_line_num_len: usize,
1565        sm: &SourceMap<'_>,
1566        primary_path: Option<&Cow<'_, str>>,
1567        matches_previous_suggestion: bool,
1568        is_first: bool,
1569        is_cont: bool,
1570    ) {
1571        let suggestions = sm.splice_lines(suggestion.markers.clone());
1572
1573        let buffer_offset = buffer.num_lines();
1574        let mut row_num = buffer_offset + usize::from(!matches_previous_suggestion);
1575        for (complete, parts, highlights) in &suggestions {
1576            let has_deletion = parts
1577                .iter()
1578                .any(|p| p.is_deletion(sm) || p.is_destructive_replacement(sm));
1579            let is_multiline = complete.lines().count() > 1;
1580
1581            if matches_previous_suggestion {
1582                buffer.puts(
1583                    row_num - 1,
1584                    max_line_num_len + 1,
1585                    self.multi_suggestion_separator(),
1586                    ElementStyle::LineNumber,
1587                );
1588            } else {
1589                self.draw_col_separator_start(buffer, row_num - 1, max_line_num_len + 1);
1590            }
1591            if suggestion.path.as_ref() != primary_path {
1592                if let Some(path) = suggestion.path.as_ref() {
1593                    if !matches_previous_suggestion {
1594                        let (loc, _) = sm.span_to_locations(parts[0].span.clone());
1595                        // --> file.rs:line:col
1596                        //  |
1597                        let arrow = self.file_start(is_first);
1598                        buffer.puts(row_num - 1, 0, arrow, ElementStyle::LineNumber);
1599                        let message = format!("{}:{}:{}", path, loc.line, loc.char + 1);
1600                        let col = usize::max(max_line_num_len + 1, arrow.len());
1601                        buffer.puts(row_num - 1, col, &message, ElementStyle::LineAndColumn);
1602                        for _ in 0..max_line_num_len {
1603                            buffer.prepend(row_num - 1, " ", ElementStyle::NoStyle);
1604                        }
1605                        self.draw_col_separator_no_space(buffer, row_num, max_line_num_len + 1);
1606                        row_num += 1;
1607                    }
1608                }
1609            }
1610            let show_code_change = if has_deletion && !is_multiline {
1611                DisplaySuggestion::Diff
1612            } else if parts.len() == 1
1613                && parts.first().map_or(false, |p| {
1614                    p.replacement.ends_with('\n') && p.replacement.trim() == complete.trim()
1615                })
1616            {
1617                // We are adding a line(s) of code before code that was already there.
1618                DisplaySuggestion::Add
1619            } else if (parts.len() != 1 || parts[0].replacement.trim() != complete.trim())
1620                && !is_multiline
1621            {
1622                DisplaySuggestion::Underline
1623            } else {
1624                DisplaySuggestion::None
1625            };
1626
1627            if let DisplaySuggestion::Diff = show_code_change {
1628                row_num += 1;
1629            }
1630
1631            let file_lines = sm.span_to_lines(parts[0].span.clone());
1632            let (line_start, line_end) = sm.span_to_locations(parts[0].span.clone());
1633            let mut lines = complete.lines();
1634            if lines.clone().next().is_none() {
1635                // Account for a suggestion to completely remove a line(s) with whitespace (#94192).
1636                for line in line_start.line..=line_end.line {
1637                    buffer.puts(
1638                        row_num - 1 + line - line_start.line,
1639                        0,
1640                        &self.maybe_anonymized(line, max_line_num_len),
1641                        ElementStyle::LineNumber,
1642                    );
1643                    buffer.puts(
1644                        row_num - 1 + line - line_start.line,
1645                        max_line_num_len + 1,
1646                        "- ",
1647                        ElementStyle::Removal,
1648                    );
1649                    buffer.puts(
1650                        row_num - 1 + line - line_start.line,
1651                        max_line_num_len + 3,
1652                        &normalize_whitespace(sm.get_line(line).unwrap()),
1653                        ElementStyle::Removal,
1654                    );
1655                }
1656                row_num += line_end.line - line_start.line;
1657            }
1658            let mut last_pos = 0;
1659            let mut is_item_attribute = false;
1660            let mut unhighlighted_lines = Vec::new();
1661            for (line_pos, (line, highlight_parts)) in lines.by_ref().zip(highlights).enumerate() {
1662                last_pos = line_pos;
1663
1664                // Remember lines that are not highlighted to hide them if needed
1665                if highlight_parts.is_empty() {
1666                    unhighlighted_lines.push((line_pos, line));
1667                    continue;
1668                }
1669                if highlight_parts.len() == 1
1670                    && line.trim().starts_with("#[")
1671                    && line.trim().ends_with(']')
1672                {
1673                    is_item_attribute = true;
1674                }
1675
1676                match unhighlighted_lines.len() {
1677                    0 => (),
1678                    // Since we show first line, "..." line and last line,
1679                    // There is no reason to hide if there are 3 or less lines
1680                    // (because then we just replace a line with ... which is
1681                    // not helpful)
1682                    n if n <= 3 => unhighlighted_lines.drain(..).for_each(|(p, l)| {
1683                        self.draw_code_line(
1684                            buffer,
1685                            &mut row_num,
1686                            &[],
1687                            p + line_start.line,
1688                            l,
1689                            show_code_change,
1690                            max_line_num_len,
1691                            &file_lines,
1692                            is_multiline,
1693                        );
1694                    }),
1695                    // Print first unhighlighted line, "..." and last unhighlighted line, like so:
1696                    //
1697                    // LL | this line was highlighted
1698                    // LL | this line is just for context
1699                    // ...
1700                    // LL | this line is just for context
1701                    // LL | this line was highlighted
1702                    _ => {
1703                        let last_line = unhighlighted_lines.pop();
1704                        let first_line = unhighlighted_lines.drain(..).next();
1705
1706                        if let Some((p, l)) = first_line {
1707                            self.draw_code_line(
1708                                buffer,
1709                                &mut row_num,
1710                                &[],
1711                                p + line_start.line,
1712                                l,
1713                                show_code_change,
1714                                max_line_num_len,
1715                                &file_lines,
1716                                is_multiline,
1717                            );
1718                        }
1719
1720                        let placeholder = self.margin();
1721                        let padding = str_width(placeholder);
1722                        buffer.puts(
1723                            row_num,
1724                            max_line_num_len.saturating_sub(padding),
1725                            placeholder,
1726                            ElementStyle::LineNumber,
1727                        );
1728                        row_num += 1;
1729
1730                        if let Some((p, l)) = last_line {
1731                            self.draw_code_line(
1732                                buffer,
1733                                &mut row_num,
1734                                &[],
1735                                p + line_start.line,
1736                                l,
1737                                show_code_change,
1738                                max_line_num_len,
1739                                &file_lines,
1740                                is_multiline,
1741                            );
1742                        }
1743                    }
1744                }
1745                self.draw_code_line(
1746                    buffer,
1747                    &mut row_num,
1748                    highlight_parts,
1749                    line_pos + line_start.line,
1750                    line,
1751                    show_code_change,
1752                    max_line_num_len,
1753                    &file_lines,
1754                    is_multiline,
1755                );
1756            }
1757
1758            if matches!(show_code_change, DisplaySuggestion::Add) && is_item_attribute {
1759                // The suggestion adds an entire line of code, ending on a newline, so we'll also
1760                // print the *following* line, to provide context of what we're advising people to
1761                // do. Otherwise you would only see contextless code that can be confused for
1762                // already existing code, despite the colors and UI elements.
1763                // We special case `#[derive(_)]\n` and other attribute suggestions, because those
1764                // are the ones where context is most useful.
1765                let file_lines = sm.span_to_lines(parts[0].span.end..parts[0].span.end);
1766                let (lo, _) = sm.span_to_locations(parts[0].span.clone());
1767                let line_num = lo.line;
1768                if let Some(line) = sm.get_line(line_num) {
1769                    let line = normalize_whitespace(line);
1770                    self.draw_code_line(
1771                        buffer,
1772                        &mut row_num,
1773                        &[],
1774                        line_num + last_pos + 1,
1775                        &line,
1776                        DisplaySuggestion::None,
1777                        max_line_num_len,
1778                        &file_lines,
1779                        is_multiline,
1780                    );
1781                }
1782            }
1783            // This offset and the ones below need to be signed to account for replacement code
1784            // that is shorter than the original code.
1785            let mut offsets: Vec<(usize, isize)> = Vec::new();
1786            // Only show an underline in the suggestions if the suggestion is not the
1787            // entirety of the code being shown and the displayed code is not multiline.
1788            if let DisplaySuggestion::Diff | DisplaySuggestion::Underline | DisplaySuggestion::Add =
1789                show_code_change
1790            {
1791                for part in parts {
1792                    let snippet = sm.span_to_snippet(part.span.clone()).unwrap_or_default();
1793                    let (span_start, span_end) = sm.span_to_locations(part.span.clone());
1794                    let span_start_pos = span_start.display;
1795                    let span_end_pos = span_end.display;
1796
1797                    // If this addition is _only_ whitespace, then don't trim it,
1798                    // or else we're just not rendering anything.
1799                    let is_whitespace_addition = part.replacement.trim().is_empty();
1800
1801                    // Do not underline the leading...
1802                    let start = if is_whitespace_addition {
1803                        0
1804                    } else {
1805                        part.replacement
1806                            .len()
1807                            .saturating_sub(part.replacement.trim_start().len())
1808                    };
1809                    // ...or trailing spaces. Account for substitutions containing unicode
1810                    // characters.
1811                    let sub_len: usize = str_width(if is_whitespace_addition {
1812                        &part.replacement
1813                    } else {
1814                        part.replacement.trim()
1815                    });
1816
1817                    let offset: isize = offsets
1818                        .iter()
1819                        .filter_map(|(start, v)| {
1820                            if span_start_pos < *start {
1821                                None
1822                            } else {
1823                                Some(v)
1824                            }
1825                        })
1826                        .sum();
1827                    let underline_start = (span_start_pos + start) as isize + offset;
1828                    let underline_end = (span_start_pos + start + sub_len) as isize + offset;
1829                    assert!(underline_start >= 0 && underline_end >= 0);
1830                    let padding: usize = max_line_num_len + 3;
1831                    for p in underline_start..underline_end {
1832                        if matches!(show_code_change, DisplaySuggestion::Underline) {
1833                            // If this is a replacement, underline with `~`, if this is an addition
1834                            // underline with `+`.
1835                            buffer.putc(
1836                                row_num,
1837                                (padding as isize + p) as usize,
1838                                if part.is_addition(sm) {
1839                                    '+'
1840                                } else {
1841                                    self.diff()
1842                                },
1843                                ElementStyle::Addition,
1844                            );
1845                        }
1846                    }
1847                    if let DisplaySuggestion::Diff = show_code_change {
1848                        // Colorize removal with red in diff format.
1849
1850                        // Below, there's some tricky buffer indexing going on. `row_num` at this
1851                        // point corresponds to:
1852                        //
1853                        //    |
1854                        // LL | CODE
1855                        //    | ++++  <- `row_num`
1856                        //
1857                        // in the buffer. When we have a diff format output, we end up with
1858                        //
1859                        //    |
1860                        // LL - OLDER   <- row_num - 2
1861                        // LL + NEWER
1862                        //    |         <- row_num
1863                        //
1864                        // The `row_num - 2` is to select the buffer line that has the "old version
1865                        // of the diff" at that point. When the removal is a single line, `i` is
1866                        // `0`, `newlines` is `1` so `(newlines - i - 1)` ends up being `0`, so row
1867                        // points at `LL - OLDER`. When the removal corresponds to multiple lines,
1868                        // we end up with `newlines > 1` and `i` being `0..newlines - 1`.
1869                        //
1870                        //    |
1871                        // LL - OLDER   <- row_num - 2 - (newlines - last_i - 1)
1872                        // LL - CODE
1873                        // LL - BEING
1874                        // LL - REMOVED <- row_num - 2 - (newlines - first_i - 1)
1875                        // LL + NEWER
1876                        //    |         <- row_num
1877
1878                        let newlines = snippet.lines().count();
1879                        if newlines > 0 && row_num > newlines {
1880                            // Account for removals where the part being removed spans multiple
1881                            // lines.
1882                            // FIXME: We check the number of rows because in some cases, like in
1883                            // `tests/ui/lint/invalid-nan-comparison-suggestion.rs`, the rendered
1884                            // suggestion will only show the first line of code being replaced. The
1885                            // proper way of doing this would be to change the suggestion rendering
1886                            // logic to show the whole prior snippet, but the current output is not
1887                            // too bad to begin with, so we side-step that issue here.
1888                            for (i, line) in snippet.lines().enumerate() {
1889                                let line = normalize_whitespace(line);
1890                                let row = row_num - 2 - (newlines - i - 1);
1891                                // On the first line, we highlight between the start of the part
1892                                // span, and the end of that line.
1893                                // On the last line, we highlight between the start of the line, and
1894                                // the column of the part span end.
1895                                // On all others, we highlight the whole line.
1896                                let start = if i == 0 {
1897                                    (padding as isize + span_start_pos as isize) as usize
1898                                } else {
1899                                    padding
1900                                };
1901                                let end = if i == 0 {
1902                                    (padding as isize
1903                                        + span_start_pos as isize
1904                                        + line.len() as isize)
1905                                        as usize
1906                                } else if i == newlines - 1 {
1907                                    (padding as isize + span_end_pos as isize) as usize
1908                                } else {
1909                                    (padding as isize + line.len() as isize) as usize
1910                                };
1911                                buffer.set_style_range(
1912                                    row,
1913                                    start,
1914                                    end,
1915                                    ElementStyle::Removal,
1916                                    true,
1917                                );
1918                            }
1919                        } else {
1920                            // The removed code fits all in one line.
1921                            buffer.set_style_range(
1922                                row_num - 2,
1923                                (padding as isize + span_start_pos as isize) as usize,
1924                                (padding as isize + span_end_pos as isize) as usize,
1925                                ElementStyle::Removal,
1926                                true,
1927                            );
1928                        }
1929                    }
1930
1931                    // length of the code after substitution
1932                    let full_sub_len = str_width(&part.replacement) as isize;
1933
1934                    // length of the code to be substituted
1935                    let snippet_len = span_end_pos as isize - span_start_pos as isize;
1936                    // For multiple substitutions, use the position *after* the previous
1937                    // substitutions have happened, only when further substitutions are
1938                    // located strictly after.
1939                    offsets.push((span_end_pos, full_sub_len - snippet_len));
1940                }
1941                row_num += 1;
1942            }
1943
1944            // if we elided some lines, add an ellipsis
1945            if lines.next().is_some() {
1946                let placeholder = self.margin();
1947                let padding = str_width(placeholder);
1948                buffer.puts(
1949                    row_num,
1950                    max_line_num_len.saturating_sub(padding),
1951                    placeholder,
1952                    ElementStyle::LineNumber,
1953                );
1954            } else {
1955                let row = match show_code_change {
1956                    DisplaySuggestion::Diff
1957                    | DisplaySuggestion::Add
1958                    | DisplaySuggestion::Underline => row_num - 1,
1959                    DisplaySuggestion::None => row_num,
1960                };
1961                if is_cont {
1962                    self.draw_col_separator_no_space(buffer, row, max_line_num_len + 1);
1963                } else {
1964                    self.draw_col_separator_end(buffer, row, max_line_num_len + 1);
1965                }
1966                row_num = row + 1;
1967            }
1968        }
1969    }
1970
1971    #[allow(clippy::too_many_arguments)]
1972    fn draw_code_line(
1973        &self,
1974        buffer: &mut StyledBuffer,
1975        row_num: &mut usize,
1976        highlight_parts: &[SubstitutionHighlight],
1977        line_num: usize,
1978        line_to_add: &str,
1979        show_code_change: DisplaySuggestion,
1980        max_line_num_len: usize,
1981        file_lines: &[&LineInfo<'_>],
1982        is_multiline: bool,
1983    ) {
1984        if let DisplaySuggestion::Diff = show_code_change {
1985            // We need to print more than one line if the span we need to remove is multiline.
1986            // For more info: https://github.com/rust-lang/rust/issues/92741
1987            let lines_to_remove = file_lines.iter().take(file_lines.len() - 1);
1988            for (index, line_to_remove) in lines_to_remove.enumerate() {
1989                buffer.puts(
1990                    *row_num - 1,
1991                    0,
1992                    &self.maybe_anonymized(line_num + index, max_line_num_len),
1993                    ElementStyle::LineNumber,
1994                );
1995                buffer.puts(
1996                    *row_num - 1,
1997                    max_line_num_len + 1,
1998                    "- ",
1999                    ElementStyle::Removal,
2000                );
2001                let line = normalize_whitespace(line_to_remove.line);
2002                buffer.puts(
2003                    *row_num - 1,
2004                    max_line_num_len + 3,
2005                    &line,
2006                    ElementStyle::NoStyle,
2007                );
2008                *row_num += 1;
2009            }
2010            // If the last line is exactly equal to the line we need to add, we can skip both of
2011            // them. This allows us to avoid output like the following:
2012            // 2 - &
2013            // 2 + if true { true } else { false }
2014            // 3 - if true { true } else { false }
2015            // If those lines aren't equal, we print their diff
2016            let last_line = &file_lines.last().unwrap();
2017            if last_line.line == line_to_add {
2018                *row_num -= 2;
2019            } else {
2020                buffer.puts(
2021                    *row_num - 1,
2022                    0,
2023                    &self.maybe_anonymized(line_num + file_lines.len() - 1, max_line_num_len),
2024                    ElementStyle::LineNumber,
2025                );
2026                buffer.puts(
2027                    *row_num - 1,
2028                    max_line_num_len + 1,
2029                    "- ",
2030                    ElementStyle::Removal,
2031                );
2032                buffer.puts(
2033                    *row_num - 1,
2034                    max_line_num_len + 3,
2035                    &normalize_whitespace(last_line.line),
2036                    ElementStyle::NoStyle,
2037                );
2038                if line_to_add.trim().is_empty() {
2039                    *row_num -= 1;
2040                } else {
2041                    // Check if after the removal, the line is left with only whitespace. If so, we
2042                    // will not show an "addition" line, as removing the whole line is what the user
2043                    // would really want.
2044                    // For example, for the following:
2045                    //   |
2046                    // 2 -     .await
2047                    // 2 +     (note the left over whitespace)
2048                    //   |
2049                    // We really want
2050                    //   |
2051                    // 2 -     .await
2052                    //   |
2053                    // *row_num -= 1;
2054                    buffer.puts(
2055                        *row_num,
2056                        0,
2057                        &self.maybe_anonymized(line_num, max_line_num_len),
2058                        ElementStyle::LineNumber,
2059                    );
2060                    buffer.puts(*row_num, max_line_num_len + 1, "+ ", ElementStyle::Addition);
2061                    buffer.append(
2062                        *row_num,
2063                        &normalize_whitespace(line_to_add),
2064                        ElementStyle::NoStyle,
2065                    );
2066                }
2067            }
2068        } else if is_multiline {
2069            buffer.puts(
2070                *row_num,
2071                0,
2072                &self.maybe_anonymized(line_num, max_line_num_len),
2073                ElementStyle::LineNumber,
2074            );
2075            match &highlight_parts {
2076                [SubstitutionHighlight { start: 0, end }] if *end == line_to_add.len() => {
2077                    buffer.puts(*row_num, max_line_num_len + 1, "+ ", ElementStyle::Addition);
2078                }
2079                [] => {
2080                    // FIXME: needed? Doesn't get exercised in any test.
2081                    self.draw_col_separator_no_space(buffer, *row_num, max_line_num_len + 1);
2082                }
2083                _ => {
2084                    let diff = self.diff();
2085                    buffer.puts(
2086                        *row_num,
2087                        max_line_num_len + 1,
2088                        &format!("{diff} "),
2089                        ElementStyle::Addition,
2090                    );
2091                }
2092            }
2093            //   LL | line_to_add
2094            //   ++^^^
2095            //    |  |
2096            //    |  magic `3`
2097            //    `max_line_num_len`
2098            buffer.puts(
2099                *row_num,
2100                max_line_num_len + 3,
2101                &normalize_whitespace(line_to_add),
2102                ElementStyle::NoStyle,
2103            );
2104        } else if let DisplaySuggestion::Add = show_code_change {
2105            buffer.puts(
2106                *row_num,
2107                0,
2108                &self.maybe_anonymized(line_num, max_line_num_len),
2109                ElementStyle::LineNumber,
2110            );
2111            buffer.puts(*row_num, max_line_num_len + 1, "+ ", ElementStyle::Addition);
2112            buffer.append(
2113                *row_num,
2114                &normalize_whitespace(line_to_add),
2115                ElementStyle::NoStyle,
2116            );
2117        } else {
2118            buffer.puts(
2119                *row_num,
2120                0,
2121                &self.maybe_anonymized(line_num, max_line_num_len),
2122                ElementStyle::LineNumber,
2123            );
2124            self.draw_col_separator(buffer, *row_num, max_line_num_len + 1);
2125            buffer.append(
2126                *row_num,
2127                &normalize_whitespace(line_to_add),
2128                ElementStyle::NoStyle,
2129            );
2130        }
2131
2132        // Colorize addition/replacements with green.
2133        for &SubstitutionHighlight { start, end } in highlight_parts {
2134            // This is a no-op for empty ranges
2135            if start != end {
2136                // Account for tabs when highlighting (#87972).
2137                let tabs: usize = line_to_add
2138                    .chars()
2139                    .take(start)
2140                    .map(|ch| match ch {
2141                        '\t' => 3,
2142                        _ => 0,
2143                    })
2144                    .sum();
2145                buffer.set_style_range(
2146                    *row_num,
2147                    max_line_num_len + 3 + start + tabs,
2148                    max_line_num_len + 3 + end + tabs,
2149                    ElementStyle::Addition,
2150                    true,
2151                );
2152            }
2153        }
2154        *row_num += 1;
2155    }
2156
2157    #[allow(clippy::too_many_arguments)]
2158    fn draw_line(
2159        &self,
2160        buffer: &mut StyledBuffer,
2161        source_string: &str,
2162        line_index: usize,
2163        line_offset: usize,
2164        width_offset: usize,
2165        code_offset: usize,
2166        max_line_num_len: usize,
2167        margin: Margin,
2168    ) -> usize {
2169        // Tabs are assumed to have been replaced by spaces in calling code.
2170        debug_assert!(!source_string.contains('\t'));
2171        let line_len = str_width(source_string);
2172        // Create the source line we will highlight.
2173        let mut left = margin.left(line_len);
2174        let right = margin.right(line_len);
2175        // FIXME: The following code looks fishy. See #132860.
2176        // On long lines, we strip the source line, accounting for unicode.
2177        let mut taken = 0;
2178        let mut skipped = 0;
2179        let code: String = source_string
2180            .chars()
2181            .skip_while(|ch| {
2182                skipped += char_width(*ch);
2183                skipped <= left
2184            })
2185            .take_while(|ch| {
2186                // Make sure that the trimming on the right will fall within the terminal width.
2187                taken += char_width(*ch);
2188                taken <= (right - left)
2189            })
2190            .collect();
2191
2192        let placeholder = self.margin();
2193        let padding = str_width(placeholder);
2194        let (width_taken, bytes_taken) = if margin.was_cut_left() {
2195            // We have stripped some code/whitespace from the beginning, make it clear.
2196            let mut bytes_taken = 0;
2197            let mut width_taken = 0;
2198            for ch in code.chars() {
2199                width_taken += char_width(ch);
2200                bytes_taken += ch.len_utf8();
2201
2202                if width_taken >= padding {
2203                    break;
2204                }
2205            }
2206
2207            if width_taken > padding {
2208                left -= width_taken - padding;
2209            }
2210
2211            buffer.puts(
2212                line_offset,
2213                code_offset,
2214                placeholder,
2215                ElementStyle::LineNumber,
2216            );
2217            (width_taken, bytes_taken)
2218        } else {
2219            (0, 0)
2220        };
2221
2222        buffer.puts(
2223            line_offset,
2224            code_offset + width_taken,
2225            &code[bytes_taken..],
2226            ElementStyle::Quotation,
2227        );
2228
2229        if line_len > right {
2230            // We have stripped some code/whitespace from the beginning, make it clear.
2231            let mut char_taken = 0;
2232            let mut width_taken_inner = 0;
2233            for ch in code.chars().rev() {
2234                width_taken_inner += char_width(ch);
2235                char_taken += 1;
2236
2237                if width_taken_inner >= padding {
2238                    break;
2239                }
2240            }
2241
2242            buffer.puts(
2243                line_offset,
2244                code_offset + width_taken + code[bytes_taken..].chars().count() - char_taken,
2245                placeholder,
2246                ElementStyle::LineNumber,
2247            );
2248        }
2249
2250        buffer.puts(
2251            line_offset,
2252            0,
2253            &self.maybe_anonymized(line_index, max_line_num_len),
2254            ElementStyle::LineNumber,
2255        );
2256
2257        self.draw_col_separator_no_space(buffer, line_offset, width_offset - 2);
2258
2259        left
2260    }
2261
2262    fn draw_range(
2263        &self,
2264        buffer: &mut StyledBuffer,
2265        symbol: char,
2266        line: usize,
2267        col_from: usize,
2268        col_to: usize,
2269        style: ElementStyle,
2270    ) {
2271        for col in col_from..col_to {
2272            buffer.putc(line, col, symbol, style);
2273        }
2274    }
2275
2276    fn draw_multiline_line(
2277        &self,
2278        buffer: &mut StyledBuffer,
2279        line: usize,
2280        offset: usize,
2281        depth: usize,
2282        style: ElementStyle,
2283    ) {
2284        let chr = match (style, self.decor_style) {
2285            (ElementStyle::UnderlinePrimary | ElementStyle::LabelPrimary, DecorStyle::Ascii) => '|',
2286            (_, DecorStyle::Ascii) => '|',
2287            (ElementStyle::UnderlinePrimary | ElementStyle::LabelPrimary, DecorStyle::Unicode) => {
2288                '┃'
2289            }
2290            (_, DecorStyle::Unicode) => '│',
2291        };
2292        buffer.putc(line, offset + depth - 1, chr, style);
2293    }
2294
2295    fn col_separator(&self) -> char {
2296        match self.decor_style {
2297            DecorStyle::Ascii => '|',
2298            DecorStyle::Unicode => '│',
2299        }
2300    }
2301
2302    fn multi_suggestion_separator(&self) -> &'static str {
2303        match self.decor_style {
2304            DecorStyle::Ascii => "|",
2305            DecorStyle::Unicode => "├╴",
2306        }
2307    }
2308
2309    fn draw_col_separator(&self, buffer: &mut StyledBuffer, line: usize, col: usize) {
2310        let chr = self.col_separator();
2311        buffer.puts(line, col, &format!("{chr} "), ElementStyle::LineNumber);
2312    }
2313
2314    fn draw_col_separator_no_space(&self, buffer: &mut StyledBuffer, line: usize, col: usize) {
2315        let chr = self.col_separator();
2316        self.draw_col_separator_no_space_with_style(
2317            buffer,
2318            chr,
2319            line,
2320            col,
2321            ElementStyle::LineNumber,
2322        );
2323    }
2324
2325    fn draw_col_separator_start(&self, buffer: &mut StyledBuffer, line: usize, col: usize) {
2326        match self.decor_style {
2327            DecorStyle::Ascii => {
2328                self.draw_col_separator_no_space_with_style(
2329                    buffer,
2330                    '|',
2331                    line,
2332                    col,
2333                    ElementStyle::LineNumber,
2334                );
2335            }
2336            DecorStyle::Unicode => {
2337                self.draw_col_separator_no_space_with_style(
2338                    buffer,
2339                    '╭',
2340                    line,
2341                    col,
2342                    ElementStyle::LineNumber,
2343                );
2344                self.draw_col_separator_no_space_with_style(
2345                    buffer,
2346                    '╴',
2347                    line,
2348                    col + 1,
2349                    ElementStyle::LineNumber,
2350                );
2351            }
2352        }
2353    }
2354
2355    fn draw_col_separator_end(&self, buffer: &mut StyledBuffer, line: usize, col: usize) {
2356        match self.decor_style {
2357            DecorStyle::Ascii => {
2358                self.draw_col_separator_no_space_with_style(
2359                    buffer,
2360                    '|',
2361                    line,
2362                    col,
2363                    ElementStyle::LineNumber,
2364                );
2365            }
2366            DecorStyle::Unicode => {
2367                self.draw_col_separator_no_space_with_style(
2368                    buffer,
2369                    '╰',
2370                    line,
2371                    col,
2372                    ElementStyle::LineNumber,
2373                );
2374                self.draw_col_separator_no_space_with_style(
2375                    buffer,
2376                    '╴',
2377                    line,
2378                    col + 1,
2379                    ElementStyle::LineNumber,
2380                );
2381            }
2382        }
2383    }
2384
2385    fn draw_col_separator_no_space_with_style(
2386        &self,
2387        buffer: &mut StyledBuffer,
2388        chr: char,
2389        line: usize,
2390        col: usize,
2391        style: ElementStyle,
2392    ) {
2393        buffer.putc(line, col, chr, style);
2394    }
2395
2396    fn maybe_anonymized(&self, line_num: usize, max_line_num_len: usize) -> String {
2397        format!(
2398            "{:>max_line_num_len$}",
2399            if self.anonymized_line_numbers {
2400                Cow::Borrowed(ANONYMIZED_LINE_NUM)
2401            } else {
2402                Cow::Owned(line_num.to_string())
2403            }
2404        )
2405    }
2406
2407    fn file_start(&self, is_first: bool) -> &'static str {
2408        match self.decor_style {
2409            DecorStyle::Ascii => "--> ",
2410            DecorStyle::Unicode if is_first => " ╭▸ ",
2411            DecorStyle::Unicode => " ├▸ ",
2412        }
2413    }
2414
2415    fn secondary_file_start(&self) -> &'static str {
2416        match self.decor_style {
2417            DecorStyle::Ascii => "::: ",
2418            DecorStyle::Unicode => " ⸬  ",
2419        }
2420    }
2421
2422    fn draw_note_separator(
2423        &self,
2424        buffer: &mut StyledBuffer,
2425        line: usize,
2426        col: usize,
2427        is_cont: bool,
2428    ) {
2429        let chr = match self.decor_style {
2430            DecorStyle::Ascii => "= ",
2431            DecorStyle::Unicode if is_cont => "├ ",
2432            DecorStyle::Unicode => "╰ ",
2433        };
2434        buffer.puts(line, col, chr, ElementStyle::LineNumber);
2435    }
2436
2437    fn diff(&self) -> char {
2438        match self.decor_style {
2439            DecorStyle::Ascii => '~',
2440            DecorStyle::Unicode => '±',
2441        }
2442    }
2443
2444    fn draw_line_separator(&self, buffer: &mut StyledBuffer, line: usize, col: usize) {
2445        let (column, dots) = match self.decor_style {
2446            DecorStyle::Ascii => (0, "..."),
2447            DecorStyle::Unicode => (col - 2, "‡"),
2448        };
2449        buffer.puts(line, column, dots, ElementStyle::LineNumber);
2450    }
2451
2452    fn margin(&self) -> &'static str {
2453        match self.decor_style {
2454            DecorStyle::Ascii => "...",
2455            DecorStyle::Unicode => "…",
2456        }
2457    }
2458
2459    fn underline(&self, is_primary: bool) -> UnderlineParts {
2460        //               X0 Y0
2461        // label_start > ┯━━━━ < underline
2462        //               │ < vertical_text_line
2463        //               text
2464
2465        //    multiline_start_down ⤷ X0 Y0
2466        //            top_left > ┌───╿──┘ < top_right_flat
2467        //           top_left > ┏│━━━┙ < top_right
2468        // multiline_vertical > ┃│
2469        //                      ┃│   X1 Y1
2470        //                      ┃│   X2 Y2
2471        //                      ┃└────╿──┘ < multiline_end_same_line
2472        //        bottom_left > ┗━━━━━┥ < bottom_right_with_text
2473        //   multiline_horizontal ^   `X` is a good letter
2474
2475        // multiline_whole_line > ┏ X0 Y0
2476        //                        ┃   X1 Y1
2477        //                        ┗━━━━┛ < multiline_end_same_line
2478
2479        // multiline_whole_line > ┏ X0 Y0
2480        //                        ┃ X1 Y1
2481        //                        ┃  ╿ < multiline_end_up
2482        //                        ┗━━┛ < bottom_right
2483
2484        match (self.decor_style, is_primary) {
2485            (DecorStyle::Ascii, true) => UnderlineParts {
2486                style: ElementStyle::UnderlinePrimary,
2487                underline: '^',
2488                label_start: '^',
2489                vertical_text_line: '|',
2490                multiline_vertical: '|',
2491                multiline_horizontal: '_',
2492                multiline_whole_line: '/',
2493                multiline_start_down: '^',
2494                bottom_right: '|',
2495                top_left: ' ',
2496                top_right_flat: '^',
2497                bottom_left: '|',
2498                multiline_end_up: '^',
2499                multiline_end_same_line: '^',
2500                multiline_bottom_right_with_text: '|',
2501            },
2502            (DecorStyle::Ascii, false) => UnderlineParts {
2503                style: ElementStyle::UnderlineSecondary,
2504                underline: '-',
2505                label_start: '-',
2506                vertical_text_line: '|',
2507                multiline_vertical: '|',
2508                multiline_horizontal: '_',
2509                multiline_whole_line: '/',
2510                multiline_start_down: '-',
2511                bottom_right: '|',
2512                top_left: ' ',
2513                top_right_flat: '-',
2514                bottom_left: '|',
2515                multiline_end_up: '-',
2516                multiline_end_same_line: '-',
2517                multiline_bottom_right_with_text: '|',
2518            },
2519            (DecorStyle::Unicode, true) => UnderlineParts {
2520                style: ElementStyle::UnderlinePrimary,
2521                underline: '━',
2522                label_start: '┯',
2523                vertical_text_line: '│',
2524                multiline_vertical: '┃',
2525                multiline_horizontal: '━',
2526                multiline_whole_line: '┏',
2527                multiline_start_down: '╿',
2528                bottom_right: '┙',
2529                top_left: '┏',
2530                top_right_flat: '┛',
2531                bottom_left: '┗',
2532                multiline_end_up: '╿',
2533                multiline_end_same_line: '┛',
2534                multiline_bottom_right_with_text: '┥',
2535            },
2536            (DecorStyle::Unicode, false) => UnderlineParts {
2537                style: ElementStyle::UnderlineSecondary,
2538                underline: '─',
2539                label_start: '┬',
2540                vertical_text_line: '│',
2541                multiline_vertical: '│',
2542                multiline_horizontal: '─',
2543                multiline_whole_line: '┌',
2544                multiline_start_down: '│',
2545                bottom_right: '┘',
2546                top_left: '┌',
2547                top_right_flat: '┘',
2548                bottom_left: '└',
2549                multiline_end_up: '│',
2550                multiline_end_same_line: '┘',
2551                multiline_bottom_right_with_text: '┤',
2552            },
2553        }
2554    }
2555}
2556
2557/// Customize [`Renderer::styled`]
2558impl Renderer {
2559    /// Override the output style for `error`
2560    pub const fn error(mut self, style: Style) -> Self {
2561        self.stylesheet.error = style;
2562        self
2563    }
2564
2565    /// Override the output style for `warning`
2566    pub const fn warning(mut self, style: Style) -> Self {
2567        self.stylesheet.warning = style;
2568        self
2569    }
2570
2571    /// Override the output style for `info`
2572    pub const fn info(mut self, style: Style) -> Self {
2573        self.stylesheet.info = style;
2574        self
2575    }
2576
2577    /// Override the output style for `note`
2578    pub const fn note(mut self, style: Style) -> Self {
2579        self.stylesheet.note = style;
2580        self
2581    }
2582
2583    /// Override the output style for `help`
2584    pub const fn help(mut self, style: Style) -> Self {
2585        self.stylesheet.help = style;
2586        self
2587    }
2588
2589    /// Override the output style for line numbers
2590    pub const fn line_num(mut self, style: Style) -> Self {
2591        self.stylesheet.line_num = style;
2592        self
2593    }
2594
2595    /// Override the output style for emphasis
2596    pub const fn emphasis(mut self, style: Style) -> Self {
2597        self.stylesheet.emphasis = style;
2598        self
2599    }
2600
2601    /// Override the output style for none
2602    pub const fn none(mut self, style: Style) -> Self {
2603        self.stylesheet.none = style;
2604        self
2605    }
2606
2607    /// Override the output style for [`AnnotationKind::Context`]
2608    pub const fn context(mut self, style: Style) -> Self {
2609        self.stylesheet.context = style;
2610        self
2611    }
2612
2613    /// Override the output style for additions
2614    pub const fn addition(mut self, style: Style) -> Self {
2615        self.stylesheet.addition = style;
2616        self
2617    }
2618
2619    /// Override the output style for removals
2620    pub const fn removal(mut self, style: Style) -> Self {
2621        self.stylesheet.removal = style;
2622        self
2623    }
2624}
2625
2626trait MessageOrTitle {
2627    fn level(&self) -> &Level<'_>;
2628    fn id(&self) -> Option<&Id<'_>>;
2629    fn text(&self) -> &str;
2630    fn allows_styling(&self) -> bool;
2631}
2632
2633impl MessageOrTitle for Title<'_> {
2634    fn level(&self) -> &Level<'_> {
2635        &self.level
2636    }
2637    fn id(&self) -> Option<&Id<'_>> {
2638        self.id.as_ref()
2639    }
2640    fn text(&self) -> &str {
2641        self.text.as_ref()
2642    }
2643    fn allows_styling(&self) -> bool {
2644        self.allows_styling
2645    }
2646}
2647
2648impl MessageOrTitle for Message<'_> {
2649    fn level(&self) -> &Level<'_> {
2650        &self.level
2651    }
2652    fn id(&self) -> Option<&Id<'_>> {
2653        None
2654    }
2655    fn text(&self) -> &str {
2656        self.text.as_ref()
2657    }
2658    fn allows_styling(&self) -> bool {
2659        true
2660    }
2661}
2662
2663// instead of taking the String length or dividing by 10 while > 0, we multiply a limit by 10 until
2664// we're higher. If the loop isn't exited by the `return`, the last multiplication will wrap, which
2665// is OK, because while we cannot fit a higher power of 10 in a usize, the loop will end anyway.
2666// This is also why we need the max number of decimal digits within a `usize`.
2667fn num_decimal_digits(num: usize) -> usize {
2668    #[cfg(target_pointer_width = "64")]
2669    const MAX_DIGITS: usize = 20;
2670
2671    #[cfg(target_pointer_width = "32")]
2672    const MAX_DIGITS: usize = 10;
2673
2674    #[cfg(target_pointer_width = "16")]
2675    const MAX_DIGITS: usize = 5;
2676
2677    let mut lim = 10;
2678    for num_digits in 1..MAX_DIGITS {
2679        if num < lim {
2680            return num_digits;
2681        }
2682        lim = lim.wrapping_mul(10);
2683    }
2684    MAX_DIGITS
2685}
2686
2687fn str_width(s: &str) -> usize {
2688    s.chars().map(char_width).sum()
2689}
2690
2691fn char_width(ch: char) -> usize {
2692    // FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` is. For now,
2693    // just accept that sometimes the code line will be longer than desired.
2694    match ch {
2695        '\t' => 4,
2696        // Keep the following list in sync with `rustc_errors::emitter::OUTPUT_REPLACEMENTS`. These
2697        // are control points that we replace before printing with a visible codepoint for the sake
2698        // of being able to point at them with underlines.
2699        '\u{0000}' | '\u{0001}' | '\u{0002}' | '\u{0003}' | '\u{0004}' | '\u{0005}'
2700        | '\u{0006}' | '\u{0007}' | '\u{0008}' | '\u{000B}' | '\u{000C}' | '\u{000D}'
2701        | '\u{000E}' | '\u{000F}' | '\u{0010}' | '\u{0011}' | '\u{0012}' | '\u{0013}'
2702        | '\u{0014}' | '\u{0015}' | '\u{0016}' | '\u{0017}' | '\u{0018}' | '\u{0019}'
2703        | '\u{001A}' | '\u{001B}' | '\u{001C}' | '\u{001D}' | '\u{001E}' | '\u{001F}'
2704        | '\u{007F}' | '\u{202A}' | '\u{202B}' | '\u{202D}' | '\u{202E}' | '\u{2066}'
2705        | '\u{2067}' | '\u{2068}' | '\u{202C}' | '\u{2069}' => 1,
2706        _ => unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1),
2707    }
2708}
2709
2710fn num_overlap(
2711    a_start: usize,
2712    a_end: usize,
2713    b_start: usize,
2714    b_end: usize,
2715    inclusive: bool,
2716) -> bool {
2717    let extra = usize::from(inclusive);
2718    (b_start..b_end + extra).contains(&a_start) || (a_start..a_end + extra).contains(&b_start)
2719}
2720
2721fn overlaps(a1: &LineAnnotation<'_>, a2: &LineAnnotation<'_>, padding: usize) -> bool {
2722    num_overlap(
2723        a1.start.display,
2724        a1.end.display + padding,
2725        a2.start.display,
2726        a2.end.display,
2727        false,
2728    )
2729}
2730
2731#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
2732pub(crate) enum LineAnnotationType {
2733    /// Annotation under a single line of code
2734    Singleline,
2735
2736    // The Multiline type above is replaced with the following three in order
2737    // to reuse the current label drawing code.
2738    //
2739    // Each of these corresponds to one part of the following diagram:
2740    //
2741    //     x |   foo(1 + bar(x,
2742    //       |  _________^              < MultilineStart
2743    //     x | |             y),        < MultilineLine
2744    //       | |______________^ label   < MultilineEnd
2745    //     x |       z);
2746    /// Annotation marking the first character of a fully shown multiline span
2747    MultilineStart(usize),
2748    /// Annotation marking the last character of a fully shown multiline span
2749    MultilineEnd(usize),
2750    /// Line at the left enclosing the lines of a fully shown multiline span
2751    // Just a placeholder for the drawing algorithm, to know that it shouldn't skip the first 4
2752    // and last 2 lines of code. The actual line is drawn in `emit_message_default` and not in
2753    // `draw_multiline_line`.
2754    MultilineLine(usize),
2755}
2756
2757#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
2758pub(crate) struct LineAnnotation<'a> {
2759    /// Start column.
2760    /// Note that it is important that this field goes
2761    /// first, so that when we sort, we sort orderings by start
2762    /// column.
2763    pub start: Loc,
2764
2765    /// End column within the line (exclusive)
2766    pub end: Loc,
2767
2768    /// level
2769    pub kind: AnnotationKind,
2770
2771    /// Optional label to display adjacent to the annotation.
2772    pub label: Option<Cow<'a, str>>,
2773
2774    /// Is this a single line, multiline or multiline span minimized down to a
2775    /// smaller span.
2776    pub annotation_type: LineAnnotationType,
2777
2778    /// Whether the source code should be highlighted
2779    pub highlight_source: bool,
2780}
2781
2782impl LineAnnotation<'_> {
2783    pub(crate) fn is_primary(&self) -> bool {
2784        self.kind == AnnotationKind::Primary
2785    }
2786
2787    /// Whether this annotation is a vertical line placeholder.
2788    pub(crate) fn is_line(&self) -> bool {
2789        matches!(self.annotation_type, LineAnnotationType::MultilineLine(_))
2790    }
2791
2792    /// Length of this annotation as displayed in the stderr output
2793    pub(crate) fn len(&self) -> usize {
2794        // Account for usize underflows
2795        self.end.display.abs_diff(self.start.display)
2796    }
2797
2798    pub(crate) fn has_label(&self) -> bool {
2799        if let Some(label) = &self.label {
2800            // Consider labels with no text as effectively not being there
2801            // to avoid weird output with unnecessary vertical lines, like:
2802            //
2803            //     X | fn foo(x: u32) {
2804            //       | -------^------
2805            //       | |      |
2806            //       | |
2807            //       |
2808            //
2809            // Note that this would be the complete output users would see.
2810            !label.is_empty()
2811        } else {
2812            false
2813        }
2814    }
2815
2816    pub(crate) fn takes_space(&self) -> bool {
2817        // Multiline annotations always have to keep vertical space.
2818        matches!(
2819            self.annotation_type,
2820            LineAnnotationType::MultilineStart(_) | LineAnnotationType::MultilineEnd(_)
2821        )
2822    }
2823}
2824
2825#[derive(Clone, Copy, Debug)]
2826pub(crate) enum DisplaySuggestion {
2827    Underline,
2828    Diff,
2829    None,
2830    Add,
2831}
2832
2833// We replace some characters so the CLI output is always consistent and underlines aligned.
2834// Keep the following list in sync with `rustc_span::char_width`.
2835const OUTPUT_REPLACEMENTS: &[(char, &str)] = &[
2836    // In terminals without Unicode support the following will be garbled, but in *all* terminals
2837    // the underlying codepoint will be as well. We could gate this replacement behind a "unicode
2838    // support" gate.
2839    ('\0', "␀"),
2840    ('\u{0001}', "␁"),
2841    ('\u{0002}', "␂"),
2842    ('\u{0003}', "␃"),
2843    ('\u{0004}', "␄"),
2844    ('\u{0005}', "␅"),
2845    ('\u{0006}', "␆"),
2846    ('\u{0007}', "␇"),
2847    ('\u{0008}', "␈"),
2848    ('\t', "    "), // We do our own tab replacement
2849    ('\u{000b}', "␋"),
2850    ('\u{000c}', "␌"),
2851    ('\u{000d}', "␍"),
2852    ('\u{000e}', "␎"),
2853    ('\u{000f}', "␏"),
2854    ('\u{0010}', "␐"),
2855    ('\u{0011}', "␑"),
2856    ('\u{0012}', "␒"),
2857    ('\u{0013}', "␓"),
2858    ('\u{0014}', "␔"),
2859    ('\u{0015}', "␕"),
2860    ('\u{0016}', "␖"),
2861    ('\u{0017}', "␗"),
2862    ('\u{0018}', "␘"),
2863    ('\u{0019}', "␙"),
2864    ('\u{001a}', "␚"),
2865    ('\u{001b}', "␛"),
2866    ('\u{001c}', "␜"),
2867    ('\u{001d}', "␝"),
2868    ('\u{001e}', "␞"),
2869    ('\u{001f}', "␟"),
2870    ('\u{007f}', "␡"),
2871    ('\u{200d}', ""), // Replace ZWJ for consistent terminal output of grapheme clusters.
2872    ('\u{202a}', "�"), // The following unicode text flow control characters are inconsistently
2873    ('\u{202b}', "�"), // supported across CLIs and can cause confusion due to the bytes on disk
2874    ('\u{202c}', "�"), // not corresponding to the visible source code, so we replace them always.
2875    ('\u{202d}', "�"),
2876    ('\u{202e}', "�"),
2877    ('\u{2066}', "�"),
2878    ('\u{2067}', "�"),
2879    ('\u{2068}', "�"),
2880    ('\u{2069}', "�"),
2881];
2882
2883pub(crate) fn normalize_whitespace(s: &str) -> String {
2884    // Scan the input string for a character in the ordered table above.
2885    // If it's present, replace it with its alternative string (it can be more than 1 char!).
2886    // Otherwise, retain the input char.
2887    s.chars().fold(String::with_capacity(s.len()), |mut s, c| {
2888        match OUTPUT_REPLACEMENTS.binary_search_by_key(&c, |(k, _)| *k) {
2889            Ok(i) => s.push_str(OUTPUT_REPLACEMENTS[i].1),
2890            _ => s.push(c),
2891        }
2892        s
2893    })
2894}
2895
2896#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)]
2897pub(crate) enum ElementStyle {
2898    MainHeaderMsg,
2899    HeaderMsg,
2900    LineAndColumn,
2901    LineNumber,
2902    Quotation,
2903    UnderlinePrimary,
2904    UnderlineSecondary,
2905    LabelPrimary,
2906    LabelSecondary,
2907    NoStyle,
2908    Level(LevelInner),
2909    Addition,
2910    Removal,
2911}
2912
2913impl ElementStyle {
2914    fn color_spec(&self, level: &Level<'_>, stylesheet: &Stylesheet) -> Style {
2915        match self {
2916            ElementStyle::Addition => stylesheet.addition,
2917            ElementStyle::Removal => stylesheet.removal,
2918            ElementStyle::LineAndColumn => stylesheet.none,
2919            ElementStyle::LineNumber => stylesheet.line_num,
2920            ElementStyle::Quotation => stylesheet.none,
2921            ElementStyle::MainHeaderMsg => stylesheet.emphasis,
2922            ElementStyle::UnderlinePrimary | ElementStyle::LabelPrimary => level.style(stylesheet),
2923            ElementStyle::UnderlineSecondary | ElementStyle::LabelSecondary => stylesheet.context,
2924            ElementStyle::HeaderMsg | ElementStyle::NoStyle => stylesheet.none,
2925            ElementStyle::Level(lvl) => lvl.style(stylesheet),
2926        }
2927    }
2928}
2929
2930#[derive(Debug, Clone, Copy)]
2931struct UnderlineParts {
2932    style: ElementStyle,
2933    underline: char,
2934    label_start: char,
2935    vertical_text_line: char,
2936    multiline_vertical: char,
2937    multiline_horizontal: char,
2938    multiline_whole_line: char,
2939    multiline_start_down: char,
2940    bottom_right: char,
2941    top_left: char,
2942    top_right_flat: char,
2943    bottom_left: char,
2944    multiline_end_up: char,
2945    multiline_end_same_line: char,
2946    multiline_bottom_right_with_text: char,
2947}
2948
2949/// The character set for rendering for decor
2950#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2951pub enum DecorStyle {
2952    Ascii,
2953    Unicode,
2954}
2955
2956#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2957enum TitleStyle {
2958    MainHeader,
2959    Header,
2960    Secondary,
2961}
2962
2963fn max_line_number(groups: &[Group<'_>]) -> usize {
2964    groups
2965        .iter()
2966        .map(|v| {
2967            v.elements
2968                .iter()
2969                .map(|s| match s {
2970                    Element::Message(_) | Element::Origin(_) | Element::Padding(_) => 0,
2971                    Element::Cause(cause) => {
2972                        if cause.fold {
2973                            let end = cause
2974                                .markers
2975                                .iter()
2976                                .map(|a| a.span.end)
2977                                .max()
2978                                .unwrap_or(cause.source.len())
2979                                .min(cause.source.len());
2980
2981                            cause.line_start + newline_count(&cause.source[..end])
2982                        } else {
2983                            cause.line_start + newline_count(&cause.source)
2984                        }
2985                    }
2986                    Element::Suggestion(suggestion) => {
2987                        if suggestion.fold {
2988                            let end = suggestion
2989                                .markers
2990                                .iter()
2991                                .map(|a| a.span.end)
2992                                .max()
2993                                .unwrap_or(suggestion.source.len())
2994                                .min(suggestion.source.len());
2995
2996                            suggestion.line_start + newline_count(&suggestion.source[..end])
2997                        } else {
2998                            suggestion.line_start + newline_count(&suggestion.source)
2999                        }
3000                    }
3001                })
3002                .max()
3003                .unwrap_or(1)
3004        })
3005        .max()
3006        .unwrap_or(1)
3007}
3008
3009fn newline_count(body: &str) -> usize {
3010    #[cfg(feature = "simd")]
3011    {
3012        memchr::memchr_iter(b'\n', body.as_bytes())
3013            .count()
3014            .saturating_sub(1)
3015    }
3016    #[cfg(not(feature = "simd"))]
3017    {
3018        body.lines().count().saturating_sub(1)
3019    }
3020}
3021
3022#[cfg(test)]
3023mod test {
3024    use super::OUTPUT_REPLACEMENTS;
3025    use snapbox::IntoData;
3026
3027    fn format_replacements(replacements: Vec<(char, &str)>) -> String {
3028        replacements
3029            .into_iter()
3030            .map(|r| format!("    {r:?}"))
3031            .collect::<Vec<_>>()
3032            .join("\n")
3033    }
3034
3035    #[test]
3036    /// The [`OUTPUT_REPLACEMENTS`] array must be sorted (for binary search to
3037    /// work) and must contain no duplicate entries
3038    fn ensure_output_replacements_is_sorted() {
3039        let mut expected = OUTPUT_REPLACEMENTS.to_owned();
3040        expected.sort_by_key(|r| r.0);
3041        expected.dedup_by_key(|r| r.0);
3042        let expected = format_replacements(expected);
3043        let actual = format_replacements(OUTPUT_REPLACEMENTS.to_owned());
3044        snapbox::assert_data_eq!(actual, expected.into_data().raw());
3045    }
3046}