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
use markdown::parse::parse;
use markdown::*;

mod common;

/// Markdown already in the form this serializer emits. These must survive
/// byte for byte — anything less means opening a note and saving it without
/// touching it would rewrite the file.
const CANONICAL: &[&str] = &[
    "Hello",
    "a\nb",
    "# Title",
    "###### Deep",
    "# Title\n\nBody",
    "**bold** and _italic_ and ~~struck~~",
    "**_x_**",
    "_**x**_",
    "`code` inline",
    "[link](https://example.com)",
    "- a\n- b",
    "- a\n    - b\n- c",
    "1. a\n2. b",
    "3. c\n4. d",
    "- [ ] todo\n- [x] done",
    "- [ ] nested\n    - [x] task",
    "- a\n    - [ ] b",
    "- [ ] a\n    - b",
    "+",
    "1.",
    "- [ ]\nafter",
    "- [ ] ",
    "> quoted",
    "```rust\nfn main() {}\n```",
    "```\nplain\n```",
    "---",
    "![alt](media://x)",
    "![](media://x)",
    "![alt](</My Notes/x.png>)",
    "[link](<a b>)",
    "[link](https://en.wikipedia.org/wiki/Rust_(programming_language))",
    "| a | b |\n| --- | ---: |\n| 1 | 2 |",
    "# Title\n\n- a\n- b\n\n> note\n\n```sh\nls\n```",
    "snake_case stays intact",
    "a #123 reference",
    "1 < 2 & 3 > 0",
    "- a\n\n    child paragraph",
    "> [!TIP]\n> GFM alerts",
    "> [!NOTE]\n> GFM alerts",
    "> [!WARNING]\n> GFM alerts",
    "> [!CAUTION]\n> GFM alerts",
    "> [!IMPORTANT]\n> GFM alerts",
    "> [!TIP]",
    "> [!TIP]\n> two\n> lines",
    // The first line of a quote is a line start like any other: what would
    // open a block there has to keep its backslash.
    "> \\- item",
    "> \\# hash",
    "> \\> angle",
    "> [!TIP]\n> \\- item",
    "> \\[!TIP\\]",
];

/// Markdown that legitimately gets rewritten — escaping added, nesting
/// flattened, alignment normalized. The guarantee here is only that the
/// rewrite settles after one pass.
const NON_CANONICAL: &[&str] = &[
    "star * and under _ alone",
    "a [bracket] in text",
    "trailing  spaces  kept",
    "> - quoted bullet",
    "- > bulleted quote",
    "> # heading in a quote",
    "- a\n            - overdeep",
    ">>> deep quote",
    "1) paren ordered",
    "* star bullet",
    "+ plus bullet",
    "Setext\n======",
    "| a |\n| :-: |\n| c |",
    "<div>raw html</div>",
    "text with <span>inline</span> html",
    "AT&T and &amp; entities",
    "1. a\n\n    ```\n    code\n    ```",
    "",
    "\n\n\n",
    "[!TIP](link)",
    "![!NOTE](image)",
    "[!WARNING]",
    "[!CAUTION] GFM alerts",
    "> [!IMPORTANT] GFM alerts",
    "> [!BOGUS]\n> not an alert",
    "> [!tip]\n> lowercase marker",
    "> [!TIP]\n> one\n>\n> two",
    "> [!NOTE]\n> outer\n> > [!TIP]\n> > inner",
];

#[test]
fn serializing_a_parse_is_a_fixed_point() {
    for source in CANONICAL.iter().chain(NON_CANONICAL) {
        let once = parse(source);
        let text = serialize(&once);
        let twice = parse(&text);
        assert_eq!(
            once, twice,
            "not a fixed point\n--- source ---\n{source}\n--- serialized ---\n{text}\n"
        );
    }
}

#[test]
fn canonical_input_survives_byte_for_byte() {
    for source in CANONICAL {
        let text = serialize(&parse(source));
        assert_eq!(text, *source, "canonical form drifted");
    }
}

#[test]
fn every_document_satisfies_the_indent_invariant() {
    // The serializer's indentation is only sound because of this.
    for source in CANONICAL.iter().chain(NON_CANONICAL) {
        let mut previous: Option<u8> = None;
        for block in &parse(source).blocks {
            let max = previous.map_or(0, |p| p + 1);
            assert!(block.indent <= max, "{source:?}: indent {}", block.indent);
            previous = Some(block.indent);
        }
    }
}

#[test]
fn mark_nesting_order_survives() {
    assert_eq!(serialize(&parse("**_x_**")), "**_x_**");
    assert_eq!(serialize(&parse("_**x**_")), "_**x**_");
}

