feat: widen markdown compatibility for AI output

This commit is contained in:
2026-10-27 11:54:03 +08:00
parent 2a4df2e3c5
commit 07ac99764f
3 changed files with 138 additions and 9 deletions

View File

@@ -390,6 +390,10 @@ fn md_to_html(md: &str) -> String {
}
fn md_to_html_with_base(md: &str, base_dir: Option<&Path>) -> String {
// A UTF-8 BOM is legal in files but not part of Markdown syntax. Strip it
// before front-matter detection so both `---` metadata and a leading
// heading still parse.
let md = md.strip_prefix('\u{feff}').unwrap_or(md);
let (front_matter, markdown) = split_yaml_front_matter(md)
.map(|(metadata, body)| (Some(metadata), body))
.unwrap_or((None, md));
@@ -398,12 +402,14 @@ fn md_to_html_with_base(md: &str, base_dir: Option<&Path>) -> String {
| Options::ENABLE_TASKLISTS
| Options::ENABLE_HEADING_ATTRIBUTES
| Options::ENABLE_MATH
| Options::ENABLE_GFM;
| Options::ENABLE_GFM
| Options::ENABLE_FOOTNOTES
| Options::ENABLE_DEFINITION_LIST;
let parser = Parser::new_ext(markdown, opts);
let events = embed_local_images(
let events = render_softbreaks_as_hard(embed_local_images(
add_mark_highlights(add_heading_ids(parser.collect())),
base_dir,
);
));
let mut html_out = String::new();
if let Some(metadata) = front_matter {
html_out.push_str(r#"<aside class="front-matter"><pre>"#);
@@ -414,6 +420,29 @@ fn md_to_html_with_base(md: &str, base_dir: Option<&Path>) -> String {
html_out
}
/// AI-generated Markdown often uses a single newline as a visual line break.
/// Treat those soft breaks as hard breaks in normal prose, but keep headings
/// untouched: a multi-line setext heading should stay one visual line.
fn render_softbreaks_as_hard<'a>(events: Vec<MdEvent<'a>>) -> Vec<MdEvent<'a>> {
let mut heading_depth = 0usize;
let mut out = Vec::with_capacity(events.len());
for event in events {
match &event {
MdEvent::Start(Tag::Heading { .. }) => heading_depth += 1,
MdEvent::End(TagEnd::Heading(_)) => {
heading_depth = heading_depth.saturating_sub(1);
}
MdEvent::SoftBreak if heading_depth == 0 => {
out.push(MdEvent::HardBreak);
continue;
}
_ => {}
}
out.push(event);
}
out
}
fn split_yaml_front_matter(md: &str) -> Option<(&str, &str)> {
let mut lines = md.split_inclusive('\n');
let first = lines.next()?;
@@ -1172,6 +1201,18 @@ body.has-tabs {{ --chrome-top: 50px; }}
#preview a:hover {{ text-decoration: underline; }}
#preview ul, #preview ol {{ padding-left: 2em; }}
#preview input[type="checkbox"] {{ margin-right: 6px; }}
#preview dl {{ margin: 1em 0; }}
#preview dt {{ font-weight: 600; }}
#preview dd {{ margin: 0 0 .6em 1.5em; }}
#preview .footnote-reference {{ font-size: .75em; }}
#preview .footnote-definition {{
margin-top: 1.5em;
padding-top: .75em;
border-top: 1px solid #e1e4e8;
color: #59636e;
font-size: .9em;
}}
#preview .footnote-definition-label {{ margin-right: .35em; font-weight: 600; }}
.empty {{ display: flex; flex-direction: column; align-items: center; justify-content: center;
min-height: 60vh; color: #999; font-size: 18px; gap: 12px; text-align: center; }}
.empty.has-recent {{
@@ -1310,6 +1351,7 @@ body.empty .toolbar {{ display: none !important; }}
#preview .front-matter pre {{ background: transparent !important; }}
#preview code:not(pre code) {{ background: #2d2d2d; }}
#preview blockquote {{ border-color: #444; color: #aaa; }}
#preview .footnote-definition {{ border-color: #444; color: #aaa; }}
#preview .markdown-alert-note,
#preview .markdown-alert-tip,
#preview .markdown-alert-important,
@@ -2141,6 +2183,86 @@ mod tests {
assert!(!html.contains("[!IMPORTANT]"));
}
#[test]
fn soft_breaks_render_as_hard_breaks_in_paragraphs() {
let html = md_to_html("2.1 默认只读讨论。\n2.2 默认工作流:先读代码。");
assert!(
html.contains("2.1 默认只读讨论。<br />\n2.2 默认工作流"),
"{html}"
);
}
#[test]
fn blank_lines_still_create_paragraphs() {
let html = md_to_html("first line\n\nsecond line");
assert_eq!(html.matches("<p>").count(), 2, "{html}");
assert!(!html.contains("<br />"), "{html}");
}
#[test]
fn soft_breaks_inside_headings_stay_soft() {
let html = md_to_html("First heading line\nsecond heading line\n===");
assert!(html.contains("<h1"), "{html}");
assert!(!html.contains("<br />"), "{html}");
}
#[test]
fn soft_breaks_in_list_items_become_hard_breaks() {
let html = md_to_html("- first line\n second line");
assert!(html.contains("<li>first line<br />"), "{html}");
assert!(html.contains("second line</li>"), "{html}");
}
#[test]
fn code_blocks_keep_newlines_without_br() {
let html = md_to_html("~~~text\nline one\nline two\n~~~");
assert!(!html.contains("<br />"), "{html}");
assert!(html.contains("line one\nline two"), "{html}");
}
#[test]
fn gfm_footnotes_render_reference_and_definition() {
let html = md_to_html("Text with a note[^1].\n\n[^1]: The footnote body.");
assert!(html.contains(r#"class="footnote-reference""#), "{html}");
assert!(html.contains(r#"class="footnote-definition""#), "{html}");
assert!(html.contains("The footnote body."), "{html}");
}
#[test]
fn definition_lists_render_as_dl_dt_dd() {
let html = md_to_html("Term\n: Definition");
assert!(html.contains("<dl>"), "{html}");
assert!(html.contains("<dt>Term</dt>"), "{html}");
assert!(html.contains("<dd>Definition</dd>"), "{html}");
}
#[test]
fn utf8_bom_is_ignored_before_heading_and_front_matter() {
let heading = md_to_html("\u{feff}# BOM heading");
assert!(
heading.contains(r#"<h1 id="bom-heading">BOM heading</h1>"#),
"{heading}"
);
let front_matter = md_to_html("\u{feff}---\ntitle: BOM\n---\n# Body");
assert!(
front_matter.contains(r#"class="front-matter""#),
"{front_matter}"
);
assert!(front_matter.contains("title: BOM"), "{front_matter}");
assert!(
front_matter.contains(r#"<h1 id="body">Body</h1>"#),
"{front_matter}"
);
}
#[test]
fn double_equals_highlight_renders_mark_without_touching_code() {
let html = md_to_html("Use ==highlight & tag== here and `==literal==` there.");