, and headings get stable ids for
//! folding and anchor navigation.
use crate::escape::html_escape_text;
use pulldown_cmark::{html, CowStr, Event as MdEvent, Options, Parser, Tag, TagEnd};
use std::collections::HashMap;
use std::fs;
use std::path::{Component, Path, PathBuf};
#[cfg(test)]
pub fn md_to_html(md: &str) -> String {
md_to_html_with_base(md, None)
}
pub 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));
let opts = Options::ENABLE_TABLES
| Options::ENABLE_STRIKETHROUGH
| Options::ENABLE_TASKLISTS
| Options::ENABLE_HEADING_ATTRIBUTES
| Options::ENABLE_MATH
| Options::ENABLE_GFM
| Options::ENABLE_FOOTNOTES
| Options::ENABLE_DEFINITION_LIST;
let parser = Parser::new_ext(markdown, opts);
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#"\n");
}
html::push_html(&mut html_out, events.into_iter());
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>) -> Vec> {
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()?;
if first.trim_end_matches(['\r', '\n']) != "---" {
return None;
}
let metadata_start = first.len();
let mut offset = metadata_start;
for line in lines {
let value = line.trim_end_matches(['\r', '\n']);
if value == "---" || value == "..." {
let metadata = &md[metadata_start..offset];
let body = &md[offset + line.len()..];
return Some((metadata, body));
}
offset += line.len();
}
None
}
fn embed_local_images<'a>(events: Vec>, base_dir: Option<&Path>) -> Vec> {
let Some(base_dir) = base_dir else {
return events;
};
events
.into_iter()
.map(|event| match event {
MdEvent::Start(Tag::Image {
link_type,
dest_url,
title,
id,
}) => {
let embedded = local_image_data_url(base_dir, dest_url.as_ref());
MdEvent::Start(Tag::Image {
link_type,
dest_url: embedded.map(CowStr::from).unwrap_or(dest_url),
title,
id,
})
}
_ => event,
})
.collect()
}
fn local_image_data_url(base_dir: &Path, url: &str) -> Option {
let image_path = resolve_local_relative_image_path(base_dir, url)?;
let mime = image_mime_type(&image_path)?;
let bytes = fs::read(image_path).ok()?;
Some(format!("data:{mime};base64,{}", base64_encode(&bytes)))
}
fn resolve_local_relative_image_path(base_dir: &Path, url: &str) -> Option {
let path_part = url.split(['#', '?']).next()?.trim();
if !is_local_relative_url(path_part) {
return None;
}
let mut candidate = base_dir.to_path_buf();
for segment in path_part.split('/') {
if segment.is_empty() || segment == "." {
continue;
}
let decoded = percent_decode_path_segment(segment)?;
let segment_path = Path::new(&decoded);
if segment_path
.components()
.any(|component| !matches!(component, Component::Normal(_)))
{
return None;
}
candidate.push(segment_path);
}
if candidate == base_dir {
return None;
}
Some(candidate)
}
fn is_local_relative_url(url: &str) -> bool {
!url.is_empty()
&& !url.starts_with('#')
&& !url.starts_with('/')
&& !url.starts_with('\\')
&& !url.starts_with("//")
&& !url.contains(':')
}
fn percent_decode_path_segment(segment: &str) -> Option {
let bytes = segment.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' {
let hi = bytes.get(i + 1).and_then(|b| hex_value(*b))?;
let lo = bytes.get(i + 2).and_then(|b| hex_value(*b))?;
out.push((hi << 4) | lo);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).ok()
}
fn hex_value(byte: u8) -> Option {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
fn image_mime_type(path: &Path) -> Option<&'static str> {
match path
.extension()?
.to_string_lossy()
.to_ascii_lowercase()
.as_str()
{
"png" => Some("image/png"),
"jpg" | "jpeg" => Some("image/jpeg"),
"gif" => Some("image/gif"),
"webp" => Some("image/webp"),
"svg" => Some("image/svg+xml"),
"bmp" => Some("image/bmp"),
"ico" => Some("image/x-icon"),
"avif" => Some("image/avif"),
_ => None,
}
}
fn base64_encode(bytes: &[u8]) -> String {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
let mut index = 0;
while index + 3 <= bytes.len() {
let n = ((bytes[index] as u32) << 16)
| ((bytes[index + 1] as u32) << 8)
| bytes[index + 2] as u32;
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
out.push(TABLE[(n & 0x3f) as usize] as char);
index += 3;
}
match &bytes[index..] {
[a] => {
let n = (*a as u32) << 16;
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
out.push('=');
out.push('=');
}
[a, b] => {
let n = ((*a as u32) << 16) | ((*b as u32) << 8);
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
out.push('=');
}
_ => {}
}
out
}
fn add_mark_highlights<'a>(events: Vec>) -> Vec> {
let mut out = Vec::with_capacity(events.len());
let mut code_block_depth = 0usize;
for event in events {
match &event {
MdEvent::Start(Tag::CodeBlock(_)) => code_block_depth += 1,
MdEvent::End(TagEnd::CodeBlock) => {
code_block_depth = code_block_depth.saturating_sub(1);
}
MdEvent::Text(text) if code_block_depth == 0 && text.contains("==") => {
push_mark_highlight_events(text.as_ref(), &mut out);
continue;
}
_ => {}
}
out.push(event);
}
out
}
fn push_mark_highlight_events<'a>(text: &str, out: &mut Vec>) {
let mut rest = text;
while let Some(open) = rest.find("==") {
let after_open = open + 2;
let Some(close_rel) = rest[after_open..].find("==") else {
break;
};
let close = after_open + close_rel;
let body = &rest[after_open..close];
if body.trim().is_empty() {
break;
}
if open > 0 {
out.push(MdEvent::Text(CowStr::Boxed(
rest[..open].to_string().into_boxed_str(),
)));
}
out.push(MdEvent::Html(CowStr::Borrowed(
r#""#,
)));
out.push(MdEvent::Text(CowStr::Boxed(
body.to_string().into_boxed_str(),
)));
out.push(MdEvent::Html(CowStr::Borrowed("")));
rest = &rest[close + 2..];
}
if !rest.is_empty() {
out.push(MdEvent::Text(CowStr::Boxed(
rest.to_string().into_boxed_str(),
)));
}
}
fn add_heading_ids<'a>(mut events: Vec>) -> Vec> {
let mut seen: HashMap = HashMap::new();
for i in 0..events.len() {
let generate_id = match &events[i] {
MdEvent::Start(Tag::Heading { id: Some(id), .. }) => {
register_heading_id(id.as_ref(), &mut seen);
false
}
MdEvent::Start(Tag::Heading { id: None, .. }) => true,
_ => false,
};
if !generate_id {
continue;
}
let text = collect_heading_text(&events, i);
let base = heading_slug(&text);
let id_value = unique_heading_id(base, &mut seen);
if let MdEvent::Start(Tag::Heading { id, .. }) = &mut events[i] {
*id = Some(CowStr::Boxed(id_value.into_boxed_str()));
}
}
events
}
fn collect_heading_text(events: &[MdEvent<'_>], start: usize) -> String {
let mut text = String::new();
for event in events.iter().skip(start + 1) {
match event {
MdEvent::End(TagEnd::Heading(_)) => break,
MdEvent::Text(value)
| MdEvent::Code(value)
| MdEvent::InlineMath(value)
| MdEvent::DisplayMath(value) => text.push_str(value.as_ref()),
MdEvent::SoftBreak | MdEvent::HardBreak => text.push(' '),
_ => {}
}
}
text
}
fn heading_slug(text: &str) -> String {
let mut slug = String::new();
let mut last_dash = false;
for c in text.trim().chars().flat_map(char::to_lowercase) {
if c.is_alphanumeric() || c == '_' || c == '-' {
slug.push(c);
last_dash = false;
} else if c.is_whitespace() && !slug.is_empty() && !last_dash {
slug.push('-');
last_dash = true;
}
}
while slug.ends_with('-') {
slug.pop();
}
if slug.is_empty() {
"section".to_string()
} else {
slug
}
}
fn register_heading_id(id: &str, seen: &mut HashMap) {
if !id.is_empty() {
*seen.entry(id.to_string()).or_insert(0) += 1;
}
}
fn unique_heading_id(base: String, seen: &mut HashMap) -> String {
let count = seen.entry(base.clone()).or_insert(0);
let id = if *count == 0 {
base
} else {
format!("{base}-{count}")
};
*count += 1;
id
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn base64_matches_known_vectors() {
assert_eq!(base64_encode(b""), "");
assert_eq!(base64_encode(b"f"), "Zg==");
assert_eq!(base64_encode(b"fo"), "Zm8=");
assert_eq!(base64_encode(b"foo"), "Zm9v");
assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
}
}