#[test]
fn a_hash_reference_is_not_escaped() {
    // The bug that made desktop's `markdown.ts` necessary: a `#123` ref
    // escaped to `\#123` matches no reader.
    assert_eq!(serialize(&parse("see #123 now")), "see #123 now");
    assert_eq!(serialize(&parse("#123 at the start")), "#123 at the start");
}

#[test]
fn a_heading_in_body_text_is_escaped() {
    let doc = Doc {
        blocks: vec![Block::new(BlockKind::Paragraph(Text::plain(
            "# not a heading",
        )))],
    };
    let text = serialize(&doc);
    assert_eq!(text, "\\# not a heading");
    assert_eq!(parse(&text), doc);
}

#[test]
fn block_syntax_opening_a_heading_is_not_escaped() {
    for source in ["## 1. Foo", "## - Foo", "## > Foo", "## ---"] {
        assert_eq!(serialize(&parse(source)), source);
    }
}

#[test]
fn text_that_looks_like_a_list_is_escaped() {
    for body in ["- item", "1. item", "> quote", "+ item"] {
        let doc = Doc {
            blocks: vec![Block::new(BlockKind::Paragraph(Text::plain(body)))],
        };
        assert_eq!(parse(&serialize(&doc)), doc, "{body:?} did not survive");
    }
}

#[test]
fn code_containing_a_fence_gets_a_longer_one() {
    let doc = Doc {
        blocks: vec![Block::new(BlockKind::Code {
            language: None,
            code: Text::plain("```\nnested\n```"),
            height: None,
        })],
    };
    assert_eq!(parse(&serialize(&doc)), doc);
}

#[test]
fn a_fence_keeps_its_height_after_the_language() {
    let source = "```mermaid 360\ngraph TD\n```";
    let doc = parse(source);
    assert!(matches!(
        &doc.blocks[0].kind,
        BlockKind::Code { language: Some(language), height: Some(360), .. } if language == "mermaid"
    ));
    assert_eq!(serialize(&doc), source);
}

#[test]
fn an_embed_keeps_its_height_in_the_title() {
    let source = "[cydonia://a#4](cydonia://a#4 \"embed 320\")";
    let doc = parse(source);
    assert!(matches!(
        &doc.blocks[0].kind,
        BlockKind::Bookmark {
            form: markdown::Form::Embed(Some(320)),
            ..
        }
    ));
    assert_eq!(serialize(&doc), source);
}

#[test]
fn a_destination_with_a_space_keeps_its_angles() {
    // A media path under a project whose name has a space in it. Written
    // bare, the destination ends at the space and the whole block comes back
    // as a line of text.
    let doc = Doc {
        blocks: vec![Block::new(BlockKind::Image {
            url: "/My Notes/shot.png".to_string(),
            alt: Text::plain("alt".to_string()),
            width: None,
        })],
    };
    assert_eq!(serialize(&doc), "![alt](</My Notes/shot.png>)");
    assert_eq!(parse(&serialize(&doc)), doc);
}

#[test]
fn a_destination_survives_whatever_it_holds() {
    for url in ["a b", "a(b", "a)b", "a\\b", "<a>", "a b(c"] {
        let doc = Doc {
            blocks: vec![Block::new(BlockKind::Paragraph(Text::link(url)))],
        };
        assert_eq!(parse(&serialize(&doc)), doc, "{url:?} did not survive");
    }
    // The one thing neither spelling holds: raw, it would end the
    // destination the same way a space does.
    let doc = Doc {
        blocks: vec![Block::new(BlockKind::Paragraph(Text::link("a\nb")))],
    };
    assert!(serialize(&doc).contains("<a%0Ab>"));
}

#[test]
fn an_empty_document_serializes_to_nothing() {
    assert_eq!(serialize(&Doc::default()), "");
    assert_eq!(parse(""), Doc::default());
}

#[test]
fn the_fixed_point_holds_for_generated_documents() {
    let mut rng = common::Rng(0x5eed);
    for case in 0..20_000 {
        let lines = 1 + rng.next() % 8;
        let source = (0..lines)
            .map(|_| common::LINES[rng.next() % common::LINES.len()])
            .collect::<Vec<_>>()
            .join("\n");

        let once = parse(&source);
        let text = serialize(&once);
        let twice = parse(&text);
        assert_eq!(
            once, twice,
            "case {case} is not a fixed point\n--- source ---\n{source}\n--- serialized ---\n{text}\n"
        );

        // And it must stay put: a third pass changes nothing either.
        assert_eq!(
            serialize(&twice),
            text,
            "case {case} drifted on a second pass"
        );
    }
}

