Broke the header link wrapping out into smaller functions

This commit is contained in:
Michael Bryan 2017-06-20 11:06:30 +08:00
parent ac16d7aef1
commit fa95546988
1 changed files with 64 additions and 50 deletions

View File

@ -399,9 +399,41 @@ fn build_header_links(html: String, filename: &str) -> String {
regex
.replace_all(&html, |caps: &Captures| {
let level = &caps[1];
let text = &caps[2];
let mut id = text.to_string();
let level = caps[1].parse().expect(
"Regex should ensure we only ever get numbers here",
);
wrap_header_with_link(level, &caps[2], &mut id_counter, filename)
})
.into_owned()
}
fn wrap_header_with_link(level: usize, content: &str, id_counter: &mut HashMap<String, usize>, filename: &str)
-> String {
let id = id_from_content(content);
let id_count = *id_counter.get(&id).unwrap_or(&0);
id_counter.insert(id.clone(), id_count + 1);
let id = if id_count > 0 {
format!("{}-{}", id, id_count)
} else {
id
};
format!(
r#"<a class="header" href="{filename}#{id}" id="{id}"><h{level}>{text}</h{level}></a>"#,
level = level,
id = id,
text = content,
filename = filename
)
}
fn id_from_content(content: &str) -> String {
let mut content = content.to_string();
// Skip any tags or html-encoded stuff
let repl_sub = vec![
"<em>",
"</em>",
@ -416,9 +448,10 @@ fn build_header_links(html: String, filename: &str) -> String {
"&quot;",
];
for sub in repl_sub {
id = id.replace(sub, "");
content = content.replace(sub, "");
}
let id = id.chars()
content.chars()
.filter_map(|c| if c.is_alphanumeric() || c == '-' || c == '_' {
if c.is_ascii() {
Some(c.to_ascii_lowercase())
@ -430,26 +463,7 @@ fn build_header_links(html: String, filename: &str) -> String {
} else {
None
})
.collect::<String>();
let id_count = *id_counter.get(&id).unwrap_or(&0);
id_counter.insert(id.clone(), id_count + 1);
let id = if id_count > 0 {
format!("{}-{}", id, id_count)
} else {
id
};
format!(
"<a class=\"header\" href=\"{filename}#{id}\" id=\"{id}\"><h{level}>{text}</h{level}></a>",
level = level,
id = id,
text = text,
filename = filename
)
})
.into_owned()
.collect()
}
// anchors to the same page (href="#anchor") do not work because of