Skip to content

Commit

Permalink
Merge pull request #214 from azerupi/fix-rust-hide
Browse files Browse the repository at this point in the history
Fix code blocks with comma separated classes
  • Loading branch information
azerupi authored Feb 28, 2017
2 parents 7f46071 + 01341a7 commit 5e3a3f3
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/renderer/html_handlebars/hbs_renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,13 @@ impl Renderer for HtmlHandlebars {
// Render the handlebars template with the data
debug!("[*]: Render template");
let rendered = try!(handlebars.render("index", &data));

// create links for headers
let rendered = build_header_links(rendered);

// fix code blocks
let rendered = fix_code_blocks(rendered);

// Write to file
let filename = Path::new(&ch.path).with_extension("html");
info!("[*] Creating {:?} ✓", filename.display());
Expand Down Expand Up @@ -143,6 +146,9 @@ impl Renderer for HtmlHandlebars {
let rendered = try!(handlebars.render("index", &data));
let rendered = build_header_links(rendered);

// fix code blocks
let rendered = fix_code_blocks(rendered);

try!(book.write_file(Path::new("print").with_extension("html"), &rendered.into_bytes()));
info!("[*] Creating print.html ✓");

Expand Down Expand Up @@ -248,3 +254,21 @@ fn build_header_links(html: String) -> String {
format!("<a class=\"header\" href=\"#{id}\" name=\"{id}\"><h{level}>{text}</h{level}></a>", level=level, id=id, text=text)
}).into_owned()
}

// The rust book uses annotations for rustdoc to test code snippets, like the following:
// ```rust,should_panic
// fn main() {
// // Code here
// }
// ```
// This function replaces all commas by spaces in the code block classes
fn fix_code_blocks(html: String) -> String {
let regex = Regex::new(r##"<code([^>]+)class="([^"]+)"([^>]*)>"##).unwrap();
regex.replace_all(&html, |caps: &Captures| {
let before = &caps[1];
let classes = &caps[2].replace(",", " ");
let after = &caps[3];

format!("<code{before}class=\"{classes}\"{after}>", before=before, classes=classes, after=after)
}).into_owned()
}

0 comments on commit 5e3a3f3

Please sign in to comment.