#[test]
fn an_alert_is_the_quote_rather_than_text() {
    let doc = parse("> [!TIP]\n> body");
    assert_eq!(
        doc.blocks,
        vec![
            Block::new(BlockKind::Paragraph(Text::plain("body"))).quoted(Quoted {
                alert: Some(QuoteKind::Tip),
            })
        ]
    );
    assert_eq!(serialize(&doc), "> [!TIP]\n> body");
}

#[test]
fn an_alert_marker_is_never_escaped() {
    // The bug this replaced: `> \[!TIP\]` is a quote holding two brackets on
    // every reader that knows what an alert is.
    for source in ["> [!TIP]\n> body", "> [!important]\n> body", "> [!NOTE]"] {
        assert!(!serialize(&parse(source)).contains('\\'), "{source:?}");
    }
}

#[test]
fn a_marker_that_names_no_alert_stays_text() {
    let doc = parse("> [!BOGUS]\n> body");
    assert_eq!(
        doc.blocks,
        vec![
            Block::new(BlockKind::Paragraph(Text::plain("[!BOGUS]\nbody")))
                .quoted(Quoted::default())
        ]
    );
}

#[test]
fn normalize_keeps_an_alert_with_no_body() {
    // `Doc::normalize` drops an empty quote because `> ` cannot be written
    // down. `> [!TIP]` can, so it stays.
    let mut doc = parse("> [!TIP]");
    doc.normalize();
    assert_eq!(serialize(&doc), "> [!TIP]");

    let mut plain = Doc {
        blocks: vec![Block::new(BlockKind::Paragraph(Text::default())).quoted(Quoted::default())],
    };
    plain.normalize();
    assert!(plain.blocks.is_empty());
}

#[test]
fn a_quotes_paragraphs_are_one_alert() {
    let source = "> [!TIP]\n> one\n>\n> two";
    let doc = parse(source);
    let tip = Some(Quoted {
        alert: Some(QuoteKind::Tip),
    });
    assert!(doc.blocks.iter().all(|block| block.quote == tip));
    assert_eq!(serialize(&doc), source);
}

#[test]
fn a_list_inside_a_quote_stays_a_list_and_stays_quoted() {
    let source = "> - one\n> - two\n>     - nested";
    let doc = parse(source);
    let quoted = Some(Quoted::default());
    assert_eq!(
        doc.blocks,
        vec![
            Block::at(BlockKind::Bullet(Text::plain("one")), 0),
            Block::at(BlockKind::Bullet(Text::plain("two")), 0),
            Block::at(BlockKind::Bullet(Text::plain("nested")), 1),
        ]
        .into_iter()
        .map(|block| Block {
            quote: quoted,
            ..block
        })
        .collect::<Vec<_>>()
    );
    assert_eq!(serialize(&doc), source);
}

#[test]
fn every_block_kind_can_be_quoted() {
    for source in [
        "> # Title",
        "> 1. one\n> 2. two",
        "> - [ ] task",
        "> ```rs\n> let x = 1;\n> ```",
        "> | a | b |\n> | --- | --- |\n> | 1 | 2 |",
        "> ---",
        "> [!NOTE]\n> - item\n>\n> text",
    ] {
        let doc = parse(source);
        assert!(
            doc.blocks.iter().all(|block| block.quote.is_some()),
            "{source:?}: {:?}",
            doc.blocks
        );
        assert_eq!(serialize(&doc), source);
    }
}

#[test]
fn a_quote_inside_a_list_item_stays_under_its_marker() {
    let doc = parse("- item\n\n    > quoted");
    assert_eq!(doc.blocks[0].quote, None);
    assert_eq!(doc.blocks[1].indent, 1);
    assert_eq!(doc.blocks[1].quote, Some(Quoted::default()));
    assert_eq!(serialize(&doc), "- item\n\n    > quoted");

    // The marker stays outside a quote that opens its item.
    let doc = parse("- > quoted");
    assert_eq!(
        doc.blocks[0],
        Block::new(BlockKind::Bullet(Text::default()))
    );
    assert_eq!(doc.blocks[1].quote, Some(Quoted::default()));
}

#[test]
fn quotes_round_trip_to_a_fixed_point() {
    for source in [
        "> a\n\nb",
        "> a\n\n> [!NOTE]\n> b",
        "- x\n\n    > - a\n    >     - b\n\n    c",
        "> - a\n\n- b",
        "> > deep\n> outer",
        "- > a\n- b",
        "> [!WARNING]\n> - [x] done\n>\n> 1. one",
    ] {
        let once = parse(source);
        let twice = parse(&serialize(&once));
        assert_eq!(once, twice, "{source:?} drifted: {:?}", serialize(&once));
    }
}