forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

import.rs857 lines, 29.7 KiBHistoryRawDownload
1//! Markdown import: the inverse of `export.rs`. Parses CommonMark into a
2//! note doc (`note_model::flat`, the layout `export::to_markdown` reads).
3//!
4//! Degradations (GFM bits that the schema cannot represent):
5//! - strikethrough: content kept, no mark
6//! - tables: one paragraph per row, cells joined with " | "
7//! - task list items: normal list items with a "[ ] " / "[x] " text prefix
8//! - raw HTML (block or inline): its text, as plain text
9//! - footnotes: not enabled, so `[^x]` stays literal text
10//! - soft breaks become a space, hard breaks become `hard_break` nodes
11//! - wiki links `[[Title]]`, `[[Title|text]]`, `[[Title#heading]]` in plain text become
12//! links to `/notes/by-title/<Title>`
13//! - local media references (links, images, `![[file]]` embeds) become `/media/...` URLs
14//! when the file was imported with the note (`rewrite_media`); other embeds `![[...]]`
15//! stay plain text
16
17use std::collections::HashMap;
18use std::ops::Range;
19
20use anyhow::Result;
21use loro::{ExportMode, LoroDoc};
22use note_model::links::{percent_decode, percent_encode};
23use note_model::marks::Marks;
24use note_model::render::embed_of;
25use note_model::schema::text_style_config;
26use note_model::flat;
27use note_model::write::{Block, Inline};
28use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, LinkType, Options, Parser, Tag, TagEnd};
29
30/// Parses markdown into a fresh LoroDoc with the note layout.
31pub fn markdown_to_doc(md: &str) -> Result<LoroDoc> {
32 let body = strip_front_matter(md);
33 let events: Vec<Event> = Parser::new_ext(body, options()).collect();
34 let mut pos = 0;
35 let blocks = parse_blocks(&events, &mut pos, false);
36 build(&blocks)
37}
38
39/// The editor's preview markup for the start of a markdown file.
40pub fn preview_markdown(md: &str) -> String {
41 match markdown_to_doc(md) {
42 Ok(doc) => note_model::render::preview_html(&doc, 128, 100_000),
43 Err(_) => String::new(),
44 }
45}
46
47/// Whether the markdown's first block is a heading. Only that block is parsed.
48pub fn starts_with_heading(md: &str) -> bool {
49 matches!(Parser::new_ext(strip_front_matter(md), options()).next(), Some(Event::Start(Tag::Heading { .. })))
50}
51
52/// The title a doc built from `md` gets, when `md` starts with a heading: the
53/// heading's plain text. Only that block is parsed.
54pub fn heading_title(md: &str) -> String {
55 let mut raw = String::new();
56 for event in Parser::new_ext(strip_front_matter(md), options()) {
57 match event {
58 Event::End(TagEnd::Heading(_)) => break,
59 Event::Text(t) | Event::Code(t) => raw.push_str(&t),
60 Event::SoftBreak | Event::HardBreak => raw.push(' '),
61 _ => {}
62 }
63 }
64 note_model::tree::title_from(&raw)
65}
66
67fn options() -> Options {
68 Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TABLES | Options::ENABLE_TASKLISTS
69}
70
71/// Same as `markdown_to_doc`, exported as a full Loro update.
72pub fn markdown_to_update(md: &str) -> Result<Vec<u8>> {
73 let doc = markdown_to_doc(md)?;
74 Ok(doc.export(ExportMode::all_updates())?)
75}
76
77/// A relative link to a `.md` file (`[text](Some%20Note.md)`, also what export writes for
78/// note links with mixed formatting) becomes a link to the note with that file's name.
79/// Any other destination is kept.
80fn note_file_href(dest: &str) -> String {
81 let path = dest.split('#').next().unwrap_or(dest);
82 let relative = !path.contains("://") && !path.starts_with(['/', '?']) && !path.starts_with("mailto:");
83 let Some(stem) = path.strip_suffix(".md").filter(|_| relative) else {
84 return dest.to_string();
85 };
86 let decoded = percent_decode(stem);
87 let title = decoded.rsplit('/').next().unwrap_or(&decoded).trim();
88 if title.is_empty() {
89 return dest.to_string();
90 }
91 format!("/notes/by-title/{}", percent_encode(title))
92}
93
94/// Drops a leading `---` ... `---` YAML block. Unclosed blocks are kept as text.
95pub fn strip_front_matter(md: &str) -> &str {
96 let mut lines = md.split_inclusive('\n');
97 let Some(first) = lines.next() else {
98 return md;
99 };
100 if first.trim_end() != "---" {
101 return md;
102 }
103 let mut offset = first.len();
104 for line in lines {
105 offset += line.len();
106 if line.trim_end() == "---" {
107 return &md[offset..];
108 }
109 }
110 md
111}
112
113/// Rewrites local media references in markdown to their `/media/` URLs. `media` maps a
114/// file path relative to the imported root to its URL, and `note_path` is the markdown
115/// file's own path relative to that root. Inline links and images with a local destination
116/// are rewritten; Obsidian embeds `![[target]]` and `![[target|alias]]` outside code become
117/// an image (or a link, for files that cannot be embedded). Anything that does not resolve
118/// is left as written.
119pub fn rewrite_media(md: &str, note_path: &str, media: &HashMap<String, String>) -> String {
120 if media.is_empty() {
121 return md.to_string();
122 }
123 let note_dir = note_path.rsplit_once('/').map_or("", |(dir, _)| dir);
124 // Lowercase basename to its URL, or None when several files share it.
125 let mut by_name: HashMap<String, Option<&String>> = HashMap::new();
126 for (path, url) in media {
127 let name = path.rsplit('/').next().unwrap_or_default().to_ascii_lowercase();
128 by_name.entry(name).and_modify(|slot| *slot = None).or_insert(Some(url));
129 }
130
131 let mut code: Vec<Range<usize>> = Vec::new();
132 let mut edits: Vec<(Range<usize>, String)> = Vec::new();
133 for (event, range) in Parser::new_ext(md, options()).into_offset_iter() {
134 match event {
135 Event::Start(Tag::CodeBlock(_)) | Event::Code(_) => code.push(range),
136 Event::Start(Tag::Image { link_type: LinkType::Inline, dest_url, .. }) => {
137 let Some(url) = resolve_media(&dest_url, note_dir, media, &by_name) else {
138 continue;
139 };
140 edits.extend(dest_edit(md, &range, &dest_url, url));
141 if embed_of(url).is_none() && md[range.start..].starts_with('!') {
142 edits.push((range.start..range.start + 1, String::new()));
143 }
144 }
145 Event::Start(Tag::Link { link_type: LinkType::Inline, dest_url, .. }) => {
146 if let Some(url) = resolve_media(&dest_url, note_dir, media, &by_name) {
147 edits.extend(dest_edit(md, &range, &dest_url, url));
148 }
149 }
150 _ => {}
151 }
152 }
153
154 // Embeds never contain `[`, `]` or a newline, so one scan per `![[` is enough.
155 let mut at = 0;
156 while let Some(found) = md[at..].find("![[") {
157 let open = at + found;
158 let inner_start = open + 3;
159 if in_ranges(&code, open) {
160 at = inner_start;
161 continue;
162 }
163 let rest = &md[inner_start..];
164 let stop = rest.find(['[', ']', '\n']).unwrap_or(rest.len());
165 if !rest[stop..].starts_with("]]") {
166 at = inner_start;
167 continue;
168 }
169 let inner = &rest[..stop];
170 let end = inner_start + stop + 2;
171 at = end;
172 let (target, alias) = match inner.split_once('|') {
173 Some((target, alias)) => (target, Some(alias.trim())),
174 None => (inner, None),
175 };
176 let Some(url) = resolve_media(target, note_dir, media, &by_name) else {
177 continue;
178 };
179 let file = target.split('#').next().unwrap_or_default().trim().rsplit('/').next().unwrap_or_default();
180 let embeddable = embed_of(url).is_some();
181 let stem = file
182 .rsplit_once('.')
183 .filter(|(stem, _)| !stem.is_empty())
184 .map_or(file, |(stem, _)| stem);
185 let shown = match alias {
186 Some(alias) if !alias.is_empty() => alias,
187 _ if embeddable => stem,
188 _ => file,
189 };
190 let replacement = if embeddable {
191 format!("![{shown}]({url})")
192 } else {
193 format!("[{shown}]({url})")
194 };
195 edits.push((open..end, replacement));
196 }
197
198 if edits.is_empty() {
199 return md.to_string();
200 }
201 edits.sort_by_key(|(range, _)| range.start);
202 let mut out = String::with_capacity(md.len());
203 let mut last = 0;
204 for (range, text) in edits {
205 if range.start < last {
206 continue;
207 }
208 out.push_str(&md[last..range.start]);
209 out.push_str(&text);
210 last = range.end;
211 }
212 out.push_str(&md[last..]);
213 out
214}
215
216/// Finds a link destination inside its event's source and pairs it with the new URL.
217/// The `<...>` brackets go with it when present. None when the destination is not found
218/// literally in the source.
219fn dest_edit(md: &str, range: &Range<usize>, dest: &str, url: &str) -> Option<(Range<usize>, String)> {
220 if dest.is_empty() {
221 return None;
222 }
223 let at = range.start + md[range.clone()].rfind(dest)?;
224 let end = at + dest.len();
225 let angled = at > range.start && md.as_bytes()[at - 1] == b'<' && md.as_bytes().get(end) == Some(&b'>');
226 if angled {
227 Some((at - 1..end + 1, format!("<{url}>")))
228 } else {
229 Some((at..end, url.to_owned()))
230 }
231}
232
233/// Whether `at` falls inside one of the sorted, disjoint ranges.
234fn in_ranges(ranges: &[Range<usize>], at: usize) -> bool {
235 let after = ranges.partition_point(|r| r.start <= at);
236 after > 0 && ranges[after - 1].end > at
237}
238
239/// The `/media/` URL of a local reference, or None. Remote, data, mailto, fragment-only,
240/// already-rewritten and markdown note targets are not media.
241fn resolve_media<'a>(
242 target: &str,
243 note_dir: &str,
244 media: &'a HashMap<String, String>,
245 by_name: &HashMap<String, Option<&'a String>>,
246) -> Option<&'a str> {
247 let target = target.trim();
248 if target.is_empty()
249 || target.contains("://")
250 || target.starts_with("mailto:")
251 || target.starts_with("data:")
252 || target.starts_with('#')
253 || target.starts_with("/media/")
254 {
255 return None;
256 }
257 let path = percent_decode(target.split(['#', '?']).next().unwrap_or_default());
258 if path.is_empty() || path.to_ascii_lowercase().ends_with(".md") {
259 return None;
260 }
261 let joined = normalize(&format!("{note_dir}/{path}"));
262 let rooted = normalize(&path);
263 let name = path.rsplit('/').next().unwrap_or_default().to_ascii_lowercase();
264 media
265 .get(&joined)
266 .or_else(|| media.get(&rooted))
267 .map(String::as_str)
268 .or_else(|| by_name.get(&name).copied().flatten().map(String::as_str))
269}
270
271/// Joins `.` and `..` segments of a forward-slash path. Empty segments are dropped.
272fn normalize(path: &str) -> String {
273 let mut parts: Vec<&str> = Vec::new();
274 for part in path.split('/') {
275 match part {
276 "" | "." => {}
277 ".." => {
278 parts.pop();
279 }
280 _ => parts.push(part),
281 }
282 }
283 parts.join("/")
284}
285
286// ---------------------------------------------------------------------------
287// Intermediate tree
288// ---------------------------------------------------------------------------
289
290// ---------------------------------------------------------------------------
291// Event -> tree
292// ---------------------------------------------------------------------------
293
294/// Parses block events starting at `pos`. In `nested` mode it returns after
295/// consuming the End event of its container.
296fn parse_blocks(ev: &[Event<'_>], pos: &mut usize, nested: bool) -> Vec<Block> {
297 let mut out = Vec::new();
298 while let Some(event) = ev.get(*pos) {
299 match event {
300 Event::End(_) => {
301 *pos += 1;
302 if nested {
303 break;
304 }
305 }
306 Event::Start(Tag::Paragraph) => {
307 *pos += 1;
308 let inl = inlines(ev, pos);
309 skip_end(ev, pos);
310 out.push(Block::Paragraph(inl));
311 }
312 Event::Start(Tag::Heading { level, .. }) => {
313 *pos += 1;
314 let inl = inlines(ev, pos);
315 skip_end(ev, pos);
316 out.push(Block::Heading(heading_level(*level), inl));
317 }
318 Event::Start(Tag::BlockQuote(_)) => {
319 *pos += 1;
320 let inner = parse_blocks(ev, pos, true);
321 out.push(Block::Quote(inner));
322 }
323 Event::Start(Tag::CodeBlock(kind)) => {
324 let lang = match kind {
325 CodeBlockKind::Fenced(info) => {
326 info.split_whitespace().next().map(str::to_owned)
327 }
328 CodeBlockKind::Indented => None,
329 };
330 *pos += 1;
331 let mut text = String::new();
332 while let Some(e) = ev.get(*pos) {
333 *pos += 1;
334 match e {
335 Event::End(_) => break,
336 Event::Text(t) => text.push_str(t),
337 _ => {}
338 }
339 }
340 out.push(Block::Code {
341 lang,
342 text: text.trim_end_matches('\n').to_owned(),
343 });
344 }
345 Event::Start(Tag::HtmlBlock) => {
346 *pos += 1;
347 let mut text = String::new();
348 while let Some(e) = ev.get(*pos) {
349 *pos += 1;
350 match e {
351 Event::End(_) => break,
352 Event::Html(t) | Event::Text(t) => text.push_str(t),
353 _ => {}
354 }
355 }
356 let t = text.trim();
357 if !t.is_empty() {
358 out.push(Block::Paragraph(vec![Inline::Text(
359 t.to_owned(),
360 Marks::default(),
361 )]));
362 }
363 }
364 Event::Start(Tag::List(start)) => {
365 *pos += 1;
366 let mut items = Vec::new();
367 while let Some(e) = ev.get(*pos) {
368 match e {
369 Event::End(_) => {
370 *pos += 1;
371 break;
372 }
373 Event::Start(Tag::Item) => {
374 *pos += 1;
375 let mut blocks = parse_blocks(ev, pos, true);
376 // Schema: list_item content is "paragraph block*".
377 if !matches!(blocks.first(), Some(Block::Paragraph(_))) {
378 blocks.insert(0, Block::Paragraph(Vec::new()));
379 }
380 items.push(blocks);
381 }
382 _ => *pos += 1,
383 }
384 }
385 out.push(Block::List {
386 ordered: start.is_some(),
387 start: (*start).unwrap_or(1) as i64,
388 items,
389 });
390 }
391 Event::Start(Tag::Table(_)) => {
392 *pos += 1;
393 parse_table(ev, pos, &mut out);
394 }
395 Event::Start(Tag::Item) => {
396 // Item outside a list: keep its content.
397 *pos += 1;
398 out.extend(parse_blocks(ev, pos, true));
399 }
400 Event::Rule => {
401 out.push(Block::Rule);
402 *pos += 1;
403 }
404 // Inline content outside a paragraph (tight list items, table-less
405 // loose text): wrap the run in a paragraph.
406 Event::Text(_)
407 | Event::Code(_)
408 | Event::SoftBreak
409 | Event::HardBreak
410 | Event::InlineHtml(_)
411 | Event::Html(_)
412 | Event::TaskListMarker(_)
413 | Event::FootnoteReference(_)
414 | Event::InlineMath(_)
415 | Event::DisplayMath(_)
416 | Event::Start(
417 Tag::Emphasis
418 | Tag::Strong
419 | Tag::Strikethrough
420 | Tag::Superscript
421 | Tag::Subscript
422 | Tag::Link { .. }
423 | Tag::Image { .. },
424 ) => {
425 let inl = inlines(ev, pos);
426 if !is_blank(&inl) {
427 out.push(Block::Paragraph(inl));
428 }
429 }
430 // Unknown containers (footnote definitions, metadata, ...): keep content.
431 Event::Start(_) => {
432 *pos += 1;
433 out.extend(parse_blocks(ev, pos, true));
434 }
435 }
436 }
437 out
438}
439
440/// Tables: each row becomes a paragraph with cells joined by " | ".
441/// Assumes `pos` is just past `Start(Table)`; consumes the table's End.
442fn parse_table(ev: &[Event<'_>], pos: &mut usize, out: &mut Vec<Block>) {
443 while let Some(e) = ev.get(*pos) {
444 match e {
445 Event::End(_) => {
446 *pos += 1;
447 break;
448 }
449 Event::Start(Tag::TableHead | Tag::TableRow) => {
450 *pos += 1;
451 let mut cells = Vec::new();
452 while let Some(c) = ev.get(*pos) {
453 match c {
454 Event::End(_) => {
455 *pos += 1;
456 break;
457 }
458 Event::Start(Tag::TableCell) => {
459 *pos += 1;
460 let mut inl = Vec::new();
461 parse_inlines(ev, pos, &Marks::default(), &mut inl, true);
462 cells.push(inl);
463 }
464 _ => *pos += 1,
465 }
466 }
467 out.extend(table_row(cells));
468 }
469 _ => *pos += 1,
470 }
471 }
472}
473
474fn table_row(cells: Vec<Vec<Inline>>) -> Option<Block> {
475 let mut inl = Vec::new();
476 for (i, cell) in cells.into_iter().enumerate() {
477 if i > 0 {
478 inl.push(Inline::Text(" | ".to_owned(), Marks::default()));
479 }
480 inl.extend(cell);
481 }
482 if is_blank(&inl) {
483 None
484 } else {
485 Some(Block::Paragraph(inl))
486 }
487}
488
489fn inlines(ev: &[Event<'_>], pos: &mut usize) -> Vec<Inline> {
490 let mut out = Vec::new();
491 parse_inlines(ev, pos, &Marks::default(), &mut out, false);
492 out
493}
494
495/// Collects inline content. With `closing`, it also consumes the End event that
496/// closes the current inline span. Without it, it stops before the first
497/// non-inline event (the caller handles that event).
498fn parse_inlines(
499 ev: &[Event<'_>],
500 pos: &mut usize,
501 marks: &Marks,
502 out: &mut Vec<Inline>,
503 closing: bool,
504) {
505 while let Some(event) = ev.get(*pos) {
506 match event {
507 Event::End(_) => {
508 if closing {
509 *pos += 1;
510 }
511 return;
512 }
513 Event::Text(s)
514 | Event::Html(s)
515 | Event::InlineHtml(s)
516 | Event::InlineMath(s)
517 | Event::DisplayMath(s) => {
518 out.push(Inline::Text(s.to_string(), marks.clone()));
519 *pos += 1;
520 }
521 Event::FootnoteReference(s) => {
522 out.push(Inline::Text(format!("[^{s}]"), marks.clone()));
523 *pos += 1;
524 }
525 Event::Code(s) => {
526 let mut m = marks.clone();
527 m.code = true;
528 out.push(Inline::Text(s.to_string(), m));
529 *pos += 1;
530 }
531 Event::SoftBreak => {
532 out.push(Inline::Text(" ".to_owned(), marks.clone()));
533 *pos += 1;
534 }
535 Event::HardBreak => {
536 out.push(Inline::HardBreak);
537 *pos += 1;
538 }
539 Event::TaskListMarker(done) => {
540 let s = if *done { "[x] " } else { "[ ] " };
541 out.push(Inline::Text(s.to_owned(), Marks::default()));
542 *pos += 1;
543 }
544 Event::Start(Tag::Emphasis) => {
545 *pos += 1;
546 let mut m = marks.clone();
547 m.em = true;
548 parse_inlines(ev, pos, &m, out, true);
549 }
550 Event::Start(Tag::Strong) => {
551 *pos += 1;
552 let mut m = marks.clone();
553 m.strong = true;
554 parse_inlines(ev, pos, &m, out, true);
555 }
556 // Degraded: content kept, no mark.
557 Event::Start(Tag::Strikethrough | Tag::Superscript | Tag::Subscript) => {
558 *pos += 1;
559 parse_inlines(ev, pos, marks, out, true);
560 }
561 Event::Start(Tag::Link {
562 dest_url, title, ..
563 }) => {
564 *pos += 1;
565 let mut m = marks.clone();
566 let title = (!title.is_empty()).then(|| title.to_string());
567 m.link = Some((note_file_href(&dest_url), title));
568 parse_inlines(ev, pos, &m, out, true);
569 }
570 Event::Start(Tag::Image {
571 dest_url, title, ..
572 }) => {
573 *pos += 1;
574 let mut alt = Vec::new();
575 parse_inlines(ev, pos, marks, &mut alt, true);
576 let title = (!title.is_empty()).then(|| title.to_string());
577 out.push(Inline::Image {
578 src: dest_url.to_string(),
579 alt: plain(&alt),
580 title,
581 });
582 }
583 // Block-level event: the inline run ends here.
584 _ => return,
585 }
586 }
587}
588
589fn skip_end(ev: &[Event<'_>], pos: &mut usize) {
590 if matches!(ev.get(*pos), Some(Event::End(_))) {
591 *pos += 1;
592 }
593}
594
595fn is_blank(inl: &[Inline]) -> bool {
596 inl.iter()
597 .all(|i| matches!(i, Inline::Text(s, _) if s.trim().is_empty()))
598}
599
600fn plain(inl: &[Inline]) -> String {
601 inl.iter()
602 .map(|i| match i {
603 Inline::Text(s, _) => s.as_str(),
604 Inline::HardBreak => " ",
605 Inline::Image { alt, .. } => alt.as_str(),
606 })
607 .collect()
608}
609
610fn heading_level(level: HeadingLevel) -> i64 {
611 match level {
612 HeadingLevel::H1 => 1,
613 HeadingLevel::H2 => 2,
614 HeadingLevel::H3 => 3,
615 HeadingLevel::H4 => 4,
616 HeadingLevel::H5 => 5,
617 HeadingLevel::H6 => 6,
618 }
619}
620
621// ---------------------------------------------------------------------------
622// Tree -> LoroDoc
623// ---------------------------------------------------------------------------
624
625/// Builds the document. Mirrors `hub::initial_note_update`: an empty input
626/// yields a single empty paragraph.
627fn build(blocks: &[Block]) -> Result<LoroDoc> {
628 let doc = LoroDoc::new();
629 doc.set_peer_id(note_model::write::BUILDER_PEER)?;
630 doc.config_text_style(text_style_config());
631 if blocks.is_empty() {
632 flat::init(&doc)?;
633 } else {
634 flat::write(&flat::body(&doc), 0, &flat::flatten(&wikify_blocks(blocks)), false)?;
635 }
636 doc.commit();
637 Ok(doc)
638}
639
640/// Applies `wikilinks` to every paragraph and heading in the tree.
641fn wikify_blocks(blocks: &[Block]) -> Vec<Block> {
642 blocks.iter().map(wikify_block).collect()
643}
644
645fn wikify_block(block: &Block) -> Block {
646 match block {
647 Block::Paragraph(inl) => Block::Paragraph(wikilinks(inl)),
648 Block::Heading(level, inl) => Block::Heading(*level, wikilinks(inl)),
649 Block::Quote(blocks) => Block::Quote(wikify_blocks(blocks)),
650 Block::List {
651 ordered,
652 start,
653 items,
654 } => Block::List {
655 ordered: *ordered,
656 start: *start,
657 items: items.iter().map(|item| wikify_blocks(item)).collect(),
658 },
659 other => other.clone(),
660 }
661}
662
663/// Turns `[[Title]]`, `[[Title|text]]` and `[[Title#heading]]` in plain text into links
664/// to `/notes/by-title/<Title>`, showing the text (or the title). Code, existing links and
665/// embeds (`![[...]]`, kept as text) are left alone.
666fn wikilinks(inl: &[Inline]) -> Vec<Inline> {
667 // Adjacent runs with the same marks are joined first, since a `[[` can be split
668 // across parser events.
669 let mut merged: Vec<Inline> = Vec::new();
670 for item in inl {
671 if let Inline::Text(s, m) = item {
672 if let Some(Inline::Text(prev, pm)) = merged.last_mut() {
673 if *pm == *m {
674 prev.push_str(s);
675 continue;
676 }
677 }
678 }
679 merged.push(item.clone());
680 }
681
682 let mut out = Vec::with_capacity(merged.len());
683 for item in merged {
684 match item {
685 Inline::Text(s, m) if !m.code && m.link.is_none() => split_wikilinks(&s, &m, &mut out),
686 other => out.push(other),
687 }
688 }
689 out
690}
691
692fn split_wikilinks(s: &str, marks: &Marks, out: &mut Vec<Inline>) {
693 let mut rest = s;
694 while let Some(open) = rest.find("[[") {
695 let after = &rest[open + 2..];
696 let embed = rest[..open].ends_with('!');
697 let parsed = after
698 .find("]]")
699 .and_then(|close| wikilink_parts(&after[..close]).map(|parts| (close, parts)));
700 match parsed {
701 Some((close, (target, text))) if !embed => {
702 push_text(out, &rest[..open], marks);
703 let href = format!("/notes/by-title/{}", percent_encode(&target));
704 let link = Marks {
705 link: Some((href, None)),
706 ..marks.clone()
707 };
708 out.push(Inline::Text(text, link));
709 rest = &after[close + 2..];
710 }
711 _ => {
712 push_text(out, &rest[..open + 2], marks);
713 rest = after;
714 }
715 }
716 }
717 push_text(out, rest, marks);
718}
719
720fn push_text(out: &mut Vec<Inline>, s: &str, marks: &Marks) {
721 if !s.is_empty() {
722 out.push(Inline::Text(s.to_owned(), marks.clone()));
723 }
724}
725
726/// The target title and the shown text of a wiki link's inside. The heading part of
727/// the target is dropped, and the text falls back to the target.
728fn wikilink_parts(inner: &str) -> Option<(String, String)> {
729 if inner.contains(['\n', '[', ']']) {
730 return None;
731 }
732 let (target_part, alias) = match inner.split_once('|') {
733 Some((target, alias)) => (target, Some(alias.trim())),
734 None => (inner, None),
735 };
736 let target = target_part.split('#').next().unwrap_or_default().trim();
737 if target.is_empty() {
738 return None;
739 }
740 let text = match alias {
741 Some(alias) if !alias.is_empty() => alias,
742 _ => target,
743 };
744 Some((target.to_owned(), text.to_owned()))
745}
746
747#[cfg(test)]
748mod tests {
749 use super::*;
750
751 const SAMPLE: &str = r#"# Title
752
753Some **bold**, *italic*, `code` and [link](https://example.com "Example").
754
755- Bullet one
756 - Nested bullet
757- Bullet two
758
7591. First
7602. Second
761
762> A quoted line
763
764```rust
765fn main() {}
766```
767
768---
769
770![A cat](https://example.com/cat.png)
771
772line one\
773line two
774"#;
775
776 #[test]
777 fn round_trip_and_front_matter() {
778 let doc = markdown_to_doc(SAMPLE).unwrap();
779 assert_eq!(crate::export::to_markdown(&doc), SAMPLE);
780
781 let with_front_matter = format!("---\ntitle: Test\ntags: [a]\n---\n\n{SAMPLE}");
782 let doc = markdown_to_doc(&with_front_matter).unwrap();
783 assert_eq!(crate::export::to_markdown(&doc), SAMPLE);
784
785 let wiki = "See **[[Alpha]]**, [**Be**ta](My%20Beta.md) and [[Gamma|g]].\n";
786 let doc = markdown_to_doc(wiki).unwrap();
787 assert_eq!(crate::export::to_markdown_with(&doc, &|_| None), wiki);
788
789 // Links by id filled in later read the same as when resolved at once.
790 let ids = "See [x](/notes/abc), **[y](/notes/def)**, [*m*ix](/notes/abc) and [[Alpha]].\n";
791 let doc = markdown_to_doc(ids).unwrap();
792 let titles = |id: &str| (id == "abc").then(|| "Abc Note".to_owned());
793 let deferred = crate::export::to_markdown_deferred(&doc).unwrap();
794 assert_eq!(crate::export::resolve_deferred(&deferred, &titles), crate::export::to_markdown_with(&doc, &titles));
795 }
796
797 const LAYOUT_SAMPLE: &str = "# Heading\n\
798\n\
799Some **bold**, *italic*, `code` and [link](https://example.com).\n\
800\n\
801- Bullet one\n - Nested bullet\n- Bullet two\n\
802\n\
8033. Third\n4. Fourth\n\
804\n\
805> Quoted\n\
806\n\
807```rust\nfn main() {}\n```\n\
808\n\
809---\n\
810\n\
811line one\\\nline two\n";
812
813 /// Output of the markdown export before the note-model refactor.
814 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";
815
816 #[test]
817 fn layout_sample_is_stable() {
818 let doc = markdown_to_doc(LAYOUT_SAMPLE).unwrap();
819 assert_eq!(crate::export::to_markdown(&doc), LAYOUT_EXPECTED);
820 }
821
822 #[test]
823 fn media_relative_with_parent_dirs() {
824 let media = HashMap::from([
825 ("notes/attachments/cat.png".to_owned(), "/media/a1.png".to_owned()),
826 ("notes/doc.pdf".to_owned(), "/media/b2.pdf".to_owned()),
827 ]);
828 let md = "![cat](../attachments/cat.png) and [doc](../doc.pdf)\n";
829 assert_eq!(
830 rewrite_media(md, "notes/day/note.md", &media),
831 "![cat](/media/a1.png) and [doc](/media/b2.pdf)\n"
832 );
833 }
834
835 #[test]
836 fn media_percent_encoded_and_basename() {
837 let media = HashMap::from([("photos/My Cat.png".to_owned(), "/media/c3.png".to_owned())]);
838 let md = "![cat](My%20Cat.png) and ![[my cat.png|kitty]]\n";
839 assert_eq!(
840 rewrite_media(md, "note.md", &media),
841 "![cat](/media/c3.png) and ![kitty](/media/c3.png)\n"
842 );
843 }
844
845 #[test]
846 fn media_embeds_skipped_inside_code() {
847 let media = HashMap::from([("x.png".to_owned(), "/media/d4.png".to_owned())]);
848 let md = "```\n![[x.png|alias]]\n```\n\n`![[x.png|alias]]`\n\n![[x.png|alias]]\n";
849 assert_eq!(
850 rewrite_media(md, "n.md", &media),
851 "```\n![[x.png|alias]]\n```\n\n`![[x.png|alias]]`\n\n![alias](/media/d4.png)\n"
852 );
853 }
854}
855
856
857