Skip to content

Commit 33bed1d

Browse files
committed
Allow users to format rust code in markdown code blocks
Now users can envoke rustfmt directly with a markdown file and the rust code within that file will be reformatted e.g. `rustfmt README.md`
1 parent bc52196 commit 33bed1d

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/formatting.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
use std::collections::HashMap;
44
use std::io::{self, Write};
5+
use std::path::PathBuf;
56
use std::time::{Duration, Instant};
67

78
use rustc_ast::ast;
@@ -11,6 +12,7 @@ use self::newline_style::apply_newline_style;
1112
use crate::comment::{CharClasses, FullCodeCharKind};
1213
use crate::config::{Config, FileName, Verbosity};
1314
use crate::formatting::generated::is_generated_file;
15+
use crate::markdown::rewrite_markdown;
1416
use crate::modules::Module;
1517
use crate::parse::parser::{DirectoryOwnership, Parser, ParserError};
1618
use 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.
178210
struct FormatContext<'a, T: FormatHandler> {
179211
krate: &'a ast::Crate,

0 commit comments

Comments
 (0)