tabnas_markdown/inline.rs
1/* Copyright (c) 2021-2026 Richard Rodger, MIT License */
2
3//! Phase 2 of the CommonMark parse (spec 0.31.2, Appendix A, "Phase 2:
4//! inline structure"). Port of `ts/src/inline.ts` (canonical) and
5//! `go/inline.go`; keep the three in step. The block phase left the raw
6//! text of every paragraph and heading in `string_content`; this module
7//! turns that text into inline children and clears it.
8//!
9//! The shape is the spec's own algorithm: one left-to-right scan over the
10//! subject that appends nodes as it goes, plus two auxiliary stacks that
11//! are resolved out of band, because neither construct can be decided at
12//! the point where its opener is seen:
13//!
14//! - the delimiter stack (section 6.4) holds `*` / `_` (and, under GFM,
15//! `~`) runs, and is resolved by `process_emphasis`;
16//! - the bracket stack (section 6.3) holds `[` and `![`, and is resolved
17//! by `parse_close_bracket` when a `]` turns up.
18//!
19//! Everything else (code spans, autolinks, raw HTML, entities, escapes,
20//! breaks) is decided locally at the scan position. That is what produces
21//! the precedence section 6.3 requires: a code span, autolink or raw HTML
22//! tag is consumed whole during the scan, so it binds more tightly than
23//! emphasis and more tightly than the brackets of a link label. Conversely
24//! brackets bind more tightly than emphasis, because bracket matching
25//! happens during the scan while emphasis matching happens afterwards over
26//! the delimiter stack.
27//!
28//! What differs from the TypeScript, and why (the same list as the Go port):
29//!
30//! - The subject is scanned by BYTE offset. Every character the scan
31//! branches on is ASCII, and no UTF-8 continuation byte can collide with
32//! an ASCII value, so byte scanning is exact. Wherever a whole
33//! *character* is needed (emphasis flanking above all) the character is
34//! decoded before being handed to the Unicode classifiers.
35//! - The sticky (`y`) regexes become `^`-anchored patterns matched against
36//! `subject[pos..]`.
37//! - `parse_link_label` and the small whitespace regexes are hand-coded
38//! loops. The label pattern's `{0,1000}` repeat of an alternation would
39//! expand to a thousand copies under a linear-time engine, and the rest
40//! are cheaper as loops.
41//! - The delimiter stack is a slab of entries linked by index rather than
42//! by pointer, and the bracket stack is a vector; both are what the
43//! arena tree asks for.
44
45use std::collections::HashMap;
46use std::sync::OnceLock;
47
48use regex::Regex;
49
50use crate::common::{
51 decode_entity, is_escapable, is_unicode_punctuation, is_unicode_whitespace, js_trim,
52 normalize_reference, unescape_string, ENTITY_PATTERN, ESCAPABLE_ASCII,
53};
54use crate::node::{MdNode, NodeId, NodeType, ReferenceType, Tree};
55use crate::options::{Options, RefDef, RefMap};
56
57// --- Section 6.6 raw HTML: the tag grammar, spelled out because it is
58// stricter than `<[^>]*>` in every part. Attribute names are
59// XML-restricted-to-ASCII; unquoted attribute values exclude quotes, `=`,
60// `<`, `>`, backtick and all control characters; comments, PIs,
61// declarations and CDATA each have their own terminator. `INLINE_SPACE*`
62// stands in for "spaces, tabs, and up to one line ending": a paragraph can
63// never contain a blank line, so a single run can only ever span one line
64// ending anyway.
65
66/// JavaScript's `\s`, spelled out: the `regex` crate's `\s` is a different
67/// set, so using it here would reject tags the TypeScript accepts.
68const INLINE_SPACE: &str = "[ \\t\\n\\x0B\\x0C\\r\
69\\x{00a0}\\x{1680}\\x{2000}-\\x{200a}\\x{2028}\\x{2029}\\x{202f}\\x{205f}\\x{feff}\\x{3000}]";
70
71const INLINE_TAG_NAME: &str = "[A-Za-z][A-Za-z0-9-]*";
72const INLINE_ATTRIBUTE_NAME: &str = "[a-zA-Z_:][a-zA-Z0-9:._-]*";
73const INLINE_UNQUOTED_VALUE: &str = "[^\"'=<>`\\x00-\\x20]+";
74const INLINE_SINGLE_QUOTED_VALUE: &str = "'[^']*'";
75const INLINE_DOUBLE_QUOTED_VALUE: &str = "\"[^\"]*\"";
76
77/// Section 6.6: `<!-->` and `<!--->` are comments in their own right;
78/// otherwise the body simply may not contain `-->`, which the lazy
79/// quantifier enforces.
80const INLINE_HTML_COMMENT: &str = r"<!-->|<!--->|<!--[\s\S]*?-->";
81const INLINE_PROCESSING_INSTRUCTION: &str = r"[<][?][\s\S]*?[?][>]";
82const INLINE_DECLARATION: &str = "<![A-Za-z][^>]*>";
83/// The TypeScript compiles the whole tag pattern with the `i` flag, which
84/// here only ever matters for the literal `CDATA`; every other letter in
85/// the grammar is already spelled in both cases. Written out rather than
86/// left to `(?i)`, because the `regex` crate folds case over all of
87/// Unicode: `(?i)[A-Za-z]` also matches U+017F LATIN SMALL LETTER LONG S
88/// and U+212A KELVIN SIGN, where JavaScript's non-unicode `i` does not.
89const INLINE_CDATA: &str = r"<!\[[cC][dD][aA][tT][aA]\[[\s\S]*?\]\]>";
90
91/// JavaScript's `.` without the `s` flag: it excludes `\n`, `\r`, U+2028
92/// and U+2029.
93const INLINE_JS_DOT: &str = r"[^\n\r\x{2028}\x{2029}]";
94
95fn re_html_tag() -> &'static Regex {
96 static RE: OnceLock<Regex> = OnceLock::new();
97 RE.get_or_init(|| {
98 let attribute_value = format!(
99 "(?:{INLINE_UNQUOTED_VALUE}|{INLINE_SINGLE_QUOTED_VALUE}|{INLINE_DOUBLE_QUOTED_VALUE})"
100 );
101 let attribute_value_spec = format!("(?:{INLINE_SPACE}*={INLINE_SPACE}*{attribute_value})");
102 let attribute = format!("(?:{INLINE_SPACE}+{INLINE_ATTRIBUTE_NAME}{attribute_value_spec}?)");
103 let open_tag = format!("<{INLINE_TAG_NAME}{attribute}*{INLINE_SPACE}*/?>");
104 let close_tag = format!("</{INLINE_TAG_NAME}{INLINE_SPACE}*>");
105 Regex::new(&format!(
106 "^(?:{open_tag}|{close_tag}|{INLINE_HTML_COMMENT}|{INLINE_PROCESSING_INSTRUCTION}|{INLINE_DECLARATION}|{INLINE_CDATA})"
107 ))
108 .expect("the raw HTML pattern compiles")
109 })
110}
111
112fn re_entity_here() -> &'static Regex {
113 static RE: OnceLock<Regex> = OnceLock::new();
114 RE.get_or_init(|| {
115 Regex::new(&format!("^(?:{ENTITY_PATTERN})")).expect("a literal pattern compiles")
116 })
117}
118
119/// Section 6.3 link destination, pointy-bracket form: no line endings, no
120/// unescaped `<` or `>`.
121fn re_link_destination_braces() -> &'static Regex {
122 static RE: OnceLock<Regex> = OnceLock::new();
123 RE.get_or_init(|| {
124 Regex::new(&format!(r"^<(?:[^<>\n\\\x00]|\\{INLINE_JS_DOT})*>"))
125 .expect("a literal pattern compiles")
126 })
127}
128
129/// Section 6.3 link title in `"`, `'` or `(...)` delimiters. The escape
130/// alternative comes first so that `\"` inside a double-quoted title is
131/// consumed as an escape rather than closing the title.
132fn re_link_title() -> &'static Regex {
133 static RE: OnceLock<Regex> = OnceLock::new();
134 RE.get_or_init(|| {
135 let escaped = format!(r"\\[{}]", regex::escape(ESCAPABLE_ASCII));
136 Regex::new(&format!(
137 "^(?:\"(?:{escaped}|[^\"\\x00])*\"|'(?:{escaped}|[^'\\x00])*'|\\((?:{escaped}|[^()\\x00])*\\))"
138 ))
139 .expect("a literal pattern compiles")
140 })
141}
142
143/// Section 6.5 autolinks. Scheme: an ASCII letter then 1 to 31 more of
144/// letter / digit / `+` / `.` / `-`, i.e. 2 to 32 characters in total.
145fn re_autolink() -> &'static Regex {
146 static RE: OnceLock<Regex> = OnceLock::new();
147 RE.get_or_init(|| {
148 Regex::new(r"^<[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*>")
149 .expect("a literal pattern compiles")
150 })
151}
152
153fn re_email_autolink() -> &'static Regex {
154 static RE: OnceLock<Regex> = OnceLock::new();
155 RE.get_or_init(|| {
156 Regex::new(
157 "^<([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+\
158@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\
159(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>",
160 )
161 .expect("a literal pattern compiles")
162 })
163}
164
165/// Maximum `(` nesting inside a bare link destination. The spec describes
166/// balanced parentheses without stating a bound; cmark uses 32, and the
167/// bound is what keeps an unbalanced run from being quadratic (see
168/// `scan_link_destination`).
169const MAX_LINK_PAREN_NESTING: usize = 32;
170
171/// The most inline containers (emphasis, strong emphasis, strikethrough,
172/// links and images) that may nest inside one block. A delimiter pair,
173/// link or image whose content already holds that many nested containers
174/// stays literal text.
175///
176/// The reason is the same as `block::MAX_CONTAINER_NESTING` (see there
177/// for the measurements): each wrapper is two levels of the projected
178/// `tabnas::Value`, whose destructor and `to_json` recurse per level, and
179/// `****x****` nests one `strong` per two stars a side. The canonical
180/// TypeScript has no such limit; `DIVERGENCE.md` records it, and
181/// `tests/robust_test.rs` pins the boundary.
182pub const MAX_INLINE_NESTING: usize = 50;
183
184/// The code span search memo, cmark's `backticks[]`: the start of the
185/// last backtick run of each length that a scan has passed, and whether
186/// a scan has reached the end of the subject. Once one has, every run
187/// after that scan's start is on record, so an opener whose length has
188/// no run ahead of it is refused without rescanning. Without it, a
189/// subject holding unmatched runs of distinct lengths rescanned its whole
190/// tail once per run.
191///
192/// An entry only ever moves forward. A scan that succeeds part way stops
193/// before the last run of its length, and letting it overwrite the
194/// position a full scan recorded would hide a later closer from the next
195/// opener.
196#[derive(Debug, Clone, Default)]
197pub struct BacktickMemo {
198 last_run: HashMap<usize, usize>,
199 scanned_to_end: bool,
200}
201
202fn text_node(tree: &mut Tree, literal: &str) -> NodeId {
203 let mut node = MdNode::new(NodeType::Text);
204 node.literal = literal.to_string();
205 tree.add(node)
206}
207
208/// Whether a byte can start an inline construct, i.e. whether it
209/// terminates a run of ordinary text. The TypeScript spells this as the
210/// negated classes of `reMain` / `reMainGfm`; `~` is only special under
211/// GFM.
212fn is_inline_special_byte(c: u8, gfm: bool) -> bool {
213 match c {
214 b'\n' | b'`' | b'[' | b']' | b'\\' | b'!' | b'<' | b'&' | b'*' | b'_' => true,
215 b'~' => gfm,
216 _ => false,
217 }
218}
219
220/// The TypeScript's `reWhitespaceChar`, `/[ \t\n\v\f\r]/`.
221fn is_inline_whitespace_byte(c: u8) -> bool {
222 matches!(c, b' ' | b'\t' | b'\n' | b'\x0B' | b'\x0C' | b'\r')
223}
224
225/// Drop `n` bytes from the end of a delimiter run's literal. The literal is
226/// a run of ASCII `*`, `_` or `~`, so bytes and characters agree.
227fn trim_delim_tail(s: &mut String, n: usize) {
228 let keep = s.len().saturating_sub(n);
229 s.truncate(keep);
230}
231
232/// One `*`, `_` or `~` run on the delimiter stack (section 6.4).
233#[derive(Debug, Clone)]
234struct Delimiter {
235 /// The delimiter character.
236 cc: u8,
237 /// Delimiters still unused; drops as pairs are consumed.
238 numdelims: usize,
239 /// Run length as originally scanned, what the rule of three is computed
240 /// on.
241 origdelims: usize,
242 node: NodeId,
243 previous: Option<usize>,
244 next: Option<usize>,
245 can_open: bool,
246 can_close: bool,
247}
248
249/// One `[` or `![` on the bracket stack (section 6.3).
250#[derive(Debug, Clone)]
251struct Bracket {
252 node: NodeId,
253 /// Top of the delimiter stack when this bracket opened: the emphasis
254 /// floor.
255 previous_delimiter: Option<usize>,
256 /// Offset of the `[` in the subject.
257 index: usize,
258 image: bool,
259 /// Cleared on earlier openers once a link is built: no links in links.
260 active: bool,
261 /// Another bracket opened after this one, so its text contains a `[`.
262 bracket_after: bool,
263}
264
265/// What `scan_delimiter_run` reports about a run.
266#[derive(Debug, Clone, Copy, PartialEq, Eq)]
267pub struct DelimScan {
268 pub numdelims: usize,
269 pub can_open: bool,
270 pub can_close: bool,
271}
272
273// --- pure recognizers -------------------------------------------------------
274//
275// Recognition split from node building: each function inspects `subject`
276// at `pos` and reports what it found, moving nothing and touching no tree.
277// The scanner methods below delegate to them, and they are public so any
278// other driver over the same syntax shares this exact recognition logic
279// instead of reimplementing it.
280
281/// Apply a `^`-anchored regex at `pos`; the match text, or `None`.
282fn regex_at<'s>(re: &Regex, subject: &'s str, pos: usize) -> Option<&'s str> {
283 re.find(&subject[pos..])
284 .map(|m| &subject[pos + m.start()..pos + m.end()])
285}
286
287/// The whole character ending at `end`, so an astral character is
288/// classified as one character by the flanking rules rather than as a
289/// stray byte. Start of subject counts as a line ending (section 6.4).
290pub fn code_point_before(subject: &str, end: usize) -> char {
291 if end == 0 {
292 return '\n';
293 }
294 subject[..end].chars().next_back().unwrap_or('\n')
295}
296
297/// The whole character at `i`; end of subject counts as a line ending.
298pub fn code_point_at(subject: &str, i: usize) -> char {
299 if i >= subject.len() {
300 return '\n';
301 }
302 subject[i..].chars().next().unwrap_or('\n')
303}
304
305/// The end of the run of spaces starting at `pos`.
306pub fn skip_initial_spaces(subject: &str, mut pos: usize) -> usize {
307 let bytes = subject.as_bytes();
308 while pos < bytes.len() && bytes[pos] == b' ' {
309 pos += 1;
310 }
311 pos
312}
313
314/// The end of "spaces, and at most one line ending" starting at `pos`
315/// (section 6.3).
316pub fn match_spnl(subject: &str, pos: usize) -> usize {
317 let mut pos = skip_initial_spaces(subject, pos);
318 if pos < subject.len() && subject.as_bytes()[pos] == b'\n' {
319 pos = skip_initial_spaces(subject, pos + 1);
320 }
321 pos
322}
323
324/// A code span (section 6.3), or an unmatched opener, which is literal
325/// text.
326#[derive(Debug, Clone, PartialEq, Eq)]
327pub enum CodeSpanScan {
328 Closed { end: usize, literal: String },
329 Open { end: usize, ticks: String },
330}
331
332/// The code span starting at `pos`: a backtick string to the next backtick
333/// string of *exactly* the same length. `None` when no backtick run starts
334/// at `pos`.
335///
336/// Hand-coded rather than the TypeScript's sticky and global regexes, so
337/// that no regex is built from an input-derived run length.
338pub fn scan_code_span(subject: &str, pos: usize) -> Option<CodeSpanScan> {
339 scan_code_span_memo(subject, pos, &mut BacktickMemo::default())
340}
341
342/// [`scan_code_span`] with the search memo the inline parser keeps per
343/// block, so that a subject full of unmatched runs is scanned once.
344pub fn scan_code_span_memo(
345 subject: &str,
346 pos: usize,
347 memo: &mut BacktickMemo,
348) -> Option<CodeSpanScan> {
349 let s = subject.as_bytes();
350 let mut i = pos;
351 while i < s.len() && s[i] == b'`' {
352 i += 1;
353 }
354 if i == pos {
355 return None;
356 }
357 let tick_len = i - pos;
358 let after_open_ticks = i;
359
360 // A full scan has been past here: a closer exists only if a run of
361 // this length was recorded after the opener.
362 if memo.scanned_to_end && memo.last_run.get(&tick_len).is_none_or(|&last| last <= pos) {
363 return Some(CodeSpanScan::Open {
364 end: after_open_ticks,
365 ticks: subject[pos..after_open_ticks].to_string(),
366 });
367 }
368
369 while i < s.len() {
370 if s[i] != b'`' {
371 i += 1;
372 continue;
373 }
374 let run_start = i;
375 while i < s.len() && s[i] == b'`' {
376 i += 1;
377 }
378 let run_len = i - run_start;
379 memo.last_run
380 .entry(run_len)
381 .and_modify(|last| *last = (*last).max(run_start))
382 .or_insert(run_start);
383 if run_len == tick_len {
384 // Line endings become spaces; then one leading and one trailing
385 // space are stripped together, but only if the content is not
386 // all spaces (which is what lets a code span hold backticks).
387 let contents = subject[after_open_ticks..i - tick_len].replace('\n', " ");
388 let has_non_space = contents.bytes().any(|b| b != b' ');
389 let literal = if contents.len() > 2
390 && contents.starts_with(' ')
391 && contents.ends_with(' ')
392 && has_non_space
393 {
394 contents[1..contents.len() - 1].to_string()
395 } else {
396 contents
397 };
398 return Some(CodeSpanScan::Closed { end: i, literal });
399 }
400 }
401
402 memo.scanned_to_end = true;
403 Some(CodeSpanScan::Open {
404 end: after_open_ticks,
405 ticks: subject[pos..after_open_ticks].to_string(),
406 })
407}
408
409/// How a backslash escape resolves (sections 6.1 and 6.7).
410#[derive(Debug, Clone, PartialEq, Eq)]
411pub enum EscapeKind {
412 Linebreak,
413 Char,
414 Literal,
415}
416
417#[derive(Debug, Clone, PartialEq, Eq)]
418pub struct EscapeScan {
419 pub kind: EscapeKind,
420 pub literal: String,
421 pub end: usize,
422}
423
424/// The backslash escape with `pos` at the backslash. Always succeeds: a
425/// backslash before anything unescapable is a literal backslash. The
426/// linebreak form consumes the following line's leading spaces.
427pub fn scan_escape(subject: &str, pos: usize) -> EscapeScan {
428 let bytes = subject.as_bytes();
429 let next = pos + 1;
430 if next < bytes.len() && bytes[next] == b'\n' {
431 return EscapeScan {
432 kind: EscapeKind::Linebreak,
433 literal: String::new(),
434 end: skip_initial_spaces(subject, next + 1),
435 };
436 }
437 if next < bytes.len() && is_escapable(bytes[next]) {
438 return EscapeScan {
439 kind: EscapeKind::Char,
440 literal: subject[next..next + 1].to_string(),
441 end: next + 1,
442 };
443 }
444 EscapeScan {
445 kind: EscapeKind::Literal,
446 literal: "\\".to_string(),
447 end: next,
448 }
449}
450
451/// An email or URI autolink in angle brackets (section 6.5).
452#[derive(Debug, Clone, PartialEq, Eq)]
453pub struct AngleAutolinkScan {
454 pub dest: String,
455 pub label: String,
456 pub end: usize,
457}
458
459pub fn scan_angle_autolink(subject: &str, pos: usize) -> Option<AngleAutolinkScan> {
460 if let Some(m) = regex_at(re_email_autolink(), subject, pos) {
461 let dest = &m[1..m.len() - 1];
462 return Some(AngleAutolinkScan {
463 dest: format!("mailto:{dest}"),
464 label: dest.to_string(),
465 end: pos + m.len(),
466 });
467 }
468 if let Some(m) = regex_at(re_autolink(), subject, pos) {
469 let dest = &m[1..m.len() - 1];
470 return Some(AngleAutolinkScan {
471 dest: dest.to_string(),
472 label: dest.to_string(),
473 end: pos + m.len(),
474 });
475 }
476 None
477}
478
479/// A raw HTML tag (section 6.6) at `pos`: open, close, comment, PI,
480/// declaration or CDATA. Returns the raw text and the end offset.
481pub fn scan_html_tag(subject: &str, pos: usize) -> Option<(String, usize)> {
482 regex_at(re_html_tag(), subject, pos).map(|m| (m.to_string(), pos + m.len()))
483}
484
485/// An entity or numeric character reference (section 6.2), decoded.
486/// Returns the decoded text and the end offset.
487pub fn scan_entity(subject: &str, pos: usize) -> Option<(String, usize)> {
488 regex_at(re_entity_here(), subject, pos).map(|m| (decode_entity(m), pos + m.len()))
489}
490
491/// Classify the run of `cc` starting at `pos` without consuming it
492/// (section 6.4): a run is left-flanking iff it is not followed by Unicode
493/// whitespace and either not followed by Unicode punctuation or else
494/// preceded by whitespace or punctuation; right-flanking is the mirror
495/// image. `_` additionally may not open inside a word (rules 2, 4, 6, 8),
496/// which is what keeps `snake_case_words` intact; `*` has no such
497/// restriction.
498///
499/// The two neighbouring characters are decoded as characters, not read as
500/// bytes: classify `é` or `。` by its first UTF-8 byte and most of section
501/// 6.4 silently breaks on non-ASCII input.
502pub fn scan_delimiter_run(subject: &str, pos: usize, cc: u8) -> Option<DelimScan> {
503 let bytes = subject.as_bytes();
504 let mut numdelims = 0;
505 let mut p = pos;
506 while p < bytes.len() && bytes[p] == cc {
507 numdelims += 1;
508 p += 1;
509 }
510 if numdelims == 0 {
511 return None;
512 }
513
514 let char_before = code_point_before(subject, pos);
515 let char_after = code_point_at(subject, p);
516
517 let after_is_whitespace = is_unicode_whitespace(char_after);
518 let after_is_punctuation = is_unicode_punctuation(char_after);
519 let before_is_whitespace = is_unicode_whitespace(char_before);
520 let before_is_punctuation = is_unicode_punctuation(char_before);
521
522 let left_flanking = !after_is_whitespace
523 && (!after_is_punctuation || before_is_whitespace || before_is_punctuation);
524 let right_flanking = !before_is_whitespace
525 && (!before_is_punctuation || after_is_whitespace || after_is_punctuation);
526
527 let (can_open, can_close) = if cc == b'_' {
528 (
529 left_flanking && (!right_flanking || before_is_punctuation),
530 right_flanking && (!left_flanking || after_is_punctuation),
531 )
532 } else {
533 (left_flanking, right_flanking)
534 };
535
536 Some(DelimScan {
537 numdelims,
538 can_open,
539 can_close,
540 })
541}
542
543/// How a line ending resolves (sections 6.7 and 6.8), given the literal of
544/// the text node immediately before it (`None` when that node is absent or
545/// not text). Two or more trailing spaces make a hard break; `trim` says
546/// the trailing spaces must be dropped from that node either way. Returns
547/// `(hard, trim)`.
548pub fn classify_break(prev_text_literal: Option<&str>) -> (bool, bool) {
549 let Some(prev) = prev_text_literal else {
550 return (false, false);
551 };
552 let bytes = prev.as_bytes();
553 if bytes.last() != Some(&b' ') {
554 return (false, false);
555 }
556 (bytes.len() > 1 && bytes[bytes.len() - 2] == b' ', true)
557}
558
559/// A link title at `pos` (section 6.3), without its delimiters, unescaped.
560/// Returns the title and the end offset.
561pub fn scan_link_title(subject: &str, pos: usize) -> Option<(String, usize)> {
562 regex_at(re_link_title(), subject, pos)
563 .map(|m| (unescape_string(&m[1..m.len() - 1]), pos + m.len()))
564}
565
566/// A link destination at `pos` (section 6.3): either `<...>`, or a bare run
567/// with balanced unescaped parentheses and no ASCII control characters or
568/// spaces. Returns the destination and the end offset.
569///
570/// The destination is backslash-unescaped and entity-decoded, but **not**
571/// percent-encoded: `[l](/ä)` yields `/ä`, not `/%C3%A4`. Encoding is a
572/// rendering concern and `html.rs` applies `normalize_uri` when it writes
573/// the attribute; the public AST promises the decoded form.
574pub fn scan_link_destination(subject: &str, pos: usize) -> Option<(String, usize)> {
575 if let Some(braced) = regex_at(re_link_destination_braces(), subject, pos) {
576 return Some((
577 unescape_string(&braced[1..braced.len() - 1]),
578 pos + braced.len(),
579 ));
580 }
581 let bytes = subject.as_bytes();
582 if pos < bytes.len() && bytes[pos] == b'<' {
583 return None;
584 }
585
586 let mut p = pos;
587 let mut openparens = 0usize;
588
589 while p < bytes.len() {
590 let c = bytes[p];
591 if c == b'\\' && p + 1 < bytes.len() && is_escapable(bytes[p + 1]) {
592 p += 1;
593 if p < bytes.len() {
594 p += 1;
595 }
596 } else if c == b'(' {
597 // Bail rather than scan on once nesting passes the limit.
598 // Without this, input like `[a](b` repeated makes every `]`
599 // scan to end of input looking for parens that never balance,
600 // which is quadratic in the document size. cmark caps nesting
601 // at the same depth, and no spec example nests more than two
602 // deep.
603 if openparens >= MAX_LINK_PAREN_NESTING {
604 return None;
605 }
606 p += 1;
607 openparens += 1;
608 } else if c == b')' {
609 if openparens < 1 {
610 break;
611 }
612 p += 1;
613 openparens -= 1;
614 } else if c <= b' ' || c == 0x7F {
615 // Spaces and ASCII control characters end the bare form.
616 break;
617 } else {
618 p += 1;
619 }
620 }
621
622 // An empty destination is only legal immediately before the closing
623 // paren of an inline link, as in `[link]()`.
624 if p == pos && !(p < bytes.len() && bytes[p] == b')') {
625 return None;
626 }
627 if openparens != 0 {
628 return None;
629 }
630
631 Some((unescape_string(&subject[pos..p]), p))
632}
633
634/// A link label at `pos` (sections 4.7 and 6.3), brackets included.
635/// Returns `(raw_length, length)`: `raw_length` is what was consumed, and
636/// `length` is 0 when the label is too long to be valid (at most 999
637/// characters between the brackets). `None` when no label is here at all.
638///
639/// Hand-coded where the TypeScript uses `/\[(?:[^\\[\]]|\\.){0,1000}\]/sy`.
640/// The scan accepts the same language: every alternative of the repeat
641/// begins on a character that is not `]`, so shortening the greedy run can
642/// only put a non-`]` where the closing bracket must be.
643pub fn scan_link_label(subject: &str, pos: usize) -> Option<(usize, usize)> {
644 let s = subject.as_bytes();
645 if pos >= s.len() || s[pos] != b'[' {
646 return None;
647 }
648
649 let mut i = pos + 1;
650 let mut iters = 0;
651 // Length in UTF-16 code units, which is the unit the TypeScript's
652 // `m.length > 1001` test counts in, hence the 2 for an astral character
653 // below.
654 let mut units = 1;
655
656 loop {
657 if i >= s.len() {
658 return None;
659 }
660 let c = s[i];
661 if c == b']' {
662 i += 1;
663 units += 1;
664 let raw = i - pos;
665 // Section 4.7: at most 999 characters between the brackets.
666 if units > 1001 {
667 return Some((raw, 0));
668 }
669 return Some((raw, raw));
670 }
671 // An unescaped `[` cannot be consumed by the repeat, and is not the
672 // `]` the pattern then demands. Nor can a 1001st repeat run.
673 if c == b'[' || iters == 1000 {
674 return None;
675 }
676 if c == b'\\' {
677 // `\\.`: with the `s` flag, any character at all, line endings
678 // included.
679 i += 1;
680 units += 1;
681 if i >= s.len() {
682 return None;
683 }
684 }
685 let ch = code_point_at(subject, i);
686 i += ch.len_utf8();
687 units += ch.len_utf16();
688 iters += 1;
689 }
690}
691
692/// The `(destination "title")` tail of an inline link.
693#[derive(Debug, Clone, PartialEq, Eq)]
694pub struct LinkTailScan {
695 pub dest: String,
696 pub title: Option<String>,
697 pub end: usize,
698}
699
700/// The inline-link tail with `pos` just after the `]`. `None` unless the
701/// whole tail, through the closing paren, is present.
702pub fn scan_inline_link_tail(subject: &str, pos: usize) -> Option<LinkTailScan> {
703 let bytes = subject.as_bytes();
704 if pos >= bytes.len() || bytes[pos] != b'(' {
705 return None;
706 }
707
708 let mut p = match_spnl(subject, pos + 1);
709 let (dest, d_end) = scan_link_destination(subject, p)?;
710
711 p = match_spnl(subject, d_end);
712 let mut title = None;
713 // A title has to be separated from the destination by whitespace, so
714 // `[a](/url"t")` is not a titled link.
715 if p >= 1 && p - 1 < bytes.len() && is_inline_whitespace_byte(bytes[p - 1]) {
716 if let Some((t, t_end)) = scan_link_title(subject, p) {
717 title = Some(t);
718 p = t_end;
719 }
720 }
721 p = match_spnl(subject, p);
722
723 if p < bytes.len() && bytes[p] == b')' {
724 return Some(LinkTailScan {
725 dest,
726 title,
727 end: p + 1,
728 });
729 }
730 None
731}
732
733/// The inline scanner: the subject, the scan position, and the two
734/// auxiliary stacks.
735pub struct InlineParser {
736 pub subject: String,
737 pub pos: usize,
738 delims: Vec<Delimiter>,
739 /// Top of the delimiter stack, as an index into `delims`.
740 delim_top: Option<usize>,
741 brackets: Vec<Bracket>,
742 pub refmap: RefMap,
743 pub options: Options,
744 /// The nesting height of every inline container made for the current
745 /// block: 1 for one wrapping only leaves, and one more per level.
746 /// Leaves are absent and count 0. `MAX_INLINE_NESTING` is judged from
747 /// it; see `run_height`.
748 nesting: HashMap<NodeId, usize>,
749 /// The code span search memo for the current block's subject.
750 backticks: BacktickMemo,
751 /// Read a bracketed label as a reference whether or not the document
752 /// defines it, keeping it unresolved (`link_reference`,
753 /// `image_reference`) rather than looking it up in `refmap`: the parse
754 /// the AST is projected from. The inline parse of a block then depends
755 /// on nothing outside the block, which is what lets the engine path
756 /// finish a block's inlines when the block closes. Off, the parse
757 /// resolves references as CommonMark does, which the HTML renderer
758 /// needs.
759 pub keep_references: bool,
760}
761
762/// A link reference definition as [`parse_definitions`] reads one
763/// (section 4.7).
764#[derive(Debug, Clone, PartialEq, Eq)]
765pub struct ParsedDefinition {
766 /// The BYTE range of the subject the definition takes.
767 pub start: usize,
768 pub end: usize,
769 /// The label's raw source text, between its brackets.
770 pub label: String,
771 pub destination: String,
772 pub title: Option<String>,
773}
774
775impl InlineParser {
776 pub fn new(refmap: RefMap, options: Options) -> Self {
777 InlineParser {
778 subject: String::new(),
779 pos: 0,
780 delims: Vec::new(),
781 delim_top: None,
782 brackets: Vec::new(),
783 refmap,
784 options,
785 nesting: HashMap::new(),
786 backticks: BacktickMemo::default(),
787 keep_references: false,
788 }
789 }
790
791 /// A parser that keeps references unresolved (see `keep_references`).
792 pub fn keeping_references(options: Options) -> Self {
793 let mut parser = InlineParser::new(RefMap::new(), options);
794 parser.keep_references = true;
795 parser
796 }
797
798 /// The tallest nesting height among the siblings from `from` up to
799 /// but not including `until` (or to the end of the run). Stops at
800 /// `MAX_INLINE_NESTING`, the only threshold the callers compare
801 /// against, so the walk never costs more than it decides.
802 fn run_height(&self, tree: &Tree, from: Option<NodeId>, until: Option<NodeId>) -> usize {
803 let mut height = 0;
804 let mut cur = from;
805 while let Some(id) = cur {
806 if cur == until || height >= MAX_INLINE_NESTING {
807 break;
808 }
809 height = height.max(self.nesting.get(&id).copied().unwrap_or(0));
810 cur = tree.get(id).next;
811 }
812 height
813 }
814
815 // --- scanning primitives ---
816
817 /// The byte at `pos`, or `None` at the end of the subject.
818 fn peek(&self) -> Option<u8> {
819 self.subject.as_bytes().get(self.pos).copied()
820 }
821
822 /// Spaces, and at most one line ending, between the parts of a link.
823 fn spnl(&mut self) {
824 self.pos = match_spnl(&self.subject, self.pos);
825 }
826
827 fn skip_spaces(&mut self) {
828 self.pos = skip_initial_spaces(&self.subject, self.pos);
829 }
830
831 /// The TypeScript's `reIndent`, `/ {0,3}/y`.
832 fn skip_indent(&mut self) {
833 let bytes = self.subject.as_bytes();
834 let mut n = 0;
835 while n < 3 && self.pos < bytes.len() && bytes[self.pos] == b' ' {
836 self.pos += 1;
837 n += 1;
838 }
839 }
840
841 /// The TypeScript's `reSpaceAtEndOfLine`, `/ *(?:\n|$)/y`. On failure
842 /// `pos` is left alone, as a failed sticky match would leave it.
843 fn space_at_end_of_line(&mut self) -> bool {
844 let bytes = self.subject.as_bytes();
845 let mut i = self.pos;
846 while i < bytes.len() && bytes[i] == b' ' {
847 i += 1;
848 }
849 if i < bytes.len() {
850 if bytes[i] != b'\n' {
851 return false;
852 }
853 i += 1;
854 }
855 self.pos = i;
856 true
857 }
858
859 // --- section 6.3 code spans ---
860
861 /// A code span runs from a backtick string to the next backtick string
862 /// of *exactly* the same length. Unmatched opening backticks are
863 /// literal text.
864 pub fn parse_backticks(&mut self, tree: &mut Tree, block: NodeId) -> bool {
865 let Some(scan) = scan_code_span_memo(&self.subject, self.pos, &mut self.backticks) else {
866 return false;
867 };
868 match scan {
869 CodeSpanScan::Closed { end, literal } => {
870 self.pos = end;
871 let mut node = MdNode::new(NodeType::Code);
872 node.literal = literal;
873 let id = tree.add(node);
874 tree.append_child(block, id);
875 }
876 CodeSpanScan::Open { end, ticks } => {
877 // No closing run of the same length: the opener is literal
878 // text.
879 self.pos = end;
880 let id = text_node(tree, &ticks);
881 tree.append_child(block, id);
882 }
883 }
884 true
885 }
886
887 // --- section 6.1 backslash escapes, section 6.7 hard line breaks ---
888
889 pub fn parse_backslash(&mut self, tree: &mut Tree, block: NodeId) -> bool {
890 let scan = scan_escape(&self.subject, self.pos);
891 self.pos = scan.end;
892 let id = if scan.kind == EscapeKind::Linebreak {
893 tree.new_node(NodeType::Linebreak)
894 } else {
895 text_node(tree, &scan.literal)
896 };
897 tree.append_child(block, id);
898 true
899 }
900
901 // --- section 6.5 autolinks ---
902
903 pub fn parse_autolink(&mut self, tree: &mut Tree, block: NodeId) -> bool {
904 let Some(scan) = scan_angle_autolink(&self.subject, self.pos) else {
905 return false;
906 };
907 self.pos = scan.end;
908 let id = make_autolink(tree, &scan.dest, &scan.label);
909 tree.append_child(block, id);
910 true
911 }
912
913 // --- section 6.6 raw HTML ---
914
915 pub fn parse_html_tag(&mut self, tree: &mut Tree, block: NodeId) -> bool {
916 let Some((raw, end)) = scan_html_tag(&self.subject, self.pos) else {
917 return false;
918 };
919 self.pos = end;
920 let mut node = MdNode::new(NodeType::HtmlInline);
921 node.literal = raw;
922 let id = tree.add(node);
923 tree.append_child(block, id);
924 true
925 }
926
927 // --- section 6.4 emphasis: delimiter runs and flanking ---
928
929 /// Classify the run of `cc` starting at `pos` without consuming it.
930 pub fn scan_delims(&self, cc: u8) -> Option<DelimScan> {
931 scan_delimiter_run(&self.subject, self.pos, cc)
932 }
933
934 /// Emit a delimiter run as text and push it on the delimiter stack.
935 pub fn handle_delim(&mut self, cc: u8, tree: &mut Tree, block: NodeId) -> bool {
936 let Some(res) = self.scan_delims(cc) else {
937 return false;
938 };
939
940 let numdelims = res.numdelims;
941 let startpos = self.pos;
942 self.pos += numdelims;
943
944 let node = text_node(tree, &self.subject[startpos..self.pos]);
945 tree.append_child(block, node);
946
947 // GFM strikethrough only recognises runs of one or two tildes;
948 // longer runs stay literal.
949 let stackable = if cc == b'~' { numdelims <= 2 } else { true };
950
951 if (res.can_open || res.can_close) && stackable {
952 let index = self.delims.len();
953 self.delims.push(Delimiter {
954 cc,
955 numdelims,
956 origdelims: numdelims,
957 node,
958 previous: self.delim_top,
959 next: None,
960 can_open: res.can_open,
961 can_close: res.can_close,
962 });
963 if let Some(prev) = self.delim_top {
964 self.delims[prev].next = Some(index);
965 }
966 self.delim_top = Some(index);
967 }
968
969 true
970 }
971
972 fn remove_delimiter(&mut self, delim: usize) {
973 let previous = self.delims[delim].previous;
974 let next = self.delims[delim].next;
975 if let Some(prev) = previous {
976 self.delims[prev].next = next;
977 }
978 match next {
979 // Top of stack.
980 None => self.delim_top = previous,
981 Some(n) => self.delims[n].previous = previous,
982 }
983 }
984
985 /// The spec's "process emphasis" procedure. `stack_bottom` is the
986 /// floor: for the whole-block call it is `None`, and for the inlines of
987 /// a link it is the delimiter that was on top when the link's `[`
988 /// opened.
989 pub fn process_emphasis(&mut self, tree: &mut Tree, stack_bottom: Option<usize>) {
990 // openers_bottom, keyed by (delimiter char, whether the closer can
991 // also open, closer run length mod 3). Once a closer of some class
992 // fails to find an opener, no later closer of the same class needs
993 // to look past that point either; this is what keeps the search
994 // linear.
995 let mut openers_bottom: HashMap<(u8, bool, usize), Option<usize>> = HashMap::new();
996
997 // First closer above stack_bottom.
998 let mut closer = self.delim_top;
999 while let Some(c) = closer {
1000 if self.delims[c].previous == stack_bottom {
1001 break;
1002 }
1003 closer = self.delims[c].previous;
1004 }
1005
1006 while let Some(c) = closer {
1007 if !self.delims[c].can_close {
1008 closer = self.delims[c].next;
1009 continue;
1010 }
1011
1012 let closercc = self.delims[c].cc;
1013 let key = (
1014 closercc,
1015 self.delims[c].can_open,
1016 self.delims[c].origdelims % 3,
1017 );
1018 let bottom = openers_bottom.get(&key).copied().unwrap_or(stack_bottom);
1019
1020 let mut opener = self.delims[c].previous;
1021 let mut opener_found = false;
1022 while let Some(o) = opener {
1023 if opener == stack_bottom || opener == bottom {
1024 break;
1025 }
1026 let od = &self.delims[o];
1027 if od.cc == closercc && od.can_open {
1028 if closercc == b'~' {
1029 // GFM strikethrough: opener and closer runs must be
1030 // the same length, so `~~x~` is not a match.
1031 if od.numdelims == self.delims[c].numdelims {
1032 opener_found = true;
1033 break;
1034 }
1035 } else {
1036 // Section 6.4 rules 9 and 10, the "rule of three":
1037 // when either side of the pair could both open and
1038 // close, the two run lengths may not sum to a
1039 // multiple of 3, unless both are themselves
1040 // multiples of 3.
1041 let cd = &self.delims[c];
1042 let odd_match = (cd.can_open || od.can_close)
1043 && cd.origdelims % 3 != 0
1044 && (od.origdelims + cd.origdelims) % 3 == 0;
1045 if !odd_match {
1046 opener_found = true;
1047 break;
1048 }
1049 }
1050 }
1051 opener = od.previous;
1052 }
1053
1054 // The nesting limit: a pair whose content already holds
1055 // `MAX_INLINE_NESTING` nested containers stays literal, which
1056 // is the closer finding no opener.
1057 let mut height = 0;
1058 if let Some(o) = opener.filter(|_| opener_found) {
1059 height = self.run_height(
1060 tree,
1061 tree.get(self.delims[o].node).next,
1062 Some(self.delims[c].node),
1063 );
1064 if height >= MAX_INLINE_NESTING {
1065 opener_found = false;
1066 }
1067 }
1068
1069 let old_closer = c;
1070
1071 match opener {
1072 Some(o) if opener_found => {
1073 // Two delimiters make strong, one makes emph;
1074 // strikethrough always consumes the whole (equal-length)
1075 // run.
1076 let use_delims = if closercc == b'~' {
1077 self.delims[c].numdelims
1078 } else if self.delims[c].numdelims >= 2 && self.delims[o].numdelims >= 2 {
1079 2
1080 } else {
1081 1
1082 };
1083 let node_type = if closercc == b'~' {
1084 NodeType::Del
1085 } else if use_delims == 1 {
1086 NodeType::Emph
1087 } else {
1088 NodeType::Strong
1089 };
1090
1091 let opener_inl = self.delims[o].node;
1092 let closer_inl = self.delims[c].node;
1093
1094 self.delims[o].numdelims -= use_delims;
1095 self.delims[c].numdelims -= use_delims;
1096 trim_delim_tail(&mut tree.get_mut(opener_inl).literal, use_delims);
1097 trim_delim_tail(&mut tree.get_mut(closer_inl).literal, use_delims);
1098
1099 // Everything between the two delimiter text nodes
1100 // becomes the content of the new node.
1101 let emph = tree.new_node(node_type);
1102 let mut tmp = tree.get(opener_inl).next;
1103 while let Some(t) = tmp {
1104 if t == closer_inl {
1105 break;
1106 }
1107 let nxt = tree.get(t).next;
1108 tree.unlink(t);
1109 tree.append_child(emph, t);
1110 tmp = nxt;
1111 }
1112 tree.insert_after(opener_inl, emph);
1113 self.nesting.insert(emph, height + 1);
1114
1115 // Delimiters between the pair can never match anything
1116 // now.
1117 if self.delims[o].next != Some(c) {
1118 self.delims[o].next = Some(c);
1119 self.delims[c].previous = Some(o);
1120 }
1121
1122 if self.delims[o].numdelims == 0 {
1123 tree.unlink(opener_inl);
1124 self.remove_delimiter(o);
1125 }
1126 if self.delims[c].numdelims == 0 {
1127 tree.unlink(closer_inl);
1128 let tempstack = self.delims[c].next;
1129 self.remove_delimiter(c);
1130 closer = tempstack;
1131 }
1132 }
1133 _ => {
1134 closer = self.delims[c].next;
1135 openers_bottom.insert(key, self.delims[old_closer].previous);
1136 if !self.delims[old_closer].can_open {
1137 // It found no opener and cannot be one: it is inert.
1138 self.remove_delimiter(old_closer);
1139 }
1140 }
1141 }
1142 }
1143
1144 // Drop everything above the floor.
1145 while let Some(top) = self.delim_top {
1146 if Some(top) == stack_bottom {
1147 break;
1148 }
1149 self.remove_delimiter(top);
1150 }
1151 }
1152
1153 // --- section 6.3 links and images ---
1154
1155 /// The link title without its delimiters, unescaped; `None` when there
1156 /// is no title here.
1157 pub fn parse_link_title(&mut self) -> Option<String> {
1158 let (title, end) = scan_link_title(&self.subject, self.pos)?;
1159 self.pos = end;
1160 Some(title)
1161 }
1162
1163 /// A destination that is backslash-unescaped and entity-decoded, but
1164 /// **not** percent-encoded; see `scan_link_destination`.
1165 pub fn parse_link_destination(&mut self) -> Option<String> {
1166 let (dest, end) = scan_link_destination(&self.subject, self.pos)?;
1167 self.pos = end;
1168 Some(dest)
1169 }
1170
1171 /// The byte length of the link label at `pos`, brackets included,
1172 /// advancing past it; 0 if there is no label here or it is over the
1173 /// section 4.7 999-character limit.
1174 pub fn parse_link_label(&mut self) -> usize {
1175 let Some((raw_len, length)) = scan_link_label(&self.subject, self.pos) else {
1176 return 0;
1177 };
1178 // The raw match is consumed even when it is too long to be a valid
1179 // label; callers that need the position back reset it themselves.
1180 self.pos += raw_len;
1181 length
1182 }
1183
1184 fn add_bracket(&mut self, node: NodeId, index: usize, image: bool) {
1185 if let Some(top) = self.brackets.last_mut() {
1186 top.bracket_after = true;
1187 }
1188 self.brackets.push(Bracket {
1189 node,
1190 previous_delimiter: self.delim_top,
1191 index,
1192 image,
1193 active: true,
1194 bracket_after: false,
1195 });
1196 }
1197
1198 fn remove_bracket(&mut self) {
1199 self.brackets.pop();
1200 }
1201
1202 pub fn parse_open_bracket(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1203 let startpos = self.pos;
1204 self.pos += 1;
1205 let node = text_node(tree, "[");
1206 tree.append_child(block, node);
1207 self.add_bracket(node, startpos, false);
1208 true
1209 }
1210
1211 /// `!` only matters when it introduces an image.
1212 pub fn parse_bang(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1213 let startpos = self.pos;
1214 self.pos += 1;
1215 if self.peek() == Some(b'[') {
1216 self.pos += 1;
1217 let node = text_node(tree, "![");
1218 tree.append_child(block, node);
1219 self.add_bracket(node, startpos + 1, true);
1220 } else {
1221 let node = text_node(tree, "!");
1222 tree.append_child(block, node);
1223 }
1224 true
1225 }
1226
1227 /// The spec's "look for link or image" procedure. On a `]`, walk back
1228 /// to the newest bracket opener and try, in order: an inline
1229 /// `(dest "title")`, a full `[label]`, a collapsed `[]` or a shortcut
1230 /// reference. Anything that fails backtracks to just after the `]` and
1231 /// leaves a literal `]`.
1232 pub fn parse_close_bracket(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1233 self.pos += 1;
1234 let startpos = self.pos;
1235
1236 let Some(opener) = self.brackets.last().cloned() else {
1237 let node = text_node(tree, "]");
1238 tree.append_child(block, node);
1239 return true;
1240 };
1241 if !opener.active {
1242 // Deactivated by an enclosing link: not an opener any more.
1243 let node = text_node(tree, "]");
1244 tree.append_child(block, node);
1245 self.remove_bracket();
1246 return true;
1247 }
1248
1249 let is_image = opener.image;
1250 let mut dest = String::new();
1251 let mut title: Option<String> = None;
1252 let mut matched = false;
1253 // Kept references only: the label and the form that named it.
1254 let mut kept: Option<(String, ReferenceType)> = None;
1255
1256 let savepos = self.pos;
1257
1258 // Inline link: `](` destination title `)`.
1259 if let Some(tail) = scan_inline_link_tail(&self.subject, self.pos) {
1260 self.pos = tail.end;
1261 dest = tail.dest;
1262 title = tail.title;
1263 matched = true;
1264 }
1265
1266 if !matched {
1267 // Reference forms. A second label gives the full form; an empty
1268 // or absent one means the link text is itself the label
1269 // (collapsed and shortcut), which is only possible if that text
1270 // holds no bracket.
1271 let mut reflabel: Option<String> = None;
1272 let mut reftype = ReferenceType::Shortcut;
1273 let beforelabel = self.pos;
1274 let n = self.parse_link_label();
1275 if n > 2 {
1276 reflabel = Some(self.subject[beforelabel + 1..beforelabel + n - 1].to_string());
1277 reftype = ReferenceType::Full;
1278 } else if !opener.bracket_after {
1279 let (lo, hi) = (opener.index + 1, startpos - 1);
1280 if lo <= hi && hi <= self.subject.len() {
1281 reflabel = Some(self.subject[lo..hi].to_string());
1282 if n == 2 {
1283 reftype = ReferenceType::Collapsed;
1284 }
1285 }
1286 }
1287 if n == 0 {
1288 self.pos = savepos;
1289 }
1290
1291 if let Some(label) = reflabel {
1292 if self.keep_references {
1293 // A reference wherever a definition could name the
1294 // label: one a definition's own label could be (a full
1295 // form's second label was scanned as one; the link text
1296 // of the other two forms must scan as one too), holding
1297 // more than white space.
1298 let valid = reftype == ReferenceType::Full
1299 || is_link_label_at(&self.subject, opener.index, startpos);
1300 if valid && !normalize_reference(&label).is_empty() {
1301 kept = Some((label, reftype));
1302 matched = true;
1303 }
1304 } else if let Some(link) = self.refmap.get(&normalize_reference(&label)) {
1305 dest = link.destination.clone();
1306 title = link.title.clone();
1307 matched = true;
1308 }
1309 }
1310 }
1311
1312 if !matched {
1313 self.remove_bracket();
1314 self.pos = startpos;
1315 let node = text_node(tree, "]");
1316 tree.append_child(block, node);
1317 return true;
1318 }
1319
1320 let node = match kept {
1321 Some((label, reftype)) => {
1322 let mut node = MdNode::new(if is_image {
1323 NodeType::ImageReference
1324 } else {
1325 NodeType::LinkReference
1326 });
1327 node.label = label;
1328 node.reference_type = Some(reftype);
1329 node
1330 }
1331 None => {
1332 let mut node = MdNode::new(if is_image {
1333 NodeType::Image
1334 } else {
1335 NodeType::Link
1336 });
1337 node.destination = dest;
1338 // An empty title is the same as no title at all:
1339 // `[a](/url "")` renders a bare `<a href="/url">`.
1340 node.title = title.filter(|t| !t.is_empty());
1341 node
1342 }
1343 };
1344 let node = tree.add(node);
1345
1346 let mut tmp = tree.get(opener.node).next;
1347 while let Some(t) = tmp {
1348 let nxt = tree.get(t).next;
1349 tree.unlink(t);
1350 tree.append_child(node, t);
1351 tmp = nxt;
1352 }
1353 tree.append_child(block, node);
1354
1355 // Emphasis inside the link text resolves now, and only down to the
1356 // delimiter that was current when the `[` opened.
1357 self.process_emphasis(tree, opener.previous_delimiter);
1358
1359 // The nesting limit, judged once the content's own nesting is
1360 // settled: a link or image whose text already holds
1361 // `MAX_INLINE_NESTING` nested containers stays literal. Its
1362 // children go back where they were, the `[` stays the text it
1363 // still is, and the `]` becomes text, as for any other failed
1364 // match; the tail after `]` is rescanned as text too.
1365 let height = self.run_height(tree, tree.get(node).first_child, None);
1366 if height >= MAX_INLINE_NESTING {
1367 tree.unlink(node);
1368 let mut child = tree.get(node).first_child;
1369 while let Some(c) = child {
1370 let nxt = tree.get(c).next;
1371 tree.unlink(c);
1372 tree.append_child(block, c);
1373 child = nxt;
1374 }
1375 self.remove_bracket();
1376 self.pos = startpos;
1377 let text = text_node(tree, "]");
1378 tree.append_child(block, text);
1379 return true;
1380 }
1381 self.nesting.insert(node, height + 1);
1382
1383 self.remove_bracket();
1384 tree.unlink(opener.node);
1385
1386 // Links may not contain links (section 6.3): every earlier link
1387 // opener is spent. Image openers survive, since images may nest in
1388 // links.
1389 if !is_image {
1390 for b in self.brackets.iter_mut() {
1391 if !b.image {
1392 b.active = false;
1393 }
1394 }
1395 }
1396
1397 true
1398 }
1399
1400 // --- section 6.2 entities, sections 6.8 and 6.9 breaks and plain text ---
1401
1402 pub fn parse_entity(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1403 let Some((literal, end)) = scan_entity(&self.subject, self.pos) else {
1404 return false;
1405 };
1406 self.pos = end;
1407 let node = text_node(tree, &literal);
1408 tree.append_child(block, node);
1409 true
1410 }
1411
1412 /// A chunk of ordinary text: everything up to the next character that
1413 /// could start an inline construct. A byte scan is exact, because the
1414 /// terminators are all ASCII.
1415 pub fn parse_string(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1416 let bytes = self.subject.as_bytes();
1417 let startpos = self.pos;
1418 let gfm = self.options.gfm;
1419 while self.pos < bytes.len() && !is_inline_special_byte(bytes[self.pos], gfm) {
1420 self.pos += 1;
1421 }
1422 if self.pos == startpos {
1423 return false;
1424 }
1425 let node = text_node(tree, &self.subject[startpos..self.pos]);
1426 tree.append_child(block, node);
1427 true
1428 }
1429
1430 /// Sections 6.7 and 6.8: two or more spaces before the line ending make
1431 /// a hard break, anything else a soft one. Trailing spaces are dropped
1432 /// either way, as is the indentation of the next line.
1433 pub fn parse_newline(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1434 self.pos += 1;
1435 let lastc = tree.get(block).last_child;
1436 let prev_text = lastc.and_then(|id| {
1437 let node = tree.get(id);
1438 (node.node_type == NodeType::Text).then_some(node.literal.as_str())
1439 });
1440 let (hard, trim) = classify_break(prev_text);
1441 if trim {
1442 if let Some(id) = lastc {
1443 let literal = &mut tree.get_mut(id).literal;
1444 let trimmed = literal.trim_end_matches(' ').len();
1445 literal.truncate(trimmed);
1446 }
1447 let brk = tree.new_node(if hard {
1448 NodeType::Linebreak
1449 } else {
1450 NodeType::Softbreak
1451 });
1452 tree.append_child(block, brk);
1453 } else {
1454 let brk = tree.new_node(NodeType::Softbreak);
1455 tree.append_child(block, brk);
1456 }
1457 self.skip_spaces();
1458 true
1459 }
1460
1461 /// One inline construct at `pos`; false only at the end of the subject.
1462 pub fn parse_inline(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1463 let Some(c) = self.peek() else {
1464 return false;
1465 };
1466
1467 let res = match c {
1468 b'\n' => self.parse_newline(tree, block),
1469 b'\\' => self.parse_backslash(tree, block),
1470 b'`' => self.parse_backticks(tree, block),
1471 b'*' | b'_' => self.handle_delim(c, tree, block),
1472 // Only GFM gives `~` a meaning; otherwise it is ordinary text
1473 // (and the non-GFM text scan swallows whole runs of it).
1474 b'~' => {
1475 if self.options.gfm {
1476 self.handle_delim(c, tree, block)
1477 } else {
1478 self.parse_string(tree, block)
1479 }
1480 }
1481 b'[' => self.parse_open_bracket(tree, block),
1482 b'!' => self.parse_bang(tree, block),
1483 b']' => self.parse_close_bracket(tree, block),
1484 b'<' => self.parse_autolink(tree, block) || self.parse_html_tag(tree, block),
1485 b'&' => self.parse_entity(tree, block),
1486 _ => self.parse_string(tree, block),
1487 };
1488
1489 if !res {
1490 self.parse_literal_char(tree, block);
1491 }
1492
1493 true
1494 }
1495
1496 /// A character nothing claimed: consume it as literal text. Only `<`
1497 /// and `&` reach here from the dispatch, so the byte at `pos` is a
1498 /// whole character; the engine driver's literal fallback may reach it
1499 /// with any character, so the whole character is taken either way.
1500 pub fn parse_literal_char(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1501 if self.pos >= self.subject.len() {
1502 return false;
1503 }
1504 let startpos = self.pos;
1505 self.pos += code_point_at(&self.subject, self.pos).len_utf8();
1506 let node = text_node(tree, &self.subject[startpos..self.pos]);
1507 tree.append_child(block, node);
1508 true
1509 }
1510
1511 /// Reset for one block's raw content; false when the trimmed subject
1512 /// is empty. Trimming is what stops trailing spaces at the end of a
1513 /// block from making a hard break, and drops the leading indentation
1514 /// of the first line. The trim must remove exactly what
1515 /// `String.prototype.trim` removes, which is `js_trim`.
1516 pub fn begin_block(&mut self, tree: &Tree, block: NodeId) -> bool {
1517 self.subject = js_trim(&tree.get(block).string_content).to_string();
1518 self.pos = 0;
1519 self.delims.clear();
1520 self.delim_top = None;
1521 self.brackets.clear();
1522 self.nesting.clear();
1523 self.backticks = BacktickMemo::default();
1524 !self.subject.is_empty()
1525 }
1526
1527 /// The tail of a block's inline parse: clear the raw content, resolve
1528 /// emphasis over the whole delimiter stack.
1529 pub fn finish_block(&mut self, tree: &mut Tree, block: NodeId) {
1530 tree.get_mut(block).string_content.clear();
1531 self.process_emphasis(tree, None);
1532 }
1533
1534 /// Parse one paragraph's or heading's raw content into inline children.
1535 pub fn parse(&mut self, tree: &mut Tree, block: NodeId) {
1536 self.begin_block(tree, block);
1537 while self.parse_inline(tree, block) {}
1538 self.finish_block(tree, block);
1539 }
1540
1541 /// Section 4.7: consume one link reference definition at the start
1542 /// of `s`, adding it to `refmap`. Returns the number of BYTES consumed.
1543 /// The block phase goes through [`parse_definitions`], which reads
1544 /// every leading definition of a paragraph over one copy of it.
1545 pub fn parse_reference(&mut self, s: &str, refmap: &mut RefMap) -> usize {
1546 self.subject = s.to_string();
1547 self.pos = 0;
1548 match self.parse_definition_here() {
1549 Some(d) => {
1550 refmap
1551 .entry(normalize_reference(&d.label))
1552 .or_insert(RefDef {
1553 destination: d.destination,
1554 title: d.title,
1555 });
1556 self.pos
1557 }
1558 None => 0,
1559 }
1560 }
1561
1562 /// The link reference definition at the current position of the
1563 /// current subject: on success the position is past it, on failure it
1564 /// is back where it was. Nothing here depends on a refmap: the block
1565 /// phase records each definition itself (its refmap, first definition
1566 /// wins, and the definitions beside the paragraph's container).
1567 fn parse_definition_here(&mut self) -> Option<ParsedDefinition> {
1568 let startpos = self.pos;
1569 let fail = |parser: &mut InlineParser| {
1570 parser.pos = startpos;
1571 None
1572 };
1573
1574 // Section 4.7 allows up to three spaces of indentation before the
1575 // label. The block phase normally strips a paragraph line's
1576 // indentation before it gets here, so this usually consumes
1577 // nothing.
1578 self.skip_indent();
1579
1580 let label_start = self.pos;
1581 let match_chars = self.parse_link_label();
1582 if match_chars == 0 {
1583 return fail(self);
1584 }
1585 let rawlabel = self.subject[label_start + 1..label_start + match_chars - 1].to_string();
1586
1587 if self.peek() == Some(b':') {
1588 self.pos += 1;
1589 } else {
1590 return fail(self);
1591 }
1592
1593 self.spnl();
1594
1595 let Some(dest) = self.parse_link_destination() else {
1596 return fail(self);
1597 };
1598
1599 let beforetitle = self.pos;
1600 self.spnl();
1601 let mut title = None;
1602 if self.pos != beforetitle {
1603 title = self.parse_link_title();
1604 }
1605 if title.is_none() {
1606 self.pos = beforetitle;
1607 }
1608
1609 // Nothing but spaces may follow on the definition's last line.
1610 let mut at_line_end = true;
1611 if !self.space_at_end_of_line() {
1612 if title.is_none() {
1613 at_line_end = false;
1614 } else {
1615 // What looked like a title is something else; the definition
1616 // may still be valid without it.
1617 title = None;
1618 self.pos = beforetitle;
1619 at_line_end = self.space_at_end_of_line();
1620 }
1621 }
1622 if !at_line_end {
1623 return fail(self);
1624 }
1625
1626 // A label must hold at least one non-whitespace character.
1627 if normalize_reference(&rawlabel).is_empty() {
1628 return fail(self);
1629 }
1630
1631 Some(ParsedDefinition {
1632 start: startpos,
1633 end: self.pos,
1634 label: rawlabel,
1635 destination: dest,
1636 title,
1637 })
1638 }
1639}
1640
1641/// Whether the text from `start` (a `[`) to `end` (just past its `]`) is
1642/// a link label (section 4.7): at most 999 characters between the
1643/// brackets, and a bracket inside only if backslash-escaped. A shortcut or
1644/// collapsed reference's link text names its label, so it must be one to
1645/// be a reference at all, since a definition's label always is.
1646fn is_link_label_at(subject: &str, start: usize, end: usize) -> bool {
1647 matches!(scan_link_label(subject, start), Some((raw, length)) if length != 0 && start + raw == end)
1648}
1649
1650/// Autolink text is literal: no backslash escapes, no entity references.
1651/// The destination is not percent-encoded here; see
1652/// `scan_link_destination`.
1653fn make_autolink(tree: &mut Tree, destination: &str, label: &str) -> NodeId {
1654 let mut node = MdNode::new(NodeType::Link);
1655 node.destination = destination.to_string();
1656 node.title = None;
1657 let id = tree.add(node);
1658 let text = text_node(tree, label);
1659 tree.append_child(id, text);
1660 id
1661}
1662
1663// --- GFM extended autolinks (autolink literals) -----------------------------
1664//
1665// GFM recognises `www.x.com`, `https://x.com` and `a@x.com` without the
1666// `<...>` CommonMark requires. This runs as a post-pass over the finished
1667// inline tree rather than as another branch of the scan above, which is
1668// how cmark-gfm does it and is the only shape that keeps 652/652 safe: the
1669// scanner that decides code spans, raw HTML, emphasis and links is not
1670// touched at all, and an autolink can therefore never win against a
1671// construct CommonMark says comes first.
1672//
1673// The pass rewrites text nodes into text / link / text runs. It does not
1674// descend into link (links may not contain links) or image (its children
1675// are the alt text), and code / html_inline are leaves it never looks
1676// inside.
1677//
1678// Everything here scans by BYTE, like the rest of this file. Every
1679// character the pass branches on is ASCII, and no byte of a multi-byte
1680// UTF-8 sequence can collide with one, so a non-ASCII character is exactly
1681// as unmatchable here as its UTF-16 code unit is in the TypeScript: it ends
1682// a domain run, it is not a valid autolink start, and it is not trailing
1683// punctuation. Slices therefore never cut a character in half: every
1684// boundary this pass produces sits at an ASCII character.
1685
1686/// RFC 1035's limit on a fully-qualified domain name. See
1687/// `scan_domain_end`.
1688const MAX_AUTOLINK_DOMAIN: usize = 253;
1689
1690/// RFC 5321's limit on the local part of an address, before the `@`.
1691const MAX_EMAIL_LOCAL: usize = 64;
1692
1693/// The three schemes the extension recognises without angle brackets.
1694const AUTOLINK_SCHEMES: [&str; 3] = ["https://", "http://", "ftp://"];
1695
1696fn is_ascii_alnum(c: u8) -> bool {
1697 c.is_ascii_alphanumeric()
1698}
1699
1700fn is_autolink_space(c: u8) -> bool {
1701 matches!(c, b' ' | b'\t' | b'\n' | b'\x0B' | b'\x0C' | b'\r')
1702}
1703
1704/// A domain segment holds alphanumerics, `_` and `-`; `.` separates them.
1705fn is_domain_char(c: u8) -> bool {
1706 is_ascii_alnum(c) || c == b'_' || c == b'-' || c == b'.'
1707}
1708
1709/// Before the `@`: alphanumerics and `.`, `-`, `_`, `+`.
1710fn is_email_local_char(c: u8) -> bool {
1711 is_ascii_alnum(c) || c == b'.' || c == b'-' || c == b'_' || c == b'+'
1712}
1713
1714/// "All such recognized autolinks can only come at the beginning of a line,
1715/// after whitespace, or any of the delimiting characters `*`, `_`, `~`,
1716/// `(`."
1717///
1718/// Offset 0 has no preceding character in `s` at all, so the caller
1719/// answers for it through `at_start`; see `starts_after_delimiter`.
1720fn is_autolink_start(s: &[u8], i: usize, at_start: bool) -> bool {
1721 if i == 0 {
1722 return at_start;
1723 }
1724 let c = s[i - 1];
1725 is_autolink_space(c) || c == b'*' || c == b'_' || c == b'~' || c == b'('
1726}
1727
1728/// Whether offset 0 of a text node may begin an autolink, given the sibling
1729/// in front of it.
1730///
1731/// The rule above is about the source character immediately before the
1732/// match, and by the time this pass runs the tree no longer carries source
1733/// offsets, but the previous sibling's *type* names that character
1734/// exactly:
1735///
1736/// - `emph` and `strong` end on the `*` or `_` that closed them, and `del`
1737/// on its second `~`. All three are delimiters the rule allows, so
1738/// `*a*www.b.com` links.
1739/// - `code` ends on a backtick, `link` and `image` on `)`, `]` or `>`, and
1740/// `html_inline` on `>`. None are delimiters, so `` `x`www.a.com ``,
1741/// `[l](/u)www.a.com` and `<b>www.a.com` do not link.
1742/// - a `softbreak` or `linebreak` puts offset 0 at the beginning of a line,
1743/// and so does having no previous sibling: that is the first inline of
1744/// the block, or of the emphasis span this pass descended into.
1745///
1746/// A `text` node never appears here: `linkify_children` merges every run
1747/// of adjacent text siblings before handing the first of them over.
1748fn starts_after_delimiter(tree: &Tree, prev: Option<NodeId>) -> bool {
1749 match prev {
1750 None => true,
1751 Some(id) => matches!(
1752 tree.get(id).node_type,
1753 NodeType::Softbreak
1754 | NodeType::Linebreak
1755 | NodeType::Emph
1756 | NodeType::Strong
1757 | NodeType::Del
1758 ),
1759 }
1760}
1761
1762/// ASCII case-insensitive comparison against an already-lowercase literal.
1763fn matches_ignore_case(s: &[u8], at: usize, lower: &str) -> bool {
1764 let lower = lower.as_bytes();
1765 if at + lower.len() > s.len() {
1766 return false;
1767 }
1768 lower
1769 .iter()
1770 .enumerate()
1771 .all(|(k, &l)| s[at + k].to_ascii_lowercase() == l)
1772}
1773
1774/// The end of the run of domain characters at `from`, capped at
1775/// `MAX_AUTOLINK_DOMAIN`.
1776///
1777/// The cap is what keeps this pass linear. `_` both continues a domain and
1778/// introduces a valid autolink start, so without a bound an input like
1779/// `"_www.a_b.c".repeat(n)` gives every underscore a candidate whose domain
1780/// run reaches the end of the text: quadratic. Anything past the cap is
1781/// still scanned, just as the path rather than as the domain, and no real
1782/// domain comes near it.
1783fn scan_domain_end(s: &[u8], from: usize) -> usize {
1784 let max = s.len().min(from + MAX_AUTOLINK_DOMAIN);
1785 let mut i = from;
1786 while i < max && is_domain_char(s[i]) {
1787 i += 1;
1788 }
1789 i
1790}
1791
1792/// A valid domain: at least one period, and no underscore in either of the
1793/// last two segments. `from..to` must already be a run of domain
1794/// characters.
1795fn is_valid_domain(s: &[u8], from: usize, to: usize) -> bool {
1796 if to <= from {
1797 return false;
1798 }
1799 let mut periods = 0;
1800 let mut underscores_in_last = 0;
1801 let mut underscores_in_prev = 0;
1802 for &c in &s[from..to] {
1803 if c == b'_' {
1804 underscores_in_last += 1;
1805 } else if c == b'.' {
1806 underscores_in_prev = underscores_in_last;
1807 underscores_in_last = 0;
1808 periods += 1;
1809 }
1810 }
1811 periods > 0 && underscores_in_last == 0 && underscores_in_prev == 0
1812}
1813
1814/// "Extended autolink path validation": pull the end of the match back off
1815/// trailing characters that read as sentence punctuation rather than as
1816/// part of a URL. One loop rather than three passes, because dropping a
1817/// `)` can expose a `.` and vice versa.
1818///
1819/// - `?` `!` `.` `,` `:` `*` `_` `~` are dropped wherever they trail;
1820/// - a trailing `)` is dropped only while the match holds more `)` than
1821/// `(`, so `(www.a.com/x_(y))` keeps its inner pair and loses the outer
1822/// one;
1823/// - a trailing `;` preceded by something shaped like an entity reference
1824/// takes the whole `&...;` with it.
1825///
1826/// The parenthesis counts are taken once and then maintained, not
1827/// recomputed per drop: a deeply parenthesised URL is otherwise quadratic
1828/// in its own length.
1829fn trim_autolink_end(s: &[u8], start: usize, mut end: usize) -> usize {
1830 let mut opening: Option<usize> = None;
1831 let mut closing = 0usize;
1832
1833 while start < end {
1834 let c = s[end - 1];
1835
1836 match c {
1837 b'?' | b'!' | b'.' | b',' | b':' | b'*' | b'_' | b'~' => {
1838 end -= 1;
1839 continue;
1840 }
1841
1842 b')' => {
1843 if opening.is_none() {
1844 let mut o = 0;
1845 closing = 0;
1846 for &d in &s[start..end] {
1847 if d == b'(' {
1848 o += 1;
1849 } else if d == b')' {
1850 closing += 1;
1851 }
1852 }
1853 opening = Some(o);
1854 }
1855 if closing <= opening.unwrap_or(0) {
1856 return end;
1857 }
1858 closing -= 1;
1859 end -= 1;
1860 continue;
1861 }
1862
1863 b';' => {
1864 // `&` followed by one or more alphanumerics, then this `;`.
1865 let mut j = end as isize - 2;
1866 while j > start as isize && is_ascii_alnum(s[j as usize]) {
1867 j -= 1;
1868 }
1869 if j < end as isize - 2 && j >= 0 && s[j as usize] == b'&' {
1870 end = j as usize;
1871 continue;
1872 }
1873 return end;
1874 }
1875
1876 _ => return end,
1877 }
1878 }
1879
1880 end
1881}
1882
1883/// One recognised autolink literal: `s[start..end]` linking to `href`.
1884struct AutolinkMatch {
1885 start: usize,
1886 end: usize,
1887 href: String,
1888}
1889
1890/// `www.`, `http://`, `https://` and `ftp://` all start with one of these.
1891fn could_start_url(c: u8) -> bool {
1892 matches!(c, b'w' | b'W' | b'h' | b'H' | b'f' | b'F')
1893}
1894
1895fn has_period(s: &[u8], from: usize, to: usize) -> bool {
1896 s[from..to].contains(&b'.')
1897}
1898
1899/// Every autolink literal in one text run, left to right and
1900/// non-overlapping. Returns an empty vector when there is nothing to do,
1901/// which is the overwhelmingly common case.
1902fn scan_autolinks(text: &str, at_start: bool) -> Vec<AutolinkMatch> {
1903 let s = text.as_bytes();
1904 let length = s.len();
1905 let mut out = Vec::new();
1906
1907 // The maximal run of non-space, non-`<` characters containing the
1908 // current position: "zero or more non-space non-`<` characters may
1909 // follow" the domain. Cached because candidates are tried left to
1910 // right, so each run is scanned once however many candidates start
1911 // inside it.
1912 let mut run_start = usize::MAX;
1913 let mut run_end = 0usize;
1914
1915 let mut i = 0;
1916 let mut last_end = 0;
1917
1918 while i < length {
1919 let c = s[i];
1920
1921 // --- email: found by its `@`, then rewound to the start of the
1922 // local part
1923 if c == b'@' {
1924 // The rewind is bounded to keep this pass linear, and RFC 5321
1925 // bounds a local part in the same place anyway, so the cap
1926 // costs no real address.
1927 let capped = i as isize - MAX_EMAIL_LOCAL as isize;
1928 let floor = (last_end as isize).max(capped);
1929 let mut k = i as isize;
1930 while k > floor && is_email_local_char(s[k as usize - 1]) {
1931 k -= 1;
1932 }
1933
1934 // Stopping *on* the cap is not the same as finding a boundary.
1935 // If the character just outside it still belongs to the local
1936 // part, the local part is longer than the cap allows and there
1937 // is no address here at all: accepting the match would link the
1938 // 64-character tail of a longer run and leave the rest as text,
1939 // inventing an address the source never wrote. `k` can only
1940 // reach `capped` when the cap, rather than `last_end`, is what
1941 // ended the loop; and `k` of 0 is the start of the string,
1942 // where there is no character outside the cap to disqualify
1943 // anything.
1944 if k == capped && k > 0 && is_email_local_char(s[k as usize - 1]) {
1945 i += 1;
1946 continue;
1947 }
1948
1949 let k = k as usize;
1950 if k < i && is_autolink_start(s, k, at_start) {
1951 // After the `@`: alphanumerics, `.`, `-`, `_`; at least one
1952 // period; a trailing `.` is not part of the address, and a
1953 // trailing `-` or `_` invalidates the whole thing.
1954 let mut end = i + 1;
1955 while end < length && is_domain_char(s[end]) {
1956 end += 1;
1957 }
1958 while end > i + 1 && s[end - 1] == b'.' {
1959 end -= 1;
1960 }
1961
1962 let last = if end > i + 1 { s[end - 1] } else { 0 };
1963 if end > i + 1 && last != b'-' && last != b'_' && has_period(s, i + 1, end) {
1964 out.push(AutolinkMatch {
1965 start: k,
1966 end,
1967 href: format!("mailto:{}", &text[k..end]),
1968 });
1969 last_end = end;
1970 i = end;
1971 continue;
1972 }
1973 }
1974 i += 1;
1975 continue;
1976 }
1977
1978 // --- www / scheme: both need a valid start and a valid domain
1979 if !could_start_url(c) || !is_autolink_start(s, i, at_start) {
1980 i += 1;
1981 continue;
1982 }
1983
1984 let mut domain_start: Option<usize> = None;
1985 let mut prefix = "";
1986 if matches_ignore_case(s, i, "www.") {
1987 // The domain of a `www.` autolink includes the `www.` itself, so
1988 // the required period is already there and `www.foo_bar.com` is
1989 // rejected on the same footing as `http://foo_bar.com`.
1990 domain_start = Some(i);
1991 prefix = "http://";
1992 } else {
1993 for scheme in AUTOLINK_SCHEMES {
1994 if matches_ignore_case(s, i, scheme) {
1995 domain_start = Some(i + scheme.len());
1996 break;
1997 }
1998 }
1999 }
2000 let Some(domain_start) = domain_start else {
2001 i += 1;
2002 continue;
2003 };
2004
2005 let domain_end = scan_domain_end(s, domain_start);
2006 // Checked before the run scan below, so a candidate that cannot
2007 // possibly match costs only its own domain run.
2008 if !is_valid_domain(s, domain_start, domain_end) {
2009 i += 1;
2010 continue;
2011 }
2012
2013 if i >= run_end || i < run_start {
2014 run_start = i;
2015 run_end = i;
2016 while run_end < length {
2017 let d = s[run_end];
2018 if is_autolink_space(d) || d == b'<' {
2019 break;
2020 }
2021 run_end += 1;
2022 }
2023 }
2024
2025 let end = trim_autolink_end(s, i, run_end);
2026 // Trailing punctuation can eat back into the domain
2027 // (`www.commonmark.org.` loses its last period), so the domain is
2028 // validated again over what actually survived.
2029 let survived = domain_end.min(end);
2030 if end <= domain_start || !is_valid_domain(s, domain_start, survived) {
2031 i += 1;
2032 continue;
2033 }
2034
2035 out.push(AutolinkMatch {
2036 start: i,
2037 end,
2038 href: format!("{prefix}{}", &text[i..end]),
2039 });
2040 last_end = end;
2041 i = end;
2042 }
2043
2044 out
2045}
2046
2047/// Replace one text node with the text / link / text run its literal
2048/// implies.
2049fn linkify_text_node(tree: &mut Tree, node: NodeId) {
2050 let at_start = starts_after_delimiter(tree, tree.get(node).prev);
2051 let s = tree.get(node).literal.clone();
2052 let matches = scan_autolinks(&s, at_start);
2053 if matches.is_empty() {
2054 return;
2055 }
2056
2057 let mut at = 0;
2058 for m in matches {
2059 if at < m.start {
2060 let text = text_node(tree, &s[at..m.start]);
2061 tree.insert_before(node, text);
2062 }
2063 // Not percent-encoded here, for the same reason as
2064 // `scan_link_destination`: encoding belongs to the renderer, and
2065 // the AST promises the decoded form.
2066 let link = make_autolink(tree, &m.href, &s[m.start..m.end]);
2067 tree.insert_before(node, link);
2068 at = m.end;
2069 }
2070 if at < s.len() {
2071 let text = text_node(tree, &s[at..]);
2072 tree.insert_before(node, text);
2073 }
2074
2075 tree.unlink(node);
2076}
2077
2078/// Autolink the text children of one container, and add the child
2079/// containers still to visit to `pending`.
2080fn linkify_children(tree: &mut Tree, parent: NodeId, pending: &mut Vec<NodeId>) {
2081 let mut child = tree.get(parent).first_child;
2082
2083 while let Some(c) = child {
2084 if tree.get(c).node_type == NodeType::Text {
2085 // Consolidate the run of adjacent text nodes first. The scan
2086 // above emits a node per delimiter run and per character it
2087 // could not claim, so `a.b-c_d@a.b` arrives as three siblings
2088 // and the address is only visible once they are one string.
2089 // Merging changes nothing downstream: the renderer writes text
2090 // literals back to back, and the AST projection already
2091 // coalesces adjacent runs.
2092 let mut sibling = tree.get(c).next;
2093 if sibling.is_some_and(|s| tree.get(s).node_type == NodeType::Text) {
2094 let mut merged = tree.get(c).literal.clone();
2095 while let Some(s) = sibling {
2096 if tree.get(s).node_type != NodeType::Text {
2097 break;
2098 }
2099 merged.push_str(&tree.get(s).literal);
2100 let next = tree.get(s).next;
2101 tree.unlink(s);
2102 sibling = next;
2103 }
2104 tree.get_mut(c).literal = merged;
2105 }
2106
2107 let after = tree.get(c).next;
2108 linkify_text_node(tree, c);
2109 child = after;
2110 continue;
2111 }
2112
2113 // No links inside links (section 6.3), and an image's children are
2114 // its alt text.
2115 // A kept reference is a link or an image as soon as a definition
2116 // names its label, so it is passed over the same way.
2117 let node = tree.get(c);
2118 if node.node_type != NodeType::Link
2119 && node.node_type != NodeType::Image
2120 && node.node_type != NodeType::LinkReference
2121 && node.node_type != NodeType::ImageReference
2122 && node.is_container()
2123 {
2124 pending.push(c);
2125 }
2126 child = node.next;
2127 }
2128}
2129
2130/// Recognise GFM autolink literals throughout one finished block's inlines.
2131///
2132/// Iterative rather than recursive: emphasis nests as deeply as the input
2133/// says.
2134pub fn linkify_autolinks(tree: &mut Tree, block: NodeId) {
2135 let mut pending = vec![block];
2136 while let Some(node) = pending.pop() {
2137 linkify_children(tree, node, &mut pending);
2138 }
2139}
2140
2141/// Blocks whose raw content the block phase left for this phase to parse.
2142/// GFM table cells hold inlines and nothing else ("block-level elements
2143/// cannot be inserted in a table"), so a cell is parsed exactly as a
2144/// paragraph is, autolink post-pass included.
2145pub fn is_inline_content_block(t: NodeType) -> bool {
2146 matches!(
2147 t,
2148 NodeType::Paragraph | NodeType::Heading | NodeType::TableCell
2149 )
2150}
2151
2152/// The inline content blocks of `tree`, in the order the walk exits them:
2153/// the one iteration both inline drivers share (the hand scanner and the
2154/// engine path), so which blocks get inline parsing is decided exactly
2155/// once. Inline parsing only adds children beneath these blocks, so the
2156/// list taken before the phase runs is the walk the phase would make.
2157pub fn inline_content_blocks(tree: &Tree) -> Vec<NodeId> {
2158 let mut out = Vec::new();
2159 let mut walker = tree.walker(tree.root());
2160 while let Some(event) = walker.next(tree) {
2161 if !event.entering && is_inline_content_block(tree.get(event.node).node_type) {
2162 out.push(event.node);
2163 }
2164 }
2165 out
2166}
2167
2168/// Walk the finished block tree, handing every inline content block
2169/// (paragraphs, headings, table cells) to `f` and running the GFM
2170/// autolink-literal post-pass after it, so when linkify runs is decided
2171/// exactly once for both drivers.
2172pub fn for_each_inline_block(
2173 tree: &mut Tree,
2174 options: &Options,
2175 mut f: impl FnMut(&mut Tree, NodeId),
2176) {
2177 for block in inline_content_blocks(tree) {
2178 f(tree, block);
2179 if options.gfm {
2180 linkify_autolinks(tree, block);
2181 }
2182 }
2183}
2184
2185/// Phase 2 entry point: walk the block tree and parse the string content of
2186/// every paragraph, heading and table cell into inline children.
2187pub fn parse_inlines(tree: &mut Tree, refmap: RefMap, options: Options) {
2188 let mut parser = InlineParser::new(refmap, options);
2189 for_each_inline_block(tree, &options, |tree, block| parser.parse(tree, block));
2190}
2191
2192/// [`parse_inlines`] reading every bracketed label a definition could name
2193/// as a reference, left unresolved, with no link reference map to consult:
2194/// the tree the AST is projected from (see `ast.rs`).
2195pub fn parse_inlines_keeping_references(tree: &mut Tree, options: Options) {
2196 let mut parser = InlineParser::keeping_references(options);
2197 for_each_inline_block(tree, &options, |tree, block| parser.parse(tree, block));
2198}
2199
2200/// Consume link reference definitions from the front of a paragraph's raw
2201/// content, adding them to `refmap`. Returns the number of BYTES consumed,
2202/// or 0 if `s` does not start with a definition.
2203///
2204/// Reference definitions are parsed during the block phase, before any
2205/// inline parser for the document exists, so a scratch parser is built per
2206/// call; nothing here depends on the parse options.
2207pub fn parse_reference(s: &str, refmap: &mut RefMap) -> usize {
2208 let mut parser = InlineParser::new(RefMap::new(), Options::COMMONMARK);
2209 parser.parse_reference(s, refmap)
2210}
2211
2212/// Section 4.7 over a whole paragraph: every link reference definition
2213/// at the start of `s`, in order, each added to `refmap`. Returns the
2214/// number of BYTES they take up together.
2215pub fn parse_references(s: &str, refmap: &mut RefMap) -> usize {
2216 let definitions = parse_definitions(s);
2217 for d in &definitions {
2218 refmap
2219 .entry(normalize_reference(&d.label))
2220 .or_insert(RefDef {
2221 destination: d.destination.clone(),
2222 title: d.title.clone(),
2223 });
2224 }
2225 definitions.last().map_or(0, |d| d.end)
2226}
2227
2228/// Section 4.7 over a whole paragraph: every link reference definition at
2229/// the start of `s`, in order, each with the BYTE range it takes.
2230///
2231/// One parser over one copy of `s`, advancing through it. Copying the
2232/// remaining tail once per definition, as the per-definition entry point
2233/// does, made a paragraph of n short definitions cost O(n^2).
2234pub fn parse_definitions(s: &str) -> Vec<ParsedDefinition> {
2235 let mut parser = InlineParser::new(RefMap::new(), Options::COMMONMARK);
2236 parser.subject = s.to_string();
2237 parser.pos = 0;
2238 let mut out = Vec::new();
2239 while parser.pos < s.len() && s.as_bytes()[parser.pos] == b'[' {
2240 match parser.parse_definition_here() {
2241 Some(d) => out.push(d),
2242 None => break,
2243 }
2244 }
2245 out
2246}