bezel-markdown 0.2.21

A Notion-style block document model for gpui — markdown in, markdown out
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
//! The document model.
//!
//! A [`Doc`] is a **flat** list of [`Block`]s with an indent level, not a
//! nested tree. That is Notion's model rather than CommonMark's, and it is the
//! decision the rest of this crate hangs off: editing a flat list means Enter
//! splits, Backspace merges, and Tab indents — all list operations. On a
//! nested tree "the previous block" is a traversal and every edit is a
//! restructure.
//!
//! The trade is that arbitrarily nested CommonMark does not survive a round
//! trip: a quote inside a quote flattens to one. Notion has the same
//! limitation. What is guaranteed is [`crate::serialize`]'s fixed point —
//! parse, serialize, parse again, and the document is unchanged — so an
//! edit/save cycle never drifts.

use std::{
    collections::{HashMap, HashSet},
    ops::Range,
};

/// A markdown document: blocks in document order.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Doc {
    pub blocks: Vec<Block>,
}

impl Doc {
    /// Make each run of ordered items consecutive.
    ///
    /// Markdown honours only the *first* number in a list — `1.` followed by `9.`
    /// renders as 1, 2. Two source lists that used different delimiters (`1.` then
    /// `9)`) are separate lists, but a flat document has no list identity to
    /// preserve, so they serialize as one and the second item's number would move
    /// on the next read. Deciding it here means the document already holds what the
    /// next parse would produce.
    pub(crate) fn renumber(&mut self) {
        // The number owed to the next ordered item at each indent level. A run
        // survives blocks nested under it and ends at anything else.
        let mut expected: Vec<Option<u64>> = Vec::new();
        let mut runs = Runs::default();
        let mut above: Option<Run> = None;
        for block in &mut self.blocks {
            let indent = block.indent as usize;
            let run = runs.next(block.quote, block.indent);
            // A list on the other side of a quote's `>` is another list.
            if run.is_none_or(|run| run.first) {
                let edge = [above, run]
                    .into_iter()
                    .flatten()
                    .map(|run| run.level as usize)
                    .min();
                if let Some(edge) = edge {
                    expected.truncate(edge);
                }
            }
            above = run;
            expected.truncate(indent + 1);
            expected.resize(indent + 1, None);

            if let BlockKind::Ordered { number, .. } = &mut block.kind {
                if let Some(next) = expected[indent] {
                    *number = next;
                }
                expected[indent] = Some(number.saturating_add(1));
            } else {
                expected[indent] = None;
            }
        }
    }

    /// Each heading's anchor and its block, in document order. A slug already
    /// taken by an earlier heading gets `-1`, `-2`, … as on GitHub.
    pub fn anchors(&self) -> Vec<(String, usize)> {
        let mut taken = HashSet::new();
        // The first suffix not yet tried for each slug, so a title repeated n
        // times costs n probes rather than n².
        let mut next: HashMap<String, usize> = HashMap::new();
        self.blocks
            .iter()
            .enumerate()
            .filter_map(|(ix, block)| match &block.kind {
                BlockKind::Heading { text, .. } => Some((slug(&text.text), ix)),
                _ => None,
            })
            .map(|(base, ix)| {
                let from = next.get(&base).copied().unwrap_or(0);
                let (n, anchor) = (from..)
                    .map(|n| match n {
                        0 => (n, base.clone()),
                        n => (n, format!("{base}-{n}")),
                    })
                    .find(|(_, anchor)| !taken.contains(anchor))
                    .expect("an unbounded run of suffixes");
                next.insert(base, n + 1);
                taken.insert(anchor.clone());
                (anchor, ix)
            })
            .collect()
    }
}

/// The anchor GitHub gives a heading: lowercased, punctuation dropped but for
/// `-` and `_`, each space a `-`.
pub fn slug(text: &str) -> String {
    text.chars()
        .flat_map(char::to_lowercase)
        .filter_map(|c| match c {
            ' ' => Some('-'),
            '-' | '_' => Some(c),
            c if c.is_alphanumeric() => Some(c),
            _ => None,
        })
        .collect()
}

/// One block, and how deeply it is nested.
///
/// `indent` obeys one invariant, established by the parser and relied on by
/// the serializer: the first block is at 0, and no block is more than one
/// level deeper than the block before it. A document that satisfies it always
/// serializes to markdown that parses back to the same indents.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Block {
    pub kind: BlockKind,
    pub indent: u8,
    /// The blockquote the block sits in, or `None` outside one. Adjacent
    /// quoted blocks form one blockquote — see [`quote_runs`].
    pub quote: Option<Quoted>,
}

/// A block's place in a blockquote.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Quoted {
    /// The GFM alert the blockquote opens with — see [`QuoteKind`].
    pub alert: Option<QuoteKind>,
}

