carta-readers 0.0.1

Input-format readers: parse a source format's text into the document model.
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
//! Bare-URI autolinking: a post-pass that turns plain URLs, `www.` hosts, and email addresses found
//! in ordinary text into `Link` inlines.
//!
//! A URL begins with a lowercase `http://`, `https://`, or `ftp://` scheme, or a `www.` host (which
//! is given an `http://` destination); both must sit at a non-alphanumeric boundary. The run extends
//! to the next space or `<`, with parentheses balanced and an unbalanced `)` or a `]` ending it;
//! trailing punctuation and a trailing entity reference are then dropped. A scheme URL's authority
//! must be a usable domain (at least two dot-separated labels, none ending in `-`/`_`); a `www.` host
//! is taken as-is. An email address is a local part of `[A-Za-z0-9._+-]` and an `@`, followed by a
//! domain, and is given a `mailto:` destination. Links are not nested, so an existing `Link` is left
//! untouched rather than rescanned.
//!
//! In the Markdown dialect each produced link carries a `uri` or `email` class, an email's domain
//! need only be a single non-empty label, and bare `www.` hosts are not linked; the strict dialect
//! leaves the link unclassed, requires a dotted email domain, and links `www.` hosts.

use carta_ast::{Attr, Inline, Target};

use super::scan::matches_at;

/// Whether a matched autolink is a URL or an email address; selects its dialect class.
#[derive(Clone, Copy)]
enum Kind {
    Uri,
    Email,
}

impl Kind {
    fn class(self) -> &'static str {
        match self {
            Self::Uri => "uri",
            Self::Email => "email",
        }
    }
}

/// Rewrite every text `Str` in `inlines`, recursing through inline containers, so that bare URIs,
/// `www.` hosts, and email addresses become links. Code, math, and raw inlines are left untouched.
/// In the Markdown dialect (`markdown`) each link is classed and an email domain may be a single
/// label.
pub(crate) fn autolink_inlines(inlines: &mut Vec<Inline>, markdown: bool) {
    let taken = std::mem::take(inlines);
    let mut out = Vec::with_capacity(taken.len());
    for inline in taken {
        match inline {
            Inline::Str(s) => split_text(&s, markdown, &mut out),
            Inline::Emph(mut v) => out.push(Inline::Emph(recurse(&mut v, markdown))),
            Inline::Underline(mut v) => out.push(Inline::Underline(recurse(&mut v, markdown))),
            Inline::Strong(mut v) => out.push(Inline::Strong(recurse(&mut v, markdown))),
            Inline::Strikeout(mut v) => out.push(Inline::Strikeout(recurse(&mut v, markdown))),
            Inline::Superscript(mut v) => out.push(Inline::Superscript(recurse(&mut v, markdown))),
            Inline::Subscript(mut v) => out.push(Inline::Subscript(recurse(&mut v, markdown))),
            Inline::SmallCaps(mut v) => out.push(Inline::SmallCaps(recurse(&mut v, markdown))),
            Inline::Quoted(q, mut v) => out.push(Inline::Quoted(q, recurse(&mut v, markdown))),
            Inline::Span(a, mut v) => out.push(Inline::Span(a, recurse(&mut v, markdown))),
            Inline::Image(a, mut v, t) => out.push(Inline::Image(a, recurse(&mut v, markdown), t)),
            other => out.push(other),
        }
    }
    *inlines = out;
}

fn recurse(inlines: &mut Vec<Inline>, markdown: bool) -> Vec<Inline> {
    autolink_inlines(inlines, markdown);
    std::mem::take(inlines)
}

/// A matched autolink: the half-open `start..end` span within the text, the link destination, and
/// whether it is a URL or an email.
struct Match {
    start: usize,
    end: usize,
    href: String,
    kind: Kind,
}

