Hide lines in ignored code blocks

This commit is contained in:
Benedikt Werner 2019-11-07 02:20:10 +01:00
parent f5549f2267
commit 8fffb2a704
No known key found for this signature in database
GPG Key ID: 1DBFF0F8E9E121EB
1 changed files with 60 additions and 49 deletions

View File

@ -601,7 +601,6 @@ fn fix_code_blocks(html: &str) -> String {
}
fn add_playpen_pre(html: &str, playpen_config: &Playpen) -> String {
let boring_line_regex = Regex::new(r"^(\s*)#(.?)(.*)$").unwrap();
let regex = Regex::new(r##"((?s)<code[^>]?class="([^"]+)".*?>(.*?)</code>)"##).unwrap();
regex
.replace_all(html, |caps: &Captures<'_>| {
@ -609,9 +608,8 @@ fn add_playpen_pre(html: &str, playpen_config: &Playpen) -> String {
let classes = &caps[2];
let code = &caps[3];
if (classes.contains("language-rust")
&& !classes.contains("ignore")
&& !classes.contains("noplaypen"))
if classes.contains("language-rust") {
if (!classes.contains("ignore") && !classes.contains("noplaypen"))
|| classes.contains("mdbook-runnable")
{
// wrap the contents in an external pre block
@ -635,10 +633,29 @@ fn add_playpen_pre(html: &str, playpen_config: &Playpen) -> String {
)
.into()
};
hide_lines(&content)
}
)
} else {
format!("<code class=\"{}\">{}</code>", classes, hide_lines(code))
}
} else {
// not language-rust, so no-op
text.to_owned()
}
})
.into_owned()
}
lazy_static! {
static ref BORING_LINES_REGEX: Regex = Regex::new(r"^(\s*)#(.?)(.*)$").unwrap();
}
fn hide_lines(content: &str) -> String {
let mut prev_line_hidden = false;
let mut result = String::with_capacity(content.len());
for line in content.lines() {
if let Some(caps) = boring_line_regex.captures(line) {
if let Some(caps) = BORING_LINES_REGEX.captures(line) {
if !prev_line_hidden && &caps[2] != "#" {
result += "<span class=\"boring\">";
prev_line_hidden = true;
@ -658,14 +675,6 @@ fn add_playpen_pre(html: &str, playpen_config: &Playpen) -> String {
result += "\n";
}
result
}
)
} else {
// not language-rust, so no-op
text.to_owned()
}
})
.into_owned()
}
fn partition_source(s: &str) -> (String, String) {
@ -749,6 +758,8 @@ mod tests {
"<pre class=\"playpen\"><code class=\"language-rust editable\">let s = \"foo\n # bar\n\";\n</code></pre>"),
("<code class=\"language-rust editable\">let s = \"foo\n # bar\n#\n\";</code>",
"<pre class=\"playpen\"><code class=\"language-rust editable\">let s = \"foo\n<span class=\"boring\"> bar\n\n</span>\";\n</code></pre>"),
("<code class=\"language-rust ignore\">let s = \"foo\n # bar\n#\n\";</code>",
"<code class=\"language-rust ignore\">let s = \"foo\n<span class=\"boring\"> bar\n\n</span>\";\n</code>"),
];
for (src, should_be) in &inputs {
let got = add_playpen_pre(