/// Where a quoted block falls in its blockquote.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Run {
    /// The indent the `>` is written at: the indent of the run's first block.
    pub level: u8,
    pub first: bool,
}

/// Each block's place in a blockquote, or `None` for an unquoted block.
///
/// A quoted block continues the run before it when it carries the same
/// [`Quoted`] and sits no shallower than the run's level. Anything else starts
/// a new run at its own indent.
pub(crate) fn quote_runs(
    blocks: impl IntoIterator<Item = (Option<Quoted>, u8)>,
) -> Vec<Option<Run>> {
    let mut runs = Runs::default();
    blocks
        .into_iter()
        .map(|(quote, indent)| runs.next(quote, indent))
        .collect()
}

/// [`quote_runs`] one block at a time.
#[derive(Default)]
pub(crate) struct Runs {
    open: Option<(Quoted, u8)>,
}

impl Runs {
    pub fn next(&mut self, quote: Option<Quoted>, indent: u8) -> Option<Run> {
        let Some(quote) = quote else {
            self.open = None;
            return None;
        };
        match self.open {
            Some((current, level)) if current == quote && indent >= level => Some(Run {
                level,
                first: false,
            }),
            _ => {
                self.open = Some((quote, indent));
                Some(Run {
                    level: indent,
                    first: true,
                })
            }
        }
    }
}

impl From<BlockKind> for Block {
    fn from(kind: BlockKind) -> Self {
        Self::new(kind)
    }
}

impl Block {
    pub fn new(kind: BlockKind) -> Self {
        Self::at(kind, 0)
    }

    pub fn at(kind: BlockKind, indent: u8) -> Self {
        Self {
            kind,
            indent,
            quote: None,
        }
    }

    pub fn quoted(self, quote: Quoted) -> Self {
        Self {
            quote: Some(quote),
            ..self
        }
    }

    /// One of the block's editable texts. `None` when the block has no such
    /// part — every block is atomic to some [`Part`], and bookmarks and rules
    /// are atomic to all of them.
    pub fn text_at(&self, part: Part) -> Option<&Text> {
        match (&self.kind, part) {
            (
                BlockKind::Paragraph(text)
                | BlockKind::Heading { text, .. }
                | BlockKind::Bullet(text)
                | BlockKind::Ordered { text, .. }
                | BlockKind::Task { text, .. },
                Part::Body,
            ) => Some(text),
            (BlockKind::Code { code, .. }, Part::Code) => Some(code),
            (BlockKind::Image { alt, .. }, Part::Caption) => Some(alt),
            (BlockKind::Table { header, .. }, Part::Cell { row: 0, column }) => header.get(column),
            (BlockKind::Table { rows, .. }, Part::Cell { row, column }) => {
                rows.get(row - 1)?.get(column)
            }
            _ => None,
        }
    }

    pub fn text_at_mut(&mut self, part: Part) -> Option<&mut Text> {
        match (&mut self.kind, part) {
            (
                BlockKind::Paragraph(text)
                | BlockKind::Heading { text, .. }
                | BlockKind::Bullet(text)
                | BlockKind::Ordered { text, .. }
                | BlockKind::Task { text, .. },
                Part::Body,
            ) => Some(text),
            (BlockKind::Code { code, .. }, Part::Code) => Some(code),
            (BlockKind::Image { alt, .. }, Part::Caption) => Some(alt),
            (BlockKind::Table { header, .. }, Part::Cell { row: 0, column }) => {
                header.get_mut(column)
            }
            (BlockKind::Table { rows, .. }, Part::Cell { row, column }) => {
                rows.get_mut(row - 1)?.get_mut(column)
            }
            _ => None,
        }
    }

    /// Every part a caret can sit in, in document order.
    pub fn parts(&self) -> Vec<Part> {
        match &self.kind {
            BlockKind::Paragraph(_)
            | BlockKind::Heading { .. }
            | BlockKind::Bullet(_)
            | BlockKind::Ordered { .. }
            | BlockKind::Task { .. } => vec![Part::Body],
            BlockKind::Code { .. } => vec![Part::Code],
            BlockKind::Image { .. } => vec![Part::Caption],
            BlockKind::Table { header, rows, .. } => {
                let mut parts = Vec::new();
                if !header.is_empty() {
                    parts.extend((0..header.len()).map(|column| Part::Cell { row: 0, column }));
                }
                for (ix, row) in rows.iter().enumerate() {
                    parts.extend((0..row.len()).map(|column| Part::Cell {
                        row: ix + 1,
                        column,
                    }));
                }
                parts
            }
            BlockKind::Bookmark { .. } | BlockKind::Rule => Vec::new(),
        }
    }

