convert to one pass

thanks @burntsushi ❤️
This commit is contained in:
Steve Klabnik 2017-02-16 19:29:50 -05:00
parent aba153a271
commit ec42e2f771
1 changed files with 25 additions and 28 deletions

View File

@ -214,36 +214,33 @@ fn make_data(book: &MDBook) -> Result<serde_json::Map<String, serde_json::Value>
Ok(data) Ok(data)
} }
fn build_header_links(mut html: String) -> String { fn build_header_links(html: String) -> String {
for header in &["h1", "h2", "h3", "h4", "h5"] { let regex = Regex::new(r"<h(\d)>(.*?)</h\d>").unwrap();
let regex = Regex::new(&format!("<{h}>(.*?)</{h}>", h=header)).unwrap();
html = regex.replace_all(&html, |caps: &Captures| { regex.replace_all(&html, |caps: &Captures| {
let text = &caps[1]; let level = &caps[1];
let mut id = text.to_string(); let text = &caps[2];
let repl_sub = vec!["<em>", "</em>", "<code>", "</code>", let mut id = text.to_string();
"<strong>", "</strong>", let repl_sub = vec!["<em>", "</em>", "<code>", "</code>",
"&lt;", "&gt;", "&amp;", "&#39;", "&quot;"]; "<strong>", "</strong>",
for sub in repl_sub { "&lt;", "&gt;", "&amp;", "&#39;", "&quot;"];
id = id.replace(sub, ""); for sub in repl_sub {
} id = id.replace(sub, "");
let id = id.chars().filter_map(|c| { }
if c.is_alphanumeric() || c == '-' || c == '_' { let id = id.chars().filter_map(|c| {
if c.is_ascii() { if c.is_alphanumeric() || c == '-' || c == '_' {
Some(c.to_ascii_lowercase()) if c.is_ascii() {
} else { Some(c.to_ascii_lowercase())
Some(c)
}
} else if c.is_whitespace() && c.is_ascii() {
Some('-')
} else { } else {
None Some(c)
} }
}).collect::<String>(); } else if c.is_whitespace() && c.is_ascii() {
Some('-')
} else {
None
}
}).collect::<String>();
format!("<a class=\"header\" href=\"#{id}\" name=\"{id}\"><{h}>{text}</{h}></a>", h=header, id=id, text=text) format!("<a class=\"header\" href=\"#{id}\" name=\"{id}\"><h{level}>{text}</h{level}></a>", level=level, id=id, text=text)
}).into_owned(); }).into_owned()
}
html
} }