shoin 0.2.2

A no-clutter terminal Markdown editor with modal editing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! Pass B — single left-to-right inline scan. SPEC.md §5.2.
//!
//! Delimiter matching is deliberately naive-but-safe: an opener is honored only
//! if a matching closer exists later on the SAME line. Unbalanced markers render
//! as plain text — which is exactly right while the user is mid-word typing
//! `**` before the closing pair exists.
//!
//! Markers are DIMMED, never concealed. Concealment would break SPEC.md §2.

use std::ops::Range;

use crate::config::schema::MarkdownConfig;
use crate::render::theme::{Attrs, Color, Style, Theme};
use crate::render::StyledSpan;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Inline {
    Bold,
    Italic,
    BoldItalic,
    Strikethrough,
    Highlight,
    Code,
    Link,
    WikiLink,
    Image,
    Tag,
    Autolink,
    /// `\*` — the backslash is dimmed, the next char is literal.
    Escape,
}

pub struct InlineSpan {
    pub kind: Inline,
    /// The whole construct including markers.
    pub outer: Range<usize>,
    /// The rendered body, excluding markers.
    pub inner: Range<usize>,
}

/// Scan one line. Char-indexed ranges.
///
/// Guarantees, enforced by tests and fuzzing:
///   - never panics on arbitrary input
///   - spans never overlap and never exceed the line's char length
pub fn scan(line: &str, cfg: &MarkdownConfig) -> Vec<InlineSpan> {
    let chars: Vec<char> = line.chars().collect();
    let len = chars.len();
    let mut spans = Vec::new();
    let mut i = 0;
    while i < len {
        match match_at(&chars, i, cfg) {
            // A match always starts at `i` and ends past it, so `i` advances and
            // the emitted spans stay ordered and non-overlapping.
            Some(span) => {
                i = span.outer.end.max(i + 1);
                spans.push(span);
            }
            None => i += 1,
        }
    }
    spans
}

/// The link span the cursor sits in, if it sits in one.
///
/// `!` is not part of an unexpanded `![[…]]`'s span: `bracket_link` rejects it
/// (no `(` follows the `]`), the scan falls through one character, and
/// `wiki_at` matches the `[[…]]` alone. That is fine for styling — the bang is
/// one dim character — but a reader whose cursor is ON the bang still means the
/// embed, so the bang is accepted here as belonging to the span after it.
pub fn span_at(line: &str, col: usize, cfg: &MarkdownConfig) -> Option<InlineSpan> {
    let bang = line.chars().nth(col) == Some('!');
    scan(line, cfg)
        .into_iter()
        .find(|s| s.outer.contains(&col) || (bang && s.outer.start == col + 1))
}

/// What a link span points AT — the note name or URL, never the display text.
///
/// Recovered from the line rather than stored on the span. `InlineSpan` is
/// built for every construct on every visible line, and a destination is read
/// only when someone follows a link; a third `Range` on the struct would cost
/// that on every frame to serve one keystroke.
///
/// `None` for a span that is not a link, and for a link whose destination is
/// empty — `[text]()` points nowhere.
pub fn target_of(span: &InlineSpan, line: &str) -> Option<String> {
    let chars: Vec<char> = line.chars().collect();
    let slice = |r: std::ops::Range<usize>| -> Option<String> {
        Some(chars.get(r)?.iter().collect())
    };
    let out = match span.kind {
        Inline::WikiLink => slice(span.inner.clone())?,
        // `[text](url)` — the destination is what sits between the `](` that
        // closes the body and the `)` that closes the construct.
        Inline::Link | Inline::Image => {
            slice(span.inner.end + 2..span.outer.end.checked_sub(1)?)?
        }
        Inline::Autolink => slice(span.outer.clone())?,
        _ => return None,
    };
    let out = out.trim().to_string();
    (!out.is_empty()).then_some(out)
}

