| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | use std::collections::HashMap; |
| 18 | use std::ops::Range; |
| 19 | |
| 20 | use anyhow::Result; |
| 21 | use loro::{ExportMode, LoroDoc}; |
| 22 | use note_model::links::{percent_decode, percent_encode}; |
| 23 | use note_model::marks::Marks; |
| 24 | use note_model::render::embed_of; |
| 25 | use note_model::schema::text_style_config; |
| 26 | use note_model::flat; |
| 27 | use note_model::write::{Block, Inline}; |
| 28 | use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, LinkType, Options, Parser, Tag, TagEnd}; |
| 29 | |
| 30 | |
| 31 | pub 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 | |
| 40 | pub 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 | |
| 48 | pub 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 | |
| 53 | |
| 54 | pub 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 | |
| 67 | fn options() -> Options { |
| 68 | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TABLES | Options::ENABLE_TASKLISTS |
| 69 | } |
| 70 | |
| 71 | |
| 72 | pub 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 | |
| 78 | |
| 79 | |
| 80 | fn 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 | |
| 95 | pub 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 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | pub 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 | |
| 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 | |
| 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!("") |
| 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 | |
| 217 | |
| 218 | |
| 219 | fn 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 | |
| 234 | fn 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 | |
| 240 | |
| 241 | fn 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 | |
| 272 | fn 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 | |
| 288 | |
| 289 | |
| 290 | |
| 291 | |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | fn 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 | |
| 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 | |
| 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 | |
| 405 | |
| 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 | |
| 431 | Event::Start(_) => { |
| 432 | *pos += 1; |
| 433 | out.extend(parse_blocks(ev, pos, true)); |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 | out |
| 438 | } |
| 439 | |
| 440 | |
| 441 | |
| 442 | fn 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 | |
| 474 | fn 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 | |
| 489 | fn 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 | |
| 496 | |
| 497 | |
| 498 | fn 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 | |
| 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 | |
| 584 | _ => return, |
| 585 | } |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | fn skip_end(ev: &[Event<'_>], pos: &mut usize) { |
| 590 | if matches!(ev.get(*pos), Some(Event::End(_))) { |
| 591 | *pos += 1; |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | fn is_blank(inl: &[Inline]) -> bool { |
| 596 | inl.iter() |
| 597 | .all(|i| matches!(i, Inline::Text(s, _) if s.trim().is_empty())) |
| 598 | } |
| 599 | |
| 600 | fn 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 | |
| 610 | fn 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 | |
| 623 | |
| 624 | |
| 625 | |
| 626 | |
| 627 | fn 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 | |
| 641 | fn wikify_blocks(blocks: &[Block]) -> Vec<Block> { |
| 642 | blocks.iter().map(wikify_block).collect() |
| 643 | } |
| 644 | |
| 645 | fn 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 | |
| 664 | |
| 665 | |
| 666 | fn wikilinks(inl: &[Inline]) -> Vec<Inline> { |
| 667 | |
| 668 | |
| 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 | |
| 692 | fn 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 | |
| 720 | fn 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 | |
| 727 | |
| 728 | fn 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)] |
| 748 | mod tests { |
| 749 | use super::*; |
| 750 | |
| 751 | const SAMPLE: &str = r#"# Title |
| 752 | |
| 753 | Some **bold**, *italic*, `code` and [link](https://example.com "Example"). |
| 754 | |
| 755 | - Bullet one |
| 756 | - Nested bullet |
| 757 | - Bullet two |
| 758 | |
| 759 | 1. First |
| 760 | 2. Second |
| 761 | |
| 762 | > A quoted line |
| 763 | |
| 764 | ```rust |
| 765 | fn main() {} |
| 766 | ``` |
| 767 | |
| 768 | --- |
| 769 | |
| 770 |  |
| 771 | |
| 772 | line one\ |
| 773 | line 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 | |
| 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\ |
| 799 | Some **bold**, *italic*, `code` and [link](https://example.com).\n\ |
| 800 | \n\ |
| 801 | - Bullet one\n - Nested bullet\n- Bullet two\n\ |
| 802 | \n\ |
| 803 | 3. Third\n4. Fourth\n\ |
| 804 | \n\ |
| 805 | > Quoted\n\ |
| 806 | \n\ |
| 807 | ```rust\nfn main() {}\n```\n\ |
| 808 | \n\ |
| 809 | ---\n\ |
| 810 | \n\ |
| 811 | line one\\\nline two\n"; |
| 812 | |
| 813 | |
| 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 = " and [doc](../doc.pdf)\n"; |
| 829 | assert_eq!( |
| 830 | rewrite_media(md, "notes/day/note.md", &media), |
| 831 | " 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 = " and ![[my cat.png|kitty]]\n"; |
| 839 | assert_eq!( |
| 840 | rewrite_media(md, "note.md", &media), |
| 841 | " and \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\n" |
| 852 | ); |
| 853 | } |
| 854 | } |
| 855 | |
| 856 | |
| 857 | |