mq-markdown 0.10.2

Markdown parsing and manipulation utilities for mq
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
//! Inline parsing of paragraph, heading and table cell content.
//!
//! The content is scanned once, left to right, into a flat list of items: literal text, finished
//! nodes (code spans, autolinks, breaks), delimiter runs and bracket openers. Links close over the
//! items after their opener, and emphasis is resolved with the delimiter stack algorithm of the
//! CommonMark specification, so nesting never recurses over the source.

mod emphasis;
mod entities;
mod entity;
mod html;
mod link;
mod literal;
mod punctuation;
mod tail;

pub(crate) use entity::unescape;
pub(super) use entity::{decode_references, remove_line_indent};
pub(crate) use html::is_autolink_email;
pub(crate) use link::normalize;
pub(super) use tail::{destination, title_at};

use super::error::{Located, MdxError, MdxErrorKind};
use super::flavor::Flavor;
use super::mdx::{self, Fallback, Parsed, TagKind};
use super::resolve::References;
use super::scan::{Span, eol_len};
use super::tree::InlineSource;
use crate::node::{
    Break, CodeInline, MathInline, MdxAttributeContent, MdxJsxTextElement, MdxTextExpression, Node, Position, Text,
};
use rustc_hash::FxHashMap;
use smol_str::SmolStr;
use std::borrow::Cow;
use std::cell::{OnceCell, RefCell};

/// The value of a text item: a slice of the source, or a decoded string.
pub(super) enum Value {
    Slice(Span),
    Owned(String),
}

/// A run of `*`, `_` or `~` that may open or close emphasis.
pub(super) struct Delim {
    pub(super) ch: u8,
    /// Offset of the first remaining character.
    pub(super) start: usize,
    pub(super) count: usize,
    /// Length of the whole run, which `count` shrinks from as the run is used.
    pub(super) original: usize,
    pub(super) can_open: bool,
    pub(super) can_close: bool,
}

/// A `[` or `![` that may open a link or an image.
pub(super) struct Opener {
    pub(super) image: bool,
    /// Offset of the `[`, or of the `!` of an image.
    pub(super) start: usize,
}

pub(super) enum Item {
    Text {
        start: usize,
        end: usize,
        value: Value,
    },
    /// A finished node and how deeply it nests: a leaf is 1. It is boxed to keep the items small, which
    /// are moved around while delimiters are matched.
    Node {
        node: Box<Node>,
        depth: usize,
    },
    Delim(Delim),
    Open(Opener),
    /// An email address in plain text. It is not linked inside link text.
    Email {
        start: usize,
        end: usize,
        prefixed: bool,
    },
    /// A JSX tag in MDX. Tags are paired when the items become nodes.
    Jsx(TextTag),
}

/// A JSX tag in text, with its offsets in the source.
pub(super) struct TextTag {
    name: Option<String>,
    attributes: Vec<MdxAttributeContent>,
    kind: TagKind,
    start: usize,
    end: usize,
}

/// Emphasis and links nested deeper than this are text, and JSX elements are an error. This bounds the
/// recursion of everything that walks the nodes.
pub(super) const MAX_NESTING: usize = 128;

/// How deeply the item nests: nodes carry it, and the rest are text.
pub(super) fn item_depth(item: &Item) -> usize {
    match item {
        Item::Node { depth, .. } => *depth,
        _ => 0,
    }
}

/// What inline parsing needs to know about the whole document.
#[derive(Clone, Copy)]
pub(super) struct Document<'a> {
    pub(super) references: &'a References,
    pub(super) flavor: Flavor,
}

/// What the scanner and its helpers share.
#[derive(Clone, Copy)]
pub(super) struct Context<'a> {
    pub(super) source: &'a InlineSource,
    pub(super) references: &'a References,
    pub(super) flavor: Flavor,
    /// Whether email addresses in plain text are linked: not inside link text, and not when there is no `@`
    /// in the text, which is looked for once.
    pub(super) emails: bool,
    /// The first error in the content, which only MDX has.
    error: &'a RefCell<Option<MdxError>>,
}