/// Try every construct that can begin at `i`, in priority order.
fn match_at(chars: &[char], i: usize, cfg: &MarkdownConfig) -> Option<InlineSpan> {
    match chars[i] {
        '\\' => escape_at(chars, i),
        '`' => code_at(chars, i),
        '!' if chars.get(i + 1) == Some(&'[') => bracket_link(chars, i, true),
        '[' if cfg.wiki_links && chars.get(i + 1) == Some(&'[') => wiki_at(chars, i),
        '[' => bracket_link(chars, i, false),
        '*' => emphasis_at(chars, i),
        '~' => pair_at(chars, i, '~', Inline::Strikethrough),
        '=' if cfg.highlight => pair_at(chars, i, '=', Inline::Highlight),
        '#' if cfg.tags => tag_at(chars, i),
        'h' => autolink_at(chars, i),
        _ => None,
    }
}

// ---------------------------------------------------------------- scan helpers

/// Run length of `ch` starting at `i`.
fn run_len(chars: &[char], i: usize, ch: char) -> usize {
    let mut n = 0;
    while chars.get(i + n) == Some(&ch) {
        n += 1;
    }
    n
}

/// First index at/after `from` beginning a run of at least `n` of `ch`.
fn find_delim(chars: &[char], from: usize, ch: char, n: usize) -> Option<usize> {
    let mut j = from;
    while j < chars.len() {
        if chars[j] == ch && run_len(chars, j, ch) >= n {
            return Some(j);
        }
        j += 1;
    }
    None
}

fn all_blank(chars: &[char], range: Range<usize>) -> bool {
    chars[range].iter().all(|c| c.is_whitespace())
}

fn starts_with(chars: &[char], i: usize, pat: &str) -> bool {
    pat.chars()
        .enumerate()
        .all(|(k, pc)| chars.get(i + k) == Some(&pc))
}

fn escape_at(chars: &[char], i: usize) -> Option<InlineSpan> {
    let next = *chars.get(i + 1)?;
    if next.is_ascii_punctuation() {
        Some(InlineSpan {
            kind: Inline::Escape,
            outer: i..i + 2,
            inner: i + 1..i + 2,
        })
    } else {
        None
    }
}

fn code_at(chars: &[char], i: usize) -> Option<InlineSpan> {
    let r = run_len(chars, i, '`');
    let open_end = i + r;
    let close = find_delim(chars, open_end, '`', r)?;
    if close <= open_end {
        return None;
    }
    Some(InlineSpan {
        kind: Inline::Code,
        outer: i..close + r,
        inner: open_end..close,
    })
}

/// `*` / `**` / `***`. The run length picks italic / bold / both.
fn emphasis_at(chars: &[char], i: usize) -> Option<InlineSpan> {
    let n = run_len(chars, i, '*').min(3);
    let kind = match n {
        3 => Inline::BoldItalic,
        2 => Inline::Bold,
        _ => Inline::Italic,
    };
    let open_end = i + n;
    let close = find_delim(chars, open_end, '*', n)?;
    if close <= open_end || all_blank(chars, open_end..close) {
        return None;
    }
    Some(InlineSpan {
        kind,
        outer: i..close + n,
        inner: open_end..close,
    })
}

/// A two-character symmetric fence: `~~x~~`, `==x==`.
fn pair_at(chars: &[char], i: usize, ch: char, kind: Inline) -> Option<InlineSpan> {
    if run_len(chars, i, ch) < 2 {
        return None;
    }
    let open_end = i + 2;
    let close = find_delim(chars, open_end, ch, 2)?;
    if close <= open_end || all_blank(chars, open_end..close) {
        return None;
    }
    Some(InlineSpan {
        kind,
        outer: i..close + 2,
        inner: open_end..close,
    })
}

/// `[text](url)` and `![text](url)`. The rendered body is the text; the URL and
/// brackets are markers. Naive: the first `]` closes the text.
fn bracket_link(chars: &[char], i: usize, image: bool) -> Option<InlineSpan> {
    let text_start = if image { i + 2 } else { i + 1 };
    let text_end = find_char(chars, text_start, ']')?;
    if chars.get(text_end + 1) != Some(&'(') {
        return None;
    }
    let url_end = find_char(chars, text_end + 2, ')')?;
    Some(InlineSpan {
        kind: if image { Inline::Image } else { Inline::Link },
        outer: i..url_end + 1,
        inner: text_start..text_end,
    })
}

