diff --git a/src/format.rs b/src/format.rs index 690e2e8..e6fcae5 100644 --- a/src/format.rs +++ b/src/format.rs @@ -68,6 +68,7 @@ pub fn shift_headings(raw: &str, levels: usize) -> String { let mut curr_fence: Option<(usize, char)> = None; for raw_line in raw.split_inclusive('\n') { // Code blocks can only start with backticks or tildes + // code fences can be indented by 0-3 spaces see commonmark spec. let fence_line = &trim_leading_whitespace(raw_line, 3); if fence_line.starts_with("```") | fence_line.starts_with("~~~") { let fence_info = get_fence(fence_line, true); @@ -90,8 +91,11 @@ pub fn shift_headings(raw: &str, levels: usize) -> String { } } - if curr_fence.is_none() && raw_line.starts_with('#') { - let heading = handle_heading(raw_line, levels); + // Remove up to 0-3 leading whitespaces. + // If the line has 4 or more whitespaces it is not a heading according to commonmark spec. + let heading_line = &trim_leading_whitespace(raw_line, 3); + if curr_fence.is_none() && heading_line.starts_with('#') { + let heading = handle_heading(heading_line, levels); result.push_str(&heading); } else { result.push_str(raw_line); @@ -100,7 +104,7 @@ pub fn shift_headings(raw: &str, levels: usize) -> String { result } -/// Removes leading whitespaces from code fences +/// Removes leading whitespaces from code fences if present /// However maximum of [max] whitespaces are removed. /// This is useful for code fences may have leading whitespaces (0-3). fn trim_leading_whitespace(input: &str, max: usize) -> String { @@ -145,7 +149,6 @@ pub fn get_fence(line: &str, allow_info: bool) -> Option<(usize, char)> { pub fn handle_heading(line: &str, levels: usize) -> String { let chars = line.chars(); - // let mut leading_trivials: String = String::new(); let mut hashes = String::new(); let mut rest = String::new(); for char in chars { diff --git a/src/snapshots/nixdoc__test__headings.snap b/src/snapshots/nixdoc__test__headings.snap index 877a741..0739b5e 100644 --- a/src/snapshots/nixdoc__test__headings.snap +++ b/src/snapshots/nixdoc__test__headings.snap @@ -6,8 +6,20 @@ expression: output #### h2-heading +3 leading whitespaces are okay for headings + +#### h2 heading + + # code block + + #### h2-heading-with-id {#some-id} +Indented code block + + # Code comment + a = 1; + ##### h3-heading ```nix @@ -23,6 +35,8 @@ map a from b -> 1 ##### indented (0-3) fences +3 leading whitespaces are okay for code fences + ``` lang info # Some pseudocode map a from b -> 1 diff --git a/test/headings.md b/test/headings.md index 7e606a7..9f8265a 100644 --- a/test/headings.md +++ b/test/headings.md @@ -2,8 +2,20 @@ ## h2-heading +3 leading whitespaces are okay for headings + + ## h2 heading + + # code block + + ## h2-heading-with-id {#some-id} +Indented code block + + # Code comment + a = 1; + ### h3-heading ```nix @@ -19,6 +31,8 @@ map a from b -> 1 ### indented (0-3) fences +3 leading whitespaces are okay for code fences + ``` lang info # Some pseudocode map a from b -> 1