//! Markdown import: the inverse of `export.rs`. Parses CommonMark into a
//! note doc (`note_model::flat`, the layout `export::to_markdown` reads).
//!
//! Degradations (GFM bits that the schema cannot represent):
//! - strikethrough: content kept, no mark
//! - tables: one paragraph per row, cells joined with " | "
//! - task list items: normal list items with a "[ ] " / "[x] " text prefix
//! - raw HTML (block or inline): its text, as plain text
//! - footnotes: not enabled, so `[^x]` stays literal text
//! - soft breaks become a space, hard breaks become `hard_break` nodes
//! - wiki links `[[Title]]`, `[[Title|text]]`, `[[Title#heading]]` in plain text become
//! links to `/notes/by-title/
`
//! - local media references (links, images, `![[file]]` embeds) become `/media/...` URLs
//! when the file was imported with the note (`rewrite_media`); other embeds `![[...]]`
//! stay plain text
use std::collections::HashMap;
use std::ops::Range;
use anyhow::Result;
use loro::{ExportMode, LoroDoc};
use note_model::links::{percent_decode, percent_encode};
use note_model::marks::Marks;
use note_model::render::embed_of;
use note_model::schema::text_style_config;
use note_model::flat;
use note_model::write::{Block, Inline};
use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, LinkType, Options, Parser, Tag, TagEnd};
/// Parses markdown into a fresh LoroDoc with the note layout.
pub fn markdown_to_doc(md: &str) -> Result {
let body = strip_front_matter(md);
let events: Vec = Parser::new_ext(body, options()).collect();
let mut pos = 0;
let blocks = parse_blocks(&events, &mut pos, false);
build(&blocks)
}
/// The editor's preview markup for the start of a markdown file.
pub fn preview_markdown(md: &str) -> String {
match markdown_to_doc(md) {
Ok(doc) => note_model::render::preview_html(&doc, 128, 100_000),
Err(_) => String::new(),
}
}
/// Whether the markdown's first block is a heading. Only that block is parsed.
pub fn starts_with_heading(md: &str) -> bool {
matches!(Parser::new_ext(strip_front_matter(md), options()).next(), Some(Event::Start(Tag::Heading { .. })))
}
/// The title a doc built from `md` gets, when `md` starts with a heading: the
/// heading's plain text. Only that block is parsed.
pub fn heading_title(md: &str) -> String {
let mut raw = String::new();
for event in Parser::new_ext(strip_front_matter(md), options()) {
match event {
Event::End(TagEnd::Heading(_)) => break,
Event::Text(t) | Event::Code(t) => raw.push_str(&t),
Event::SoftBreak | Event::HardBreak => raw.push(' '),
_ => {}
}
}
note_model::tree::title_from(&raw)
}
fn options() -> Options {
Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TABLES | Options::ENABLE_TASKLISTS
}
/// Same as `markdown_to_doc`, exported as a full Loro update.
pub fn markdown_to_update(md: &str) -> Result> {
let doc = markdown_to_doc(md)?;
Ok(doc.export(ExportMode::all_updates())?)
}
/// A relative link to a `.md` file (`[text](Some%20Note.md)`, also what export writes for
/// note links with mixed formatting) becomes a link to the note with that file's name.
/// Any other destination is kept.
fn note_file_href(dest: &str) -> String {
let path = dest.split('#').next().unwrap_or(dest);
let relative = !path.contains("://") && !path.starts_with(['/', '?']) && !path.starts_with("mailto:");
let Some(stem) = path.strip_suffix(".md").filter(|_| relative) else {
return dest.to_string();
};
let decoded = percent_decode(stem);
let title = decoded.rsplit('/').next().unwrap_or(&decoded).trim();
if title.is_empty() {
return dest.to_string();
}
format!("/notes/by-title/{}", percent_encode(title))
}
/// Drops a leading `---` ... `---` YAML block. Unclosed blocks are kept as text.
pub fn strip_front_matter(md: &str) -> &str {
let mut lines = md.split_inclusive('\n');
let Some(first) = lines.next() else {
return md;
};
if first.trim_end() != "---" {
return md;
}
let mut offset = first.len();
for line in lines {
offset += line.len();
if line.trim_end() == "---" {
return &md[offset..];
}
}
md
}
/// Rewrites local media references in markdown to their `/media/` URLs. `media` maps a
/// file path relative to the imported root to its URL, and `note_path` is the markdown
/// file's own path relative to that root. Inline links and images with a local destination
/// are rewritten; Obsidian embeds `![[target]]` and `![[target|alias]]` outside code become
/// an image (or a link, for files that cannot be embedded). Anything that does not resolve
/// is left as written.
pub fn rewrite_media(md: &str, note_path: &str, media: &HashMap) -> String {
if media.is_empty() {
return md.to_string();
}
let note_dir = note_path.rsplit_once('/').map_or("", |(dir, _)| dir);
// Lowercase basename to its URL, or None when several files share it.
let mut by_name: HashMap> = HashMap::new();
for (path, url) in media {
let name = path.rsplit('/').next().unwrap_or_default().to_ascii_lowercase();
by_name.entry(name).and_modify(|slot| *slot = None).or_insert(Some(url));
}
let mut code: Vec> = Vec::new();
let mut edits: Vec<(Range, String)> = Vec::new();
for (event, range) in Parser::new_ext(md, options()).into_offset_iter() {
match event {
Event::Start(Tag::CodeBlock(_)) | Event::Code(_) => code.push(range),
Event::Start(Tag::Image { link_type: LinkType::Inline, dest_url, .. }) => {
let Some(url) = resolve_media(&dest_url, note_dir, media, &by_name) else {
continue;
};
edits.extend(dest_edit(md, &range, &dest_url, url));
if embed_of(url).is_none() && md[range.start..].starts_with('!') {
edits.push((range.start..range.start + 1, String::new()));
}
}
Event::Start(Tag::Link { link_type: LinkType::Inline, dest_url, .. }) => {
if let Some(url) = resolve_media(&dest_url, note_dir, media, &by_name) {
edits.extend(dest_edit(md, &range, &dest_url, url));
}
}
_ => {}
}
}
// Embeds never contain `[`, `]` or a newline, so one scan per `![[` is enough.
let mut at = 0;
while let Some(found) = md[at..].find("![[") {
let open = at + found;
let inner_start = open + 3;
if in_ranges(&code, open) {
at = inner_start;
continue;
}
let rest = &md[inner_start..];
let stop = rest.find(['[', ']', '\n']).unwrap_or(rest.len());
if !rest[stop..].starts_with("]]") {
at = inner_start;
continue;
}
let inner = &rest[..stop];
let end = inner_start + stop + 2;
at = end;
let (target, alias) = match inner.split_once('|') {
Some((target, alias)) => (target, Some(alias.trim())),
None => (inner, None),
};
let Some(url) = resolve_media(target, note_dir, media, &by_name) else {
continue;
};
let file = target.split('#').next().unwrap_or_default().trim().rsplit('/').next().unwrap_or_default();
let embeddable = embed_of(url).is_some();
let stem = file
.rsplit_once('.')
.filter(|(stem, _)| !stem.is_empty())
.map_or(file, |(stem, _)| stem);
let shown = match alias {
Some(alias) if !alias.is_empty() => alias,
_ if embeddable => stem,
_ => file,
};
let replacement = if embeddable {
format!("")
} else {
format!("[{shown}]({url})")
};
edits.push((open..end, replacement));
}
if edits.is_empty() {
return md.to_string();
}
edits.sort_by_key(|(range, _)| range.start);
let mut out = String::with_capacity(md.len());
let mut last = 0;
for (range, text) in edits {
if range.start < last {
continue;
}
out.push_str(&md[last..range.start]);
out.push_str(&text);
last = range.end;
}
out.push_str(&md[last..]);
out
}
/// Finds a link destination inside its event's source and pairs it with the new URL.
/// The `<...>` brackets go with it when present. None when the destination is not found
/// literally in the source.
fn dest_edit(md: &str, range: &Range, dest: &str, url: &str) -> Option<(Range, String)> {
if dest.is_empty() {
return None;
}
let at = range.start + md[range.clone()].rfind(dest)?;
let end = at + dest.len();
let angled = at > range.start && md.as_bytes()[at - 1] == b'<' && md.as_bytes().get(end) == Some(&b'>');
if angled {
Some((at - 1..end + 1, format!("<{url}>")))
} else {
Some((at..end, url.to_owned()))
}
}
/// Whether `at` falls inside one of the sorted, disjoint ranges.
fn in_ranges(ranges: &[Range], at: usize) -> bool {
let after = ranges.partition_point(|r| r.start <= at);
after > 0 && ranges[after - 1].end > at
}
/// The `/media/` URL of a local reference, or None. Remote, data, mailto, fragment-only,
/// already-rewritten and markdown note targets are not media.
fn resolve_media<'a>(
target: &str,
note_dir: &str,
media: &'a HashMap,
by_name: &HashMap>,
) -> Option<&'a str> {
let target = target.trim();
if target.is_empty()
|| target.contains("://")
|| target.starts_with("mailto:")
|| target.starts_with("data:")
|| target.starts_with('#')
|| target.starts_with("/media/")
{
return None;
}
let path = percent_decode(target.split(['#', '?']).next().unwrap_or_default());
if path.is_empty() || path.to_ascii_lowercase().ends_with(".md") {
return None;
}
let joined = normalize(&format!("{note_dir}/{path}"));
let rooted = normalize(&path);
let name = path.rsplit('/').next().unwrap_or_default().to_ascii_lowercase();
media
.get(&joined)
.or_else(|| media.get(&rooted))
.map(String::as_str)
.or_else(|| by_name.get(&name).copied().flatten().map(String::as_str))
}
/// Joins `.` and `..` segments of a forward-slash path. Empty segments are dropped.
fn normalize(path: &str) -> String {
let mut parts: Vec<&str> = Vec::new();
for part in path.split('/') {
match part {
"" | "." => {}
".." => {
parts.pop();
}
_ => parts.push(part),
}
}
parts.join("/")
}
// ---------------------------------------------------------------------------
// Intermediate tree
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Event -> tree
// ---------------------------------------------------------------------------
/// Parses block events starting at `pos`. In `nested` mode it returns after
/// consuming the End event of its container.
fn parse_blocks(ev: &[Event<'_>], pos: &mut usize, nested: bool) -> Vec {
let mut out = Vec::new();
while let Some(event) = ev.get(*pos) {
match event {
Event::End(_) => {
*pos += 1;
if nested {
break;
}
}
Event::Start(Tag::Paragraph) => {
*pos += 1;
let inl = inlines(ev, pos);
skip_end(ev, pos);
out.push(Block::Paragraph(inl));
}
Event::Start(Tag::Heading { level, .. }) => {
*pos += 1;
let inl = inlines(ev, pos);
skip_end(ev, pos);
out.push(Block::Heading(heading_level(*level), inl));
}
Event::Start(Tag::BlockQuote(_)) => {
*pos += 1;
let inner = parse_blocks(ev, pos, true);
out.push(Block::Quote(inner));
}
Event::Start(Tag::CodeBlock(kind)) => {
let lang = match kind {
CodeBlockKind::Fenced(info) => {
info.split_whitespace().next().map(str::to_owned)
}
CodeBlockKind::Indented => None,
};
*pos += 1;
let mut text = String::new();
while let Some(e) = ev.get(*pos) {
*pos += 1;
match e {
Event::End(_) => break,
Event::Text(t) => text.push_str(t),
_ => {}
}
}
out.push(Block::Code {
lang,
text: text.trim_end_matches('\n').to_owned(),
});
}
Event::Start(Tag::HtmlBlock) => {
*pos += 1;
let mut text = String::new();
while let Some(e) = ev.get(*pos) {
*pos += 1;
match e {
Event::End(_) => break,
Event::Html(t) | Event::Text(t) => text.push_str(t),
_ => {}
}
}
let t = text.trim();
if !t.is_empty() {
out.push(Block::Paragraph(vec![Inline::Text(
t.to_owned(),
Marks::default(),
)]));
}
}
Event::Start(Tag::List(start)) => {
*pos += 1;
let mut items = Vec::new();
while let Some(e) = ev.get(*pos) {
match e {
Event::End(_) => {
*pos += 1;
break;
}
Event::Start(Tag::Item) => {
*pos += 1;
let mut blocks = parse_blocks(ev, pos, true);
// Schema: list_item content is "paragraph block*".
if !matches!(blocks.first(), Some(Block::Paragraph(_))) {
blocks.insert(0, Block::Paragraph(Vec::new()));
}
items.push(blocks);
}
_ => *pos += 1,
}
}
out.push(Block::List {
ordered: start.is_some(),
start: (*start).unwrap_or(1) as i64,
items,
});
}
Event::Start(Tag::Table(_)) => {
*pos += 1;
parse_table(ev, pos, &mut out);
}
Event::Start(Tag::Item) => {
// Item outside a list: keep its content.
*pos += 1;
out.extend(parse_blocks(ev, pos, true));
}
Event::Rule => {
out.push(Block::Rule);
*pos += 1;
}
// Inline content outside a paragraph (tight list items, table-less
// loose text): wrap the run in a paragraph.
Event::Text(_)
| Event::Code(_)
| Event::SoftBreak
| Event::HardBreak
| Event::InlineHtml(_)
| Event::Html(_)
| Event::TaskListMarker(_)
| Event::FootnoteReference(_)
| Event::InlineMath(_)
| Event::DisplayMath(_)
| Event::Start(
Tag::Emphasis
| Tag::Strong
| Tag::Strikethrough
| Tag::Superscript
| Tag::Subscript
| Tag::Link { .. }
| Tag::Image { .. },
) => {
let inl = inlines(ev, pos);
if !is_blank(&inl) {
out.push(Block::Paragraph(inl));
}
}
// Unknown containers (footnote definitions, metadata, ...): keep content.
Event::Start(_) => {
*pos += 1;
out.extend(parse_blocks(ev, pos, true));
}
}
}
out
}
/// Tables: each row becomes a paragraph with cells joined by " | ".
/// Assumes `pos` is just past `Start(Table)`; consumes the table's End.
fn parse_table(ev: &[Event<'_>], pos: &mut usize, out: &mut Vec) {
while let Some(e) = ev.get(*pos) {
match e {
Event::End(_) => {
*pos += 1;
break;
}
Event::Start(Tag::TableHead | Tag::TableRow) => {
*pos += 1;
let mut cells = Vec::new();
while let Some(c) = ev.get(*pos) {
match c {
Event::End(_) => {
*pos += 1;
break;
}
Event::Start(Tag::TableCell) => {
*pos += 1;
let mut inl = Vec::new();
parse_inlines(ev, pos, &Marks::default(), &mut inl, true);
cells.push(inl);
}
_ => *pos += 1,
}
}
out.extend(table_row(cells));
}
_ => *pos += 1,
}
}
}
fn table_row(cells: Vec>) -> Option {
let mut inl = Vec::new();
for (i, cell) in cells.into_iter().enumerate() {
if i > 0 {
inl.push(Inline::Text(" | ".to_owned(), Marks::default()));
}
inl.extend(cell);
}
if is_blank(&inl) {
None
} else {
Some(Block::Paragraph(inl))
}
}
fn inlines(ev: &[Event<'_>], pos: &mut usize) -> Vec {
let mut out = Vec::new();
parse_inlines(ev, pos, &Marks::default(), &mut out, false);
out
}
/// Collects inline content. With `closing`, it also consumes the End event that
/// closes the current inline span. Without it, it stops before the first
/// non-inline event (the caller handles that event).
fn parse_inlines(
ev: &[Event<'_>],
pos: &mut usize,
marks: &Marks,
out: &mut Vec,
closing: bool,
) {
while let Some(event) = ev.get(*pos) {
match event {
Event::End(_) => {
if closing {
*pos += 1;
}
return;
}
Event::Text(s)
| Event::Html(s)
| Event::InlineHtml(s)
| Event::InlineMath(s)
| Event::DisplayMath(s) => {
out.push(Inline::Text(s.to_string(), marks.clone()));
*pos += 1;
}
Event::FootnoteReference(s) => {
out.push(Inline::Text(format!("[^{s}]"), marks.clone()));
*pos += 1;
}
Event::Code(s) => {
let mut m = marks.clone();
m.code = true;
out.push(Inline::Text(s.to_string(), m));
*pos += 1;
}
Event::SoftBreak => {
out.push(Inline::Text(" ".to_owned(), marks.clone()));
*pos += 1;
}
Event::HardBreak => {
out.push(Inline::HardBreak);
*pos += 1;
}
Event::TaskListMarker(done) => {
let s = if *done { "[x] " } else { "[ ] " };
out.push(Inline::Text(s.to_owned(), Marks::default()));
*pos += 1;
}
Event::Start(Tag::Emphasis) => {
*pos += 1;
let mut m = marks.clone();
m.em = true;
parse_inlines(ev, pos, &m, out, true);
}
Event::Start(Tag::Strong) => {
*pos += 1;
let mut m = marks.clone();
m.strong = true;
parse_inlines(ev, pos, &m, out, true);
}
// Degraded: content kept, no mark.
Event::Start(Tag::Strikethrough | Tag::Superscript | Tag::Subscript) => {
*pos += 1;
parse_inlines(ev, pos, marks, out, true);
}
Event::Start(Tag::Link {
dest_url, title, ..
}) => {
*pos += 1;
let mut m = marks.clone();
let title = (!title.is_empty()).then(|| title.to_string());
m.link = Some((note_file_href(&dest_url), title));
parse_inlines(ev, pos, &m, out, true);
}
Event::Start(Tag::Image {
dest_url, title, ..
}) => {
*pos += 1;
let mut alt = Vec::new();
parse_inlines(ev, pos, marks, &mut alt, true);
let title = (!title.is_empty()).then(|| title.to_string());
out.push(Inline::Image {
src: dest_url.to_string(),
alt: plain(&alt),
title,
});
}
// Block-level event: the inline run ends here.
_ => return,
}
}
}
fn skip_end(ev: &[Event<'_>], pos: &mut usize) {
if matches!(ev.get(*pos), Some(Event::End(_))) {
*pos += 1;
}
}
fn is_blank(inl: &[Inline]) -> bool {
inl.iter()
.all(|i| matches!(i, Inline::Text(s, _) if s.trim().is_empty()))
}
fn plain(inl: &[Inline]) -> String {
inl.iter()
.map(|i| match i {
Inline::Text(s, _) => s.as_str(),
Inline::HardBreak => " ",
Inline::Image { alt, .. } => alt.as_str(),
})
.collect()
}
fn heading_level(level: HeadingLevel) -> i64 {
match level {
HeadingLevel::H1 => 1,
HeadingLevel::H2 => 2,
HeadingLevel::H3 => 3,
HeadingLevel::H4 => 4,
HeadingLevel::H5 => 5,
HeadingLevel::H6 => 6,
}
}
// ---------------------------------------------------------------------------
// Tree -> LoroDoc
// ---------------------------------------------------------------------------
/// Builds the document. Mirrors `hub::initial_note_update`: an empty input
/// yields a single empty paragraph.
fn build(blocks: &[Block]) -> Result {
let doc = LoroDoc::new();
doc.set_peer_id(note_model::write::BUILDER_PEER)?;
doc.config_text_style(text_style_config());
if blocks.is_empty() {
flat::init(&doc)?;
} else {
flat::write(&flat::body(&doc), 0, &flat::flatten(&wikify_blocks(blocks)), false)?;
}
doc.commit();
Ok(doc)
}
/// Applies `wikilinks` to every paragraph and heading in the tree.
fn wikify_blocks(blocks: &[Block]) -> Vec {
blocks.iter().map(wikify_block).collect()
}
fn wikify_block(block: &Block) -> Block {
match block {
Block::Paragraph(inl) => Block::Paragraph(wikilinks(inl)),
Block::Heading(level, inl) => Block::Heading(*level, wikilinks(inl)),
Block::Quote(blocks) => Block::Quote(wikify_blocks(blocks)),
Block::List {
ordered,
start,
items,
} => Block::List {
ordered: *ordered,
start: *start,
items: items.iter().map(|item| wikify_blocks(item)).collect(),
},
other => other.clone(),
}
}
/// Turns `[[Title]]`, `[[Title|text]]` and `[[Title#heading]]` in plain text into links
/// to `/notes/by-title/`, showing the text (or the title). Code, existing links and
/// embeds (`![[...]]`, kept as text) are left alone.
fn wikilinks(inl: &[Inline]) -> Vec {
// Adjacent runs with the same marks are joined first, since a `[[` can be split
// across parser events.
let mut merged: Vec = Vec::new();
for item in inl {
if let Inline::Text(s, m) = item {
if let Some(Inline::Text(prev, pm)) = merged.last_mut() {
if *pm == *m {
prev.push_str(s);
continue;
}
}
}
merged.push(item.clone());
}
let mut out = Vec::with_capacity(merged.len());
for item in merged {
match item {
Inline::Text(s, m) if !m.code && m.link.is_none() => split_wikilinks(&s, &m, &mut out),
other => out.push(other),
}
}
out
}
fn split_wikilinks(s: &str, marks: &Marks, out: &mut Vec) {
let mut rest = s;
while let Some(open) = rest.find("[[") {
let after = &rest[open + 2..];
let embed = rest[..open].ends_with('!');
let parsed = after
.find("]]")
.and_then(|close| wikilink_parts(&after[..close]).map(|parts| (close, parts)));
match parsed {
Some((close, (target, text))) if !embed => {
push_text(out, &rest[..open], marks);
let href = format!("/notes/by-title/{}", percent_encode(&target));
let link = Marks {
link: Some((href, None)),
..marks.clone()
};
out.push(Inline::Text(text, link));
rest = &after[close + 2..];
}
_ => {
push_text(out, &rest[..open + 2], marks);
rest = after;
}
}
}
push_text(out, rest, marks);
}
fn push_text(out: &mut Vec, s: &str, marks: &Marks) {
if !s.is_empty() {
out.push(Inline::Text(s.to_owned(), marks.clone()));
}
}
/// The target title and the shown text of a wiki link's inside. The heading part of
/// the target is dropped, and the text falls back to the target.
fn wikilink_parts(inner: &str) -> Option<(String, String)> {
if inner.contains(['\n', '[', ']']) {
return None;
}
let (target_part, alias) = match inner.split_once('|') {
Some((target, alias)) => (target, Some(alias.trim())),
None => (inner, None),
};
let target = target_part.split('#').next().unwrap_or_default().trim();
if target.is_empty() {
return None;
}
let text = match alias {
Some(alias) if !alias.is_empty() => alias,
_ => target,
};
Some((target.to_owned(), text.to_owned()))
}
#[cfg(test)]
mod tests {
use super::*;
const SAMPLE: &str = r#"# Title
Some **bold**, *italic*, `code` and [link](https://example.com "Example").
- Bullet one
- Nested bullet
- Bullet two
1. First
2. Second
> A quoted line
```rust
fn main() {}
```
---

line one\
line two
"#;
#[test]
fn round_trip_and_front_matter() {
let doc = markdown_to_doc(SAMPLE).unwrap();
assert_eq!(crate::export::to_markdown(&doc), SAMPLE);
let with_front_matter = format!("---\ntitle: Test\ntags: [a]\n---\n\n{SAMPLE}");
let doc = markdown_to_doc(&with_front_matter).unwrap();
assert_eq!(crate::export::to_markdown(&doc), SAMPLE);
let wiki = "See **[[Alpha]]**, [**Be**ta](My%20Beta.md) and [[Gamma|g]].\n";
let doc = markdown_to_doc(wiki).unwrap();
assert_eq!(crate::export::to_markdown_with(&doc, &|_| None), wiki);
// Links by id filled in later read the same as when resolved at once.
let ids = "See [x](/notes/abc), **[y](/notes/def)**, [*m*ix](/notes/abc) and [[Alpha]].\n";
let doc = markdown_to_doc(ids).unwrap();
let titles = |id: &str| (id == "abc").then(|| "Abc Note".to_owned());
let deferred = crate::export::to_markdown_deferred(&doc).unwrap();
assert_eq!(crate::export::resolve_deferred(&deferred, &titles), crate::export::to_markdown_with(&doc, &titles));
}
const LAYOUT_SAMPLE: &str = "# Heading\n\
\n\
Some **bold**, *italic*, `code` and [link](https://example.com).\n\
\n\
- Bullet one\n - Nested bullet\n- Bullet two\n\
\n\
3. Third\n4. Fourth\n\
\n\
> Quoted\n\
\n\
```rust\nfn main() {}\n```\n\
\n\
---\n\
\n\
line one\\\nline two\n";
/// Output of the markdown export before the note-model refactor.
const LAYOUT_EXPECTED: &str = "# Heading\n\nSome **bold**, *italic*, `code` and [link](https://example.com).\n\n- Bullet one\n - Nested bullet\n- Bullet two\n\n3. Third\n4. Fourth\n\n> Quoted\n\n```rust\nfn main() {}\n```\n\n---\n\nline one\\\nline two\n";
#[test]
fn layout_sample_is_stable() {
let doc = markdown_to_doc(LAYOUT_SAMPLE).unwrap();
assert_eq!(crate::export::to_markdown(&doc), LAYOUT_EXPECTED);
}
#[test]
fn media_relative_with_parent_dirs() {
let media = HashMap::from([
("notes/attachments/cat.png".to_owned(), "/media/a1.png".to_owned()),
("notes/doc.pdf".to_owned(), "/media/b2.pdf".to_owned()),
]);
let md = " and [doc](../doc.pdf)\n";
assert_eq!(
rewrite_media(md, "notes/day/note.md", &media),
" and [doc](/media/b2.pdf)\n"
);
}
#[test]
fn media_percent_encoded_and_basename() {
let media = HashMap::from([("photos/My Cat.png".to_owned(), "/media/c3.png".to_owned())]);
let md = " and ![[my cat.png|kitty]]\n";
assert_eq!(
rewrite_media(md, "note.md", &media),
" and \n"
);
}
#[test]
fn media_embeds_skipped_inside_code() {
let media = HashMap::from([("x.png".to_owned(), "/media/d4.png".to_owned())]);
let md = "```\n![[x.png|alias]]\n```\n\n`![[x.png|alias]]`\n\n![[x.png|alias]]\n";
assert_eq!(
rewrite_media(md, "n.md", &media),
"```\n![[x.png|alias]]\n```\n\n`![[x.png|alias]]`\n\n\n"
);
}
}