impl Context<'_> {
    /// Records an error at an offset of the source, keeping the first one.
    fn fail(&self, error: Located) {
        self.error
            .borrow_mut()
            .get_or_insert_with(|| error.in_source(self.source));
    }

    pub(super) fn src(&self) -> &str {
        &self.source.text
    }

    pub(super) fn position(&self, start: usize, end: usize) -> Position {
        Position {
            start: self.source.point(start),
            end: self.source.end_point(end),
        }
    }
}

/// Parses raw inline content into nodes.
pub(super) fn parse(source: &InlineSource, doc: Document<'_>) -> Result<Vec<Node>, MdxError> {
    if source.text.is_empty() {
        return Ok(Vec::new());
    }

    let error = RefCell::new(None);
    let context = Context {
        source,
        references: doc.references,
        flavor: doc.flavor,
        emails: doc.flavor.has_gfm() && source.text.contains('@'),
        error: &error,
    };
    let mut scanner = Scanner {
        context: &context,
        items: Vec::with_capacity(source.text.len() / 12 + 4),
        openers: Vec::new(),
        depths: Vec::new(),
        inactive_below: 0,
        pos: 0,
        run: 0,
        misses: html::Misses::default(),
        runs: SpanRuns::default(),
        braces: mdx::Braces::default(),
    };
    scanner.scan();
    scanner.flush();

    let Scanner { mut items, .. } = scanner;
    emphasis::process(&mut items, &context);
    let nodes = to_nodes(items, &context);

    match error.into_inner() {
        Some(error) => Err(error),
        None => Ok(nodes),
    }
}

/// Converts items to nodes, merging adjacent text. Unused delimiters and openers become text.
pub(super) fn to_nodes(items: Vec<Item>, context: &Context<'_>) -> Vec<Node> {
    let src = context.src();
    let items = if context.emails {
        literal::link_emails(src, items)
    } else {
        items
    };
    let mut nodes = Vec::with_capacity(items.len());
    // Elements that are open, with the nodes that came before them.
    let mut open: Vec<(TextTag, Vec<Node>)> = Vec::new();
    let mut current: Option<(usize, usize, String)> = None;

    let finish = |current: &mut Option<(usize, usize, String)>, nodes: &mut Vec<Node>| {
        if let Some((start, end, value)) = current.take() {
            nodes.push(Node::Text(Text {
                value,
                position: Some(context.position(start, end)),
            }));
        }
    };

    for item in items {
        let (start, end, text): (usize, usize, Cow<'_, str>) = match item {
            Item::Text { start, end, value } => match value {
                Value::Slice(span) => (start, end, Cow::Borrowed(span.of(src))),
                Value::Owned(value) => (start, end, Cow::Owned(value)),
            },
            Item::Delim(delim) => {
                let end = delim.start + delim.count;
                (delim.start, end, Cow::Borrowed(&src[delim.start..end]))
            }
            Item::Open(opener) => {
                let end = opener.start + if opener.image { 2 } else { 1 };
                (opener.start, end, Cow::Borrowed(&src[opener.start..end]))
            }
            Item::Node { node, .. } => {
                finish(&mut current, &mut nodes);
                nodes.push(*node);
                continue;
            }
            Item::Jsx(tag) => {
                finish(&mut current, &mut nodes);
                match tag.kind {
                    TagKind::Open if open.len() >= MAX_NESTING => {
                        context.fail(Located {
                            kind: MdxErrorKind::TooDeep { limit: MAX_NESTING },
                            offset: tag.start,
                        });
                    }
                    TagKind::Open => open.push((tag, std::mem::take(&mut nodes))),
                    TagKind::SelfClosing => {
                        let end = tag.end;
                        nodes.push(text_element(context, tag, Vec::new(), end));
                    }
                    TagKind::Close => match open.pop() {
                        None => context.fail(Located {
                            kind: MdxErrorKind::UnopenedClosingTag,
                            offset: tag.start,
                        }),
                        Some((opening, before)) => {
                            if opening.name != tag.name {
                                context.fail(Located {
                                    kind: MdxErrorKind::MismatchedClosingTag {
                                        closing: tag.name.clone(),
                                        opening: opening.name.clone(),
                                        opened_at: None,
                                    },
                                    offset: tag.start,
                                });
                            }
                            let children = std::mem::replace(&mut nodes, before);
                            nodes.push(text_element(context, opening, children, tag.end));
                        }
                    },
                }
                continue;
            }
            Item::Email { start, end, prefixed } => {
                finish(&mut current, &mut nodes);
                let text = &src[start..end];
                let position = Some(context.position(start, end));
                nodes.push(Node::Link(crate::node::Link {
                    url: crate::node::Url(if prefixed {
                        format!("mailto:{text}")
                    } else {
                        text.to_string()
                    }),
                    title: None,
                    values: vec![Node::Text(Text {
                        value: text.to_string(),
                        position: position.clone(),
                    })],
                    position,
                }));
                continue;
            }
        };
        match &mut current {
            Some((_, current_end, value)) => {
                value.push_str(&text);
                *current_end = end;
            }
            None => current = Some((start, end, text.into_owned())),
        }
    }
    finish(&mut current, &mut nodes);

    // Elements that never close are an error, and are closed where the content ends.
    while let Some((opening, before)) = open.pop() {
        context.fail(Located {
            kind: MdxErrorKind::UnclosedTextElement {
                name: opening.name.clone(),
            },
            offset: opening.start,
        });
        let end = opening.end;
        let children = std::mem::replace(&mut nodes, before);
        nodes.push(text_element(context, opening, children, end));
    }

    nodes
}

