//! Markdown export of a note, from its block tree (`note_model::flat`). use loro::LoroDoc; use note_model::links::{link_target, percent_encode}; use note_model::marks::Marks; use note_model::write::{Block, Inline}; pub use note_model::links::{LinkTarget, note_links}; pub use note_model::tree::title; mod html; pub use html::{html_page, to_html}; /// Maps a note id to its current title, for wiki-style links in `to_markdown_with`. pub type Resolve<'a> = &'a dyn Fn(&str) -> Option; /// Rendering options. `wiki` is set by `to_markdown_with`: note links then render as /// `[[Title]]`, and ids the resolver cannot name stay ordinary markdown links. #[derive(Clone, Copy)] struct Ctx<'a> { wiki: Option>, /// Set by `to_markdown_deferred`: links by id become placeholders, counted here. deferred: Option<&'a std::cell::Cell>, } /// Placeholder marks for links by id in `to_markdown_deferred`: Unicode noncharacters, /// which text does not hold. const DEFER_START: char = '\u{FDD0}'; const DEFER_SEP: char = '\u{FDD1}'; const DEFER_END: char = '\u{FDD2}'; /// Full note as CommonMark/GFM. Note links stay ordinary markdown links, which is /// what the search text wants. pub fn to_markdown(doc: &LoroDoc) -> String { Body::read(doc).markdown() } /// Full note as markdown with note links written as `[[Title]]` (or `[[Title|text]]` /// when the link text differs). Links by title use the stored title; links by id use /// `resolve`, and an id it cannot name stays an ordinary link. pub fn to_markdown_with(doc: &LoroDoc, resolve: Resolve<'_>) -> String { Body::read(doc).markdown_with(resolve) } /// `to_markdown_with` with the titles of links by id left as placeholders, for /// [`resolve_deferred`] to fill in: the result stays right when a linked note is /// renamed. None when the note's text holds the placeholder marks itself. pub fn to_markdown_deferred(doc: &LoroDoc) -> Option { Body::read(doc).markdown_deferred() } /// A note's body read once. Every whole-note text comes from it without the doc, so /// the hub reads it under the room lock (one pass over the text) and renders off it. pub struct Body { blocks: Vec, links: Vec, } /// As [`Body::title`], reading only the doc's start when the title is there: the first /// text block with content, when it ends within that start. pub fn title_of(doc: &LoroDoc) -> String { const START: usize = 64 << 10; let text = note_model::flat::body(doc); let len = text.len_unicode(); if len > START { if let Ok(delta) = text.slice_delta(0, START, loro::cursor::PosType::Unicode) { let mut blocks = note_model::flat::read_delta(delta); blocks.pop(); // may be cut short, and its kind unknown if let Some(b) = blocks.iter().find(|b| b.attrs.kind.is_text() && !b.plain().trim().is_empty()) { return note_model::tree::title_from(&b.plain()); } } } Body::read(doc).title() } impl Body { pub fn read(doc: &LoroDoc) -> Body { let delta = note_model::flat::body(doc).to_delta(); let links = note_model::links::links_in(&delta); Body { blocks: note_model::flat::read_delta(delta), links } } /// As [`title`]. pub fn title(&self) -> String { let first = self.blocks.iter().find(|b| b.attrs.kind.is_text() && !b.plain().trim().is_empty()); note_model::tree::title_from(&first.map(|b| b.plain()).unwrap_or_default()) } /// As [`note_links`]. pub fn note_links(&self) -> Vec { self.links.clone() } /// As [`to_markdown`]. pub fn markdown(&self) -> String { self.render(Ctx { wiki: None, deferred: None }) } /// As [`to_markdown_with`]. pub fn markdown_with(&self, resolve: Resolve<'_>) -> String { self.render(Ctx { wiki: Some(resolve), deferred: None }) } /// As [`to_markdown_deferred`]. pub fn markdown_deferred(&self) -> Option { let count = std::cell::Cell::new(0); let none = |_: &str| None; let md = self.render(Ctx { wiki: Some(&none), deferred: Some(&count) }); let marks = |c: char| md.chars().filter(|&x| x == c).count(); let n = count.get(); (marks(DEFER_START) == n && marks(DEFER_END) == n && marks(DEFER_SEP) == 4 * n).then_some(md) } /// As [`to_html`]. pub fn html(&self) -> String { html::render_blocks(¬e_model::flat::nest(&self.blocks)) } fn render(&self, cx: Ctx<'_>) -> String { let body = render_blocks(¬e_model::flat::nest(&self.blocks), false, cx); if body.is_empty() { String::new() } else { format!("{body}\n") } } } /// Fills in the links of a `to_markdown_deferred` result with the current titles, /// as `to_markdown_with` would have written them. pub fn resolve_deferred(md: &str, resolve: Resolve<'_>) -> String { let mut out = String::with_capacity(md.len()); let mut rest = md; while let Some(at) = rest.find(DEFER_START) { out.push_str(&rest[..at]); let after = &rest[at + DEFER_START.len_utf8()..]; let end = after.find(DEFER_END).unwrap_or(after.len()); let mut fields = after[..end].split(DEFER_SEP); let mut next = || fields.next().unwrap_or(""); let (id, core, flags, inner, dest) = (next(), next(), next(), next(), next()); out.push_str(&deferred_link(resolve(id), core, flags, inner, dest)); rest = after.get(end + DEFER_END.len_utf8()..).unwrap_or(""); } out.push_str(rest); out } /// One link by id of `render_group`, given the note's title if it has one. fn deferred_link(target: Option, core: &str, flags: &str, inner: &str, dest: &str) -> String { let Some(target) = target else { return format!("[{inner}]({dest})") }; if flags.contains('u') { if let Some(mut link) = wiki_link(&target, core) { if flags.contains('e') { link = format!("*{link}*"); } if flags.contains('s') { link = format!("**{link}**"); } return link; } } format!("[{inner}]({})", percent_encode(&format!("{target}.md"))) } /// The note a link mark points at, as a title, when the link is a note link the /// resolver can name. Links by title need no resolver. fn wiki_target(href: &str, cx: Ctx<'_>) -> Option { let resolve = cx.wiki?; match link_target(href)? { LinkTarget::Title(title) => Some(title), LinkTarget::Id(id) => resolve(&id), } } /// `[[target]]`, or `[[target|text]]` when the link text differs. None when the title or /// the text holds wiki syntax (`[ ] | #` or a line break), so the link stays a markdown link. fn wiki_link(target: &str, text: &str) -> Option { let reserved = |s: &str| s.contains(['[', ']', '|', '#', '\n']); if target.trim().is_empty() || reserved(target) || reserved(text) { return None; } if text == target { Some(format!("[[{target}]]")) } else { Some(format!("[[{target}|{text}]]")) } } // --------------------------------------------------------------------------- // Block rendering // --------------------------------------------------------------------------- /// Renders blocks separated by blank lines. With `tight`, a nested list directly /// follows its sibling with a single newline instead of a blank line (used inside /// list items). fn render_blocks(blocks: &[Block], tight: bool, cx: Ctx<'_>) -> String { let mut out = String::new(); let mut first = true; for b in blocks { let Some(s) = render_block(b, cx) else { continue }; if !first { out.push_str(if tight && matches!(b, Block::List { .. }) { "\n" } else { "\n\n" }); } first = false; out.push_str(&s); } out } fn render_block(block: &Block, cx: Ctx<'_>) -> Option { let out = match block { Block::Paragraph(inl) => paragraph_text(inline(inl, cx)), Block::Heading(level, inl) => { let level = (*level).clamp(1, 6) as usize; let text = inline(inl, cx).replace('\n', " "); let text = text.trim(); if text.is_empty() { String::new() } else { format!("{} {}", "#".repeat(level), text) } } Block::Quote(inner) => render_blocks(inner, false, cx) .lines() .map(|l| { if l.is_empty() { ">".to_string() } else { format!("> {l}") } }) .collect::>() .join("\n"), Block::Code { lang, text } => code_block(lang.as_deref(), text), Block::Rule => "---".to_string(), Block::List { ordered, start, items } => render_list(items, *ordered, *start, cx), }; if out.trim().is_empty() { None } else { Some(out.trim_end().to_string()) } } fn render_list(list: &[Vec], ordered: bool, start: i64, cx: Ctx<'_>) -> String { let start = if ordered { start } else { 1 }; let mut items = Vec::new(); for (index, item) in list.iter().enumerate() { let marker = if ordered { format!("{}. ", start + index as i64) } else { "- ".to_string() }; let body = render_blocks(item, true, cx); if body.is_empty() { items.push(marker.trim_end().to_string()); continue; } let pad = " ".repeat(marker.len()); let mut lines = body.lines(); let mut text = format!("{marker}{}", lines.next().unwrap_or("")); for line in lines { text.push('\n'); if !line.is_empty() { text.push_str(&pad); text.push_str(line); } } items.push(text); } items.join("\n") } fn code_block(lang: Option<&str>, content: &str) -> String { let content = content.trim_end_matches('\n'); let fence = "`".repeat((longest_backtick_run(content) + 1).max(3)); // An explicit language wins; without one, the language is detected. let lang = lang .filter(|l| !l.trim().is_empty()) .or_else(|| note_model::lang::detect(content)) .unwrap_or_default(); if content.is_empty() { format!("{fence}{lang}\n{fence}") } else { format!("{fence}{lang}\n{content}\n{fence}") } } fn longest_backtick_run(s: &str) -> usize { let mut best = 0; let mut cur = 0; for c in s.chars() { if c == '`' { cur += 1; best = best.max(cur); } else { cur = 0; } } best } /// Trims the inline output and protects the start of each line from being /// read as block syntax (heading, list, blockquote, ordered list marker). fn paragraph_text(inline: String) -> String { inline .trim() .split('\n') .map(escape_line_start) .collect::>() .join("\n") } fn escape_line_start(line: &str) -> String { let mut chars = line.chars(); match chars.next() { Some('>') => format!("\\>{}", chars.as_str()), Some('-') | Some('+') => { let next = line.chars().nth(1); if next.is_none() || next == Some(' ') || next == Some('-') { format!("\\{line}") } else { line.to_string() } } Some('#') => { let hashes = line.chars().take_while(|&c| c == '#').count(); let after = line.chars().nth(hashes); if (1..=6).contains(&hashes) && (after.is_none() || after == Some(' ')) { format!("\\{line}") } else { line.to_string() } } Some(c) if c.is_ascii_digit() => { let digits = line.chars().take_while(|c| c.is_ascii_digit()).count(); let rest = &line[digits..]; if rest.starts_with('.') || rest.starts_with(')') { format!("{}\\{}", &line[..digits], rest) } else { line.to_string() } } _ => line.to_string(), } } // --------------------------------------------------------------------------- // Inline rendering // --------------------------------------------------------------------------- /// Inline content as markdown. Each stretch of text between breaks and images merges /// adjacent runs with identical marks, so e.g. two bold runs become one `**...**` span. fn inline(inl: &[Inline], cx: Ctx<'_>) -> String { let mut out = String::new(); let mut runs: Vec<(String, Marks)> = Vec::new(); for i in inl { match i { Inline::Text(s, m) => match runs.last_mut() { Some((t, last)) if last == m => t.push_str(s), _ => runs.push((s.clone(), m.clone())), }, Inline::HardBreak => { out.push_str(&text_runs(&std::mem::take(&mut runs), cx)); out.push_str("\\\n"); } Inline::Image { src, alt, title } => { out.push_str(&text_runs(&std::mem::take(&mut runs), cx)); out.push_str(&image_md(src, alt, title.as_deref())); } } } out.push_str(&text_runs(&runs, cx)); out } /// Consecutive runs under the same link render as one link, so a partly bold link /// stays a single link. fn text_runs(runs: &[(String, Marks)], cx: Ctx<'_>) -> String { let mut out = String::new(); let mut i = 0; while i < runs.len() { let mut j = i + 1; if runs[i].1.link.is_some() { while j < runs.len() && runs[j].1.link == runs[i].1.link { j += 1; } } out.push_str(&render_group(&runs[i..j], cx)); i = j; } out } fn render_group(group: &[(String, Marks)], cx: Ctx<'_>) -> String { let Some((href, title)) = group[0].1.link.clone() else { return render_marks(&group[0].0, &group[0].1); }; let text: String = group.iter().map(|(s, _)| s.as_str()).collect(); let core = text.trim(); if core.is_empty() || href.is_empty() { return group.iter().map(|(s, m)| render_marks(s, m)).collect(); } let lead = &text[..text.len() - text.trim_start().len()]; let trail = &text[lead.len() + core.len()..]; let first = &group[0].1; // Marks that cover the whole link go around `[[...]]`, which can't hold any. let uniform = !first.code && group.iter().all(|(_, m)| m.strong == first.strong && m.em == first.em); if let (Some(count), Some(LinkTarget::Id(id))) = (cx.deferred, link_target(&href)) { count.set(count.get() + 1); let inner: String = group.iter().map(|(s, m)| render_marks(s, m)).collect(); let flags = [(uniform, 'u'), (first.em, 'e'), (first.strong, 's')].iter().filter(|f| f.0).map(|f| f.1).collect::(); let dest = link_dest(&href, title.as_deref()); return format!( "{lead}{DEFER_START}{id}{DEFER_SEP}{core}{DEFER_SEP}{flags}{DEFER_SEP}{}{DEFER_SEP}{dest}{DEFER_END}{trail}", inner.trim() ); } if let Some(target) = wiki_target(&href, cx) { if uniform { if let Some(mut link) = wiki_link(&target, core) { if first.em { link = format!("*{link}*"); } if first.strong { link = format!("**{link}**"); } return format!("{lead}{link}{trail}"); } } // Mixed marks: a markdown link to the note's file, which Obsidian also follows. let inner: String = group.iter().map(|(s, m)| render_marks(s, m)).collect(); let file = percent_encode(&format!("{target}.md")); return format!("{lead}[{}]({file}){trail}", inner.trim()); } let inner: String = group.iter().map(|(s, m)| render_marks(s, m)).collect(); format!( "{lead}[{}]({}){trail}", inner.trim(), link_dest(&href, title.as_deref()) ) } /// A run's text with its emphasis and code marks; links are handled by `render_group`. fn render_marks(s: &str, m: &Marks) -> String { let core = s.trim(); if core.is_empty() { return s.to_string(); } // Keep surrounding whitespace outside the emphasis markers. let lead_len = s.len() - s.trim_start().len(); let lead = &s[..lead_len]; let trail = &s[lead_len + core.len()..]; let mut out = if m.code { code_span(core) } else { escape_text(core) }; if m.em { out = format!("*{out}*"); } if m.strong { out = format!("**{out}**"); } format!("{lead}{out}{trail}") } /// Escapes markdown-significant characters in plain text. Underscores inside /// a word (snake_case) are left alone. fn escape_text(s: &str) -> String { let chars: Vec = s.chars().collect(); let mut out = String::with_capacity(s.len()); for (i, &c) in chars.iter().enumerate() { let escape = match c { '\\' | '`' | '*' | '[' | ']' | '<' | '~' => true, '_' => { let prev = i.checked_sub(1).map(|p| chars[p]); let next = chars.get(i + 1).copied(); !(prev.is_some_and(char::is_alphanumeric) && next.is_some_and(char::is_alphanumeric)) } _ => false, }; if escape { out.push('\\'); } out.push(c); } out } fn code_span(s: &str) -> String { let fence = "`".repeat(longest_backtick_run(s) + 1); let pad = if s.starts_with('`') || s.ends_with('`') { " " } else { "" }; format!("{fence}{pad}{s}{pad}{fence}") } fn link_dest(href: &str, title: Option<&str>) -> String { let dest = if href.chars().any(|c| c.is_whitespace() || c == '(' || c == ')') { format!("<{}>", href.replace('<', "\\<").replace('>', "\\>")) } else { href.to_string() }; match title.filter(|t| !t.is_empty()) { Some(t) => format!( "{dest} \"{}\"", t.replace('\\', "\\\\").replace('"', "\\\"") ), None => dest, } } fn image_md(src: &str, alt: &str, title: Option<&str>) -> String { if src.is_empty() { return escape_text(alt); } let alt = alt .replace('\\', "\\\\") .replace('[', "\\[") .replace(']', "\\]"); let title = title.filter(|t| !t.is_empty()); format!("![{alt}]({})", link_dest(src, title)) }