//! Markdown export from a loro-prosemirror shaped LoroDoc. //! //! Layout (see loro-prosemirror `createLoroMap` / `createLoroText`): the root //! is `doc.get_map("doc")`. Every non-text node is a LoroMap with `nodeName`, //! `attributes` (LoroMap) and `children` (LoroList). Children are either node //! maps or a LoroText whose rich-text deltas carry the marks as attributes. use loro::{Container, LoroDoc, LoroMap, LoroText, LoroValue, TextDelta, ValueOrContainer}; 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>, } /// 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 { render_doc(doc, Ctx { wiki: None }) } /// 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 { render_doc(doc, Ctx { wiki: Some(resolve) }) } fn render_doc(doc: &LoroDoc, cx: Ctx<'_>) -> String { let root = doc.get_map("doc"); let body = render_children(&root, false, cx); if body.is_empty() { String::new() } else { format!("{body}\n") } } /// A link to another note: by id (`/notes/`) or by title (`/notes/by-title/`). #[derive(Clone, Debug, PartialEq, Eq)] pub enum LinkTarget { Id(String), Title(String), } /// Every note the doc links to, each target once, in document order. Hrefs that are /// not note links are ignored. pub fn note_links(doc: &LoroDoc) -> Vec<LinkTarget> { let mut out = Vec::new(); collect_links(&doc.get_map("doc"), &mut out); out } fn collect_links(node: &LoroMap, out: &mut Vec<LinkTarget>) { for child in children(node) { match child { Child::Text(text) => { for delta in text.to_delta() { let TextDelta::Insert { attributes: Some(attrs), .. } = delta else { continue; }; let Some(href) = attrs .get("link") .and_then(|link| link.get_by_key("href")) .and_then(value_str) else { continue; }; if let Some(target) = link_target(&href) { if !out.contains(&target) { out.push(target); } } } } Child::Node(m) => collect_links(&m, out), } } } fn link_target(href: &str) -> Option<LinkTarget> { let rest = href.strip_prefix("/notes/")?; if let Some(encoded) = rest.strip_prefix("by-title/") { let title = percent_decode(encoded); return (!title.trim().is_empty()).then_some(LinkTarget::Title(title)); } let is_id = !rest.is_empty() && !rest.contains(['/', '?', '#']); is_id.then(|| LinkTarget::Id(rest.to_owned())) } /// 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<String> { 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<String> { 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}]]")) } } /// Percent-encodes everything except RFC 3986 unreserved characters. pub fn percent_encode(s: &str) -> String { let mut out = String::with_capacity(s.len()); for b in s.bytes() { match b { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { out.push(b as char) } _ => out.push_str(&format!("%{b:02X}")), } } out } /// Decodes `%XX` escapes. Malformed escapes are kept as they are. pub fn percent_decode(s: &str) -> String { let bytes = s.as_bytes(); let mut out = Vec::with_capacity(bytes.len()); let mut i = 0; while i < bytes.len() { if bytes[i] == b'%' && i + 2 < bytes.len() { let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok(); if let Some(v) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) { out.push(v); i += 3; continue; } } out.push(bytes[i]); i += 1; } String::from_utf8_lossy(&out).into_owned() } /// Plain text of the first non-empty block, trimmed, max 80 chars. "Untitled" if empty. pub fn title(doc: &LoroDoc) -> String { let root = doc.get_map("doc"); let raw = first_text(&root).unwrap_or_default(); let collapsed = raw.split_whitespace().collect::<Vec<_>>().join(" "); let truncated: String = collapsed.chars().take(80).collect(); let trimmed = truncated.trim_end(); if trimmed.is_empty() { "Untitled".to_string() } else { trimmed.to_string() } } // --------------------------------------------------------------------------- // Tree access helpers // --------------------------------------------------------------------------- pub(super) enum Child { Text(LoroText), Node(LoroMap), } pub(super) fn children(node: &LoroMap) -> Vec<Child> { let mut out = Vec::new(); let Some(ValueOrContainer::Container(Container::List(list))) = node.get("children") else { return out; }; for i in 0..list.len() { match list.get(i) { Some(ValueOrContainer::Container(Container::Text(t))) => out.push(Child::Text(t)), Some(ValueOrContainer::Container(Container::Map(m))) => out.push(Child::Node(m)), _ => {} } } out } pub(super) fn node_name(node: &LoroMap) -> String { match node.get("nodeName") { Some(ValueOrContainer::Value(v)) => value_str(&v).unwrap_or_default(), _ => String::new(), } } pub(super) fn attr(node: &LoroMap, key: &str) -> Option<LoroValue> { match node.get("attributes") { Some(ValueOrContainer::Container(Container::Map(attrs))) => match attrs.get(key) { Some(ValueOrContainer::Value(v)) => Some(v), _ => None, }, _ => None, } } pub(super) fn attr_str(node: &LoroMap, key: &str) -> Option<String> { attr(node, key).and_then(|v| value_str(&v)) } pub(super) fn attr_num(node: &LoroMap, key: &str) -> Option<i64> { match attr(node, key)? { LoroValue::I64(i) => Some(i), LoroValue::Double(d) => Some(d as i64), _ => None, } } pub(super) fn value_str(v: &LoroValue) -> Option<String> { v.as_string().map(|s| s.as_str().to_owned()) } pub(super) fn plain_text(text: &LoroText) -> String { text.to_delta() .into_iter() .filter_map(|d| match d { TextDelta::Insert { insert, .. } => Some(insert), _ => None, }) .collect() } pub(super) fn plain_node_text(node: &LoroMap) -> String { children(node) .into_iter() .map(|c| match c { Child::Text(t) => plain_text(&t), Child::Node(m) => plain_node_text(&m), }) .collect() } /// First non-blank text of the tree, in document order. fn first_text(node: &LoroMap) -> Option<String> { for child in children(node) { let found = match child { Child::Text(t) => Some(plain_text(&t)), Child::Node(m) => first_text(&m), }; if let Some(s) = found { if !s.trim().is_empty() { return Some(s); } } } None } // --------------------------------------------------------------------------- // Block rendering // --------------------------------------------------------------------------- /// Renders the children of `node` as 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_children(node: &LoroMap, tight: bool, cx: Ctx<'_>) -> String { let mut blocks: Vec<(String, bool)> = Vec::new(); for child in children(node) { match child { Child::Text(t) => { let s = paragraph_text(inline_text(&t, cx)); if !s.is_empty() { blocks.push((s, false)); } } Child::Node(m) => { let is_list = matches!(node_name(&m).as_str(), "bullet_list" | "ordered_list"); if let Some(s) = render_block(&m, cx) { blocks.push((s, is_list)); } } } } let mut out = String::new(); for (i, (block, is_list)) in blocks.iter().enumerate() { if i > 0 { out.push_str(if tight && *is_list { "\n" } else { "\n\n" }); } out.push_str(block); } out } fn render_block(node: &LoroMap, cx: Ctx<'_>) -> Option<String> { let name = node_name(node); let out = match name.as_str() { "paragraph" => paragraph_text(inline_children(node, cx)), "heading" => { let level = attr_num(node, "level").unwrap_or(1).clamp(1, 6) as usize; let text = inline_children(node, cx).replace('\n', " "); let text = text.trim(); if text.is_empty() { String::new() } else { format!("{} {}", "#".repeat(level), text) } } "blockquote" => render_children(node, false, cx) .lines() .map(|l| { if l.is_empty() { ">".to_string() } else { format!("> {l}") } }) .collect::<Vec<_>>() .join("\n"), "code_block" => code_block(node), "horizontal_rule" => "---".to_string(), "bullet_list" => render_list(node, false, cx), "ordered_list" => render_list(node, true, cx), "list_item" => render_children(node, true, cx), "image" => paragraph_text(image_md(node)), "hard_break" => String::new(), // doc and unknown containers: render their children. _ => render_children(node, false, cx), }; if out.trim().is_empty() { None } else { Some(out.trim_end().to_string()) } } fn render_list(node: &LoroMap, ordered: bool, cx: Ctx<'_>) -> String { let start = if ordered { attr_num(node, "order").unwrap_or(1) } else { 1 }; let mut items = Vec::new(); let mut index: i64 = 0; for child in children(node) { let Child::Node(item) = child else { continue; }; let marker = if ordered { format!("{}. ", start + index) } else { "- ".to_string() }; index += 1; let body = render_children(&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(node: &LoroMap) -> String { let mut content = String::new(); for child in children(node) { match child { Child::Text(t) => content.push_str(&plain_text(&t)), Child::Node(m) if node_name(&m) == "hard_break" => content.push('\n'), Child::Node(m) => content.push_str(&plain_node_text(&m)), } } let content = content.trim_end_matches('\n'); let fence = "`".repeat((longest_backtick_run(content) + 1).max(3)); let lang = attr_str(node, "language").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::<Vec<_>>() .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 // --------------------------------------------------------------------------- /// Concatenated inline content of a node: text runs and inline child nodes. fn inline_children(node: &LoroMap, cx: Ctx<'_>) -> String { let mut out = String::new(); for child in children(node) { match child { Child::Text(t) => out.push_str(&inline_text(&t, cx)), Child::Node(m) => out.push_str(&inline_node(&m, cx)), } } out } fn inline_node(node: &LoroMap, cx: Ctx<'_>) -> String { match node_name(node).as_str() { "hard_break" => "\\\n".to_string(), "image" => image_md(node), _ => inline_children(node, cx), } } #[derive(PartialEq, Clone, Default)] struct Marks { strong: bool, em: bool, code: bool, link: Option<(String, Option<String>)>, } /// Renders a LoroText as markdown, merging adjacent runs with identical marks /// so that e.g. two bold runs become one `**...**` span. fn inline_text(text: &LoroText, cx: Ctx<'_>) -> String { let mut runs: Vec<(String, Marks)> = Vec::new(); for delta in text.to_delta() { let TextDelta::Insert { insert, attributes } = delta else { continue; }; let attrs = attributes.unwrap_or_default(); let on = |k: &str| attrs.get(k).is_some_and(|v| !matches!(v, LoroValue::Null)); let link = attrs.get("link").map(|v| { let href = v.get_by_key("href").and_then(value_str).unwrap_or_default(); let title = v .get_by_key("title") .and_then(value_str) .filter(|t| !t.is_empty()); (href, title) }); let marks = Marks { strong: on("strong"), em: on("em"), code: on("code"), link, }; match runs.last_mut() { Some((s, m)) if *m == marks => s.push_str(&insert), _ => runs.push((insert, marks)), } } // Consecutive runs under the same link render as one link, so a partly bold link // stays a single link. 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 } /// One run without a link, or every run of one link. 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()..]; if let Some(target) = wiki_target(&href, cx) { // Marks that cover the whole link go around `[[...]]`, which can't hold any. let first = &group[0].1; let uniform = !first.code && group.iter().all(|(_, m)| m.strong == first.strong && m.em == first.em); 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<char> = 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(node: &LoroMap) -> String { let alt = attr_str(node, "alt").unwrap_or_default(); let src = attr_str(node, "src").unwrap_or_default(); if src.is_empty() { return escape_text(&alt); } let alt = alt .replace('\\', "\\\\") .replace('[', "\\[") .replace(']', "\\]"); let title = attr_str(node, "title").filter(|t| !t.is_empty()); format!("![{alt}]({})", link_dest(&src, title.as_deref())) }