Skip to content

Commit ec42e2f

Browse files
committed
convert to one pass
thanks @BurntSushi ❤️
1 parent aba153a commit ec42e2f

File tree

1 file changed

+26
-29
lines changed

1 file changed

+26
-29
lines changed

src/renderer/html_handlebars/hbs_renderer.rs

+26-29
Original file line numberDiff line numberDiff line change
@@ -214,36 +214,33 @@ fn make_data(book: &MDBook) -> Result<serde_json::Map<String, serde_json::Value>
214214
Ok(data)
215215
}
216216

217-
fn build_header_links(mut html: String) -> String {
218-
for header in &["h1", "h2", "h3", "h4", "h5"] {
219-
let regex = Regex::new(&format!("<{h}>(.*?)</{h}>", h=header)).unwrap();
220-
221-
html = regex.replace_all(&html, |caps: &Captures| {
222-
let text = &caps[1];
223-
let mut id = text.to_string();
224-
let repl_sub = vec!["<em>", "</em>", "<code>", "</code>",
225-
"<strong>", "</strong>",
226-
"&lt;", "&gt;", "&amp;", "&#39;", "&quot;"];
227-
for sub in repl_sub {
228-
id = id.replace(sub, "");
229-
}
230-
let id = id.chars().filter_map(|c| {
231-
if c.is_alphanumeric() || c == '-' || c == '_' {
232-
if c.is_ascii() {
233-
Some(c.to_ascii_lowercase())
234-
} else {
235-
Some(c)
236-
}
237-
} else if c.is_whitespace() && c.is_ascii() {
238-
Some('-')
217+
fn build_header_links(html: String) -> String {
218+
let regex = Regex::new(r"<h(\d)>(.*?)</h\d>").unwrap();
219+
220+
regex.replace_all(&html, |caps: &Captures| {
221+
let level = &caps[1];
222+
let text = &caps[2];
223+
let mut id = text.to_string();
224+
let repl_sub = vec!["<em>", "</em>", "<code>", "</code>",
225+
"<strong>", "</strong>",
226+
"&lt;", "&gt;", "&amp;", "&#39;", "&quot;"];
227+
for sub in repl_sub {
228+
id = id.replace(sub, "");
229+
}
230+
let id = id.chars().filter_map(|c| {
231+
if c.is_alphanumeric() || c == '-' || c == '_' {
232+
if c.is_ascii() {
233+
Some(c.to_ascii_lowercase())
239234
} else {
240-
None
235+
Some(c)
241236
}
242-
}).collect::<String>();
243-
244-
format!("<a class=\"header\" href=\"#{id}\" name=\"{id}\"><{h}>{text}</{h}></a>", h=header, id=id, text=text)
245-
}).into_owned();
246-
}
237+
} else if c.is_whitespace() && c.is_ascii() {
238+
Some('-')
239+
} else {
240+
None
241+
}
242+
}).collect::<String>();
247243

248-
html
244+
format!("<a class=\"header\" href=\"#{id}\" name=\"{id}\"><h{level}>{text}</h{level}></a>", level=level, id=id, text=text)
245+
}).into_owned()
249246
}

0 commit comments

Comments
 (0)