    /// Whether the block is a blank paragraph: the empty line an editor leaves
    /// behind, which markdown has no way to write down. The empty body of an
    /// alert is not one: `> [!TIP]` writes down and reads back.
    pub(crate) fn blank(&self) -> bool {
        matches!(&self.kind, BlockKind::Paragraph(text) if text.is_empty() && text.marks.is_empty())
            && !self.quote.is_some_and(|quote| quote.alert.is_some())
    }

    /// Whether what the block paints past its parts holds no caret — a picture,
    /// a card, a line. What a selection has to wash for itself, since there is
    /// no text under it to carry the highlight.
    pub fn opaque(&self) -> bool {
        matches!(
            self.kind,
            BlockKind::Image { .. } | BlockKind::Bookmark { .. } | BlockKind::Rule
        )
    }
}

/// Which of a block's texts a caret sits in.
///
/// A block has one kind of part and never a mix — prose blocks have a body, a
/// code block has its code, a table has cells — so this is a coordinate rather
/// than a path, and the model stays flat. The ordering is document order, which
/// is what makes a [`crate::Cursor`] comparable and therefore what makes a
/// selection a range.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum Part {
    #[default]
    Body,
    Code,
    /// An image's caption, which is also its alt text.
    Caption,
    /// Row 0 is the header row; row `n` is `rows[n - 1]`.
    Cell {
        row: usize,
        column: usize,
    },
}

/// The block vocabulary. Closed by design — a consumer that needs a block of
/// its own is a reason to widen this enum rather than to grow an extension
/// system.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum BlockKind {
    Paragraph(Text),
    Heading {
        /// 1–6.
        level: u8,
        text: Text,
    },
    Bullet(Text),
    Ordered {
        /// The rendered number. Stored rather than derived so a list starting
        /// at 3 survives the round trip.
        number: u64,
        text: Text,
    },
    Task {
        checked: bool,
        text: Text,
    },
    /// The code carries a [`Text`] like every other editable region, so one
    /// accessor and one edit path cover the whole document. Its marks are
    /// unreachable rather than forbidden: nothing that writes here creates one.
    Code {
        language: Option<String>,
        code: Text,
        /// The height a painted fence stands at, in whole pixels, from a drag
        /// off its handle in `bezel-editor`. `None` is the block's own height.
        /// Spelled as the info string's second word: ` ```mermaid 360 `.
        height: Option<u32>,
    },
    /// The caption is the alt text — markdown has one slot, and a reader that
    /// cannot see the picture reads the same words. Like [`BlockKind::Code`]'s,
    /// its marks are unreachable rather than forbidden.
    Image {
        url: String,
        alt: Text,
        /// A drag off the handle in `bezel-editor`, in whole pixels — `None` is
        /// the natural width. `u32` rather than a float: this derives `Eq`, and
        /// a `f32` cannot because of NaN. Spelled `![alt|480](url)`, which
        /// leaves the title slot to say what a title says.
        width: Option<u32>,
    },
    /// A link with a block to itself, painted richly. Atomic on purpose:
    /// everything it shows past the URL comes from [`crate::app::preview`], so there
    /// is nothing here for a caret to edit.
    ///
    /// [`Form`] picks a card or a card with its picture across the width;
    /// [`Form::Chip`] paints as the card. A chip is a [`Mark::Mention`], on a
    /// line of its own or not.
    Bookmark {
        url: String,
        form: Form,
    },
    Table {
        align: Vec<Align>,
        header: Vec<Text>,
        rows: Vec<Vec<Text>>,
    },
    Rule,
}

/// A GFM alert's kind — the `[!NOTE]` marker a blockquote opens with.
///
/// Only recognised when the marker is alone on the quote's first line and
/// names one of these five; anything else stays the text it was written as.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum QuoteKind {
    Note,
    Tip,
    Important,
    Warning,
    Caution,
}

impl QuoteKind {
    /// The marker line, bracket to bracket.
    pub fn marker(self) -> &'static str {
        match self {
            Self::Note => "[!NOTE]",
            Self::Tip => "[!TIP]",
            Self::Important => "[!IMPORTANT]",
            Self::Warning => "[!WARNING]",
            Self::Caution => "[!CAUTION]",
        }
    }

    /// What the alert calls itself where it is painted.
    pub fn label(self) -> &'static str {
        match self {
            Self::Note => "Note",
            Self::Tip => "Tip",
            Self::Important => "Important",
            Self::Warning => "Warning",
            Self::Caution => "Caution",
        }
    }
}

/// GFM column alignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Align {
    #[default]
    Left,
    Center,
    Right,
}