fn text_element(context: &Context<'_>, tag: TextTag, children: Vec<Node>, end: usize) -> Node {
    Node::MdxJsxTextElement(MdxJsxTextElement {
        children,
        position: Some(context.position(tag.start, end)),
        name: tag.name.map(SmolStr::new),
        attributes: tag.attributes,
    })
}

/// How far [`SpanRuns::next_nearby`] looks before leaving the search to the index.
const NEARBY_SPAN: usize = 256;

/// What a search of the next [`NEARBY_SPAN`] bytes tells about the closing run of a span.
enum Nearby {
    Found(usize),
    /// The source ends before a closing run.
    Missing,
    /// There may be a closing run further on.
    Unknown,
}

/// Where the runs of backticks and of dollar signs start, by length, found in one pass the first time a
/// span asks, so that openers without a closer do not each scan to the end.
#[derive(Default)]
struct SpanRuns {
    backticks: OnceCell<FxHashMap<usize, Vec<usize>>>,
    dollars: OnceCell<FxHashMap<usize, Vec<usize>>>,
}

impl SpanRuns {
    /// The start of the first run of exactly `size` bytes `ch` that starts at or after `from`.
    fn next_of_length(&self, src: &str, ch: u8, size: usize, from: usize) -> Option<usize> {
        let runs = if ch == b'`' { &self.backticks } else { &self.dollars };
        // Most spans close nearby, so look there before building the index.
        if runs.get().is_none() {
            match Self::next_nearby(src.as_bytes(), ch, size, from) {
                Nearby::Found(start) => return Some(start),
                Nearby::Missing => return None,
                Nearby::Unknown => {}
            }
        }
        let starts = runs
            .get_or_init(|| {
                let bytes = src.as_bytes();
                let mut runs: FxHashMap<usize, Vec<usize>> = FxHashMap::default();
                let mut index = 0;
                while index < bytes.len() {
                    if bytes[index] == ch {
                        let length = bytes[index..].iter().take_while(|&&b| b == ch).count();
                        runs.entry(length).or_default().push(index);
                        index += length;
                    } else {
                        index += 1;
                    }
                }
                runs
            })
            .get(&size)?;
        starts.get(starts.partition_point(|&start| start < from)).copied()
    }
}

