@@ -93,13 +93,18 @@ impl Mode {
9393/// a script or a pipe, where whatever reads stderr gets the plain message it
9494/// can grep for.
9595pub fn enabled ( ) -> bool {
96- // Read once: this runs before the argument capture of every caret .
97- static MODE : OnceLock < Mode > = OnceLock :: new ( ) ;
98- match MODE . get_or_init ( || Mode :: from_env ( env:: var_os ( MODE_VAR ) . as_deref ( ) ) ) {
96+ // Decided once: a utility may ask for every location it records .
97+ static ENABLED : OnceLock < bool > = OnceLock :: new ( ) ;
98+ * ENABLED . get_or_init ( || match Mode :: from_env ( env:: var_os ( MODE_VAR ) . as_deref ( ) ) {
9999 Mode :: Always => true ,
100100 Mode :: Never => false ,
101101 Mode :: Auto => std:: io:: stderr ( ) . is_terminal ( ) ,
102- }
102+ } )
103+ }
104+
105+ /// Whether a drawn report is colored: at a terminal, unless `NO_COLOR` is set.
106+ pub fn use_color ( ) -> bool {
107+ env:: var_os ( "NO_COLOR" ) . is_none ( ) && std:: io:: stderr ( ) . is_terminal ( )
103108}
104109
105110/// Keep the arguments a diagnostic would point at, as they were typed.
@@ -670,7 +675,8 @@ impl Snapshot {
670675 /// * `has_help` - Whether an advice line was asked for at all.
671676 fn localize_help ( body : & str , has_help : bool ) -> Cow < ' _ , str > {
672677 let localized = translate ! ( "diagnostics-help-label" ) ;
673- if !has_help || localized == "Help" {
678+ // Without a localizer, the lookup hands back the id.
679+ if !has_help || localized == "Help" || localized == "diagnostics-help-label" {
674680 return Cow :: Borrowed ( body) ;
675681 }
676682 let mut lines: Vec < Cow < ' _ , str > > = body. lines ( ) . map ( Cow :: Borrowed ) . collect ( ) ;
@@ -713,13 +719,13 @@ impl Snapshot {
713719 /// `None` when ariadne could not render, in which case the caller falls
714720 /// back to the plain one-line message.
715721 fn render_body (
716- & self ,
722+ id : & str ,
723+ text : & str ,
717724 span : Range < usize > ,
718725 label : Option < & str > ,
719726 help : Option < & str > ,
720727 color : bool ,
721728 ) -> Option < String > {
722- let id = crate :: util_name ( ) ;
723729 let config = Config :: default ( )
724730 // ariadne counts characters unless told otherwise, which would drift
725731 // on multi-byte arguments.
@@ -743,7 +749,7 @@ impl Snapshot {
743749 let mut rendered = Vec :: new ( ) ;
744750 if report
745751 . finish ( )
746- . write ( ( id, Source :: from ( self . text . as_str ( ) ) ) , & mut rendered)
752+ . write ( ( id, Source :: from ( text) ) , & mut rendered)
747753 . is_err ( )
748754 {
749755 return None ;
@@ -769,14 +775,26 @@ impl Snapshot {
769775 help : Option < & str > ,
770776 ) -> bool {
771777 let id = crate :: util_name ( ) ;
772- let color = env:: var_os ( "NO_COLOR" ) . is_none ( ) && std:: io:: stderr ( ) . is_terminal ( ) ;
773- let Some ( body) = self . render_body ( span, label, help, color) else {
778+ let Some ( body) = Self :: draw ( id, & self . text , span, label, help, use_color ( ) ) else {
774779 return false ;
775780 } ;
781+ eprint ! ( "{id}: {message}\n {body}" ) ;
782+ true
783+ }
784+
785+ /// The finished report for `span` in `text`, ending with a newline.
786+ fn draw (
787+ id : & str ,
788+ text : & str ,
789+ span : Range < usize > ,
790+ label : Option < & str > ,
791+ help : Option < & str > ,
792+ color : bool ,
793+ ) -> Option < String > {
794+ let body = Self :: render_body ( id, text, span, label, help, color) ?;
776795 let body = Self :: localize_help ( & body, help. is_some ( ) ) ;
777- let body = body. as_ref ( ) ;
778796 if label. is_some ( ) {
779- eprint ! ( "{id}: {message} \n { body}" ) ;
797+ Some ( body. into_owned ( ) )
780798 } else {
781799 // The empty message left an arrow arm pointing at nothing: drop it
782800 // and flatten the tee, so only the underline remains. Only the two
@@ -789,16 +807,113 @@ impl Snapshot {
789807 . filter ( |& ( row, line) | !( Self :: is_label_row ( row) && line. contains ( '╰' ) ) )
790808 . map ( |( row, line) | {
791809 if Self :: is_label_row ( row) {
792- Cow :: Owned ( line. replace ( '┬' , "─" ) )
810+ Cow :: Owned ( line. replace ( '┬' , "─" ) . trim_end ( ) . to_string ( ) )
793811 } else {
794812 Cow :: Borrowed ( line)
795813 }
796814 } )
797815 . collect :: < Vec < _ > > ( )
798816 . join ( "\n " ) ;
799- eprintln ! ( "{id}: {message} \n {body}" ) ;
817+ Some ( body + " \n " )
800818 }
801- true
819+ }
820+ }
821+
822+ /// One line of a script or a pattern file, for a report to point into, as
823+ /// [`Snapshot`] does into the arguments.
824+ pub struct SourceLine < ' a > {
825+ name : & ' a str ,
826+ line_number : usize ,
827+ text : & ' a str ,
828+ }
829+
830+ impl < ' a > SourceLine < ' a > {
831+ /// Line `line_number` (1-based) of the text called `name`.
832+ pub fn new ( name : & ' a str , line_number : usize , text : & ' a str ) -> Self {
833+ Self {
834+ name,
835+ line_number,
836+ text,
837+ }
838+ }
839+
840+ /// The report pointing at the byte range `span` of the line, headed by
841+ /// `name:line:column` with a byte column, without the message line.
842+ /// An empty span marks one character, or the place just past the end.
843+ pub fn report (
844+ & self ,
845+ span : Range < usize > ,
846+ label : Option < & str > ,
847+ help : Option < & str > ,
848+ ) -> Option < String > {
849+ self . report_colored ( span, label, help, use_color ( ) )
850+ }
851+
852+ fn report_colored (
853+ & self ,
854+ span : Range < usize > ,
855+ label : Option < & str > ,
856+ help : Option < & str > ,
857+ color : bool ,
858+ ) -> Option < String > {
859+ if self . line_number == 0 {
860+ return None ;
861+ }
862+ // The trailing space gives a caret past the end something to sit
863+ // under; ariadne panics on a span past the text otherwise.
864+ let text = format ! ( "{} " , self . text) ;
865+ let start = floor_boundary ( self . text , span. start . min ( self . text . len ( ) ) ) ;
866+ let end = floor_boundary ( self . text , span. end . clamp ( start, self . text . len ( ) ) ) ;
867+ let span = if start < end {
868+ start..end
869+ } else {
870+ char_span ( & text, start)
871+ } ;
872+ let body = Snapshot :: draw ( self . name , & text, span, label, help, color) ?;
873+ self . renumber ( & body, start)
874+ }
875+
876+ /// `body`, drawn as line 1, moved to the line's own number.
877+ ///
878+ /// ariadne applies a display offset to the header but not to the gutter,
879+ /// so the gutter is widened here instead. Only the margin is touched, and
880+ /// it holds no text of ours; the colors sit around its characters, so the
881+ /// marks below are found whether or not the report is colored.
882+ fn renumber ( & self , body : & str , start : usize ) -> Option < String > {
883+ /// Row holding the line itself, below the header and a blank gutter.
884+ const SOURCE : usize = 2 ;
885+ let number = self . line_number . to_string ( ) ;
886+ let widen = number. len ( ) - 1 ;
887+ let rows: Vec < & str > = body. lines ( ) . collect ( ) ;
888+ let last = rows. len ( ) . checked_sub ( 1 ) ?;
889+ let mut out = String :: with_capacity ( body. len ( ) + rows. len ( ) * widen) ;
890+ for ( row, line) in rows. iter ( ) . enumerate ( ) {
891+ if row == 0 {
892+ // ariadne counts the header's column in characters, not bytes.
893+ let drawn = format ! ( " {}:1:" , self . name) ;
894+ let from = line. find ( & drawn) ? + 1 ;
895+ let to = from + line[ from..] . find ( ' ' ) ?;
896+ let location = format ! ( "{}:{number}:{}" , self . name, start + 1 ) ;
897+ let _ = write ! (
898+ out,
899+ "{}{}{location}{}" ,
900+ " " . repeat( widen) ,
901+ & line[ ..from] ,
902+ & line[ to..]
903+ ) ;
904+ } else if row == SOURCE {
905+ out. push_str ( & line. replacen ( "1 │" , & format ! ( "{number} │" ) , 1 ) ) ;
906+ } else if row == last {
907+ out. push_str ( & line. replacen ( '╯' , & format ! ( "{}╯" , "─" . repeat( widen) ) , 1 ) ) ;
908+ } else {
909+ out. push_str ( & " " . repeat ( widen) ) ;
910+ out. push_str ( line) ;
911+ }
912+ if row != last {
913+ out. push ( '\n' ) ;
914+ }
915+ }
916+ Some ( out)
802917 }
803918}
804919
@@ -834,9 +949,15 @@ mod tests {
834949 #[ test]
835950 fn the_rendered_report_has_the_row_shape_the_rewriting_assumes ( ) {
836951 let snap = snapshot ( & [ "-k" , "1,0" ] ) ;
837- let body = snap
838- . render_body ( 3 ..6 , Some ( "a label" ) , Some ( "some advice" ) , false )
839- . unwrap ( ) ;
952+ let body = Snapshot :: render_body (
953+ "sort" ,
954+ & snap. text ,
955+ 3 ..6 ,
956+ Some ( "a label" ) ,
957+ Some ( "some advice" ) ,
958+ false ,
959+ )
960+ . unwrap ( ) ;
840961 let rows: Vec < & str > = body. lines ( ) . collect ( ) ;
841962
842963 // Row 2 echoes the arguments; rewriting it would edit what was typed.
@@ -859,6 +980,74 @@ mod tests {
859980 ) ;
860981 }
861982
983+ #[ test]
984+ fn a_source_line_keeps_its_number_and_counts_its_column_in_bytes ( ) {
985+ // `ü` is two bytes; the caret sits past the end of the line.
986+ let report = SourceLine :: new ( "f.sed" , 12 , "ü/b" )
987+ . report_colored ( 4 ..4 , None , None , false )
988+ . unwrap ( ) ;
989+ assert_eq ! (
990+ report,
991+ concat!(
992+ " ╭─[ f.sed:12:5 ]\n " ,
993+ " │\n " ,
994+ " 12 │ ü/b\n " ,
995+ " │ ─\n " ,
996+ "────╯" ,
997+ )
998+ ) ;
999+ }
1000+
1001+ #[ test]
1002+ fn a_colored_source_line_still_gets_its_location ( ) {
1003+ let report = SourceLine :: new ( "f.sed" , 12 , "x/y" )
1004+ . report_colored ( 1 ..2 , Some ( "here" ) , None , true )
1005+ . unwrap ( ) ;
1006+ assert ! ( report. contains( " f.sed:12:2 " ) , "{report:?}" ) ;
1007+ assert ! ( report. contains( "12 │" ) , "{report:?}" ) ;
1008+ assert ! ( !report. contains( ":1:" ) , "{report:?}" ) ;
1009+ }
1010+
1011+ #[ test]
1012+ fn an_empty_source_line_marks_its_first_column ( ) {
1013+ let report = SourceLine :: new ( "pats" , 3 , "" )
1014+ . report_colored ( 0 ..0 , None , None , false )
1015+ . unwrap ( ) ;
1016+ assert_eq ! (
1017+ report,
1018+ concat!(
1019+ " ╭─[ pats:3:1 ]\n " ,
1020+ " │\n " ,
1021+ " 3 │ \n " ,
1022+ " │ ─\n " ,
1023+ "───╯" ,
1024+ )
1025+ ) ;
1026+ }
1027+
1028+ #[ test]
1029+ fn a_far_source_line_is_drawn_alone ( ) {
1030+ let report = SourceLine :: new ( "big" , 4_000_321 , "q" )
1031+ . report_colored ( 0 ..1 , None , Some ( "hint" ) , false )
1032+ . unwrap ( ) ;
1033+ assert ! ( report. len( ) < 200 , "{report:?}" ) ;
1034+ let rows: Vec < & str > = report. lines ( ) . collect ( ) ;
1035+ assert_eq ! ( rows[ 0 ] , " ╭─[ big:4000321:1 ]" ) ;
1036+ assert_eq ! ( rows[ 2 ] , " 4000321 │ q" ) ;
1037+ assert_eq ! ( * rows. last( ) . unwrap( ) , "─────────╯" ) ;
1038+ // Every row keeps its gutter bar in the same column.
1039+ for row in & rows[ 1 ..rows. len ( ) - 1 ] {
1040+ assert_eq ! ( row. chars( ) . nth( 9 ) , Some ( '│' ) , "{row:?}" ) ;
1041+ }
1042+ }
1043+
1044+ #[ test]
1045+ fn advice_keeps_its_label_without_a_localizer ( ) {
1046+ // Unit tests set up no localizer.
1047+ let body = Snapshot :: render_body ( "t" , "abc" , 1 ..2 , Some ( "x" ) , Some ( "y" ) , false ) . unwrap ( ) ;
1048+ assert_eq ! ( Snapshot :: localize_help( & body, true ) , body) ;
1049+ }
1050+
8621051 #[ test]
8631052 fn spans_cover_each_argument ( ) {
8641053 let snap = snapshot ( & [ "a" , "=" , "" ] ) ;
0 commit comments