Skip to main content

cosmic_applet_avestruz/nostr/
markdown.rs

1// SPDX-License-Identifier: MIT
2
3//! Markdown, as far as notes are written in it: what a note marks as
4//! bold, slanted, struck out or code, its headings, what it quotes, its
5//! lists, its tables, and the links it names by something other than
6//! their address.
7//!
8//! A note is plain text, and most are only that. Some are written as
9//! Markdown, in whole or in a word, and nothing in a note says which. So
10//! there is no deciding whether a note is Markdown: each mark is taken for
11//! what it is where it could be nothing else, and left as written
12//! everywhere else. A note with none of them comes out as it went in, one
13//! run of text, the same to the letter.
14//!
15//! ```mermaid
16//! flowchart TD
17//!     note["What a note says"] --> lines["Line by line"]
18//!     lines --> fence{"Between two fences?"}
19//!     fence -->|"yes"| block["Code, as written"]
20//!     fence -->|"no"| kind{"How the line starts"}
21//!     kind -->|"# "| heading["A heading: bold, larger"]
22//!     kind -->|"> "| quoted["Quoted: quiet, behind a bar"]
23//!     kind -->|"- "| item["An item: behind a dot or a box"]
24//!     kind -->|"--- alone"| rule["A rule"]
25//!     kind -->|"cells, and --- under them"| table["A table"]
26//!     kind -->|"anything else"| text["Text"]
27//!     heading --> inline["Within the line"]
28//!     quoted --> inline
29//!     item --> inline
30//!     text --> inline
31//!     inline --> runs["Runs: text in one style, code, links, blocks"]
32//!     table -->|"each cell"| inline
33//!     block --> runs
34//!     rule --> runs
35//! ```
36//!
37//! What is taken for Markdown, and what is not:
38//!
39//! | Written | Shown as | Left as written when |
40//! |---|---|---|
41//! | `*slanted*`, `_slanted_` | Slanted | The marks are inside a word (`2*3*4`, `snake_case`), have a space on their inside, are not closed on the line, have a `\` before them, or have no letter or figure between them (`*_*`) |
42//! | `**bold**`, `__bold__`, `***both***` | Bold | Likewise (`f**k`) |
43//! | `~~struck~~` | Struck out | Likewise; one `~` is never a mark |
44//! | `` `code` ``, with any number of backticks | Code | The same number does not close it on the line, or the backticks are inside a word (`don`t`) |
45//! | A fence of three backticks or tildes, alone at the start of a line, and what follows down to another | A block of code | No fence closes it |
46//! | `# Heading`, with up to six `#`, or a line with `===` under it | Bold, and the first three levels larger | There is no space after the `#`: that is a hashtag |
47//! | `> quoted`, `>quoted` | Quiet, behind a bar | What follows the `>` with no space is not a letter (`>_<`, `>100`) |
48//! | `- item`, `* item`, `+ item`, set in or not | The item, behind a dot | No other item stands on the line before or after: that is a dash, a footnote, a signature |
49//! | `- [ ] to do`, `- [x] done` | The item, behind a box, ticked or not | |
50//! | `1. item` | As written: it reads as what it is | |
51//! | `---`, `***` or `___` alone on a line | A rule | |
52//! | A line of cells between `\|`, and under it a line of `---` between as many | A table, each column set left, right or in the middle as its `:---`, `---:` or `:---:` says | The line under it is no such line |
53//! | `[label](https://…)` | A link that reads as its label | The address is not one for the web |
54//! | `![label](https://…)` | The picture or the video there, or a link | Likewise |
55//! | `<https://…>` | The link | |
56//! | `<br>` | A line break | |
57//! | `\*`, and a `\` before any other mark | The mark, and no `\` | It is a shrug (`¯\_(ツ)_/¯`): a `\_` with no letter on either side |
58//!
59//! Not Markdown here, and left as written: a line with `---` under it (it
60//! is a line and a rule, not a heading), code set in by four spaces (notes
61//! are set in for other reasons), links whose address is given elsewhere
62//! (`[label][1]`), footnotes, and HTML other than `<br>`, which is never
63//! taken for anything.
64//!
65//! A line break is a line break: lines are not joined into paragraphs, as
66//! Markdown would have it, since a note's lines are its author's.
67//!
68//! Web addresses are passed over whole: what is in one is not a mark. A
69//! mark at the very end of one can still close what was opened before it
70//! (`*see https://example.com/a*`).
71//!
72//! Nothing here reads links, mentions or hashtags: that is
73//! [`content`](crate::nostr::content)'s, which reads each run of text it
74//! is handed. What is code is not read for them at all.
75
76use std::collections::HashSet;
77
78use nostr_sdk::prelude::Url;
79
80/// How a run of text is set.
81#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
82pub struct Style {
83    pub bold: bool,
84    /// Slanted.
85    pub italic: bool,
86    /// Struck out.
87    pub strike: bool,
88    /// Code: in a face whose letters are all as wide, as it was written.
89    pub code: bool,
90    /// Quieter than the text around it: what is quoted.
91    pub quiet: bool,
92    /// A heading of this level, 1 to 6, or 0 for none.
93    pub heading: u8,
94}
95
96impl Style {
97    /// Whether this is text as any other.
98    pub fn is_plain(&self) -> bool {
99        *self == Self::default()
100    }
101}
102
103/// A piece of a note, in reading order.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub enum Run {
106    /// Text in one style, still to be read for the links, the mentions and
107    /// the hashtags in it.
108    Text { text: String, style: Style },
109    /// Code: shown as written, and read for nothing.
110    Code { text: String, style: Style },
111    /// A link the note gives a label of its own, which may be empty.
112    Link { url: Url, label: String },
113    /// What stands apart from the text, between the lines before it and
114    /// the lines after: no line break is left on either side of it.
115    Block(Block<Vec<Run>>),
116}
117
118/// What stands apart from a note's text, with cells of `Cell`: of runs
119/// here, and of what [`content`](crate::nostr::content) reads them into.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub enum Block<Cell> {
122    /// Lines of code, as written.
123    Code(String),
124    /// A rule between two parts of a note.
125    Rule,
126    Table(Table<Cell>),
127}
128
129/// A table: its columns, and its rows of as many cells each, the first
130/// of them the one that says what the columns are.
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct Table<Cell> {
133    pub columns: Vec<Align>,
134    pub rows: Vec<Vec<Cell>>,
135}
136
137/// Where in its column a cell stands.
138#[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    /// The same block, each cell of it made into another by `read`.
148    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
160/// What stands before what a note quotes.
161const QUOTE_BAR: &str = "\u{258e} ";
162
163/// What stands before an item of a list, and before one that is to be
164/// done or is.
165const ITEM_DOT: &str = "\u{2022} ";
166const ITEM_TO_DO: &str = "\u{2610} ";
167const ITEM_DONE: &str = "\u{2611} ";
168
169/// How many cells a table may have, all told. One of more is text.
170const TABLE_MAX_CELLS: usize = 2_000;
171
172/// How deep marks inside marks are followed. Past this they are text:
173/// nobody writes them so, and a note is whatever its author sent.
174const MAX_DEPTH: usize = 6;
175
176/// How far a link's label and its address are looked for the end of, in
177/// characters: longer than any is, and short enough that a note made of
178/// nothing but openings is read in the time any other is.
179const LINK_PART_MAX_CHARS: usize = 2048;
180
181/// The characters a mark may come straight after, a space apart: what
182/// opens a bracket or a quotation, and a dash.
183const OPENING: &str = "([{\"'\u{201c}\u{2018}\u{ab}\u{2013}\u{2014}";
184
185/// The characters a mark may come straight before, a space apart: what
186/// closes a bracket or a quotation, or ends a clause, and a dash.
187const CLOSING: &str = ".,!?;:)]}\"'\u{201d}\u{2019}\u{bb}\u{2026}\u{2013}\u{2014}";
188
189/// The punctuation that follows a web address without being part of it.
190const AFTER_ADDRESS: &str = ".,;:!?)]}";
191
192/// Whether `c` is written without spaces between words, as Chinese,
193/// Japanese and Korean are: a mark beside one is not inside a word.
194fn 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
198/// Whether `c` is a letter or a figure of a word: one written with spaces
199/// between words.
200fn of_a_word(c: char) -> bool {
201    c.is_alphanumeric() && !unspaced(c)
202}
203
204/// Whether `c` is one of the characters marks are made of: what a `\`
205/// before it keeps from being one.
206fn is_mark(c: char) -> bool {
207    matches!(c, '*' | '_' | '~' | '`' | '[' | ']' | '|')
208}
209
210/// What the mark of `count` times `c` adds to a style, if it is a mark.
211fn 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/// The runs a note is made of, gathered: text of one style that follows
222/// text of the same is one run.
223#[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    /// Set a block down: apart from the text, so without the line breaks
244    /// and the empty lines that stood between it and the text before.
245    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    /// All of it as text, without its styles: what a label says.
257    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
269/// One line of a note, or a part of one, read for the marks in it.
270struct Inline<'a> {
271    text: &'a str,
272    /// Its characters, each with where it starts.
273    chars: Vec<(usize, char)>,
274    /// The closing marks that were looked for to the end and not found:
275    /// which character, how many times. There is none further on either.
276    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    /// The character at `at`, counted in characters.
285    fn char(&self, at: usize) -> Option<char> {
286        self.chars.get(at).map(|(_, c)| *c)
287    }
288
289    /// The text from the character at `from` up to the one at `to`.
290    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    /// How many times the character at `at` stands there in a row.
296    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    /// Whether the `\` at `at` stands before a mark: neither is one then.
302    fn escapes(&self, at: usize) -> bool {
303        self.char(at) == Some('\\') && self.char(at + 1).is_some_and(is_mark)
304    }
305
306    /// Whether the `\` at `at`, which stands before a mark, is left out
307    /// of what is shown: always, but before a `_` with no letter or
308    /// figure on either side of the two, which is the arm of a shrug.
309    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    /// What stands at `at` between `<` and `>`, and where it ends: a web
315    /// address, which is shown without them and read for the link it is,
316    /// or a `br`, which is a line break.
317    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    /// Where the web address ends whose `://` starts with the `:` at
332    /// `colon`, if that is what it is: at a space, at what no address
333    /// holds, or at the end.
334    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    /// Where the address that ends at `end` has `count` times `mark` as
344    /// the last of it, before the punctuation after it: marks that close
345    /// what was opened before the address, and are no part of it.
346    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    /// The code the backticks at `at` open, if they do: how many they
357    /// are, and where as many, no more and no fewer, close it. Not a
358    /// backtick inside a word, or one that would close in one: those are
359    /// apostrophes of a keyboard that has none (`don`t`, `it`s`).
360    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    /// Whether `count` marks at `at` may open: after a space, an opening
383    /// bracket or nothing, and with something other than a space after.
384    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    /// Whether `count` marks at `at` may close: with something other than
392    /// a space before, and a space, what ends a clause or nothing after.
393    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    /// Where what `count` times `mark` open at `at` is closed, if it is,
401    /// on this line: code and web addresses are passed over on the way.
402    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    /// The link written at `at` as `[label](address)`, or with a `!`
440    /// before it, and where it ends: a link if the address is one for the
441    /// web, and the address alone, as text, if it is a `nostr:` one, which
442    /// is read for what it names like any other.
443    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        // The address runs to the bracket that closes the one before it,
454        // those inside it apart; what follows a space in there is a
455        // title, which is not shown.
456        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        // What the label says, without the marks in it.
477        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    /// Read the line into `runs`, in `style` where nothing marks it
483    /// otherwise.
484    fn read(&mut self, style: Style, depth: usize, runs: &mut Runs) {
485        // Where the text not yet handed over starts, and where reading is.
486        let (mut pending, mut at) = (0, 0);
487        while let Some(c) = self.char(at) {
488            // What a mark at `at` turns into, and where reading goes on.
489            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                    // What is stressed is words: marks around anything
522                    // else are a face (`*_*`, `(_._)`), or decoration.
523                    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
554/// Code as it was written between its backticks, less the one space at
555/// either end that sets it off from them, if there is one at both.
556fn 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
560/// The character a fence is made of and how many of them, if `line` is
561/// one: three or more backticks or tildes at its start. `opening`, it may
562/// say after them what the code is written in, which a closing one
563/// doesn't.
564fn 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
572/// How deep a heading is and what it says, if `line` is one: up to six
573/// `#`, a space, and something after it, less the `#` some close a
574/// heading with, a space after what it says.
575fn 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
587/// Whether `line` is the line under a heading written as a line of text
588/// with `===` under it.
589fn underlines(line: &str) -> bool {
590    let marks = line.trim_end();
591    marks.len() >= 3 && marks.chars().all(|c| c == '=')
592}
593
594/// What is quoted, if `line` quotes: after a `>`, or several, each with a
595/// space after it or not. With no space at all, only what starts with a
596/// letter is quoted: `>_<` is a face, and `>100` a number.
597fn 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
613/// The room before it and what it says, if `line` is written as an item
614/// of a list: a `-`, a `*` or a `+`, a space, and something after it.
615fn 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
622/// Whether it is done and what it is, if what an item says is something
623/// to do: `[ ]` or `[x]` before it.
624fn 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
635/// Whether `line` is a rule: three or more of `-`, `*` or `_`, all the
636/// same, and nothing else but spaces.
637fn 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
646/// The cells of a line of a table: what stands between its `|`, less
647/// the empty one before the first `|` and after the last. A `|` with a
648/// `\` before it is no end of a cell, in code either, and is a `|` in it.
649fn 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
674/// Where each column stands, if `line` is the line under the first of a
675/// table: nothing but `---` between `|`, with a `:` at the end the
676/// column is set towards, or at both for the middle.
677fn 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
695/// The table that starts at the first of `lines`, if one does, and how
696/// many lines it is: a line of cells, the line that says where its
697/// columns stand, and every line of cells after that.
698fn 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        // A row has as many cells as there are columns: those it lacks
718        // are empty, and those it has too many of are left out.
719        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
727/// One line of a note, outside any block, read into `runs`. `listed`, it
728/// is an item of a list if it is written as one.
729fn line(line: &str, listed: bool, runs: &mut Runs) {
730    let plain = Style::default();
731    let quiet = Style { quiet: true, ..plain };
732    // A line may end in the `\r` of a line break written as two
733    // characters, which is no part of what it says.
734    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
758/// What `content` says, as runs: its text in the styles it marks, its
759/// code, the links it labels, and what stands apart from its text. Of a
760/// note that marks nothing, one run of text that is the note.
761pub 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    // The fences that were looked for a closing one of and had none: no
766    // fence of that character and as long or longer is closed further on.
767    let mut unclosed: Vec<(char, usize)> = Vec::new();
768    // Whether a line of text was the last thing read: a line break stands
769    // between it and the next. None does on either side of a block, and
770    // the empty lines there are left out: a block stands apart as it is.
771    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        // A line of text with `===` under it is a heading.
811        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        // An item of a list has another on the line before it or after.
818        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    /// Lines of code that stand apart.
850    fn lines_of_code(code: &str) -> Run {
851        Run::Block(Block::Code(code.to_string()))
852    }
853
854    /// A heading of `level`, in the style it is set in.
855    fn heading(level: u8) -> Style {
856        Style { bold: true, heading: level, ..PLAIN }
857    }
858
859    /// What a note that marks nothing comes out as: itself.
860    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        // But not the arm of a shrug, and not one before anything else.
907        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        // Two underscores are bold as two stars are: what is named so is
935        // code, and written as code.
936        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        // As many backticks close it as opened it, so it can hold fewer.
962        assert_eq!(runs("`` a ` b ``"), [code("a ` b")]);
963        // One that is not closed is a backtick, and so is one in a word:
964        // an apostrophe, on a keyboard without one.
965        untouched("it's 5 o`clock somewhere, and `` there");
966        untouched("I don`t think it`s fair, `tis not");
967        // A mark is not closed by one inside code.
968        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        // No line break is left on either side of it, nor an empty line.
974        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        // A longer fence holds a shorter one.
980        assert_eq!(runs("````\n```\n````"), [lines_of_code("```")]);
981        // One that nothing closes is what was written, and what follows
982        // it is read as it would be without it.
983        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        // Not what is something else already, and not two of them.
1007        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        // One with no other beside it is a dash: a signature, a footnote.
1035        untouched("so it goes\n\n- signed, me");
1036        untouched("* terms apply\nto all of it");
1037        // Numbers read as what they are, and are left.
1038        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        // Alone too: it could be nothing else.
1045        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        // A row has as many cells as there are columns, whatever it has.
1096        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        // A picture is a link too, until it is seen what is there.
1115        assert_eq!(runs("![a cat](https://example.com/cat.png \"Tom\")"), [link("https://example.com/cat.png", "a cat")]);
1116        // An address that is not one for the web is no link.
1117        untouched("[click](javascript:alert(1)) or [here](/local) or [x] (y) or [a [b](c)");
1118        // One for Nostr is read as it would be without the brackets.
1119        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        // Nothing else between them is taken for anything.
1127        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        // But a mark that ends one closes what was opened before it.
1134        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        // And are no part of a table, a fence or a rule.
1142        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        // Each of these would take minutes if every mark looked to the
1151        // end of the note for the one that closes it: a mark that was
1152        // looked for once and not found is not looked for again.
1153        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        // A link's label and address are looked for the end of so far and
1169        // no further, however many open.
1170        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        // Nobody writes them so, and whoever does gets text for it.
1178        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}