/// Inline content: a string, plus marks over byte ranges of it.
///
/// Marks are a separate list rather than flags on a run because an editor has
/// to *map* them through insertions and deletions, and because run flags lose
/// nesting order — under flags `**_x_**` and `_**x**_` are the same value.
/// Here they differ by the order of the two spans, and both survive a round
/// trip.
///
/// A newline in `text` is a line break within the block (markdown's soft or
/// hard break, which this model does not distinguish — neither does Notion).
/// Whether it paints as a break or a space is a rendering decision.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct Text {
    pub text: String,
    /// Outermost first. Ranges may overlap and may be identical.
    pub marks: Vec<MarkSpan>,
}

impl From<&str> for Text {
    fn from(text: &str) -> Self {
        Self::plain(text)
    }
}

impl From<String> for Text {
    fn from(text: String) -> Self {
        Self::plain(text)
    }
}

impl Text {
    /// Unmarked text.
    pub fn plain(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            marks: Vec::new(),
        }
    }

    /// A URL that links to itself — what a pasted link is, and what a bookmark
    /// hands back when it turns into prose.
    pub fn link(url: &str) -> Self {
        Self {
            text: url.to_string(),
            marks: vec![MarkSpan {
                range: 0..url.len(),
                mark: Mark::Link(url.to_string()),
            }],
        }
    }

    pub fn is_empty(&self) -> bool {
        self.text.is_empty()
    }

    /// The mention `offset` falls strictly inside. A caret has no place there:
    /// the mention shows its preview, not its text.
    pub(crate) fn mention_around(&self, offset: usize) -> Option<Range<usize>> {
        self.marks
            .iter()
            .find(|span| {
                matches!(span.mark, Mark::Mention { .. })
                    && span.range.start < offset
                    && offset < span.range.end
            })
            .map(|span| span.range.clone())
    }

    /// Whether no other mark overlaps the one at `ix`.
    ///
    /// A mark written whole — a code span, a mention — leaves no room inside
    /// itself for another mark's boundary, so this is what decides whether it
    /// can be spelled its own way at all.
    pub(crate) fn alone(&self, ix: usize) -> bool {
        let span = &self.marks[ix].range;
        self.marks.iter().enumerate().all(|(other, mark)| {
            other == ix || mark.range.end <= span.start || mark.range.start >= span.end
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MarkSpan {
    pub range: Range<usize>,
    pub mark: Mark,
}

/// How a [`Mark::Mention`] was written down, which is also how it paints.
///
/// `Auto` is the shorthand `<https://x>`: a chip in a sentence, a card on a
/// line of its own. It is a variant rather than a resolved form because the
/// spelling is what has to survive the round trip — resolve it at parse and
/// every `<url>` grows brackets the first time the file is saved.
///
/// The other two are CommonMark's title slot, `[url](url "chip")`, which is
/// core, ignored by every other renderer, and the only place left to say what
/// the shorthand cannot: a chip alone on a line, and the bigger card.
/// [`Form::Chip`] stays inline wherever it is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Form {
    Auto,
    Chip,
    /// The bigger card, at a height in whole pixels from a drag off its
    /// handle in `bezel-editor`, or its own height for `None`. Spelled
    /// `"embed 360"`.
    Embed(Option<u32>),
}

impl Form {
    /// The title that spells this form, and `None` for the shorthand.
    pub(crate) fn title(self) -> Option<String> {
        match self {
            Self::Auto => None,
            Self::Chip => Some("chip".to_owned()),
            Self::Embed(None) => Some("embed".to_owned()),
            Self::Embed(Some(height)) => Some(format!("embed {height}")),
        }
    }

    pub(crate) fn from_title(title: &str) -> Option<Self> {
        let (name, height) = crate::parse::split_size(title);
        match (name, height) {
            ("chip", None) => Some(Self::Chip),
            ("embed", height) => Some(Self::Embed(height)),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Mark {
    Bold,
    Italic,
    Strike,
    Code,
    Link(String),
    /// A link painted richly rather than as underlined text — a chip inline, a
    /// [`BlockKind::Bookmark`] with a block to itself.
    ///
    /// The chip shows a favicon and the [`crate::app::preview`] title in place of
    /// its text, and opens the card on hover. Its text is atomic: a caret sits
    /// at either end, never inside, and typing at its end falls outside it.
    Mention {
        url: String,
        form: Form,
    },
    /// A mark the app spells itself — underline, a highlight, a colour. The
    /// name is [`crate::Marks`]'s, and the delimiter that writes it comes from
    /// the same registry.
    Custom(String),
    /// An image among text. [`BlockKind::Image`] is the shape an editor offers;
    /// this is what keeps `see ![x](u) here` from silently becoming a link when
    /// the document is saved. No width: one among text has no box of its own to
    /// resize, and the `|480` that would say so stays the ordinary text it is.
    Image(String),
}