impl SpanRuns {
    /// Looks for the run [`Self::next_of_length`] returns in the bytes right after `from`, which must
    /// not be inside a run of `ch`.
    fn next_nearby(bytes: &[u8], ch: u8, size: usize, from: usize) -> Nearby {
        let limit = bytes.len().min(from + NEARBY_SPAN);
        let mut index = from;
        while let Some(found) = memchr::memchr(ch, &bytes[index..limit]) {
            let start = index + found;
            let length = bytes[start..].iter().take_while(|&&b| b == ch).count();
            if length == size {
                return Nearby::Found(start);
            }
            index = start + length;
            if index >= limit {
                break;
            }
        }
        if limit == bytes.len() {
            Nearby::Missing
        } else {
            Nearby::Unknown
        }
    }
}

struct Scanner<'a> {
    context: &'a Context<'a>,
    items: Vec<Item>,
    /// Indexes of the `Item::Open` items that are still waiting for a `]`.
    openers: Vec<usize>,
    /// For each opener, the deepest node pushed inside it so far.
    depths: Vec<usize>,
    /// Links cannot contain links, so the `[` openers below this many are deactivated.
    inactive_below: usize,
    pos: usize,
    /// Start of the plain text that has not been pushed as an item yet.
    run: usize,
    /// Raw HTML terminators already known to be missing.
    misses: html::Misses,
    runs: SpanRuns,
    /// Where the braces of the content close, for MDX.
    braces: mdx::Braces,
}

/// Bytes where `Scanner::scan` may start a construct. Every other byte is plain text.
static SPECIAL: [bool; 256] = {
    let mut table = [false; 256];
    let special = b"\\&`$*_~[!]<{\n\rhHwW";
    let mut index = 0;
    while index < special.len() {
        table[special[index] as usize] = true;
        index += 1;
    }
    table
};

