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
//! The pulldown-cmark event machine that builds a `Doc`.
use super::*;
/// A list item's marker, held until the item's first paragraph arrives.
#[derive(Clone, Copy)]
pub(super) enum Marker {
Bullet,
Ordered(u64),
Task(bool),
}
impl Marker {
pub(super) fn into_kind(self, text: Text) -> BlockKind {
match self {
Self::Bullet => BlockKind::Bullet(text),
Self::Ordered(number) => BlockKind::Ordered { number, text },
Self::Task(checked) => BlockKind::Task { checked, text },
}
}
}
#[derive(Default)]
pub(super) struct TableBuild {
align: Vec<Align>,
header: Vec<Text>,
rows: Vec<Vec<Text>>,
row: Vec<Text>,
in_head: bool,
}
/// An open blockquote, and how many blocks had been pushed when it opened.
pub(super) struct OpenQuote {
kind: Option<QuoteKind>,
at: usize,
}
#[derive(Default)]
pub(super) struct ParseState {
pub(super) doc: Doc,
builder: TextBuilder,
/// One entry per open list; `Some` counts an ordered list's next number.
lists: Vec<Option<u64>>,
/// One entry per open blockquote, innermost last.
quotes: Vec<OpenQuote>,
/// The marker, and the quote its item opened in.
pending_marker: Option<(Marker, Option<Quoted>)>,
heading: Option<u8>,
code: Option<(Option<String>, Option<u32>, String)>,
table: Option<TableBuild>,
/// The event being handled. What a block that owns no inline run — an
/// empty marker, a rule — is placed from.
at: Range<usize>,
/// Where the run being accumulated started: the first event since the last
/// block was pushed. A paragraph is pushed by whatever *follows* it, so
/// the event in hand at that point is the next block's, not this one's.
span: Option<usize>,
/// Where each block started, in the order they were pushed.
pub(super) starts: Vec<usize>,
/// Every block pushed, absorbed ones included.
pushed: usize,
}
impl ParseState {
/// Indent level for a block that is not a list marker.
///
/// Only list nesting counts. A blockquote sets a block's
/// [`Block::quote`], not how deep it sits.
pub(super) fn indent(&self) -> u8 {
self.lists.len() as u8
}
/// The quote a block opened now sits in. Nested blockquotes are one quote,
/// with the innermost one's alert.
pub(super) fn quoted(&self) -> Option<Quoted> {
self.quotes.last().map(|open| Quoted { alert: open.kind })
}
/// Append a block in the open quote — see [`Self::push_in`].
pub(super) fn push(&mut self, kind: BlockKind, indent: u8) {
let quote = self.quoted();
self.push_in(kind, indent, quote);
}
/// Append a block, clamping its indent so the document invariant holds
/// (first block at 0, never more than one deeper than its predecessor).
pub(super) fn push_in(&mut self, kind: BlockKind, indent: u8, quote: Option<Quoted>) {
let start = self.span.take().unwrap_or(self.at.start);
self.pushed += 1;
// An alert with no body holds one empty paragraph, which only stands
// while nothing follows it in the same quote. The block that does takes
// its place and its start.
let bodyless = self.doc.blocks.last().is_some_and(|last| {
quote.is_some()
&& last.quote == quote
&& indent >= last.indent
&& matches!(&last.kind, BlockKind::Paragraph(text) if text.is_empty())
});
if bodyless {
self.doc.blocks.pop();
} else {
self.starts.push(start);
}
let max = self.doc.blocks.last().map_or(0, |b| b.indent + 1);
self.doc.blocks.push(Block {
kind,
indent: indent.min(max),
quote,
});
}
/// Emit a pending marker as an empty block so a non-paragraph leaf (a code
/// block, a table) nests *under* its bullet instead of replacing it.
pub(super) fn flush_marker(&mut self) {
let Some((marker, quote)) = self.pending_marker.take() else {
return;
};
let indent = self.indent().saturating_sub(1);
self.push_in(marker.into_kind(Text::default()), indent, quote);
}
/// Close any inline content still open as a block.
///
/// A *tight* list item carries no `Paragraph` tags — pulldown-cmark emits
/// its text directly between `Item` tags — so every block boundary has to
/// close the run itself rather than waiting for an end tag that never
/// comes. Table cells are exempt: their builder is per-cell, and closing it
/// here would push a block out of the middle of a table.
pub(super) fn flush_inline(&mut self) {
if self.table.is_none() && !self.builder.is_empty() {
self.finish_paragraph();
}
}
/// Close the current run of inline content as a block.
pub(super) fn finish_paragraph(&mut self) {
let text = self.builder.take();
// A paragraph that is nothing but one image is an image block — the
// ``-on-its-own-line shape. Anything else keeps the image
// inline, where it stays an image rather than decaying to a link.
if let [
MarkSpan {
range,
mark: Mark::Image(url),
},
] = text.marks.as_slice()
&& range.start == 0
&& range.end == text.text.len()
{
let (caption, width) = split_width(&text.text);
let (url, alt) = (url.clone(), Text::plain(caption.to_string()));
self.flush_marker();
let indent = self.indent();
self.push(BlockKind::Image { url, alt, width }, indent);
return;
}
// A paragraph that is nothing but a mention is a bookmark — the same
// `<https://x>` that paints as a chip inside a sentence, given a line
// of its own. A bare URL is what someone types when they mean a link
// and `[Title](url)` is what a sentence spells, so carding either would
// leave no way to write a link that stays one — and it is the paste
// menu's `Dismiss` that has to write that down.
//
// A chip stays a paragraph, so text can go either side of it.
//
// The text has to *be* the URL. `[Example Site](url "chip")` alone on a
// line keeps its title and stays a paragraph, because promoting it
// would drop words someone wrote — a block shows only what the preview
// gave it.
if let [
MarkSpan {
range,
mark: Mark::Mention { url, form },
},
] = text.marks.as_slice()
&& range.start == 0
&& range.end == text.text.len()
&& *form != Form::Chip
&& text.text == *url
&& is_link(url)
{
let (url, form) = (url.clone(), *form);
self.flush_marker();
let indent = self.indent();
self.push(BlockKind::Bookmark { url, form }, indent);
return;
}
// A quote opened inside the item holds the text, and the marker stays
// outside it as an empty block of its own.
if let Some((marker, quote)) = self.pending_marker
&& quote == self.quoted()
{
self.pending_marker = None;
let indent = self.indent().saturating_sub(1);
self.push_in(marker.into_kind(text), indent, quote);
} else {
self.flush_marker();
let indent = self.indent();
self.push(BlockKind::Paragraph(text), indent);
}
}
pub(super) fn event(&mut self, event: Event<'_>, range: Range<usize>) {
// An `End` carries the range of the whole element it closes, which for
// a list or a quote opens well before the block that just went in.
// Only something that starts content can start a run.
if !matches!(event, Event::End(_)) {
self.span.get_or_insert(range.start);
}
self.at = range;
match event {
Event::Start(tag) => self.start(tag),
Event::End(tag) => self.end(tag),
Event::Text(t) => match &mut self.code {
Some((_, _, code)) => code.push_str(&t),
None => self.builder.text.push_str(&t),
},
Event::Code(t) => self.builder.wrap(Mark::Code, &t),
// Raw HTML is content, not structure: this model has no HTML node,
// so it survives as the literal text the author typed.
Event::Html(t) | Event::InlineHtml(t) => self.builder.text.push_str(&t),
// Soft and hard breaks are both just a line break in a block —
// the distinction has no meaning in this model, or in Notion.
Event::SoftBreak | Event::HardBreak => match &mut self.code {
Some((_, _, code)) => code.push('\n'),
None => self.builder.text.push('\n'),
},
Event::Rule => {
self.flush_inline();
self.flush_marker();
let indent = self.indent();
self.push(BlockKind::Rule, indent);
}
Event::TaskListMarker(checked) => {
if let Some((marker, _)) = &mut self.pending_marker {
*marker = Marker::Task(checked);
}
}
Event::FootnoteReference(label) => {
self.builder.text.push_str(&format!("[^{label}]"));
}
_ => {}
}
}
pub(super) fn start(&mut self, tag: Tag<'_>) {
match tag {
Tag::Heading { level, .. } => {
self.flush_inline();
self.heading = Some(level as u8);
}
Tag::BlockQuote(kind) => {
self.flush_inline();
let at = self.pushed;
self.quotes.push(OpenQuote {
kind: kind.map(QuoteKind::from),
at,
});
}
Tag::CodeBlock(kind) => {
self.flush_inline();
self.flush_marker();
let (language, height) = match kind {
CodeBlockKind::Fenced(info) => {
let (tag, height) = super::split_size(info.trim());
let tag = tag.split_whitespace().next().unwrap_or("");
((!tag.is_empty()).then(|| tag.to_string()), height)
}
CodeBlockKind::Indented => (None, None),
};
self.code = Some((language, height, String::new()));
}
Tag::List(start) => {
self.flush_inline();
// An item whose content is only a nested list still has to emit
// its own marker first. `flush_inline` covers the item that had
// text; this covers the empty one, whose pending marker the
// nested `Start(Item)` would otherwise overwrite — losing a
// level of nesting. It runs before the push so the marker is
// numbered at the outer list's depth.
self.flush_marker();
self.lists.push(start);
}
Tag::Item => {
self.flush_inline();
let marker = match self.lists.last_mut() {
Some(Some(number)) => {
let n = *number;
*number += 1;
Marker::Ordered(n)
}
_ => Marker::Bullet,
};
self.pending_marker = Some((marker, self.quoted()));
}
Tag::Table(aligns) => {
self.flush_inline();
self.flush_marker();
self.table = Some(TableBuild {
align: aligns.iter().map(align_of).collect(),
..TableBuild::default()
});
}
Tag::TableHead => {
if let Some(table) = &mut self.table {
table.in_head = true;
}
}
Tag::Emphasis => {
self.builder.open(Mark::Italic);
}
Tag::Strong => {
self.builder.open(Mark::Bold);
}
Tag::Strikethrough => {
self.builder.open(Mark::Strike);
}
// A rich link is its own mark rather than a flag on a link: where
// the spelling came from is what decides the painting, and a flag
// beside the mark is a second place for that to be recorded.
Tag::Link {
link_type,
dest_url,
title,
..
} => {
let url = dest_url.into_string();
let form = match link_type {
LinkType::Autolink => Some(Form::Auto),
_ => Form::from_title(&title),
};
self.builder.open(match form {
Some(form) => Mark::Mention { url, form },
None => Mark::Link(url),
});
}
Tag::Image { dest_url, .. } => {
self.builder.open(Mark::Image(dest_url.into_string()));
}
_ => {}
}
}
pub(super) fn end(&mut self, tag: TagEnd) {
match tag {
TagEnd::Paragraph | TagEnd::HtmlBlock => self.flush_inline(),
TagEnd::Heading(_) => {
self.flush_marker();
let level = self.heading.take().unwrap_or(1);
let mut text = self.builder.take();
collapse_to_one_line(&mut text);
let indent = self.indent();
self.push(BlockKind::Heading { level, text }, indent);
}
// Flushed before the quote closes, so trailing text still lands
// inside it rather than as a paragraph after it.
TagEnd::BlockQuote(_) => {
self.flush_inline();
// pulldown-cmark takes the marker line out of the text, so a
// blockquote that held nothing else arrives here empty.
if let Some(open) = self.quotes.last()
&& open.kind.is_some()
&& self.pushed == open.at
{
let indent = self.indent();
self.push(BlockKind::Paragraph(Text::default()), indent);
}
self.quotes.pop();
}
TagEnd::CodeBlock => {
if let Some((language, height, code)) = self.code.take() {
let indent = self.indent();
// The fence swallows the final newline; storing it would
// grow the block by one blank line on every round trip.
let code = code.strip_suffix('\n').map_or(code.clone(), str::to_string);
self.push(
BlockKind::Code {
language,
code: Text::plain(code),
height,
},
indent,
);
}
}
TagEnd::List(_) => {
self.flush_inline();
self.lists.pop();
}
// A tight item's text arrives with no `Paragraph` tag to close it,
// so the item's end is what turns it into the marker block. Only an
// item that produced nothing at all falls through to an empty one.
TagEnd::Item => {
self.flush_inline();
self.flush_marker();
}
TagEnd::Table => {
if let Some(table) = self.table.take() {
let indent = self.indent();
self.push(
BlockKind::Table {
align: table.align,
header: table.header,
rows: table.rows,
},
indent,
);
}
}
TagEnd::TableHead => {
if let Some(table) = &mut self.table {
table.header = std::mem::take(&mut table.row);
table.in_head = false;
}
}
TagEnd::TableRow => {
if let Some(table) = &mut self.table {
let row = std::mem::take(&mut table.row);
table.rows.push(row);
}
}
TagEnd::TableCell => {
let mut cell = self.builder.take();
collapse_to_one_line(&mut cell);
if let Some(table) = &mut self.table {
table.row.push(cell);
}
}
TagEnd::Emphasis | TagEnd::Strong | TagEnd::Strikethrough | TagEnd::Link => {
self.builder.close();
}
TagEnd::Image => self.builder.close(),
_ => {}
}
}
}
pub(super) fn align_of(alignment: &Alignment) -> Align {
match alignment {
Alignment::Center => Align::Center,
Alignment::Right => Align::Right,
Alignment::Left | Alignment::None => Align::Left,
}
}