bezel-markdown 0.1.20

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
//! 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 list inside a quote inside a list flattens. 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::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();
        for block in &mut self.blocks {
            let indent = block.indent as usize;
            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;
            }
        }
    }
}

/// 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)]
pub struct Block {
    pub kind: BlockKind,
    pub indent: u8,
}

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

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

    /// 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, .. }
                | BlockKind::Quote { 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, .. }
                | BlockKind::Quote { 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 { .. }
            | BlockKind::Quote { .. } => 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 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)]
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,
    },
    /// A blockquote. `kind` is the GFM alert it opens with — see [`QuoteKind`].
    Quote {
        kind: Option<QuoteKind>,
        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 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::preview`], so there
    /// is nothing here for a caret to edit.
    ///
    /// [`Form`] picks which of the three — a chip, a card, or a card with its
    /// picture across the width. Off a line of its own the same link is a
    /// [`Mark::Mention`], which is the same three minus what shaped text cannot
    /// hold.
    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.
/// A blockquote holding two paragraphs becomes two [`BlockKind::Quote`] blocks
/// and each carries the kind, so writing the document back gives two alerts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
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, 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)]
pub struct Text {
    pub text: String,
    /// Outermost first. Ranges may overlap and may be identical.
    pub marks: Vec<MarkSpan>,
}

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()
    }

    /// 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)]
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.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Form {
    Auto,
    Chip,
    Embed,
}

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

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

#[derive(Debug, Clone, PartialEq, Eq)]
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 the URL, because a [`Text`] is one string and every caret
    /// offset is a byte into it: an inline atom painted wider or narrower than
    /// the text under it has nowhere to put the offsets in between.
    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),
}