impl Scanner<'_> {
    fn src(&self) -> &str {
        self.context.src()
    }

    fn scan(&mut self) {
        let len = self.src().len();
        while self.pos < len {
            let bytes = self.src().as_bytes();
            let skip = bytes[self.pos..].iter().take_while(|&&b| !SPECIAL[b as usize]).count();
            let pos = self.pos + skip;
            if pos == len {
                self.pos = len;
                break;
            }
            let (byte, image) = (bytes[pos], bytes.get(pos + 1) == Some(&b'['));
            self.pos = pos;
            let link = if matches!(byte, b'[' | b'!') {
                self.obsidian_link()
            } else {
                None
            };
            match byte {
                _ if link.is_some() => {
                    if let Some((node, end)) = link {
                        self.push_node(node, end);
                    }
                }
                b'\\' => self.escape(),
                b'&' => self.entity(),
                b'`' => self.span(b'`'),
                b'$' if self.context.flavor.has_math() => self.span(b'$'),
                b'*' | b'_' => self.delimiter(),
                b'~' if self.context.flavor.has_gfm() => self.delimiter(),
                b'[' => self.open(false),
                b'!' if image => self.open(true),
                b']' => self.close(),
                b'<' if self.context.flavor.has_html() => self.angle(),
                b'<' => self.jsx(),
                b'{' if self.context.flavor.has_jsx() => self.expression(),
                b'\n' | b'\r' => self.line_ending(),
                b'h' | b'H' | b'w' | b'W' if self.context.flavor.has_gfm() => self.literal_url(),
                _ => self.pos += 1,
            }
        }
    }

    /// The wikilink `[[target|text]]` or the embed `![[target|display]]` at the current position, and the
    /// offset where it ends. The target is not empty, and neither part holds a bracket or a line ending.
    #[cfg(any(feature = "wikilink", feature = "embed"))]
    fn obsidian_link(&self) -> Option<(Node, usize)> {
        if !self.context.flavor.has_obsidian() {
            return None;
        }
        let src = self.src();
        let start = self.pos;
        let rest = &src[start..];
        let (embed, open) = match rest.as_bytes() {
            [b'!', b'[', b'[', ..] if cfg!(feature = "embed") => (true, start + 3),
            [b'[', b'[', ..] if cfg!(feature = "wikilink") => (false, start + 2),
            _ => return None,
        };
        // The content holds no bracket or line ending, so the first one found must start the `]]`.
        let close = open + src[open..].find(['[', ']', '\n', '\r'])?;
        if !src[close..].starts_with("]]") {
            return None;
        }
        let content = &src[open..close];
        // In a table cell `\|` stands for the pipe, as in a code span.
        let unescaped;
        let content = if self.context.source.table && content.contains("\\|") {
            unescaped = content.replace("\\|", "|");
            unescaped.as_str()
        } else {
            content
        };
        let (target, label) = match content.split_once('|') {
            Some((target, label)) => (target.trim(), Some(label.trim().to_string())),
            None => (content.trim(), None),
        };
        if target.is_empty() {
            return None;
        }
        let end = close + 2;
        let position = Some(self.context.position(start, end));
        let target = target.to_string();
        let node = if embed {
            #[cfg(feature = "embed")]
            {
                Node::Embed(crate::node::Embed {
                    target,
                    display: label,
                    position,
                })
            }
            #[cfg(not(feature = "embed"))]
            unreachable!("embeds are off")
        } else {
            #[cfg(feature = "wikilink")]
            {
                Node::WikiLink(crate::node::WikiLink {
                    target,
                    text: label,
                    position,
                })
            }
            #[cfg(not(feature = "wikilink"))]
            unreachable!("wikilinks are off")
        };
        Some((node, end))
    }

    #[cfg(not(any(feature = "wikilink", feature = "embed")))]
    fn obsidian_link(&self) -> Option<(Node, usize)> {
        None
    }

    /// Pushes the pending plain text up to the current position as an item.
    fn flush(&mut self) {
        if self.run < self.pos {
            self.items.push(Item::Text {
                start: self.run,
                end: self.pos,
                value: Value::Slice(Span::new(self.run, self.pos)),
            });
        }
        self.run = self.pos;
    }

    /// Pushes `item` after the pending text and continues scanning at `end`.
    fn push(&mut self, item: Item, end: usize) {
        self.flush();
        if let Item::Node { depth, .. } = &item {
            self.note_depth(*depth);
        }
        self.items.push(item);
        self.pos = end;
        self.run = end;
    }

    /// Records that a node of `depth` is inside the innermost open bracket.
    fn note_depth(&mut self, depth: usize) {
        if let Some(innermost) = self.depths.last_mut() {
            *innermost = (*innermost).max(depth);
        }
    }

    fn push_node(&mut self, node: Node, end: usize) {
        self.push(
            Item::Node {
                node: Box::new(node),
                depth: 1,
            },
            end,
        );
    }

    fn escape(&mut self) {
        let src = self.src();
        let bytes = src.as_bytes();
        let pos = self.pos;
        match bytes.get(pos + 1) {
            Some(next) if next.is_ascii_punctuation() => {
                let item = Item::Text {
                    start: pos,
                    end: pos + 2,
                    value: Value::Slice(Span::new(pos + 1, pos + 2)),
                };
                self.push(item, pos + 2);
            }
            Some(b'\n' | b'\r') => {
                let end = pos + 1 + eol_len(bytes, pos + 1);
                let node = Node::Break(Break {
                    position: Some(self.context.position(pos, end)),
                });
                self.push_node(node, end);
                // The indentation of the next line is not part of the text.
                while matches!(self.src().as_bytes().get(self.pos), Some(b' ' | b'\t')) {
                    self.pos += 1;
                }
                self.run = self.pos;
            }
            _ => self.pos += 1,
        }
    }

    fn entity(&mut self) {
        match entity::decode(self.src(), self.pos) {
            Some((end, value)) => {
                let item = Item::Text {
                    start: self.pos,
                    end,
                    value: Value::Owned(value),
                };
                self.push(item, end);
            }
            None => self.pos += 1,
        }
    }

    fn line_ending(&mut self) {
        let src = self.src();
        let bytes = src.as_bytes();
        let pos = self.pos;
        let eol = eol_len(bytes, pos);

        // Trailing whitespace before the line ending is dropped, or makes a hard break.
        let mut start = pos;
        while start > self.run && matches!(bytes[start - 1], b' ' | b'\t') {
            start -= 1;
        }
        let hard = pos - start >= 2 && bytes[start..pos].iter().all(|&b| b == b' ');
        // The indentation of the next line is not part of the text.
        let mut after = pos + eol;
        while matches!(bytes.get(after), Some(b' ' | b'\t')) {
            after += 1;
        }

        self.pos = start;
        self.flush();
        if hard {
            let node = Node::Break(Break {
                position: Some(self.context.position(start, pos + eol)),
            });
            self.note_depth(1);
            self.items.push(Item::Node {
                node: Box::new(node),
                depth: 1,
            });
        } else {
            self.items.push(Item::Text {
                start: pos,
                end: pos + eol,
                value: Value::Slice(Span::new(pos, pos + eol)),
            });
        }
        self.pos = after;
        self.run = after;
    }

    /// A code span (`` ` ``) or an inline math span (`$`).
    fn span(&mut self, ch: u8) {
        let src = self.context.src();
        let bytes = src.as_bytes();
        let start = self.pos;
        let size = bytes[start..].iter().take_while(|&&b| b == ch).count();

        let close = self.runs.next_of_length(src, ch, size, start + size);

        let Some(close) = close else {
            self.pos = start + size;
            return;
        };

        let end = close + size;
        // In a table cell, `\|` stands for `|` inside code as well.
        let content = &src[start + size..close];
        // The lines of a paragraph lose their leading whitespace before the inline content is read.
        let content = if self.context.flavor.strips_span_indent() {
            remove_line_indent(content)
        } else {
            Cow::Borrowed(content)
        };
        let content = content.as_ref();
        let value = if self.context.source.table && content.contains("\\|") {
            span_value(&content.replace("\\|", "|"))
        } else {
            span_value(content)
        };
        let position = Some(self.context.position(start, end));
        let node = if ch == b'`' {
            Node::CodeInline(CodeInline { value, position })
        } else {
            Node::MathInline(MathInline { value, position })
        };
        self.push_node(node, end);
    }

    fn delimiter(&mut self) {
        let src = self.src();
        let bytes = src.as_bytes();
        let start = self.pos;
        let ch = bytes[start];
        let size = bytes[start..].iter().take_while(|&&b| b == ch).count();
        let end = start + size;

        // Strikethrough runs are one or two tildes.
        if ch == b'~' && size > 2 {
            self.pos = end;
            return;
        }

        let before = src[..start].chars().next_back();
        let after = src[end..].chars().next();
        let (can_open, can_close) = emphasis::flanking(ch, before, after, self.context.flavor.has_gfm());
        if !can_open && !can_close {
            self.pos = end;
            return;
        }

        let delim = Delim {
            ch,
            start,
            count: size,
            original: size,
            can_open,
            can_close,
        };
        self.push(Item::Delim(delim), end);
    }

    fn open(&mut self, image: bool) {
        let opener = Opener { image, start: self.pos };
        let end = self.pos + if image { 2 } else { 1 };
        self.flush();
        self.openers.push(self.items.len());
        self.depths.push(0);
        self.items.push(Item::Open(opener));
        self.pos = end;
        self.run = end;
    }

    fn close(&mut self) {
        self.flush();
        if !link::close(self) {
            // Not a link: the bracket stays plain text.
            self.pos += 1;
        }
    }

    /// `<` starts an autolink or raw inline HTML.
    fn angle(&mut self) {
        let context = self.context;
        let src = context.src();
        let pos = self.pos;
        if let Some(autolink) = html::autolink(src, pos) {
            let position = |start, end| Some(self.context.position(start, end));
            let node = Node::Link(crate::node::Link {
                url: crate::node::Url(autolink.url),
                title: None,
                values: vec![Node::Text(Text {
                    value: autolink.text.of(src).to_string(),
                    position: position(autolink.text.start, autolink.text.end),
                })],
                position: position(pos, autolink.end),
            });
            self.push_node(node, autolink.end);
        } else if let Some(end) = html::inline_html(src, pos, &mut self.misses) {
            // Lines of a paragraph lose their leading whitespace, also inside a tag.
            let value = src[pos..end]
                .split_inclusive('\n')
                .enumerate()
                .map(|(index, line)| {
                    if index == 0 {
                        line
                    } else {
                        line.trim_start_matches([' ', '\t'])
                    }
                })
                .collect::<String>();
            let node = Node::Html(crate::node::Html {
                value,
                position: Some(self.context.position(pos, end)),
            });
            self.push_node(node, end);
        } else {
            self.pos += 1;
        }
    }

    /// A JSX tag in MDX text.
    fn jsx(&mut self) {
        match mdx::tag(self.src(), self.pos, Some(&self.braces)) {
            Parsed::Ok(tag) => {
                let end = tag.end;
                let item = Item::Jsx(TextTag {
                    name: tag.name,
                    attributes: tag.attributes,
                    kind: tag.kind,
                    start: self.pos,
                    end,
                });
                self.push(item, end);
            }
            Parsed::Error(error) | Parsed::More(Fallback::Error(error)) => {
                self.context.fail(error);
                self.pos += 1;
            }
            Parsed::Nok | Parsed::More(Fallback::Nok) => self.pos += 1,
        }
    }

    /// An expression in MDX text.
    fn expression(&mut self) {
        match mdx::expression(self.src(), self.pos, Some(&self.braces)) {
            Parsed::Ok((end, value)) => {
                let node = Node::MdxTextExpression(MdxTextExpression {
                    value,
                    position: Some(self.context.position(self.pos, end)),
                });
                self.push_node(node, end);
            }
            Parsed::Error(error) | Parsed::More(Fallback::Error(error)) => {
                self.context.fail(error);
                self.pos += 1;
            }
            Parsed::Nok | Parsed::More(Fallback::Nok) => self.pos += 1,
        }
    }

    fn literal_url(&mut self) {
        literal::url(self);
    }
}

