1use std::collections::HashSet;
77
78use nostr_sdk::prelude::Url;
79
80#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
82pub struct Style {
83 pub bold: bool,
84 pub italic: bool,
86 pub strike: bool,
88 pub code: bool,
90 pub quiet: bool,
92 pub heading: u8,
94}
95
96impl Style {
97 pub fn is_plain(&self) -> bool {
99 *self == Self::default()
100 }
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
105pub enum Run {
106 Text { text: String, style: Style },
109 Code { text: String, style: Style },
111 Link { url: Url, label: String },
113 Block(Block<Vec<Run>>),
116}
117
118#[derive(Debug, Clone, PartialEq, Eq)]
121pub enum Block<Cell> {
122 Code(String),
124 Rule,
126 Table(Table<Cell>),
127}
128
129#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct Table<Cell> {
133 pub columns: Vec<Align>,
134 pub rows: Vec<Vec<Cell>>,
135}
136
137#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
139pub enum Align {
140 #[default]
141 Left,
142 Middle,
143 Right,
144}
145
146impl<Cell> Block<Cell> {
147 pub fn map<Other>(self, mut read: impl FnMut(Cell) -> Other) -> Block<Other> {
149 match self {
150 Self::Code(code) => Block::Code(code),
151 Self::Rule => Block::Rule,
152 Self::Table(Table { columns, rows }) => Block::Table(Table {
153 columns,
154 rows: rows.into_iter().map(|row| row.into_iter().map(&mut read).collect()).collect(),
155 }),
156 }
157 }
158}
159
160const QUOTE_BAR: &str = "\u{258e} ";
162
163const ITEM_DOT: &str = "\u{2022} ";
166const ITEM_TO_DO: &str = "\u{2610} ";
167const ITEM_DONE: &str = "\u{2611} ";
168
169const TABLE_MAX_CELLS: usize = 2_000;
171
172const MAX_DEPTH: usize = 6;
175
176const LINK_PART_MAX_CHARS: usize = 2048;
180
181const OPENING: &str = "([{\"'\u{201c}\u{2018}\u{ab}\u{2013}\u{2014}";
184
185const CLOSING: &str = ".,!?;:)]}\"'\u{201d}\u{2019}\u{bb}\u{2026}\u{2013}\u{2014}";
188
189const AFTER_ADDRESS: &str = ".,;:!?)]}";
191
192fn unspaced(c: char) -> bool {
195 matches!(u32::from(c), 0x3000..=0x30ff | 0x3400..=0x4dbf | 0x4e00..=0x9fff | 0xac00..=0xd7af | 0xff00..=0xffef | 0x2_0000..=0x2_ffff)
196}
197
198fn of_a_word(c: char) -> bool {
201 c.is_alphanumeric() && !unspaced(c)
202}
203
204fn is_mark(c: char) -> bool {
207 matches!(c, '*' | '_' | '~' | '`' | '[' | ']' | '|')
208}
209
210fn stress(c: char, count: usize, style: Style) -> Option<Style> {
212 match (c, count) {
213 ('*' | '_', 1) => Some(Style { italic: true, ..style }),
214 ('*' | '_', 2) => Some(Style { bold: true, ..style }),
215 ('*' | '_', 3) => Some(Style { bold: true, italic: true, ..style }),
216 ('~', 2) => Some(Style { strike: true, ..style }),
217 _ => None,
218 }
219}
220
221#[derive(Default)]
224struct Runs(Vec<Run>);
225
226impl Runs {
227 fn text(&mut self, text: &str, style: Style) {
228 if text.is_empty() {
229 return;
230 }
231 match self.0.last_mut() {
232 Some(Run::Text { text: last, style: same }) if *same == style => last.push_str(text),
233 _ => self.0.push(Run::Text { text: text.to_string(), style }),
234 }
235 }
236
237 fn code(&mut self, text: &str, style: Style) {
238 if !text.is_empty() {
239 self.0.push(Run::Code { text: text.to_string(), style: Style { code: true, ..style } });
240 }
241 }
242
243 fn block(&mut self, block: Block<Vec<Run>>) {
246 while let Some(Run::Text { text, .. }) = self.0.last_mut() {
247 text.truncate(text.trim_end().len());
248 if !text.is_empty() {
249 break;
250 }
251 self.0.pop();
252 }
253 self.0.push(Run::Block(block));
254 }
255
256 fn said(self) -> String {
258 self.0
259 .into_iter()
260 .map(|run| match run {
261 Run::Text { text, .. } | Run::Code { text, .. } => text,
262 Run::Link { label, .. } => label,
263 Run::Block(_) => String::new(),
264 })
265 .collect()
266 }
267}
268
269struct Inline<'a> {
271 text: &'a str,
272 chars: Vec<(usize, char)>,
274 missing: HashSet<(char, usize)>,
277}
278
279impl<'a> Inline<'a> {
280 fn new(text: &'a str) -> Self {
281 Self { text, chars: text.char_indices().collect(), missing: HashSet::new() }
282 }
283
284 fn char(&self, at: usize) -> Option<char> {
286 self.chars.get(at).map(|(_, c)| *c)
287 }
288
289 fn slice(&self, from: usize, to: usize) -> &'a str {
291 let byte = |at: usize| self.chars.get(at).map_or(self.text.len(), |(byte, _)| *byte);
292 self.text.get(byte(from)..byte(to)).unwrap_or_default()
293 }
294
295 fn run(&self, at: usize) -> usize {
297 let c = self.char(at);
298 (at..).take_while(|next| c.is_some() && self.char(*next) == c).count()
299 }
300
301 fn escapes(&self, at: usize) -> bool {
303 self.char(at) == Some('\\') && self.char(at + 1).is_some_and(is_mark)
304 }
305
306 fn escape_goes(&self, at: usize) -> bool {
310 let lettered = |at: Option<usize>| at.and_then(|at| self.char(at)).is_some_and(char::is_alphanumeric);
311 self.char(at + 1) != Some('_') || lettered(at.checked_sub(1)) || lettered(Some(at + 2))
312 }
313
314 fn angled(&self, at: usize, style: Style) -> Option<(Run, usize)> {
318 let end =
319 (at + 1..at + LINK_PART_MAX_CHARS).find(|at| self.char(*at).is_none_or(|c| c == '>' || c == '<' || c == '\n'))?;
320 if self.char(end) != Some('>') {
321 return None;
322 }
323 let inside = self.slice(at + 1, end);
324 if matches!(inside.to_ascii_lowercase().as_str(), "br" | "br/" | "br /") {
325 return Some((Run::Text { text: "\n".to_string(), style }, end + 1));
326 }
327 let address = (inside.starts_with("https://") || inside.starts_with("http://")) && !inside.contains(char::is_whitespace);
328 address.then(|| (Run::Text { text: inside.to_string(), style }, end + 1))
329 }
330
331 fn address_end(&self, colon: usize) -> Option<usize> {
335 let scheme = colon.checked_sub(1).and_then(|before| self.char(before)).is_some_and(|c| c.is_ascii_alphanumeric());
336 if !scheme || self.char(colon + 1) != Some('/') || self.char(colon + 2) != Some('/') {
337 return None;
338 }
339 let ends = |c: char| c.is_whitespace() || !c.is_ascii() || matches!(c, '`' | '<' | '>' | '"');
340 Some((colon + 3..).find(|at| self.char(*at).is_none_or(ends)).unwrap_or(self.chars.len()))
341 }
342
343 fn closed_by_address(&self, colon: usize, end: usize, mark: char, count: usize) -> Option<usize> {
347 let mut last = end;
348 while last > colon && self.char(last - 1).is_some_and(|c| AFTER_ADDRESS.contains(c)) {
349 last -= 1;
350 }
351 let at = last.checked_sub(count).filter(|at| *at > colon + 2)?;
352 let marks = (at..last).all(|each| self.char(each) == Some(mark));
353 (marks && self.char(at - 1) != Some(mark)).then_some(at)
354 }
355
356 fn code(&mut self, at: usize) -> Option<(usize, usize)> {
361 let count = self.run(at);
362 let inside = at.checked_sub(1).and_then(|before| self.char(before)).is_some_and(of_a_word);
363 if inside || self.missing.contains(&('`', count)) {
364 return None;
365 }
366 let mut next = at + count;
367 while let Some(c) = self.char(next) {
368 if c != '`' {
369 next += 1;
370 continue;
371 }
372 let ticks = self.run(next);
373 if ticks == count && !self.char(next + ticks).is_some_and(of_a_word) {
374 return Some((count, next));
375 }
376 next += ticks;
377 }
378 self.missing.insert(('`', count));
379 None
380 }
381
382 fn opens(&self, at: usize, count: usize) -> bool {
385 let before = at.checked_sub(1).and_then(|before| self.char(before));
386 let after = self.char(at + count);
387 before.is_none_or(|c| c.is_whitespace() || OPENING.contains(c) || unspaced(c))
388 && after.is_some_and(|c| !c.is_whitespace())
389 }
390
391 fn closes(&self, at: usize, count: usize) -> bool {
394 let before = at.checked_sub(1).and_then(|before| self.char(before));
395 let after = self.char(at + count);
396 before.is_some_and(|c| !c.is_whitespace())
397 && after.is_none_or(|c| c.is_whitespace() || CLOSING.contains(c) || unspaced(c))
398 }
399
400 fn stress_end(&mut self, at: usize, mark: char, count: usize) -> Option<usize> {
403 if self.missing.contains(&(mark, count)) {
404 return None;
405 }
406 let mut next = at + count;
407 while let Some(c) = self.char(next) {
408 match c {
409 '\\' if self.escapes(next) => next += 2,
410 '`' => {
411 next = match self.code(next) {
412 Some((ticks, end)) => end + ticks,
413 None => next + self.run(next),
414 };
415 }
416 ':' => match self.address_end(next) {
417 Some(end) => {
418 if let Some(closing) = self.closed_by_address(next, end, mark, count) {
419 return Some(closing);
420 }
421 next = end;
422 }
423 None => next += 1,
424 },
425 c if c == mark => {
426 let marks = self.run(next);
427 if marks == count && self.closes(next, count) {
428 return Some(next);
429 }
430 next += marks;
431 }
432 _ => next += 1,
433 }
434 }
435 self.missing.insert((mark, count));
436 None
437 }
438
439 fn link(&self, at: usize, depth: usize) -> Option<(Run, usize)> {
444 let open = if self.char(at) == Some('!') { at + 1 } else { at };
445 if self.char(open) != Some('[') {
446 return None;
447 }
448 let label_end =
449 (open + 1..open + LINK_PART_MAX_CHARS).find(|at| self.char(*at).is_none_or(|c| matches!(c, ']' | '[')))?;
450 if self.char(label_end) != Some(']') || self.char(label_end + 1) != Some('(') {
451 return None;
452 }
453 let start = label_end + 2;
457 let (mut nested, mut address_end, mut end) = (0_usize, None, None);
458 for at in start..start + LINK_PART_MAX_CHARS {
459 match self.char(at)? {
460 '(' => nested += 1,
461 ')' if nested == 0 => {
462 end = Some(at);
463 break;
464 }
465 ')' => nested -= 1,
466 c if c.is_whitespace() && address_end.is_none() => address_end = Some(at),
467 _ => {}
468 }
469 }
470 let end = end?;
471 let address = self.slice(start, address_end.unwrap_or(end)).trim_matches(['<', '>']);
472 if address.starts_with("nostr:") {
473 return Some((Run::Text { text: address.to_string(), style: Style::default() }, end + 1));
474 }
475 let url = Url::parse(address).ok().filter(|url| matches!(url.scheme(), "http" | "https"))?;
476 let mut label = Runs::default();
478 Inline::new(self.slice(open + 1, label_end)).read(Style::default(), depth + 1, &mut label);
479 Some((Run::Link { url, label: label.said().trim().to_string() }, end + 1))
480 }
481
482 fn read(&mut self, style: Style, depth: usize, runs: &mut Runs) {
485 let (mut pending, mut at) = (0, 0);
487 while let Some(c) = self.char(at) {
488 let marked: Option<(Run, usize)> = match c {
490 '\\' if self.escapes(at) => {
491 if self.escape_goes(at) {
492 runs.text(self.slice(pending, at), style);
493 pending = at + 1;
494 }
495 at += 2;
496 continue;
497 }
498 '<' => self.angled(at, style),
499 '`' => match self.code(at) {
500 Some((ticks, end)) => {
501 let code = Run::Code {
502 text: unpadded(self.slice(at + ticks, end)).to_string(),
503 style: Style { code: true, ..style },
504 };
505 Some((code, end + ticks))
506 }
507 None => {
508 at += self.run(at);
509 continue;
510 }
511 },
512 '!' | '[' if depth < MAX_DEPTH => self.link(at, depth),
513 ':' => {
514 at = self.address_end(at).unwrap_or(at + 1);
515 continue;
516 }
517 '*' | '_' | '~' => {
518 let marks = self.run(at);
519 let stressed = stress(c, marks, style).filter(|_| depth < MAX_DEPTH && self.opens(at, marks));
520 let end = stressed.and_then(|stressed| Some((stressed, self.stress_end(at, c, marks)?)));
521 let end = end.filter(|(_, end)| self.slice(at + marks, *end).chars().any(char::is_alphanumeric));
524 let Some((stressed, end)) = end else {
525 at += marks;
526 continue;
527 };
528 runs.text(self.slice(pending, at), style);
529 Inline::new(self.slice(at + marks, end)).read(stressed, depth + 1, runs);
530 at = end + marks;
531 pending = at;
532 continue;
533 }
534 _ => None,
535 };
536 match marked {
537 Some((run, end)) => {
538 runs.text(self.slice(pending, at), style);
539 match run {
540 Run::Text { text, style } => runs.text(&text, style),
541 Run::Code { text, style } => runs.code(&text, style),
542 other => runs.0.push(other),
543 }
544 at = end;
545 pending = at;
546 }
547 None => at += 1,
548 }
549 }
550 runs.text(self.slice(pending, self.chars.len()), style);
551 }
552}
553
554fn unpadded(code: &str) -> &str {
557 code.strip_prefix(' ').and_then(|code| code.strip_suffix(' ')).filter(|code| !code.trim().is_empty()).unwrap_or(code)
558}
559
560fn fence(line: &str, opening: bool) -> Option<(char, usize)> {
565 let mark = line.chars().next().filter(|c| matches!(c, '`' | '~'))?;
566 let count = line.chars().take_while(|c| *c == mark).count();
567 let rest = line.get(count * mark.len_utf8()..)?;
568 let fits = if opening { !rest.contains('`') } else { rest.trim().is_empty() };
569 (count >= 3 && fits).then_some((mark, count))
570}
571
572fn heading(line: &str) -> Option<(u8, &str)> {
576 let said = line.trim_start_matches('#');
577 let level = u8::try_from(line.len() - said.len()).ok().filter(|level| (1..=6).contains(level))?;
578 if !said.starts_with([' ', '\t']) {
579 return None;
580 }
581 let said = said.trim();
582 let open = said.trim_end_matches('#');
583 let said = if open.ends_with(' ') { open.trim_end() } else { said };
584 (!said.is_empty()).then_some((level, said))
585}
586
587fn underlines(line: &str) -> bool {
590 let marks = line.trim_end();
591 marks.len() >= 3 && marks.chars().all(|c| c == '=')
592}
593
594fn quoted(line: &str) -> Option<&str> {
598 let mut rest = line.strip_prefix('>')?;
599 let mut spaced = false;
600 loop {
601 if let Some(inner) = rest.strip_prefix(' ') {
602 spaced = true;
603 rest = inner;
604 }
605 match rest.strip_prefix('>') {
606 Some(inner) => rest = inner,
607 None => break,
608 }
609 }
610 (spaced || rest.is_empty() || rest.starts_with(char::is_alphabetic)).then_some(rest)
611}
612
613fn item(line: &str) -> Option<(&str, &str)> {
616 let said = line.trim_start_matches(' ');
617 let room = line.get(..line.len() - said.len())?;
618 let said = said.strip_prefix(['-', '*', '+'])?.strip_prefix(' ')?.trim_start();
619 (!said.is_empty() && !is_rule(line)).then_some((room, said))
620}
621
622fn to_do(said: &str) -> Option<(bool, &str)> {
625 let done = if said.starts_with("[ ] ") {
626 false
627 } else if said.starts_with("[x] ") || said.starts_with("[X] ") {
628 true
629 } else {
630 return None;
631 };
632 Some((done, said.get(4..)?.trim_start()))
633}
634
635fn is_rule(line: &str) -> bool {
638 let mut marks = line.chars().filter(|c| *c != ' ');
639 let Some(mark) = marks.next().filter(|c| matches!(c, '-' | '*' | '_')) else {
640 return false;
641 };
642 let more = marks.try_fold(1, |count, c| (c == mark).then_some(count + 1));
643 more.is_some_and(|count| count >= 3)
644}
645
646fn cells(line: &str) -> Vec<String> {
650 let line = line.trim();
651 let mut cells = vec![String::new()];
652 let mut escaped = false;
653 for c in line.chars() {
654 let Some(cell) = cells.last_mut() else { break };
655 match c {
656 '|' if escaped => {
657 cell.pop();
658 cell.push('|');
659 }
660 '|' => cells.push(String::new()),
661 _ => cell.push(c),
662 }
663 escaped = c == '\\' && !escaped;
664 }
665 if line.starts_with('|') {
666 cells.remove(0);
667 }
668 if cells.len() > 1 && cells.last().is_some_and(|last| last.trim().is_empty()) {
669 cells.pop();
670 }
671 cells.into_iter().map(|cell| cell.trim().to_string()).collect()
672}
673
674fn columns(line: &str) -> Option<Vec<Align>> {
678 if !line.contains('|') || !line.chars().all(|c| matches!(c, '|' | '-' | ':' | ' ' | '\t')) {
679 return None;
680 }
681 cells(line)
682 .into_iter()
683 .map(|cell| {
684 let dashes = cell.trim_matches(':');
685 let lined = !dashes.is_empty() && dashes.chars().all(|c| c == '-');
686 lined.then_some(match (cell.starts_with(':'), cell.ends_with(':')) {
687 (true, true) => Align::Middle,
688 (false, true) => Align::Right,
689 _ => Align::Left,
690 })
691 })
692 .collect()
693}
694
695fn table<'a>(lines: &[&'a str]) -> Option<(Table<Vec<Run>>, usize)> {
699 let unbroken = |line: &&'a str| -> &'a str { line.strip_suffix('\r').unwrap_or(line) };
700 let (first, under) = (lines.first().map(unbroken)?, lines.get(1).map(unbroken)?);
701 if !first.contains('|') {
702 return None;
703 }
704 let columns = columns(under)?;
705 let head = cells(first);
706 if head.len() != columns.len() {
707 return None;
708 }
709 let read = |cell: String| {
710 let mut runs = Runs::default();
711 Inline::new(&cell).read(Style::default(), 0, &mut runs);
712 runs.0
713 };
714 let mut rows = vec![head.into_iter().map(read).collect::<Vec<_>>()];
715 let rest = lines.iter().skip(2).map(unbroken).take_while(|line| line.contains('|') && !line.trim().is_empty());
716 for line in rest.take(TABLE_MAX_CELLS / columns.len().max(1)) {
717 let mut row: Vec<Vec<Run>> = cells(line).into_iter().take(columns.len()).map(read).collect();
720 row.resize(columns.len(), Vec::new());
721 rows.push(row);
722 }
723 let lines = rows.len() + 1;
724 Some((Table { columns, rows }, lines))
725}
726
727fn line(line: &str, listed: bool, runs: &mut Runs) {
730 let plain = Style::default();
731 let quiet = Style { quiet: true, ..plain };
732 let said = line.strip_suffix('\r').unwrap_or(line);
735 if let Some((level, title)) = heading(said) {
736 Inline::new(title).read(Style { bold: true, heading: level, ..plain }, 0, runs);
737 } else if let Some(quoted) = quoted(said) {
738 runs.text(QUOTE_BAR, quiet);
739 Inline::new(quoted).read(quiet, 0, runs);
740 } else if let Some((room, said)) = item(said).filter(|(_, said)| listed || to_do(said).is_some()) {
741 runs.text(room, plain);
742 let said = match to_do(said) {
743 Some((done, said)) => {
744 runs.text(if done { ITEM_DONE } else { ITEM_TO_DO }, plain);
745 said
746 }
747 None => {
748 runs.text(ITEM_DOT, plain);
749 said
750 }
751 };
752 Inline::new(said).read(plain, 0, runs);
753 } else {
754 Inline::new(line).read(plain, 0, runs);
755 }
756}
757
758pub fn runs(content: &str) -> Vec<Run> {
762 let lines: Vec<&str> = content.split('\n').collect();
763 let unbroken = |at: usize| lines.get(at).map(|line| line.strip_suffix('\r').unwrap_or(line));
764 let mut runs = Runs::default();
765 let mut unclosed: Vec<(char, usize)> = Vec::new();
768 let mut after_text = false;
772 let mut at = 0;
773 while let Some(said) = unbroken(at) {
774 let opened =
775 fence(said, true).filter(|(mark, count)| !unclosed.iter().any(|(same, shorter)| same == mark && shorter <= count));
776 if let Some((mark, count)) = opened {
777 let closes = |line: &&str| {
778 fence(line.trim_end_matches('\r'), false).is_some_and(|(same, longer)| same == mark && longer >= count)
779 };
780 match lines.iter().skip(at + 1).position(closes) {
781 Some(lines_of_code) => {
782 let code: Vec<&str> =
783 lines.iter().skip(at + 1).take(lines_of_code).map(|line| line.trim_end_matches('\r')).collect();
784 runs.block(Block::Code(code.join("\n")));
785 (after_text, at) = (false, at + lines_of_code + 2);
786 continue;
787 }
788 None => unclosed.push((mark, count)),
789 }
790 }
791 if let Some((table, lines_of_it)) = lines.get(at..).and_then(table) {
792 runs.block(Block::Table(table));
793 (after_text, at) = (false, at + lines_of_it);
794 continue;
795 }
796 if is_rule(said) {
797 runs.block(Block::Rule);
798 (after_text, at) = (false, at + 1);
799 continue;
800 }
801 let after_block = matches!(runs.0.last(), Some(Run::Block(_)));
802 if after_block && !after_text && said.trim().is_empty() {
803 at += 1;
804 continue;
805 }
806 if after_text {
807 runs.text("\n", Style::default());
808 }
809 after_text = true;
810 let plainly_text = !said.trim().is_empty() && heading(said).is_none() && quoted(said).is_none() && item(said).is_none();
812 if plainly_text && unbroken(at + 1).is_some_and(underlines) {
813 Inline::new(said.trim()).read(Style { bold: true, heading: 1, ..Style::default() }, 0, &mut runs);
814 at += 2;
815 continue;
816 }
817 let is_item = |at: Option<usize>| at.and_then(unbroken).is_some_and(|line| item(line).is_some());
819 let listed = is_item(at.checked_sub(1)) || is_item(Some(at + 1));
820 line(lines.get(at).copied().unwrap_or_default(), listed, &mut runs);
821 at += 1;
822 }
823 runs.0
824}
825
826#[cfg(test)]
827mod tests {
828 use super::{Align, Block, Run, Style, Table, runs};
829
830 const PLAIN: Style = Style { bold: false, italic: false, strike: false, code: false, quiet: false, heading: 0 };
831 const BOLD: Style = Style { bold: true, ..PLAIN };
832 const ITALIC: Style = Style { italic: true, ..PLAIN };
833 const STRUCK: Style = Style { strike: true, ..PLAIN };
834 const CODE: Style = Style { code: true, ..PLAIN };
835 const QUIET: Style = Style { quiet: true, ..PLAIN };
836
837 fn text(text: &str, style: Style) -> Run {
838 Run::Text { text: text.to_string(), style }
839 }
840
841 fn code(text: &str) -> Run {
842 Run::Code { text: text.to_string(), style: CODE }
843 }
844
845 fn link(url: &str, label: &str) -> Run {
846 Run::Link { url: url.parse().unwrap(), label: label.to_string() }
847 }
848
849 fn lines_of_code(code: &str) -> Run {
851 Run::Block(Block::Code(code.to_string()))
852 }
853
854 fn heading(level: u8) -> Style {
856 Style { bold: true, heading: level, ..PLAIN }
857 }
858
859 fn untouched(said: &str) {
861 assert_eq!(runs(said), [text(said, PLAIN)], "{said:?}");
862 }
863
864 #[test]
865 fn a_note_that_marks_nothing_is_one_run_of_itself() {
866 untouched("Just a note.\n\nWith two paragraphs, a #hashtag and https://example.com/a_b_c/*d*.");
867 assert_eq!(runs(""), []);
868 }
869
870 #[test]
871 fn marks_inside_words_are_not_marks() {
872 for said in [
873 "2*3*4 = 24 and 5 * 3 * 7 = 105",
874 "f**k this s**t",
875 "snake_case_names and a_b__c__d",
876 "about ~5 minutes, or ~10",
877 "a footnote* and another*",
878 "*unclosed and **unclosed too",
879 "*not closed on\nthe line*",
880 "**** and ***** and ~~~~",
881 ] {
882 untouched(said);
883 }
884 }
885
886 #[test]
887 fn faces_made_of_marks_stay_faces() {
888 for said in [
889 "¯\\_(ツ)_/¯",
890 "¯_(ツ)_/¯",
891 "^_^ and again ^_^",
892 "(>_<) (>_<)",
893 "o_O ... O_o",
894 "*_* (_._) *-*",
895 "*** !!! ***?",
896 ">_< and\n>:( and\n>100 came",
897 ] {
898 untouched(said);
899 }
900 }
901
902 #[test]
903 fn a_backslash_before_a_mark_keeps_it_from_being_one_and_goes() {
904 assert_eq!(runs("\\*not slanted\\* and \\`not code\\`"), [text("*not slanted* and `not code`", PLAIN)]);
905 assert_eq!(runs("snake\\_case and \\_private\\_"), [text("snake_case and _private_", PLAIN)]);
906 untouched("¯\\_(ツ)_/¯ in C:\\Users\\me, and a \\n");
908 }
909
910 #[test]
911 fn what_is_marked_is_set_as_marked_without_its_marks() {
912 assert_eq!(
913 runs("Check out *Avestruz*! It has a ```--toggle``` flag, I have *not* **read** it ~~all~~."),
914 [
915 text("Check out ", PLAIN),
916 text("Avestruz", ITALIC),
917 text("! It has a ", PLAIN),
918 code("--toggle"),
919 text(" flag, I have ", PLAIN),
920 text("not", ITALIC),
921 text(" ", PLAIN),
922 text("read", BOLD),
923 text(" it ", PLAIN),
924 text("all", STRUCK),
925 text(".", PLAIN),
926 ]
927 );
928 assert_eq!(
929 runs("_one_ and (_two_)"),
930 [text("one", ITALIC), text(" and (", PLAIN), text("two", ITALIC), text(")", PLAIN)]
931 );
932 let both = Style { bold: true, italic: true, ..PLAIN };
933 assert_eq!(runs("***both*** and ___both___"), [text("both", both), text(" and ", PLAIN), text("both", both)]);
934 assert_eq!(runs("__bold__ and `__init__`"), [text("bold", BOLD), text(" and ", PLAIN), code("__init__")]);
937 }
938
939 #[test]
940 fn marks_inside_marks_add_up() {
941 assert_eq!(
942 runs("**bold with *slanted* and `code` in it**"),
943 [
944 text("bold with ", BOLD),
945 text("slanted", Style { bold: true, italic: true, ..PLAIN }),
946 text(" and ", BOLD),
947 Run::Code { text: "code".into(), style: Style { bold: true, code: true, ..PLAIN } },
948 text(" in it", BOLD),
949 ]
950 );
951 }
952
953 #[test]
954 fn marks_beside_text_written_without_spaces_are_marks() {
955 assert_eq!(runs("这是**重点**内容"), [text("这是", PLAIN), text("重点", BOLD), text("内容", PLAIN)]);
956 }
957
958 #[test]
959 fn code_is_as_written_whatever_is_in_it() {
960 assert_eq!(runs("run `a *b* _c_ #d` now"), [text("run ", PLAIN), code("a *b* _c_ #d"), text(" now", PLAIN)]);
961 assert_eq!(runs("`` a ` b ``"), [code("a ` b")]);
963 untouched("it's 5 o`clock somewhere, and `` there");
966 untouched("I don`t think it`s fair, `tis not");
967 assert_eq!(runs("*open `closed*` here"), [text("*open ", PLAIN), code("closed*"), text(" here", PLAIN)]);
969 }
970
971 #[test]
972 fn what_is_between_two_fences_is_code_that_stands_apart() {
973 assert_eq!(
975 runs("Look:\n\n```rust\nfn main() {\n let *x* = 1;\n}\n```\n\ndone"),
976 [text("Look:", PLAIN), lines_of_code("fn main() {\n let *x* = 1;\n}"), text("done", PLAIN)]
977 );
978 assert_eq!(runs("~~~\na\n~~~"), [lines_of_code("a")]);
979 assert_eq!(runs("````\n```\n````"), [lines_of_code("```")]);
981 untouched("```\nnever closed");
984 assert_eq!(runs("```\nopen\n*but* here"), [text("```\nopen\n", PLAIN), text("but", ITALIC), text(" here", PLAIN)]);
985 }
986
987 #[test]
988 fn a_heading_is_bold_and_says_how_deep_and_a_hashtag_is_not_one() {
989 assert_eq!(
990 runs("## What *is* new ##\nthis"),
991 [
992 text("What ", heading(2)),
993 text("is", Style { italic: true, ..heading(2) }),
994 text(" new", heading(2)),
995 text("\nthis", PLAIN)
996 ]
997 );
998 assert_eq!(runs("# I write C#"), [text("I write C#", heading(1))]);
999 assert_eq!(runs("###### six"), [text("six", heading(6))]);
1000 untouched("#nostr is not a heading\n####### neither are seven\n# ");
1001 }
1002
1003 #[test]
1004 fn a_line_with_equals_signs_under_it_is_a_heading() {
1005 assert_eq!(runs("The title\n=========\nand so on"), [text("The title", heading(1)), text("\nand so on", PLAIN)]);
1006 untouched("a == b\n==\nc");
1008 assert_eq!(runs("> said\n===="), [text("\u{258e} said", QUIET), text("\n====", PLAIN)]);
1009 }
1010
1011 #[test]
1012 fn what_is_quoted_is_quiet_behind_a_bar() {
1013 assert_eq!(
1014 runs("> to be, or *not*\n> > to be\n>be me\nsaid he"),
1015 [
1016 text("\u{258e} to be, or ", QUIET),
1017 text("not", Style { italic: true, ..QUIET }),
1018 text("\n", PLAIN),
1019 text("\u{258e} to be", QUIET),
1020 text("\n", PLAIN),
1021 text("\u{258e} be me", QUIET),
1022 text("\nsaid he", PLAIN),
1023 ]
1024 );
1025 untouched("-> not this\n2 > 1");
1026 }
1027
1028 #[test]
1029 fn items_of_a_list_get_a_dot_and_a_dash_alone_does_not() {
1030 assert_eq!(
1031 runs("- one\n * *two*\n+ three"),
1032 [text("\u{2022} one\n \u{2022} ", PLAIN), text("two", ITALIC), text("\n\u{2022} three", PLAIN)]
1033 );
1034 untouched("so it goes\n\n- signed, me");
1036 untouched("* terms apply\nto all of it");
1037 untouched("1. one\n2. two\n3) three");
1039 }
1040
1041 #[test]
1042 fn what_is_to_do_gets_a_box_ticked_or_not() {
1043 assert_eq!(runs("- [ ] write it\n- [x] ship it"), [text("\u{2610} write it\n\u{2611} ship it", PLAIN)]);
1044 assert_eq!(runs("* [X] done"), [text("\u{2611} done", PLAIN)]);
1046 }
1047
1048 #[test]
1049 fn three_marks_alone_on_a_line_are_a_rule_that_stands_apart() {
1050 for marks in ["---", "***", "___", "- - -", "-----"] {
1051 assert_eq!(
1052 runs(&format!("above\n\n{marks}\nbelow")),
1053 [text("above", PLAIN), Run::Block(Block::Rule), text("below", PLAIN)],
1054 "{marks}"
1055 );
1056 }
1057 untouched("--\n-- \n--- not alone\n-*-");
1058 }
1059
1060 #[test]
1061 fn lines_of_cells_with_a_line_of_dashes_under_the_first_are_a_table() {
1062 let cell = |said: &str| vec![text(said, PLAIN)];
1063 assert_eq!(
1064 runs(
1065 "Dams:\n|Category|Approximate count|\n|---|---|\n|Large dams in the U.S.|92,000+|\n|Large dams worldwide|~200,000|\n\nso many"
1066 ),
1067 [
1068 text("Dams:", PLAIN),
1069 Run::Block(Block::Table(Table {
1070 columns: vec![Align::Left, Align::Left],
1071 rows: vec![
1072 vec![cell("Category"), cell("Approximate count")],
1073 vec![cell("Large dams in the U.S."), cell("92,000+")],
1074 vec![cell("Large dams worldwide"), cell("~200,000")],
1075 ],
1076 })),
1077 text("so many", PLAIN),
1078 ]
1079 );
1080 }
1081
1082 #[test]
1083 fn a_table_says_where_its_columns_stand_and_reads_its_cells_as_text() {
1084 let table = match runs("a | b | c\n:-- | :-: | --:\n**x** | `y \\| z` | [w](https://example.com)\nshort |\n1 | 2 | 3 | 4")
1085 .as_slice()
1086 {
1087 [Run::Block(Block::Table(table))] => table.clone(),
1088 other => panic!("not a table: {other:?}"),
1089 };
1090 assert_eq!(table.columns, [Align::Left, Align::Middle, Align::Right]);
1091 assert_eq!(
1092 table.rows.get(1),
1093 Some(&vec![vec![text("x", BOLD)], vec![code("y | z")], vec![link("https://example.com", "w")]])
1094 );
1095 assert_eq!(table.rows.get(2), Some(&vec![vec![text("short", PLAIN)], vec![], vec![]]));
1097 assert_eq!(table.rows.get(3).map(Vec::len), Some(3));
1098 }
1099
1100 #[test]
1101 fn a_line_with_a_bar_in_it_is_not_a_table_by_itself() {
1102 untouched("this | that\nand the other");
1103 untouched("a | b\n--\nc");
1104 untouched("| a | b |\n| --- |\n| c |");
1105 untouched("yes | no\n-- maybe | so");
1106 }
1107
1108 #[test]
1109 fn a_labelled_link_is_a_link_that_says_its_label() {
1110 assert_eq!(
1111 runs("Read [the **notes**](https://example.com/a_(b)) first."),
1112 [text("Read ", PLAIN), link("https://example.com/a_(b)", "the notes"), text(" first.", PLAIN)]
1113 );
1114 assert_eq!(runs(""), [link("https://example.com/cat.png", "a cat")]);
1116 untouched("[click](javascript:alert(1)) or [here](/local) or [x] (y) or [a [b](c)");
1118 assert_eq!(runs("by [me](nostr:npub1xyz)"), [text("by nostr:npub1xyz", PLAIN)]);
1120 }
1121
1122 #[test]
1123 fn an_address_between_angle_brackets_is_shown_without_them_and_a_br_is_a_line_break() {
1124 assert_eq!(runs("see <https://example.com/a>, or not"), [text("see https://example.com/a, or not", PLAIN)]);
1125 assert_eq!(runs("one<br>two<BR/>three"), [text("one\ntwo\nthree", PLAIN)]);
1126 untouched("<b>not bold</b> <script>alert(1)</script> <3 a < b > c <mailto:a@b.c>");
1128 }
1129
1130 #[test]
1131 fn what_is_in_a_web_address_is_not_a_mark() {
1132 untouched("see https://example.com/a_b_/c*d*/~~e~~ and _https://example.com/x");
1133 assert_eq!(runs("*see https://example.com/a*."), [text("see https://example.com/a", ITALIC), text(".", PLAIN)]);
1135 }
1136
1137 #[test]
1138 fn line_breaks_written_as_two_characters_are_kept_where_nothing_is_marked() {
1139 untouched("one\r\ntwo\r\n");
1140 assert_eq!(runs("# Title\r\ntext"), [text("Title", heading(1)), text("\ntext", PLAIN)]);
1141 assert!(
1143 matches!(runs("a|b\r\n-|-\r\nc|d\r\n").as_slice(), [Run::Block(Block::Table(table)), ..] if table.rows.len() == 2)
1144 );
1145 assert_eq!(runs("```\r\ncode\r\n```\r\n---\r"), [lines_of_code("code"), Run::Block(Block::Rule)]);
1146 }
1147
1148 #[test]
1149 fn a_note_of_nothing_but_marks_is_read_in_the_time_any_other_is() {
1150 let started = std::time::Instant::now();
1154 for said in [
1155 " *a".repeat(40_000),
1156 " `a".repeat(40_000),
1157 "*_".repeat(60_000),
1158 "```x\n".repeat(20_000),
1159 " **a `".repeat(20_000),
1160 "a|b\n".repeat(30_000),
1161 "|a\n|-\n".repeat(20_000),
1162 "|".repeat(60_000),
1163 "- a\n".repeat(30_000),
1164 "<a ".repeat(40_000),
1165 ] {
1166 let _ = runs(&said);
1167 }
1168 let _ = runs(&"[a](".repeat(4_000));
1171 let _ = runs(&"<".repeat(4_000));
1172 assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
1173 }
1174
1175 #[test]
1176 fn marks_inside_marks_are_followed_so_deep_and_no_deeper() {
1177 let deep = format!("{}deep{}", "*_".repeat(50), "_*".repeat(50));
1179 let said: String = runs(&deep)
1180 .into_iter()
1181 .map(|run| match run {
1182 Run::Text { text, .. } | Run::Code { text, .. } => text,
1183 Run::Link { label, .. } => label,
1184 Run::Block(_) => String::new(),
1185 })
1186 .collect();
1187 assert!(said.contains("deep") && said.contains('*'), "{said}");
1188 }
1189}