/// `[[target]]`.
fn wiki_at(chars: &[char], i: usize) -> Option<InlineSpan> {
    let text_start = i + 2;
    let mut j = text_start;
    while j + 1 < chars.len() {
        if chars[j] == ']' && chars[j + 1] == ']' {
            return Some(InlineSpan {
                kind: Inline::WikiLink,
                outer: i..j + 2,
                inner: text_start..j,
            });
        }
        j += 1;
    }
    None
}

/// `#tag` at a word boundary. A purely numeric tag (`#123`) is rejected, as in
/// Obsidian.
fn tag_at(chars: &[char], i: usize) -> Option<InlineSpan> {
    if i > 0 && !chars[i - 1].is_whitespace() {
        return None;
    }
    let start = i + 1;
    let first = *chars.get(start)?;
    if !(first.is_alphanumeric() || first == '_') {
        return None;
    }
    let mut j = start;
    while j < chars.len() && (chars[j].is_alphanumeric() || matches!(chars[j], '_' | '-' | '/')) {
        j += 1;
    }
    if !chars[start..j].iter().any(|c| c.is_alphabetic() || *c == '_') {
        return None;
    }
    Some(InlineSpan {
        kind: Inline::Tag,
        outer: i..j,
        inner: start..j,
    })
}

/// A bare `http://` / `https://` URL, ending at whitespace or a closing
/// bracket, with trailing sentence punctuation trimmed off.
fn autolink_at(chars: &[char], i: usize) -> Option<InlineSpan> {
    let scheme = if starts_with(chars, i, "https://") {
        8
    } else if starts_with(chars, i, "http://") {
        7
    } else {
        return None;
    };
    let mut j = i + scheme;
    while j < chars.len()
        && !chars[j].is_whitespace()
        && !matches!(chars[j], '<' | '>' | '"' | '\'' | '`' | ')' | ']' | '}')
    {
        j += 1;
    }
    while j > i + scheme && matches!(chars[j - 1], '.' | ',' | ';' | ':' | '!' | '?') {
        j -= 1;
    }
    if j <= i + scheme {
        return None;
    }
    Some(InlineSpan {
        kind: Inline::Autolink,
        outer: i..j,
        inner: i..j,
    })
}

fn find_char(chars: &[char], from: usize, ch: char) -> Option<usize> {
    (from..chars.len()).find(|&j| chars[j] == ch)
}

// ---------------------------------------------------------------------- styling

/// Flatten inline spans into a gap-free, non-overlapping cover of `base.range`.
///
/// Each span contributes up to three pieces: a dimmed leading marker, the
/// kind-styled body, and a dimmed trailing marker. Gaps between spans keep the
/// block `base` style. Spans not fully inside the region are ignored.
pub fn to_styled(
    line: &str,
    spans: &[InlineSpan],
    base: &StyledSpan,
    theme: &Theme,
) -> Vec<StyledSpan> {
    let len = line.chars().count();
    let region_start = base.range.start;
    let region_end = base.range.end.min(len);
    let marker = marker_style(theme);

    let mut out = Vec::new();
    let mut cursor = region_start;

    for sp in spans {
        if sp.outer.start < cursor || sp.outer.start < region_start || sp.outer.end > region_end {
            continue;
        }
        if sp.outer.start > cursor {
            out.push(StyledSpan {
                range: cursor..sp.outer.start,
                style: base.style,
            });
        }
        if sp.inner.start > sp.outer.start {
            out.push(StyledSpan {
                range: sp.outer.start..sp.inner.start,
                style: marker,
            });
        }
        if sp.inner.end > sp.inner.start {
            out.push(StyledSpan {
                range: sp.inner.clone(),
                style: body_style(sp.kind, base.style, theme),
            });
        }
        if sp.outer.end > sp.inner.end {
            out.push(StyledSpan {
                range: sp.inner.end..sp.outer.end,
                style: marker,
            });
        }
        cursor = sp.outer.end;
    }

    if cursor < region_end {
        out.push(StyledSpan {
            range: cursor..region_end,
            style: base.style,
        });
    }
    out
}

fn marker_style(theme: &Theme) -> Style {
    Style {
        fg: theme.text_dim,
        bg: Color::None,
        attrs: Attrs {
            dim: theme.dim_markers,
            ..Attrs::default()
        },
    }
}