/// Scan one text token, emitting `Str` for the gaps and `Link` for each autolink found.
fn split_text(text: &str, markdown: bool, out: &mut Vec<Inline>) {
    let chars: Vec<char> = text.chars().collect();
    let len = chars.len();
    let mut i = 0;
    let mut emit_from = 0;
    while i < len {
        // A bare `www.` host (no scheme) autolinks only in the strict dialect; the Markdown dialect
        // links scheme URLs and emails alone.
        let found = match_url(&chars, i)
            .or_else(|| (!markdown).then(|| match_www(&chars, i)).flatten())
            .or_else(|| match_email(&chars, i, emit_from, markdown));
        if let Some(m) = found {
            push_text(&chars, emit_from, m.start, out);
            if let Some(span) = chars.get(m.start..m.end) {
                let label: String = span.iter().collect();
                let attr = if markdown {
                    Attr {
                        id: String::new(),
                        classes: vec![m.kind.class().to_owned()],
                        attributes: Vec::new(),
                    }
                } else {
                    Attr::default()
                };
                // The markdown dialect percent-encodes the destination's unsafe characters; the
                // GitHub dialect keeps the matched text verbatim.
                let url = if markdown {
                    super::scan::escape_uri(&m.href)
                } else {
                    m.href
                };
                out.push(Inline::Link(
                    attr,
                    vec![Inline::Str(label)],
                    Target {
                        url,
                        title: String::new(),
                    },
                ));
            }
            emit_from = m.end;
            i = m.end;
        } else {
            i += 1;
        }
    }
    push_text(&chars, emit_from, len, out);
}

fn push_text(chars: &[char], a: usize, b: usize, out: &mut Vec<Inline>) {
    if let Some(slice) = chars.get(a..b)
        && !slice.is_empty()
    {
        out.push(Inline::Str(slice.iter().collect()));
    }
}

fn match_url(chars: &[char], i: usize) -> Option<Match> {
    if alnum_before(chars, i) {
        return None;
    }
    let scheme_len = url_scheme_len(chars, i)?;
    let content_start = i + scheme_len;
    let scan_end = forward_scan(chars, i);
    if !valid_host(chars.get(content_start..scan_end)?) {
        return None;
    }
    let end = trim_trailing(chars, content_start, scan_end);
    if end <= content_start {
        return None;
    }
    let href: String = chars.get(i..end)?.iter().collect();
    Some(Match {
        start: i,
        end,
        href,
        kind: Kind::Uri,
    })
}

/// Whether `rest` opens with a usable domain. Starting at the first character, labels of
/// alphanumerics, `-`, and `_` are read greedily and joined by single dots; the domain is the longest
/// such prefix whose labels are non-empty and end in neither `-` nor `_`. It is usable when that
/// prefix holds at least two labels. Whatever follows the domain (port, path, an extra dot) is not
/// examined here — it stays part of the link.
fn valid_host(rest: &[char]) -> bool {
    let mut labels = 0;
    let mut i = 0;
    loop {
        let start = i;
        while rest.get(i).is_some_and(|&c| is_label_char(c)) {
            i += 1;
        }
        if i == start || matches!(rest.get(i - 1), Some('-' | '_')) {
            break;
        }
        labels += 1;
        if rest.get(i) != Some(&'.') {
            break;
        }
        i += 1;
    }
    labels >= 2
}

fn is_label_char(c: char) -> bool {
    c.is_alphanumeric() || matches!(c, '-' | '_')
}

fn match_www(chars: &[char], i: usize) -> Option<Match> {
    if alnum_before(chars, i) || !matches_at(chars, i, "www.") {
        return None;
    }
    let content_start = i + 4;
    let scan_end = forward_scan(chars, i);
    if !valid_host(chars.get(i..scan_end)?) {
        return None;
    }
    let end = trim_trailing(chars, content_start, scan_end);
    if end <= content_start {
        return None;
    }
    let label: String = chars.get(i..end)?.iter().collect();
    let href = format!("http://{label}");
    Some(Match {
        start: i,
        end,
        href,
        kind: Kind::Uri,
    })
}

