Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 36 additions & 3 deletions crates/mdbook-html/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ pub(crate) fn id_from_content(content: &str) -> String {
// - https://pandoc.org/MANUAL.html#extension-auto_identifiers
// - https://kramdown.gettalong.org/converter/html#auto-ids
// - https://docs.rs/comrak/latest/comrak/options/struct.Extension.html#structfield.header_ids
content
let id: String = content
.trim()
.to_lowercase()
.chars()
Expand All @@ -96,7 +96,16 @@ pub(crate) fn id_from_content(content: &str) -> String {
None
}
})
.collect()
.collect();
// Headings consisting entirely of stripped characters (e.g. `## ::`) would
// otherwise produce an empty id and an empty `href="#"`, so fall back to
// "section" the way pandoc and kramdown do. `unique_id` will append a
// numeric suffix when the same fallback is used more than once.
if id.is_empty() {
String::from("section")
} else {
id
}
}

#[cfg(test)]
Expand Down Expand Up @@ -128,8 +137,32 @@ mod tests {
assert_eq!(id_from_content("中文"), "中文");
assert_eq!(id_from_content("にほんご"), "にほんご");
assert_eq!(id_from_content("한국어"), "한국어");
assert_eq!(id_from_content(""), "");
assert_eq!(id_from_content(""), "section");
assert_eq!(id_from_content("::"), "section");
assert_eq!(id_from_content("!.():"), "section");
assert_eq!(id_from_content(" "), "section");
assert_eq!(id_from_content("中文標題 CJK title"), "中文標題-cjk-title");
assert_eq!(id_from_content("Über"), "über");
}

#[test]
fn punctuation_only_headings_get_unique_section_ids() {
let mut id_counter = Default::default();
assert_eq!(
unique_id(&id_from_content("::"), &mut id_counter),
"section"
);
assert_eq!(
unique_id(&id_from_content("!!!"), &mut id_counter),
"section-1"
);
assert_eq!(
unique_id(&id_from_content("Real Heading"), &mut id_counter),
"real-heading"
);
assert_eq!(
unique_id(&id_from_content("***"), &mut id_counter),
"section-2"
);
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<h1 id="header-links"><a class="header" href="#header-links">Header Links</a></h1>
<h2 id="foobar"><a class="header" href="#foobar">Foo^bar</a></h2>
<h3 id=""><a class="header" href="#"></a></h3>
<h4 id="-1"><a class="header" href="#-1"></a></h4>
<h3 id="section"><a class="header" href="#section"></a></h3>
<h4 id="section-1"><a class="header" href="#section-1"></a></h4>
<h2 id="hï"><a class="header" href="#hï">Hï</a></h2>
<h2 id="repeat"><a class="header" href="#repeat">Repeat</a></h2>
<h2 id="repeat-1"><a class="header" href="#repeat-1">Repeat</a></h2>
Expand Down
Loading