forked from rust-lang/annotate-snippets-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
2736 lines (2575 loc) · 102 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Most of this file is adapted from https://github.com/rust-lang/rust/blob/160905b6253f42967ed4aef4b98002944c7df24c/compiler/rustc_errors/src/emitter.rs
//! The renderer for [`Message`]s
//!
//! # Example
//! ```
//! use annotate_snippets::*;
//! use annotate_snippets::Level;
//!
//! let source = r#"
//! use baz::zed::bar;
//!
//! mod baz {}
//! mod zed {
//! pub fn bar() { println!("bar3"); }
//! }
//! fn main() {
//! bar();
//! }
//! "#;
//! Level::ERROR
//! .header("unresolved import `baz::zed`")
//! .id("E0432")
//! .group(
//! Group::new().element(
//! Snippet::source(source)
//! .origin("temp.rs")
//! .line_start(1)
//! .fold(true)
//! .annotation(
//! AnnotationKind::Primary
//! .span(10..13)
//! .label("could not find `zed` in `baz`"),
//! )
//! )
//! );
//! ```
mod margin;
pub(crate) mod source_map;
mod styled_buffer;
pub(crate) mod stylesheet;
use crate::level::{Level, LevelInner};
use crate::renderer::source_map::{
AnnotatedLineInfo, LineInfo, Loc, SourceMap, SubstitutionHighlight,
};
use crate::renderer::styled_buffer::StyledBuffer;
use crate::{Annotation, AnnotationKind, Element, Group, Message, Origin, Patch, Snippet, Title};
pub use anstyle::*;
use margin::Margin;
use std::borrow::Cow;
use std::cmp::{max, min, Ordering, Reverse};
use std::collections::{HashMap, VecDeque};
use std::ops::Range;
use stylesheet::Stylesheet;
const ANONYMIZED_LINE_NUM: &str = "LL";
pub const DEFAULT_TERM_WIDTH: usize = 140;
/// A renderer for [`Message`]s
#[derive(Clone, Debug)]
pub struct Renderer {
anonymized_line_numbers: bool,
term_width: usize,
theme: OutputTheme,
stylesheet: Stylesheet,
}
impl Renderer {
/// No terminal styling
pub const fn plain() -> Self {
Self {
anonymized_line_numbers: false,
term_width: DEFAULT_TERM_WIDTH,
theme: OutputTheme::Ascii,
stylesheet: Stylesheet::plain(),
}
}
/// Default terminal styling
///
/// # Note
/// When testing styled terminal output, see the [`testing-colors` feature](crate#features)
pub const fn styled() -> Self {
const USE_WINDOWS_COLORS: bool = cfg!(windows) && !cfg!(feature = "testing-colors");
const BRIGHT_BLUE: Style = if USE_WINDOWS_COLORS {
AnsiColor::BrightCyan.on_default()
} else {
AnsiColor::BrightBlue.on_default()
};
Self {
stylesheet: Stylesheet {
error: AnsiColor::BrightRed.on_default().effects(Effects::BOLD),
warning: if USE_WINDOWS_COLORS {
AnsiColor::BrightYellow.on_default()
} else {
AnsiColor::Yellow.on_default()
}
.effects(Effects::BOLD),
info: BRIGHT_BLUE.effects(Effects::BOLD),
note: AnsiColor::BrightGreen.on_default().effects(Effects::BOLD),
help: AnsiColor::BrightCyan.on_default().effects(Effects::BOLD),
line_num: BRIGHT_BLUE.effects(Effects::BOLD),
emphasis: if USE_WINDOWS_COLORS {
AnsiColor::BrightWhite.on_default()
} else {
Style::new()
}
.effects(Effects::BOLD),
none: Style::new(),
context: BRIGHT_BLUE.effects(Effects::BOLD),
addition: AnsiColor::BrightGreen.on_default(),
removal: AnsiColor::BrightRed.on_default(),
},
..Self::plain()
}
}
/// Anonymize line numbers
///
/// This enables (or disables) line number anonymization. When enabled, line numbers are replaced
/// with `LL`.
///
/// # Example
///
/// ```text
/// --> $DIR/whitespace-trimming.rs:4:193
/// |
/// LL | ... let _: () = 42;
/// | ^^ expected (), found integer
/// |
/// ```
pub const fn anonymized_line_numbers(mut self, anonymized_line_numbers: bool) -> Self {
self.anonymized_line_numbers = anonymized_line_numbers;
self
}
// Set the terminal width
pub const fn term_width(mut self, term_width: usize) -> Self {
self.term_width = term_width;
self
}
pub const fn theme(mut self, output_theme: OutputTheme) -> Self {
self.theme = output_theme;
self
}
/// Set the output style for `error`
pub const fn error(mut self, style: Style) -> Self {
self.stylesheet.error = style;
self
}
/// Set the output style for `warning`
pub const fn warning(mut self, style: Style) -> Self {
self.stylesheet.warning = style;
self
}
/// Set the output style for `info`
pub const fn info(mut self, style: Style) -> Self {
self.stylesheet.info = style;
self
}
/// Set the output style for `note`
pub const fn note(mut self, style: Style) -> Self {
self.stylesheet.note = style;
self
}
/// Set the output style for `help`
pub const fn help(mut self, style: Style) -> Self {
self.stylesheet.help = style;
self
}
/// Set the output style for line numbers
pub const fn line_num(mut self, style: Style) -> Self {
self.stylesheet.line_num = style;
self
}
/// Set the output style for emphasis
pub const fn emphasis(mut self, style: Style) -> Self {
self.stylesheet.emphasis = style;
self
}
/// Set the output style for none
pub const fn none(mut self, style: Style) -> Self {
self.stylesheet.none = style;
self
}
}
impl Renderer {
pub fn render(&self, mut message: Message<'_>) -> String {
let mut buffer = StyledBuffer::new();
let max_line_num_len = if self.anonymized_line_numbers {
ANONYMIZED_LINE_NUM.len()
} else {
let n = message.max_line_number();
num_decimal_digits(n)
};
let title = message.groups.remove(0).elements.remove(0);
let level = if let Element::Title(title) = &title {
title.level.clone()
} else {
panic!("Expected a title as the first element of the message")
};
if let Some(first) = message.groups.first_mut() {
first.elements.insert(0, title);
} else {
message.groups.push(Group::new().element(title));
}
self.render_message(&mut buffer, message, max_line_num_len);
buffer.render(level, &self.stylesheet).unwrap()
}
fn render_message(
&self,
buffer: &mut StyledBuffer,
message: Message<'_>,
max_line_num_len: usize,
) {
let og_primary_origin = message
.groups
.iter()
.find_map(|group| {
group.elements.iter().find_map(|s| match &s {
Element::Cause(cause) => {
if cause.markers.iter().any(|m| m.kind.is_primary()) {
Some(cause.origin)
} else {
None
}
}
Element::Origin(origin) => {
if origin.primary {
Some(Some(origin.origin))
} else {
None
}
}
_ => None,
})
})
.unwrap_or(
message
.groups
.iter()
.find_map(|group| {
group.elements.iter().find_map(|s| match &s {
Element::Cause(cause) => Some(cause.origin),
Element::Origin(origin) => Some(Some(origin.origin)),
_ => None,
})
})
.unwrap_or_default(),
);
let group_len = message.groups.len();
for (g, group) in message.groups.into_iter().enumerate() {
let primary_origin = group
.elements
.iter()
.find_map(|s| match &s {
Element::Cause(cause) => {
if cause.markers.iter().any(|m| m.kind.is_primary()) {
Some(cause.origin)
} else {
None
}
}
Element::Origin(origin) => {
if origin.primary {
Some(Some(origin.origin))
} else {
None
}
}
_ => None,
})
.unwrap_or(
group
.elements
.iter()
.find_map(|s| match &s {
Element::Cause(cause) => Some(cause.origin),
Element::Origin(origin) => Some(Some(origin.origin)),
_ => None,
})
.unwrap_or_default(),
);
let mut source_map_annotated_lines = VecDeque::new();
let mut max_depth = 0;
for e in &group.elements {
if let Element::Cause(cause) = e {
let source_map = SourceMap::new(cause.source, cause.line_start);
let (depth, annotated_lines) =
source_map.annotated_lines(cause.markers.clone(), cause.fold);
max_depth = max(max_depth, depth);
source_map_annotated_lines.push_back((source_map, annotated_lines));
}
}
let mut message_iter = group.elements.iter().enumerate().peekable();
let mut last_was_suggestion = false;
while let Some((i, section)) = message_iter.next() {
let peek = message_iter.peek().map(|(_, s)| s).copied();
match §ion {
Element::Title(title) => {
self.render_title(
buffer,
title,
peek,
max_line_num_len,
if i == 0 { false } else { !title.primary },
message.id.as_ref().and_then(|id| {
if g == 0 && i == 0 {
Some(id)
} else {
None
}
}),
matches!(peek, Some(Element::Title(_))),
);
last_was_suggestion = false;
}
Element::Cause(cause) => {
if let Some((source_map, annotated_lines)) =
source_map_annotated_lines.pop_front()
{
self.render_snippet_annotations(
buffer,
max_line_num_len,
cause,
primary_origin,
&source_map,
&annotated_lines,
max_depth,
peek.is_some() || (g == 0 && group_len > 1),
);
if g == 0 && group_len > 1 {
if matches!(peek, Some(Element::Title(level)) if level.level.name != Some(None))
{
self.draw_col_separator_no_space(
buffer,
buffer.num_lines(),
max_line_num_len + 1,
);
// We want to draw the separator when it is
// requested, or when it is the last element
} else if peek.is_none() {
self.draw_col_separator_end(
buffer,
buffer.num_lines(),
max_line_num_len + 1,
);
}
}
}
last_was_suggestion = false;
}
Element::Suggestion(suggestion) => {
let source_map = SourceMap::new(suggestion.source, suggestion.line_start);
self.emit_suggestion_default(
buffer,
suggestion,
max_line_num_len,
&source_map,
primary_origin.or(og_primary_origin),
last_was_suggestion,
);
last_was_suggestion = true;
}
Element::Origin(origin) => {
self.render_origin(buffer, max_line_num_len, origin);
last_was_suggestion = false;
}
Element::Padding(_) => {
self.draw_col_separator_no_space(
buffer,
buffer.num_lines(),
max_line_num_len + 1,
);
}
}
if g == 0
&& (matches!(section, Element::Origin(_))
|| (matches!(section, Element::Title(_)) && i == 0)
|| matches!(section, Element::Title(level) if level.level.name == Some(None)))
{
if peek.is_none() && group_len > 1 {
self.draw_col_separator_end(
buffer,
buffer.num_lines(),
max_line_num_len + 1,
);
} else if matches!(peek, Some(Element::Title(level)) if level.level.name != Some(None))
{
self.draw_col_separator_no_space(
buffer,
buffer.num_lines(),
max_line_num_len + 1,
);
}
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn render_title(
&self,
buffer: &mut StyledBuffer,
title: &Title<'_>,
next_section: Option<&Element<'_>>,
max_line_num_len: usize,
is_secondary: bool,
id: Option<&&str>,
is_cont: bool,
) {
let line_offset = buffer.num_lines();
let (has_primary_spans, has_span_labels) =
next_section.map_or((false, false), |s| match s {
Element::Title(_) | Element::Padding(_) => (false, false),
Element::Cause(cause) => (
cause.markers.iter().any(|m| m.kind.is_primary()),
cause.markers.iter().any(|m| m.label.is_some()),
),
Element::Suggestion(_) => (true, false),
Element::Origin(_) => (false, true),
});
if !has_primary_spans && !has_span_labels && is_secondary {
// This is a secondary message with no span info
for _ in 0..max_line_num_len {
buffer.prepend(line_offset, " ", ElementStyle::NoStyle);
}
if title.level.name != Some(None) {
self.draw_note_separator(buffer, line_offset, max_line_num_len + 1, is_cont);
buffer.append(
line_offset,
title.level.as_str(),
ElementStyle::MainHeaderMsg,
);
buffer.append(line_offset, ": ", ElementStyle::NoStyle);
}
let printed_lines =
self.msgs_to_buffer(buffer, title.title, max_line_num_len, "note", None);
if is_cont && matches!(self.theme, OutputTheme::Unicode) {
// There's another note after this one, associated to the subwindow above.
// We write additional vertical lines to join them:
// ╭▸ test.rs:3:3
// │
// 3 │ code
// │ ━━━━
// │
// ├ note: foo
// │ bar
// ╰ note: foo
// bar
for i in line_offset + 1..=printed_lines {
self.draw_col_separator_no_space(buffer, i, max_line_num_len + 1);
}
}
} else {
let mut label_width = 0;
if title.level.name != Some(None) {
buffer.append(
line_offset,
title.level.as_str(),
ElementStyle::Level(title.level.level),
);
}
label_width += title.level.as_str().len();
if let Some(id) = id {
buffer.append(line_offset, "[", ElementStyle::Level(title.level.level));
buffer.append(line_offset, id, ElementStyle::Level(title.level.level));
buffer.append(line_offset, "]", ElementStyle::Level(title.level.level));
label_width += 2 + id.len();
}
let header_style = if is_secondary {
ElementStyle::HeaderMsg
} else {
ElementStyle::MainHeaderMsg
};
if title.level.name != Some(None) {
buffer.append(line_offset, ": ", header_style);
label_width += 2;
}
if !title.title.is_empty() {
for (line, text) in normalize_whitespace(title.title).lines().enumerate() {
buffer.append(
line_offset + line,
&format!(
"{}{}",
if line == 0 {
String::new()
} else {
" ".repeat(label_width)
},
text
),
header_style,
);
}
}
}
}
/// Adds a left margin to every line but the first, given a padding length and the label being
/// displayed, keeping the provided highlighting.
fn msgs_to_buffer(
&self,
buffer: &mut StyledBuffer,
title: &str,
padding: usize,
label: &str,
override_style: Option<ElementStyle>,
) -> usize {
// The extra 5 ` ` is padding that's always needed to align to the `note: `:
//
// error: message
// --> file.rs:13:20
// |
// 13 | <CODE>
// | ^^^^
// |
// = note: multiline
// message
// ++^^^----xx
// | | | |
// | | | magic `2`
// | | length of label
// | magic `3`
// `max_line_num_len`
let padding = " ".repeat(padding + label.len() + 5);
let mut line_number = buffer.num_lines().saturating_sub(1);
// Provided the following diagnostic message:
//
// let msgs = vec![
// ("
// ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
// ("looks", Style::Highlight),
// ("with\nvery ", Style::NoStyle),
// ("weird", Style::Highlight),
// (" formats\n", Style::NoStyle),
// ("see?", Style::Highlight),
// ];
//
// the expected output on a note is (* surround the highlighted text)
//
// = note: highlighted multiline
// string to
// see how it *looks* with
// very *weird* formats
// see?
let style = if let Some(override_style) = override_style {
override_style
} else {
ElementStyle::NoStyle
};
let lines = title.split('\n').collect::<Vec<_>>();
if lines.len() > 1 {
for (i, line) in lines.iter().enumerate() {
if i != 0 {
line_number += 1;
buffer.append(line_number, &padding, ElementStyle::NoStyle);
}
buffer.append(line_number, line, style);
}
} else {
buffer.append(line_number, title, style);
}
line_number
}
fn render_origin(
&self,
buffer: &mut StyledBuffer,
max_line_num_len: usize,
origin: &Origin<'_>,
) {
let buffer_msg_line_offset = buffer.num_lines();
if origin.primary {
buffer.prepend(
buffer_msg_line_offset,
self.file_start(),
ElementStyle::LineNumber,
);
} else {
// if !origin.standalone {
// // Add spacing line, as shown:
// // --> $DIR/file:54:15
// // |
// // LL | code
// // | ^^^^
// // | (<- It prints *this* line)
// // ::: $DIR/other_file.rs:15:5
// // |
// // LL | code
// // | ----
// self.draw_col_separator_no_space(
// buffer,
// buffer_msg_line_offset,
// max_line_num_len + 1,
// );
//
// buffer_msg_line_offset += 1;
// }
// Then, the secondary file indicator
buffer.prepend(
buffer_msg_line_offset,
self.secondary_file_start(),
ElementStyle::LineNumber,
);
}
let str = match (&origin.line, &origin.char_column) {
(Some(line), Some(col)) => {
format!("{}:{}:{}", origin.origin, line, col)
}
(Some(line), None) => format!("{}:{}", origin.origin, line),
_ => origin.origin.to_owned(),
};
buffer.append(buffer_msg_line_offset, &str, ElementStyle::LineAndColumn);
for _ in 0..max_line_num_len {
buffer.prepend(buffer_msg_line_offset, " ", ElementStyle::NoStyle);
}
if let Some(label) = &origin.label {
self.draw_col_separator_no_space(
buffer,
buffer_msg_line_offset + 1,
max_line_num_len + 1,
);
let title = Level::NOTE.title(label);
self.render_title(buffer, &title, None, max_line_num_len, true, None, false);
}
}
#[allow(clippy::too_many_arguments)]
fn render_snippet_annotations(
&self,
buffer: &mut StyledBuffer,
max_line_num_len: usize,
snippet: &Snippet<'_, Annotation<'_>>,
primary_origin: Option<&str>,
sm: &SourceMap<'_>,
annotated_lines: &[AnnotatedLineInfo<'_>],
multiline_depth: usize,
is_cont: bool,
) {
if let Some(origin) = snippet.origin {
let mut origin = Origin::new(origin);
// print out the span location and spacer before we print the annotated source
// to do this, we need to know if this span will be primary
let is_primary = primary_origin == Some(origin.origin);
if is_primary {
origin.primary = true;
if let Some(primary_line) = annotated_lines
.iter()
.find(|l| l.annotations.iter().any(LineAnnotation::is_primary))
.or(annotated_lines.iter().find(|l| !l.annotations.is_empty()))
{
origin.line = Some(primary_line.line_index);
if let Some(first_annotation) = primary_line
.annotations
.iter()
.find(|a| a.is_primary())
.or(primary_line.annotations.first())
{
origin.char_column = Some(first_annotation.start.char + 1);
}
}
} else {
let buffer_msg_line_offset = buffer.num_lines();
// Add spacing line, as shown:
// --> $DIR/file:54:15
// |
// LL | code
// | ^^^^
// | (<- It prints *this* line)
// ::: $DIR/other_file.rs:15:5
// |
// LL | code
// | ----
self.draw_col_separator_no_space(
buffer,
buffer_msg_line_offset,
max_line_num_len + 1,
);
if let Some(first_line) = annotated_lines.first() {
origin.line = Some(first_line.line_index);
if let Some(first_annotation) = first_line.annotations.first() {
origin.char_column = Some(first_annotation.start.char + 1);
}
}
}
self.render_origin(buffer, max_line_num_len, &origin);
}
// Put in the spacer between the location and annotated source
let buffer_msg_line_offset = buffer.num_lines();
self.draw_col_separator_no_space(buffer, buffer_msg_line_offset, max_line_num_len + 1);
// Contains the vertical lines' positions for active multiline annotations
let mut multilines = Vec::new();
// Get the left-side margin to remove it
let mut whitespace_margin = usize::MAX;
for line_info in annotated_lines {
// Whitespace can only be removed (aka considered leading)
// if the lexer considers it whitespace.
// non-rustc_lexer::is_whitespace() chars are reported as an
// error (ex. no-break-spaces \u{a0}), and thus can't be considered
// for removal during error reporting.
let leading_whitespace = line_info
.line
.chars()
.take_while(|c| c.is_whitespace())
.map(|c| {
match c {
// Tabs are displayed as 4 spaces
'\t' => 4,
_ => 1,
}
})
.sum();
if line_info.line.chars().any(|c| !c.is_whitespace()) {
whitespace_margin = min(whitespace_margin, leading_whitespace);
}
}
if whitespace_margin == usize::MAX {
whitespace_margin = 0;
}
// Left-most column any visible span points at.
let mut span_left_margin = usize::MAX;
for line_info in annotated_lines {
for ann in &line_info.annotations {
span_left_margin = min(span_left_margin, ann.start.display);
span_left_margin = min(span_left_margin, ann.end.display);
}
}
if span_left_margin == usize::MAX {
span_left_margin = 0;
}
// Right-most column any visible span points at.
let mut span_right_margin = 0;
let mut label_right_margin = 0;
let mut max_line_len = 0;
for line_info in annotated_lines {
max_line_len = max(max_line_len, line_info.line.len());
for ann in &line_info.annotations {
span_right_margin = max(span_right_margin, ann.start.display);
span_right_margin = max(span_right_margin, ann.end.display);
// FIXME: account for labels not in the same line
let label_right = ann.label.as_ref().map_or(0, |l| l.len() + 1);
label_right_margin = max(label_right_margin, ann.end.display + label_right);
}
}
let width_offset = 3 + max_line_num_len;
let code_offset = if multiline_depth == 0 {
width_offset
} else {
width_offset + multiline_depth + 1
};
let column_width = self.term_width.saturating_sub(code_offset);
let margin = Margin::new(
whitespace_margin,
span_left_margin,
span_right_margin,
label_right_margin,
column_width,
max_line_len,
);
// Next, output the annotate source for this file
for annotated_line_idx in 0..annotated_lines.len() {
let previous_buffer_line = buffer.num_lines();
let depths = self.render_source_line(
&annotated_lines[annotated_line_idx],
buffer,
width_offset,
code_offset,
max_line_num_len,
margin,
!is_cont && annotated_line_idx + 1 == annotated_lines.len(),
);
let mut to_add = HashMap::new();
for (depth, style) in depths {
if let Some(index) = multilines.iter().position(|(d, _)| d == &depth) {
multilines.swap_remove(index);
} else {
to_add.insert(depth, style);
}
}
// Set the multiline annotation vertical lines to the left of
// the code in this line.
for (depth, style) in &multilines {
for line in previous_buffer_line..buffer.num_lines() {
self.draw_multiline_line(buffer, line, width_offset, *depth, *style);
}
}
// check to see if we need to print out or elide lines that come between
// this annotated line and the next one.
if annotated_line_idx < (annotated_lines.len() - 1) {
let line_idx_delta = annotated_lines[annotated_line_idx + 1].line_index
- annotated_lines[annotated_line_idx].line_index;
match line_idx_delta.cmp(&2) {
Ordering::Greater => {
let last_buffer_line_num = buffer.num_lines();
self.draw_line_separator(buffer, last_buffer_line_num, width_offset);
// Set the multiline annotation vertical lines on `...` bridging line.
for (depth, style) in &multilines {
self.draw_multiline_line(
buffer,
last_buffer_line_num,
width_offset,
*depth,
*style,
);
}
if let Some(line) = annotated_lines.get(annotated_line_idx) {
for ann in &line.annotations {
if let LineAnnotationType::MultilineStart(pos) = ann.annotation_type
{
// In the case where we have elided the entire start of the
// multispan because those lines were empty, we still need
// to draw the `|`s across the `...`.
self.draw_multiline_line(
buffer,
last_buffer_line_num,
width_offset,
pos,
if ann.is_primary() {
ElementStyle::UnderlinePrimary
} else {
ElementStyle::UnderlineSecondary
},
);
}
}
}
}
Ordering::Equal => {
let unannotated_line = sm
.get_line(annotated_lines[annotated_line_idx].line_index + 1)
.unwrap_or("");
let last_buffer_line_num = buffer.num_lines();
self.draw_line(
buffer,
&normalize_whitespace(unannotated_line),
annotated_lines[annotated_line_idx + 1].line_index - 1,
last_buffer_line_num,
width_offset,
code_offset,
max_line_num_len,
margin,
);
for (depth, style) in &multilines {
self.draw_multiline_line(
buffer,
last_buffer_line_num,
width_offset,
*depth,
*style,
);
}
if let Some(line) = annotated_lines.get(annotated_line_idx) {
for ann in &line.annotations {
if let LineAnnotationType::MultilineStart(pos) = ann.annotation_type
{
self.draw_multiline_line(
buffer,
last_buffer_line_num,
width_offset,
pos,
if ann.is_primary() {
ElementStyle::UnderlinePrimary
} else {
ElementStyle::UnderlineSecondary
},
);
}
}
}
}
Ordering::Less => {}
}
}
multilines.extend(to_add);
}
}
#[allow(clippy::too_many_arguments)]
fn render_source_line(
&self,
line_info: &AnnotatedLineInfo<'_>,
buffer: &mut StyledBuffer,
width_offset: usize,
code_offset: usize,
max_line_num_len: usize,
margin: Margin,
close_window: bool,
) -> Vec<(usize, ElementStyle)> {
// Draw:
//
// LL | ... code ...
// | ^^-^ span label
// | |
// | secondary span label
//
// ^^ ^ ^^^ ^^^^ ^^^ we don't care about code too far to the right of a span, we trim it
// | | | |
// | | | actual code found in your source code and the spans we use to mark it
// | | when there's too much wasted space to the left, trim it
// | vertical divider between the column number and the code
// column number
if line_info.line_index == 0 {
return Vec::new();
}
let source_string = normalize_whitespace(line_info.line);
let line_offset = buffer.num_lines();
// Left trim
let left = margin.left(str_width(&source_string));
// FIXME: This looks fishy. See #132860.
// Account for unicode characters of width !=0 that were removed.
let mut taken = 0;
source_string.chars().for_each(|ch| {
let next = char_width(ch);
if taken + next <= left {
taken += next;
}
});
let left = taken;
self.draw_line(
buffer,
&source_string,
line_info.line_index,
line_offset,
width_offset,
code_offset,
max_line_num_len,
margin,
);
// Special case when there's only one annotation involved, it is the start of a multiline
// span and there's no text at the beginning of the code line. Instead of doing the whole
// graph:
//
// 2 | fn foo() {
// | _^
// 3 | |
// 4 | | }
// | |_^ test
//
// we simplify the output to:
//
// 2 | / fn foo() {
// 3 | |
// 4 | | }
// | |_^ test
let mut buffer_ops = vec![];
let mut annotations = vec![];