@@ -22,6 +22,7 @@ use rustc_ast as ast;
22
22
use rustc_codegen_ssa:: { traits:: CodegenBackend , CodegenErrors , CodegenResults } ;
23
23
use rustc_data_structures:: profiling:: { get_resident_set_size, print_time_passes_entry} ;
24
24
use rustc_data_structures:: sync:: SeqCst ;
25
+ use rustc_errors:: markdown;
25
26
use rustc_errors:: registry:: { InvalidErrorCode , Registry } ;
26
27
use rustc_errors:: { ErrorGuaranteed , PResult } ;
27
28
use rustc_feature:: find_gated_cfg;
@@ -511,7 +512,7 @@ fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
511
512
text. push ( '\n' ) ;
512
513
}
513
514
if io:: stdout ( ) . is_terminal ( ) {
514
- show_content_with_pager ( & text) ;
515
+ show_md_content_with_pager ( & text) ;
515
516
} else {
516
517
print ! ( "{}" , text) ;
517
518
}
@@ -525,17 +526,38 @@ fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
525
526
}
526
527
}
527
528
528
- fn show_content_with_pager ( content : & str ) {
529
+ fn show_md_content_with_pager ( content : & str ) {
530
+ let mut print_color = true ;
531
+ let mut fallback_to_println = false ;
532
+
529
533
let pager_name = env:: var_os ( "PAGER" ) . unwrap_or_else ( || {
530
534
if cfg ! ( windows) { OsString :: from ( "more.com" ) } else { OsString :: from ( "less" ) }
531
535
} ) ;
532
536
533
- let mut fallback_to_println = false ;
537
+ let mut cmd = Command :: new ( & pager_name) ;
538
+
539
+ // FIXME: find if other pagers accept color options
540
+ if pager_name == "less" {
541
+ cmd. arg ( "-r" ) ;
542
+ } else {
543
+ print_color = false ;
544
+ } ;
534
545
535
- match Command :: new ( pager_name) . stdin ( Stdio :: piped ( ) ) . spawn ( ) {
546
+ let md_ast = markdown:: create_ast ( content) ;
547
+ let bufwtr = markdown:: create_stdout_bufwtr ( ) ;
548
+ let mut buffer = bufwtr. buffer ( ) ;
549
+ md_ast. write_termcolor_buf ( & mut buffer) ;
550
+
551
+ match cmd. stdin ( Stdio :: piped ( ) ) . spawn ( ) {
536
552
Ok ( mut pager) => {
537
553
if let Some ( pipe) = pager. stdin . as_mut ( ) {
538
- if pipe. write_all ( content. as_bytes ( ) ) . is_err ( ) {
554
+ let res = if print_color {
555
+ pipe. write_all ( buffer. as_slice ( ) )
556
+ } else {
557
+ pipe. write_all ( content. as_bytes ( ) )
558
+ } ;
559
+
560
+ if res. is_err ( ) {
539
561
fallback_to_println = true ;
540
562
}
541
563
}
@@ -551,8 +573,13 @@ fn show_content_with_pager(content: &str) {
551
573
552
574
// If pager fails for whatever reason, we should still print the content
553
575
// to standard output
554
- if fallback_to_println {
555
- print ! ( "{}" , content) ;
576
+ if fallback_to_println && print_color {
577
+ // If we fail to print the buffer, we'll just fall back to println
578
+ print_color = bufwtr. print ( & buffer) . is_ok ( ) ;
579
+ }
580
+
581
+ if fallback_to_println && !print_color {
582
+ println ! ( "{content}" ) ;
556
583
}
557
584
}
558
585
0 commit comments