/// The value of a code or math span: the content as it is, except that one space or line ending is
/// removed from both ends when both have one and the content is not only spaces and line endings.
fn span_value(content: &str) -> SmolStr {
    let is_space = |b: &u8| matches!(b, b' ' | b'\n');
    let bytes = content.as_bytes();
    if bytes.len() > 2 && is_space(&bytes[0]) && is_space(&bytes[bytes.len() - 1]) && !bytes.iter().all(is_space) {
        SmolStr::new(&content[1..content.len() - 1])
    } else {
        SmolStr::new(content)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    /// The first run of exactly `size` backticks that starts at or after `from`.
    fn first_run(src: &str, size: usize, from: usize) -> Option<usize> {
        let bytes = src.as_bytes();
        (from..bytes.len()).find(|&start| {
            bytes[start] == b'`'
                && (start == 0 || bytes[start - 1] != b'`')
                && bytes[start..].iter().take_while(|&&b| b == b'`').count() == size
        })
    }

    proptest! {
        /// The nearby search and the index agree, on either side of `NEARBY_SPAN`.
        #[test]
        fn next_of_length_finds_the_first_run(
            head in "[`a]{0,12}",
            gap in 0usize..2 * NEARBY_SPAN,
            tail in "[`a]{0,12}",
            size in 1usize..4,
        ) {
            let src = format!("{head}{}{tail}", "a".repeat(gap));
            for from in (0..=src.len()).filter(|&from| src.as_bytes().get(from) != Some(&b'`')) {
                // A fresh index each time, so that every search starts nearby.
                let runs = SpanRuns::default();
                prop_assert_eq!(runs.next_of_length(&src, b'`', size, from), first_run(&src, size, from));
                prop_assert_eq!(runs.next_of_length(&src, b'`', size, from), first_run(&src, size, from));
            }
        }
    }
}