/// Match an email address centered on the `@` at `at`. The local part extends left over
/// `[A-Za-z0-9._+-]` (but no earlier than `lower`, the start of the not-yet-emitted text), and the
/// domain extends right over `[A-Za-z0-9._-]` and must end on an alphanumeric with no empty label.
/// The strict dialect additionally requires the domain to be dotted; the Markdown dialect accepts a
/// single-label domain such as `5@home`.
fn match_email(chars: &[char], at: usize, lower: usize, markdown: bool) -> Option<Match> {
    if chars.get(at) != Some(&'@') {
        return None;
    }
    let mut start = at;
    while start > lower {
        match chars.get(start - 1) {
            Some(&c) if is_local_char(c) => start -= 1,
            _ => break,
        }
    }
    if start == at {
        return None;
    }
    let mut end = at + 1;
    while chars.get(end).is_some_and(|&c| is_domain_char(c)) {
        end += 1;
    }
    while end > at + 1 && chars.get(end - 1) == Some(&'.') {
        end -= 1;
    }
    let domain = chars.get(at + 1..end)?;
    let ends_alnum = domain.last().is_some_and(char::is_ascii_alphanumeric);
    let dotted_ok = markdown || domain.contains(&'.');
    if !dotted_ok || !ends_alnum || domain.windows(2).any(|w| matches!(w, ['.', '.'])) {
        return None;
    }
    let label: String = chars.get(start..end)?.iter().collect();
    let href = format!("mailto:{label}");
    Some(Match {
        start,
        end,
        href,
        kind: Kind::Email,
    })
}

/// Walk the URL run forward from `from`, stopping at whitespace or `<`, at an unbalanced `)`, or at a
/// `]` outside any parenthesis. Returns the index just past the last character of the run.
fn forward_scan(chars: &[char], from: usize) -> usize {
    let mut depth: i32 = 0;
    let mut j = from;
    while let Some(&c) = chars.get(j) {
        if c.is_whitespace() || c == '<' {
            break;
        }
        match c {
            '(' => depth += 1,
            ')' | ']' if depth == 0 => break,
            ')' => depth -= 1,
            _ => {}
        }
        j += 1;
    }
    j
}

/// Drop trailing punctuation from a URL run, never trimming below `min` (the start of the host).
/// A trailing `;` takes its preceding `&entity;` with it when one is present.
fn trim_trailing(chars: &[char], min: usize, mut end: usize) -> usize {
    while end > min {
        match chars.get(end - 1) {
            Some('!' | '"' | '\'' | '*' | ',' | '.' | ':' | '?' | '_' | '~') => end -= 1,
            Some(';') => {
                let mut j = end - 1;
                while j > min && chars.get(j - 1).is_some_and(|&c| is_entity_char(c)) {
                    j -= 1;
                }
                end = if j > min && chars.get(j - 1) == Some(&'&') {
                    j - 1
                } else {
                    end - 1
                };
            }
            _ => break,
        }
    }
    end
}

fn url_scheme_len(chars: &[char], i: usize) -> Option<usize> {
    ["https://", "http://", "ftp://"]
        .into_iter()
        .find(|scheme| matches_at(chars, i, scheme))
        .map(str::len)
}

fn alnum_before(chars: &[char], i: usize) -> bool {
    i.checked_sub(1)
        .and_then(|p| chars.get(p))
        .is_some_and(|c| c.is_alphanumeric())
}

fn is_local_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '-')
}

fn is_domain_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')
}

