@@ -22,6 +22,7 @@ use rustc_ast as ast;
2222use rustc_codegen_ssa:: { traits:: CodegenBackend , CodegenErrors , CodegenResults } ;
2323use rustc_data_structures:: profiling:: { get_resident_set_size, print_time_passes_entry} ;
2424use rustc_data_structures:: sync:: SeqCst ;
25+ use rustc_errors:: markdown;
2526use rustc_errors:: registry:: { InvalidErrorCode , Registry } ;
2627use rustc_errors:: { ErrorGuaranteed , PResult } ;
2728use rustc_feature:: find_gated_cfg;
@@ -511,7 +512,7 @@ fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
511512 text. push ( '\n' ) ;
512513 }
513514 if io:: stdout ( ) . is_terminal ( ) {
514- show_content_with_pager ( & text) ;
515+ show_md_content_with_pager ( & text) ;
515516 } else {
516517 print ! ( "{}" , text) ;
517518 }
@@ -525,17 +526,38 @@ fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
525526 }
526527}
527528
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+
529533 let pager_name = env:: var_os ( "PAGER" ) . unwrap_or_else ( || {
530534 if cfg ! ( windows) { OsString :: from ( "more.com" ) } else { OsString :: from ( "less" ) }
531535 } ) ;
532536
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+ } ;
534545
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 ( ) {
536552 Ok ( mut pager) => {
537553 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 ( ) {
539561 fallback_to_println = true ;
540562 }
541563 }
@@ -551,8 +573,13 @@ fn show_content_with_pager(content: &str) {
551573
552574 // If pager fails for whatever reason, we should still print the content
553575 // 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}" ) ;
556583 }
557584}
558585
0 commit comments