22
33use std:: collections:: HashMap ;
44use std:: io:: { self , Write } ;
5+ use std:: path:: PathBuf ;
56use std:: time:: { Duration , Instant } ;
67
78use rustc_ast:: ast;
@@ -11,6 +12,7 @@ use self::newline_style::apply_newline_style;
1112use crate :: comment:: { CharClasses , FullCodeCharKind } ;
1213use crate :: config:: { Config , FileName , Verbosity } ;
1314use crate :: formatting:: generated:: is_generated_file;
15+ use crate :: markdown:: rewrite_markdown;
1416use crate :: modules:: Module ;
1517use crate :: parse:: parser:: { DirectoryOwnership , Parser , ParserError } ;
1618use crate :: parse:: session:: ParseSess ;
@@ -35,6 +37,14 @@ impl<'b, T: Write + 'b> Session<'b, T> {
3537 return Err ( ErrorKind :: VersionMismatch ) ;
3638 }
3739
40+ match input {
41+ Input :: File ( ref path) if path. extension ( ) . map ( |ext| ext == "md" ) . unwrap_or ( false ) => {
42+ let config = self . config . clone ( ) ;
43+ return format_markdown_code_snippets ( path. clone ( ) , & config, self ) ;
44+ }
45+ _ => { }
46+ }
47+
3848 rustc_span:: create_session_if_not_set_then ( self . config . edition ( ) . into ( ) , |_| {
3949 if self . config . disable_all_formatting ( ) {
4050 // When the input is from stdin, echo back the input.
@@ -174,6 +184,28 @@ fn format_project<T: FormatHandler>(
174184 Ok ( context. report )
175185}
176186
187+ fn format_markdown_code_snippets < T : FormatHandler > (
188+ path : PathBuf ,
189+ config : & Config ,
190+ handler : & mut T ,
191+ ) -> Result < FormatReport , ErrorKind > {
192+ let input = std:: fs:: read_to_string ( & path) ?;
193+ let mut result = rewrite_markdown ( & input, config) . into_owned ( ) ;
194+
195+ if !result. ends_with ( '\n' ) {
196+ // Add a trailing newline if needed
197+ result. push ( '\n' ) ;
198+ }
199+
200+ apply_newline_style ( config. newline_style ( ) , & mut result, & input) ;
201+
202+ let file_name = FileName :: Real ( path) ;
203+ let mut report = FormatReport :: new ( ) ;
204+ handler. handle_formatted_file ( None , file_name, result, & mut report) ?;
205+
206+ Ok ( report)
207+ }
208+
177209// Used for formatting files.
178210struct FormatContext < ' a , T : FormatHandler > {
179211 krate : & ' a ast:: Crate ,
0 commit comments