fn is_entity_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '#'
}

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

    /// Autolink a single text token in the strict dialect, reporting each link as `(label, href)`.
    fn links(text: &str) -> Vec<(String, String)> {
        classed_links(text, false)
            .into_iter()
            .map(|(label, href, _)| (label, href))
            .collect()
    }

    /// Autolink a single text token, reporting each link as `(label, href, classes)`.
    fn classed_links(text: &str, markdown: bool) -> Vec<(String, String, Vec<String>)> {
        let mut inlines = vec![Inline::Str(text.to_owned())];
        autolink_inlines(&mut inlines, markdown);
        inlines
            .iter()
            .filter_map(|inline| match inline {
                Inline::Link(attr, label, target) => {
                    let text: String = label
                        .iter()
                        .map(|i| match i {
                            Inline::Str(s) => s.as_str(),
                            _ => "",
                        })
                        .collect();
                    Some((text, target.url.clone(), attr.classes.clone()))
                }
                _ => None,
            })
            .collect()
    }

    fn host(s: &str) -> bool {
        valid_host(&s.chars().collect::<Vec<_>>())
    }

    fn scan(s: &str) -> usize {
        forward_scan(&s.chars().collect::<Vec<_>>(), 0)
    }

    #[test]
    fn valid_host_needs_two_well_formed_labels() {
        assert!(host("example.com"));
        assert!(host("a.b.c.com"));
        assert!(host("-a.com")); // a leading hyphen is fine
        assert!(host("ex_ample.com")); // an interior underscore is fine
        assert!(!host("localhost")); // a single label is not a domain
        assert!(!host("a-.com")); // a label may not end in '-'
        assert!(!host("example.com_")); // ...nor in '_'
        assert!(!host(".com")); // an empty leading label
        assert!(!host("a..com")); // an empty interior label cuts the prefix to one label
    }

    #[test]
    fn valid_host_reads_only_the_leading_domain() {
        // The domain is a prefix; trailing junk past two good labels does not invalidate it.
        assert!(host("a.com..post"));
        assert!(host("example.com:8080/path"));
        assert!(host("example.com./x")); // a trailing dot then path
    }

    #[test]
    fn forward_scan_balances_parens_and_stops_at_boundaries() {
        assert_eq!(scan("http://e.com/a b"), 14); // stops at the space
        assert_eq!(scan("http://e.com/a(b)c)"), 18); // closes the balanced pair, stops at the loose ')'
        assert_eq!(scan("http://e.com]x"), 12); // a ']' at depth zero ends the run
        assert_eq!(scan("http://e.com<x"), 12); // so does a '<'
    }

    #[test]
    fn trim_trailing_drops_punctuation_and_entities() {
        let chars: Vec<char> = "http://e.com/p.,".chars().collect();
        assert_eq!(trim_trailing(&chars, 7, chars.len()), 14); // drops the trailing '.' and ','
        let ent: Vec<char> = "http://e.com/p&amp;".chars().collect();
        assert_eq!(trim_trailing(&ent, 7, ent.len()), 14); // a trailing '&entity;' goes whole
    }

    #[test]
    fn bare_url_www_and_email_become_links() {
        assert_eq!(
            links("see http://example.com/p?q=1 now"),
            vec![(
                "http://example.com/p?q=1".to_owned(),
                "http://example.com/p?q=1".to_owned()
            )]
        );
        assert_eq!(
            links("at www.example.com today"),
            vec![(
                "www.example.com".to_owned(),
                "http://www.example.com".to_owned()
            )]
        );
        assert_eq!(
            links("mail me@example.com please"),
            vec![(
                "me@example.com".to_owned(),
                "mailto:me@example.com".to_owned()
            )]
        );
    }

    #[test]
    fn trailing_sentence_punctuation_is_excluded() {
        assert_eq!(
            links("read http://example.com.")
                .first()
                .map(|l| l.1.clone()),
            Some("http://example.com".to_owned())
        );
    }

    #[test]
    fn invalid_domains_do_not_link() {
        assert!(links("ping http://localhost/here").is_empty());
        assert!(links("ping http://a..b.com here").is_empty());
    }

    #[test]
    fn existing_links_are_not_rescanned() {
        // A link is never nested inside another link: a pre-formed Link is passed through verbatim.
        let inner = Inline::Link(
            Attr::default(),
            vec![Inline::Str("http://example.com".to_owned())],
            Target {
                url: "http://example.com".to_owned(),
                title: String::new(),
            },
        );
        let mut inlines = vec![inner.clone()];
        autolink_inlines(&mut inlines, false);
        assert_eq!(inlines, vec![inner]);
    }

    #[test]
    fn code_is_left_untouched() {
        let code = Inline::Code(Attr::default(), "http://example.com".to_owned());
        let mut inlines = vec![code.clone()];
        autolink_inlines(&mut inlines, false);
        assert_eq!(inlines, vec![code]);
    }

    #[test]
    fn markdown_dialect_classes_links_and_accepts_single_label_email() {
        // A URL is tagged `uri`, an email `email`, and a single-label domain links in the dialect.
        assert_eq!(
            classed_links("see http://example.com and 5@home now", true),
            vec![
                (
                    "http://example.com".to_owned(),
                    "http://example.com".to_owned(),
                    vec!["uri".to_owned()]
                ),
                (
                    "5@home".to_owned(),
                    "mailto:5@home".to_owned(),
                    vec!["email".to_owned()]
                ),
            ]
        );
        // The strict dialect leaves links unclassed and never links a single-label email domain.
        assert!(classed_links("ping 5@home now", false).is_empty());
        assert_eq!(
            classed_links("at www.example.com today", false),
            vec![(
                "www.example.com".to_owned(),
                "http://www.example.com".to_owned(),
                Vec::new()
            )]
        );
    }
}