| 1 | |
| 2 | |
| 3 | use loro::LoroDoc; |
| 4 | use note_model::links::{link_target, percent_encode}; |
| 5 | use note_model::marks::Marks; |
| 6 | use note_model::write::{Block, Inline}; |
| 7 | |
| 8 | pub use note_model::links::{LinkTarget, note_links}; |
| 9 | pub use note_model::tree::title; |
| 10 | |
| 11 | mod html; |
| 12 | pub use html::{html_page, to_html}; |
| 13 | |
| 14 | |
| 15 | pub type Resolve<'a> = &'a dyn Fn(&str) -> Option<String>; |
| 16 | |
| 17 | |
| 18 | |
| 19 | #[derive(Clone, Copy)] |
| 20 | struct Ctx<'a> { |
| 21 | wiki: Option<Resolve<'a>>, |
| 22 | |
| 23 | deferred: Option<&'a std::cell::Cell<usize>>, |
| 24 | } |
| 25 | |
| 26 | |
| 27 | |
| 28 | const DEFER_START: char = '\u{FDD0}'; |
| 29 | const DEFER_SEP: char = '\u{FDD1}'; |
| 30 | const DEFER_END: char = '\u{FDD2}'; |
| 31 | |
| 32 | |
| 33 | |
| 34 | pub fn to_markdown(doc: &LoroDoc) -> String { |
| 35 | Body::read(doc).markdown() |
| 36 | } |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | pub fn to_markdown_with(doc: &LoroDoc, resolve: Resolve<'_>) -> String { |
| 42 | Body::read(doc).markdown_with(resolve) |
| 43 | } |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | pub fn to_markdown_deferred(doc: &LoroDoc) -> Option<String> { |
| 49 | Body::read(doc).markdown_deferred() |
| 50 | } |
| 51 | |
| 52 | |
| 53 | |
| 54 | pub struct Body { |
| 55 | blocks: Vec<note_model::flat::FlatBlock>, |
| 56 | links: Vec<LinkTarget>, |
| 57 | } |
| 58 | |
| 59 | |
| 60 | |
| 61 | pub fn title_of(doc: &LoroDoc) -> String { |
| 62 | const START: usize = 64 << 10; |
| 63 | let text = note_model::flat::body(doc); |
| 64 | let len = text.len_unicode(); |
| 65 | if len > START { |
| 66 | if let Ok(delta) = text.slice_delta(0, START, loro::cursor::PosType::Unicode) { |
| 67 | let mut blocks = note_model::flat::read_delta(delta); |
| 68 | blocks.pop(); |
| 69 | if let Some(b) = blocks.iter().find(|b| b.attrs.kind.is_text() && !b.plain().trim().is_empty()) { |
| 70 | return note_model::tree::title_from(&b.plain()); |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | Body::read(doc).title() |
| 75 | } |
| 76 | |
| 77 | impl Body { |
| 78 | pub fn read(doc: &LoroDoc) -> Body { |
| 79 | let delta = note_model::flat::body(doc).to_delta(); |
| 80 | let links = note_model::links::links_in(&delta); |
| 81 | Body { blocks: note_model::flat::read_delta(delta), links } |
| 82 | } |
| 83 | |
| 84 | |
| 85 | pub fn title(&self) -> String { |
| 86 | let first = self.blocks.iter().find(|b| b.attrs.kind.is_text() && !b.plain().trim().is_empty()); |
| 87 | note_model::tree::title_from(&first.map(|b| b.plain()).unwrap_or_default()) |
| 88 | } |
| 89 | |
| 90 | |
| 91 | pub fn note_links(&self) -> Vec<LinkTarget> { |
| 92 | self.links.clone() |
| 93 | } |
| 94 | |
| 95 | |
| 96 | pub fn markdown(&self) -> String { |
| 97 | self.render(Ctx { wiki: None, deferred: None }) |
| 98 | } |
| 99 | |
| 100 | |
| 101 | pub fn markdown_with(&self, resolve: Resolve<'_>) -> String { |
| 102 | self.render(Ctx { wiki: Some(resolve), deferred: None }) |
| 103 | } |
| 104 | |
| 105 | |
| 106 | pub fn markdown_deferred(&self) -> Option<String> { |
| 107 | let count = std::cell::Cell::new(0); |
| 108 | let none = |_: &str| None; |
| 109 | let md = self.render(Ctx { wiki: Some(&none), deferred: Some(&count) }); |
| 110 | let marks = |c: char| md.chars().filter(|&x| x == c).count(); |
| 111 | let n = count.get(); |
| 112 | (marks(DEFER_START) == n && marks(DEFER_END) == n && marks(DEFER_SEP) == 4 * n).then_some(md) |
| 113 | } |
| 114 | |
| 115 | |
| 116 | pub fn html(&self) -> String { |
| 117 | html::render_blocks(¬e_model::flat::nest(&self.blocks)) |
| 118 | } |
| 119 | |
| 120 | fn render(&self, cx: Ctx<'_>) -> String { |
| 121 | let body = render_blocks(¬e_model::flat::nest(&self.blocks), false, cx); |
| 122 | if body.is_empty() { String::new() } else { format!("{body}\n") } |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | |
| 127 | |
| 128 | pub fn resolve_deferred(md: &str, resolve: Resolve<'_>) -> String { |
| 129 | let mut out = String::with_capacity(md.len()); |
| 130 | let mut rest = md; |
| 131 | while let Some(at) = rest.find(DEFER_START) { |
| 132 | out.push_str(&rest[..at]); |
| 133 | let after = &rest[at + DEFER_START.len_utf8()..]; |
| 134 | let end = after.find(DEFER_END).unwrap_or(after.len()); |
| 135 | let mut fields = after[..end].split(DEFER_SEP); |
| 136 | let mut next = || fields.next().unwrap_or(""); |
| 137 | let (id, core, flags, inner, dest) = (next(), next(), next(), next(), next()); |
| 138 | out.push_str(&deferred_link(resolve(id), core, flags, inner, dest)); |
| 139 | rest = after.get(end + DEFER_END.len_utf8()..).unwrap_or(""); |
| 140 | } |
| 141 | out.push_str(rest); |
| 142 | out |
| 143 | } |
| 144 | |
| 145 | |
| 146 | fn deferred_link(target: Option<String>, core: &str, flags: &str, inner: &str, dest: &str) -> String { |
| 147 | let Some(target) = target else { return format!("[{inner}]({dest})") }; |
| 148 | if flags.contains('u') { |
| 149 | if let Some(mut link) = wiki_link(&target, core) { |
| 150 | if flags.contains('e') { |
| 151 | link = format!("*{link}*"); |
| 152 | } |
| 153 | if flags.contains('s') { |
| 154 | link = format!("**{link}**"); |
| 155 | } |
| 156 | return link; |
| 157 | } |
| 158 | } |
| 159 | format!("[{inner}]({})", percent_encode(&format!("{target}.md"))) |
| 160 | } |
| 161 | |
| 162 | |
| 163 | |
| 164 | fn wiki_target(href: &str, cx: Ctx<'_>) -> Option<String> { |
| 165 | let resolve = cx.wiki?; |
| 166 | match link_target(href)? { |
| 167 | LinkTarget::Title(title) => Some(title), |
| 168 | LinkTarget::Id(id) => resolve(&id), |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | |
| 173 | |
| 174 | fn wiki_link(target: &str, text: &str) -> Option<String> { |
| 175 | let reserved = |s: &str| s.contains(['[', ']', '|', '#', '\n']); |
| 176 | if target.trim().is_empty() || reserved(target) || reserved(text) { |
| 177 | return None; |
| 178 | } |
| 179 | if text == target { |
| 180 | Some(format!("[[{target}]]")) |
| 181 | } else { |
| 182 | Some(format!("[[{target}|{text}]]")) |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | fn render_blocks(blocks: &[Block], tight: bool, cx: Ctx<'_>) -> String { |
| 194 | let mut out = String::new(); |
| 195 | let mut first = true; |
| 196 | for b in blocks { |
| 197 | let Some(s) = render_block(b, cx) else { continue }; |
| 198 | if !first { |
| 199 | out.push_str(if tight && matches!(b, Block::List { .. }) { "\n" } else { "\n\n" }); |
| 200 | } |
| 201 | first = false; |
| 202 | out.push_str(&s); |
| 203 | } |
| 204 | out |
| 205 | } |
| 206 | |
| 207 | fn render_block(block: &Block, cx: Ctx<'_>) -> Option<String> { |
| 208 | let out = match block { |
| 209 | Block::Paragraph(inl) => paragraph_text(inline(inl, cx)), |
| 210 | Block::Heading(level, inl) => { |
| 211 | let level = (*level).clamp(1, 6) as usize; |
| 212 | let text = inline(inl, cx).replace('\n', " "); |
| 213 | let text = text.trim(); |
| 214 | if text.is_empty() { |
| 215 | String::new() |
| 216 | } else { |
| 217 | format!("{} {}", "#".repeat(level), text) |
| 218 | } |
| 219 | } |
| 220 | Block::Quote(inner) => render_blocks(inner, false, cx) |
| 221 | .lines() |
| 222 | .map(|l| { |
| 223 | if l.is_empty() { |
| 224 | ">".to_string() |
| 225 | } else { |
| 226 | format!("> {l}") |
| 227 | } |
| 228 | }) |
| 229 | .collect::<Vec<_>>() |
| 230 | .join("\n"), |
| 231 | Block::Code { lang, text } => code_block(lang.as_deref(), text), |
| 232 | Block::Rule => "---".to_string(), |
| 233 | Block::List { ordered, start, items } => render_list(items, *ordered, *start, cx), |
| 234 | }; |
| 235 | |
| 236 | if out.trim().is_empty() { |
| 237 | None |
| 238 | } else { |
| 239 | Some(out.trim_end().to_string()) |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | fn render_list(list: &[Vec<Block>], ordered: bool, start: i64, cx: Ctx<'_>) -> String { |
| 244 | let start = if ordered { start } else { 1 }; |
| 245 | let mut items = Vec::new(); |
| 246 | for (index, item) in list.iter().enumerate() { |
| 247 | let marker = if ordered { |
| 248 | format!("{}. ", start + index as i64) |
| 249 | } else { |
| 250 | "- ".to_string() |
| 251 | }; |
| 252 | |
| 253 | let body = render_blocks(item, true, cx); |
| 254 | if body.is_empty() { |
| 255 | items.push(marker.trim_end().to_string()); |
| 256 | continue; |
| 257 | } |
| 258 | let pad = " ".repeat(marker.len()); |
| 259 | let mut lines = body.lines(); |
| 260 | let mut text = format!("{marker}{}", lines.next().unwrap_or("")); |
| 261 | for line in lines { |
| 262 | text.push('\n'); |
| 263 | if !line.is_empty() { |
| 264 | text.push_str(&pad); |
| 265 | text.push_str(line); |
| 266 | } |
| 267 | } |
| 268 | items.push(text); |
| 269 | } |
| 270 | items.join("\n") |
| 271 | } |
| 272 | |
| 273 | fn code_block(lang: Option<&str>, content: &str) -> String { |
| 274 | let content = content.trim_end_matches('\n'); |
| 275 | let fence = "`".repeat((longest_backtick_run(content) + 1).max(3)); |
| 276 | |
| 277 | let lang = lang |
| 278 | .filter(|l| !l.trim().is_empty()) |
| 279 | .or_else(|| note_model::lang::detect(content)) |
| 280 | .unwrap_or_default(); |
| 281 | if content.is_empty() { |
| 282 | format!("{fence}{lang}\n{fence}") |
| 283 | } else { |
| 284 | format!("{fence}{lang}\n{content}\n{fence}") |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | fn longest_backtick_run(s: &str) -> usize { |
| 289 | let mut best = 0; |
| 290 | let mut cur = 0; |
| 291 | for c in s.chars() { |
| 292 | if c == '`' { |
| 293 | cur += 1; |
| 294 | best = best.max(cur); |
| 295 | } else { |
| 296 | cur = 0; |
| 297 | } |
| 298 | } |
| 299 | best |
| 300 | } |
| 301 | |
| 302 | |
| 303 | |
| 304 | fn paragraph_text(inline: String) -> String { |
| 305 | inline |
| 306 | .trim() |
| 307 | .split('\n') |
| 308 | .map(escape_line_start) |
| 309 | .collect::<Vec<_>>() |
| 310 | .join("\n") |
| 311 | } |
| 312 | |
| 313 | fn escape_line_start(line: &str) -> String { |
| 314 | let mut chars = line.chars(); |
| 315 | match chars.next() { |
| 316 | Some('>') => format!("\\>{}", chars.as_str()), |
| 317 | Some('-') | Some('+') => { |
| 318 | let next = line.chars().nth(1); |
| 319 | if next.is_none() || next == Some(' ') || next == Some('-') { |
| 320 | format!("\\{line}") |
| 321 | } else { |
| 322 | line.to_string() |
| 323 | } |
| 324 | } |
| 325 | Some('#') => { |
| 326 | let hashes = line.chars().take_while(|&c| c == '#').count(); |
| 327 | let after = line.chars().nth(hashes); |
| 328 | if (1..=6).contains(&hashes) && (after.is_none() || after == Some(' ')) { |
| 329 | format!("\\{line}") |
| 330 | } else { |
| 331 | line.to_string() |
| 332 | } |
| 333 | } |
| 334 | Some(c) if c.is_ascii_digit() => { |
| 335 | let digits = line.chars().take_while(|c| c.is_ascii_digit()).count(); |
| 336 | let rest = &line[digits..]; |
| 337 | if rest.starts_with('.') || rest.starts_with(')') { |
| 338 | format!("{}\\{}", &line[..digits], rest) |
| 339 | } else { |
| 340 | line.to_string() |
| 341 | } |
| 342 | } |
| 343 | _ => line.to_string(), |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | fn inline(inl: &[Inline], cx: Ctx<'_>) -> String { |
| 354 | let mut out = String::new(); |
| 355 | let mut runs: Vec<(String, Marks)> = Vec::new(); |
| 356 | for i in inl { |
| 357 | match i { |
| 358 | Inline::Text(s, m) => match runs.last_mut() { |
| 359 | Some((t, last)) if last == m => t.push_str(s), |
| 360 | _ => runs.push((s.clone(), m.clone())), |
| 361 | }, |
| 362 | Inline::HardBreak => { |
| 363 | out.push_str(&text_runs(&std::mem::take(&mut runs), cx)); |
| 364 | out.push_str("\\\n"); |
| 365 | } |
| 366 | Inline::Image { src, alt, title } => { |
| 367 | out.push_str(&text_runs(&std::mem::take(&mut runs), cx)); |
| 368 | out.push_str(&image_md(src, alt, title.as_deref())); |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | out.push_str(&text_runs(&runs, cx)); |
| 373 | out |
| 374 | } |
| 375 | |
| 376 | |
| 377 | |
| 378 | fn text_runs(runs: &[(String, Marks)], cx: Ctx<'_>) -> String { |
| 379 | let mut out = String::new(); |
| 380 | let mut i = 0; |
| 381 | while i < runs.len() { |
| 382 | let mut j = i + 1; |
| 383 | if runs[i].1.link.is_some() { |
| 384 | while j < runs.len() && runs[j].1.link == runs[i].1.link { |
| 385 | j += 1; |
| 386 | } |
| 387 | } |
| 388 | out.push_str(&render_group(&runs[i..j], cx)); |
| 389 | i = j; |
| 390 | } |
| 391 | out |
| 392 | } |
| 393 | |
| 394 | fn render_group(group: &[(String, Marks)], cx: Ctx<'_>) -> String { |
| 395 | let Some((href, title)) = group[0].1.link.clone() else { |
| 396 | return render_marks(&group[0].0, &group[0].1); |
| 397 | }; |
| 398 | let text: String = group.iter().map(|(s, _)| s.as_str()).collect(); |
| 399 | let core = text.trim(); |
| 400 | if core.is_empty() || href.is_empty() { |
| 401 | return group.iter().map(|(s, m)| render_marks(s, m)).collect(); |
| 402 | } |
| 403 | let lead = &text[..text.len() - text.trim_start().len()]; |
| 404 | let trail = &text[lead.len() + core.len()..]; |
| 405 | |
| 406 | let first = &group[0].1; |
| 407 | |
| 408 | let uniform = !first.code && group.iter().all(|(_, m)| m.strong == first.strong && m.em == first.em); |
| 409 | if let (Some(count), Some(LinkTarget::Id(id))) = (cx.deferred, link_target(&href)) { |
| 410 | count.set(count.get() + 1); |
| 411 | let inner: String = group.iter().map(|(s, m)| render_marks(s, m)).collect(); |
| 412 | let flags = [(uniform, 'u'), (first.em, 'e'), (first.strong, 's')].iter().filter(|f| f.0).map(|f| f.1).collect::<String>(); |
| 413 | let dest = link_dest(&href, title.as_deref()); |
| 414 | return format!( |
| 415 | "{lead}{DEFER_START}{id}{DEFER_SEP}{core}{DEFER_SEP}{flags}{DEFER_SEP}{}{DEFER_SEP}{dest}{DEFER_END}{trail}", |
| 416 | inner.trim() |
| 417 | ); |
| 418 | } |
| 419 | if let Some(target) = wiki_target(&href, cx) { |
| 420 | if uniform { |
| 421 | if let Some(mut link) = wiki_link(&target, core) { |
| 422 | if first.em { |
| 423 | link = format!("*{link}*"); |
| 424 | } |
| 425 | if first.strong { |
| 426 | link = format!("**{link}**"); |
| 427 | } |
| 428 | return format!("{lead}{link}{trail}"); |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | let inner: String = group.iter().map(|(s, m)| render_marks(s, m)).collect(); |
| 433 | let file = percent_encode(&format!("{target}.md")); |
| 434 | return format!("{lead}[{}]({file}){trail}", inner.trim()); |
| 435 | } |
| 436 | |
| 437 | let inner: String = group.iter().map(|(s, m)| render_marks(s, m)).collect(); |
| 438 | format!( |
| 439 | "{lead}[{}]({}){trail}", |
| 440 | inner.trim(), |
| 441 | link_dest(&href, title.as_deref()) |
| 442 | ) |
| 443 | } |
| 444 | |
| 445 | |
| 446 | fn render_marks(s: &str, m: &Marks) -> String { |
| 447 | let core = s.trim(); |
| 448 | if core.is_empty() { |
| 449 | return s.to_string(); |
| 450 | } |
| 451 | |
| 452 | let lead_len = s.len() - s.trim_start().len(); |
| 453 | let lead = &s[..lead_len]; |
| 454 | let trail = &s[lead_len + core.len()..]; |
| 455 | |
| 456 | let mut out = if m.code { |
| 457 | code_span(core) |
| 458 | } else { |
| 459 | escape_text(core) |
| 460 | }; |
| 461 | if m.em { |
| 462 | out = format!("*{out}*"); |
| 463 | } |
| 464 | if m.strong { |
| 465 | out = format!("**{out}**"); |
| 466 | } |
| 467 | format!("{lead}{out}{trail}") |
| 468 | } |
| 469 | |
| 470 | |
| 471 | |
| 472 | fn escape_text(s: &str) -> String { |
| 473 | let chars: Vec<char> = s.chars().collect(); |
| 474 | let mut out = String::with_capacity(s.len()); |
| 475 | for (i, &c) in chars.iter().enumerate() { |
| 476 | let escape = match c { |
| 477 | '\\' | '`' | '*' | '[' | ']' | '<' | '~' => true, |
| 478 | '_' => { |
| 479 | let prev = i.checked_sub(1).map(|p| chars[p]); |
| 480 | let next = chars.get(i + 1).copied(); |
| 481 | !(prev.is_some_and(char::is_alphanumeric) && next.is_some_and(char::is_alphanumeric)) |
| 482 | } |
| 483 | _ => false, |
| 484 | }; |
| 485 | if escape { |
| 486 | out.push('\\'); |
| 487 | } |
| 488 | out.push(c); |
| 489 | } |
| 490 | out |
| 491 | } |
| 492 | |
| 493 | fn code_span(s: &str) -> String { |
| 494 | let fence = "`".repeat(longest_backtick_run(s) + 1); |
| 495 | let pad = if s.starts_with('`') || s.ends_with('`') { |
| 496 | " " |
| 497 | } else { |
| 498 | "" |
| 499 | }; |
| 500 | format!("{fence}{pad}{s}{pad}{fence}") |
| 501 | } |
| 502 | |
| 503 | fn link_dest(href: &str, title: Option<&str>) -> String { |
| 504 | let dest = if href.chars().any(|c| c.is_whitespace() || c == '(' || c == ')') { |
| 505 | format!("<{}>", href.replace('<', "\\<").replace('>', "\\>")) |
| 506 | } else { |
| 507 | href.to_string() |
| 508 | }; |
| 509 | match title.filter(|t| !t.is_empty()) { |
| 510 | Some(t) => format!( |
| 511 | "{dest} \"{}\"", |
| 512 | t.replace('\\', "\\\\").replace('"', "\\\"") |
| 513 | ), |
| 514 | None => dest, |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | fn image_md(src: &str, alt: &str, title: Option<&str>) -> String { |
| 519 | if src.is_empty() { |
| 520 | return escape_text(alt); |
| 521 | } |
| 522 | let alt = alt |
| 523 | .replace('\\', "\\\\") |
| 524 | .replace('[', "\\[") |
| 525 | .replace(']', "\\]"); |
| 526 | let title = title.filter(|t| !t.is_empty()); |
| 527 | format!("", link_dest(src, title)) |
| 528 | } |