/// A construct's body style, layered over the block's base style.
fn body_style(kind: Inline, base: Style, theme: &Theme) -> Style {
    let mut s = base;
    match kind {
        Inline::Bold => {
            s.fg = theme.bold;
            s.attrs.bold = theme.bold_attr;
        }
        Inline::Italic => {
            s.fg = theme.italic;
            s.attrs.italic = theme.italic_attr;
        }
        Inline::BoldItalic => {
            s.fg = theme.bold;
            s.attrs.bold = theme.bold_attr;
            s.attrs.italic = theme.italic_attr;
        }
        Inline::Strikethrough => {
            s.fg = theme.strikethrough;
            s.attrs.strikethrough = true;
        }
        Inline::Highlight => s.bg = theme.highlight_bg,
        Inline::Code => {
            s.fg = theme.code;
            s.bg = theme.code_bg;
        }
        Inline::Link | Inline::Image | Inline::Autolink => {
            s.fg = theme.link;
            s.attrs.underline = theme.link_underline;
        }
        Inline::WikiLink => {
            s.fg = theme.wiki_link;
            s.attrs.underline = theme.link_underline;
        }
        Inline::Tag => {
            s.fg = theme.tag;
            s.bg = theme.tag_bg;
        }
        // The backslash is the marker; the escaped char shows in the base style.
        Inline::Escape => {}
    }
    s
}

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

    fn md() -> MarkdownConfig {
        MarkdownConfig::default()
    }

    /// Char-slice of a span's outer/inner, for readable assertions.
    fn text(line: &str, r: &Range<usize>) -> String {
        line.chars().skip(r.start).take(r.end - r.start).collect()
    }

    fn only(line: &str) -> InlineSpan {
        let mut v = scan(line, &md());
        assert_eq!(v.len(), 1, "expected exactly one span in {line:?}");
        v.pop().unwrap()
    }

    #[test]
    fn emphasis_variants() {
        let s = only("a **bold** b");
        assert_eq!(s.kind, Inline::Bold);
        assert_eq!(text("a **bold** b", &s.inner), "bold");
        assert_eq!(text("a **bold** b", &s.outer), "**bold**");

        assert_eq!(only("*i*").kind, Inline::Italic);
        assert_eq!(only("***x***").kind, Inline::BoldItalic);
        assert_eq!(only("~~gone~~").kind, Inline::Strikethrough);
        assert_eq!(only("==hi==").kind, Inline::Highlight);
    }

    #[test]
    fn unbalanced_markers_are_plain() {
        // The whole point: half-typed constructs never produce a span.
        assert!(scan("a **bold", &md()).is_empty());
        assert!(scan("just * one", &md()).is_empty());
        assert!(scan("`unclosed", &md()).is_empty());
        assert!(scan("** **", &md()).is_empty()); // blank inner
    }

    #[test]
    fn code_is_literal_inside() {
        let s = only("call `f(*x*)` now");
        assert_eq!(s.kind, Inline::Code);
        assert_eq!(text("call `f(*x*)` now", &s.inner), "f(*x*)");
        // The `*x*` inside the code span is not separately parsed.
        assert_eq!(scan("call `f(*x*)` now", &md()).len(), 1);
    }

    #[test]
    fn links_images_wikis() {
        let s = only("see [text](http://x.y)");
        assert_eq!(s.kind, Inline::Link);
        assert_eq!(text("see [text](http://x.y)", &s.inner), "text");

        let img = only("![alt](p.png)");
        assert_eq!(img.kind, Inline::Image);
        assert_eq!(text("![alt](p.png)", &img.inner), "alt");

        let w = only("a [[Note Name]] b");
        assert_eq!(w.kind, Inline::WikiLink);
        assert_eq!(text("a [[Note Name]] b", &w.inner), "Note Name");
    }

    #[test]
    fn tags_need_boundaries() {
        let s = only("a #project tag");
        assert_eq!(s.kind, Inline::Tag);
        assert_eq!(text("a #project tag", &s.inner), "project");
        // Mid-word `#` is not a tag; a numeric-only tag is rejected.
        assert!(scan("foo#bar", &md()).is_empty());
        assert!(scan("#123", &md()).is_empty());
    }

    /// The span under the cursor is what a follow command acts on — including
    /// from the `!` of an `![[…]]`, which is NOT inside the span the scanner
    /// emits for it.
    #[test]
    fn span_at_finds_the_link_the_cursor_is_in() {
        let cfg = MarkdownConfig::default();
        let line = "see ![[frag#Head]] and [x](y.md) and https://a.example/b";

        let bang = line.find('!').unwrap();
        assert_eq!(span_at(line, bang, &cfg).unwrap().kind, Inline::WikiLink);
        assert_eq!(span_at(line, bang + 3, &cfg).unwrap().kind, Inline::WikiLink);

        let md = line.find("[x]").unwrap();
        assert_eq!(span_at(line, md + 1, &cfg).unwrap().kind, Inline::Link);

        let url = line.find("https").unwrap();
        assert_eq!(span_at(line, url + 2, &cfg).unwrap().kind, Inline::Autolink);

        assert!(span_at(line, 1, &cfg).is_none(), "plain prose is not a link");
    }

    /// A destination is never the display text.
    #[test]
    fn target_of_reads_the_destination_not_the_label() {
        let cfg = MarkdownConfig::default();
        let cases = [
            ("[[frag#Head]]", "frag#Head"),
            ("![[frag]]", "frag"),
            ("[the label](notes/x.md)", "notes/x.md"),
            ("https://a.example/b", "https://a.example/b"),
        ];
        for (line, want) in cases {
            let span = span_at(line, line.len() / 2, &cfg).unwrap();
            assert_eq!(target_of(&span, line).as_deref(), Some(want), "{line}");
        }
        // A link that points nowhere has no destination to follow.
        let span = span_at("[label]()", 2, &cfg).unwrap();
        assert_eq!(target_of(&span, "[label]()"), None);
    }

    #[test]
    fn autolink_trims_trailing_punctuation() {
        let s = only("visit https://example.com/path.");
        assert_eq!(s.kind, Inline::Autolink);
        assert_eq!(
            text("visit https://example.com/path.", &s.outer),
            "https://example.com/path"
        );
    }

    #[test]
    fn escape_dims_backslash() {
        let s = only(r"a \* b");
        assert_eq!(s.kind, Inline::Escape);
        assert_eq!(text(r"a \* b", &s.outer), r"\*");
        assert_eq!(text(r"a \* b", &s.inner), "*");
    }

    #[test]
    fn config_gates() {
        let mut cfg = md();
        cfg.wiki_links = false;
        cfg.tags = false;
        cfg.highlight = false;
        assert!(scan("[[note]] #tag ==hi==", &cfg).is_empty());
    }

    #[test]
    fn spans_never_overlap_and_stay_in_bounds() {
        let line = "**a** `b` [c](d) #e ~~f~~ *g* \\!";
        let spans = scan(line, &md());
        let len = line.chars().count();
        let mut prev_end = 0;
        for s in &spans {
            assert!(s.outer.start >= prev_end, "overlap at {:?}", s.outer);
            assert!(s.inner.start >= s.outer.start && s.inner.end <= s.outer.end);
            assert!(s.outer.end <= len);
            prev_end = s.outer.end;
        }
    }

    #[test]
    fn to_styled_covers_region_without_gaps() {
        let line = "a **b** c";
        let theme = Theme::default();
        let base = StyledSpan {
            range: 0..line.chars().count(),
            style: Style::fg(theme.text),
        };
        let out = to_styled(line, &scan(line, &md()), &base, &theme);
        // Contiguous cover of the whole region.
        assert_eq!(out.first().unwrap().range.start, 0);
        assert_eq!(out.last().unwrap().range.end, line.chars().count());
        for w in out.windows(2) {
            assert_eq!(w[0].range.end, w[1].range.start);
        }
        // The `**` markers are dimmed; the body carries the bold color.
        assert!(out.iter().any(|s| s.style.fg == theme.text_dim && s.style.attrs.dim));
        assert!(out.iter().any(|s| s.style.fg == theme.bold));
    }

    #[test]
    fn never_panics_on_odd_input() {
        for line in [
            "", "*", "**", "***", "~", "==", "`", "[", "](", "![]", "[[", "]]",
            "\\", "#", "# ", "http://", "https://", "*******", "``````", "[a](b",
            "😀 **bold** 🎉", "\t\t- x", "a*b*c*d*e",
        ] {
            let _ = scan(line, &md()); // must not panic
        }
    }
}