rushdown 0.18.0

A 100% CommonMark-compatible GitHub Flavored Markdown parser and renderer
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
extern crate alloc;

use alloc::rc::Rc;
use core::{cell::RefCell, ops::Range};

#[allow(unused_imports)]
#[cfg(all(not(feature = "std"), feature = "no-std-unix-debug"))]
use crate::println;
use crate::{
    as_kind_data, as_kind_data_mut, as_type_data,
    ast::{Arena, KindData, List, ListItem, NodeRef},
    context::{BoolValue, ContextKey, ContextKeyRegistry},
    matches_kind,
    parser::{is_thematic_break, matches_setext_heading_bar, BlockParser, Context, State},
    text,
    text::Reader,
    util::{indent_position, indent_width, is_blank},
};

const SKIP_LIST_PARSER: &str = "_slp";
const EMPTY_LIST_ITEM_WITH_BLANK_LINES: &str = "_eliwbl";

/// [`BlockParser`] for lists.
#[derive(Debug)]
pub struct ListParser {
    skip_list_parser: ContextKey<BoolValue>,
    empty_list_item_with_blank_lines: ContextKey<BoolValue>,
}

impl ListParser {
    /// Returns a new [`ListParser`].
    pub fn new(reg: Rc<RefCell<ContextKeyRegistry>>) -> Self {
        let skip_list_parser = reg
            .borrow_mut()
            .get_or_create::<BoolValue>(SKIP_LIST_PARSER);
        let empty_list_item_with_blank_lines = reg
            .borrow_mut()
            .get_or_create::<BoolValue>(EMPTY_LIST_ITEM_WITH_BLANK_LINES);
        Self {
            skip_list_parser,
            empty_list_item_with_blank_lines,
        }
    }
}

impl BlockParser for ListParser {
    fn trigger(&self) -> &[u8] {
        b"-+*0123456789"
    }

    fn open(
        &self,
        arena: &mut Arena,
        parent_ref: NodeRef,
        reader: &mut text::BasicReader,
        ctx: &mut Context,
    ) -> Option<(NodeRef, State)> {
        if let Some(last) = ctx.last_opened_block() {
            if matches_kind!(arena[last], List) {
                return None;
            }
        }

        if matches!(ctx.remove(self.skip_list_parser), Some(true)) {
            return None;
        }

        let (line, _) = reader.peek_line_bytes()?;
        let parse_result = parse_list_item(&line)?;
        if let Some(last) = ctx.last_opened_block() {
            if matches_kind!(arena, last, Paragraph) && arena[last].parent() == Some(parent_ref) {
                // we allow only lists starting with 1 to interrupt paragraphs.
                if parse_result.typ == ListItemMarkerType::Ordered
                    && parse_result.start_number != Some(1)
                {
                    return None;
                }
                // an empty list item cannot interrupt a paragraph.
                if parse_result.is_blank_content {
                    return None;
                }
            }
        }
        let node_ref = arena.new_node(List::new(parse_result.marker_char));
        if let Some(start_number) = parse_result.start_number {
            as_kind_data_mut!(arena, node_ref, List).set_start(start_number);
        }
        ctx.insert(self.empty_list_item_with_blank_lines, false);
        Some((node_ref, State::HAS_CHILDREN))
    }

    fn cont(
        &self,
        arena: &mut Arena,
        node_ref: NodeRef,
        reader: &mut text::BasicReader,
        ctx: &mut Context,
    ) -> Option<State> {
        let Some((line, _)) = reader.peek_line_bytes() else {
            return Some(State::HAS_CHILDREN);
        };
        if is_blank(&line) {
            if let Some(last_child_ref) = arena[node_ref].last_child() {
                if !arena[last_child_ref].has_children() {
                    ctx.insert(self.empty_list_item_with_blank_lines, true);
                }
            }
            return Some(State::HAS_CHILDREN);
        }

        // "offset" means a width that bar indicates.
        //    -  aaaaaaaa
        // |----|
        //
        // If the indent is less than the last offset like
        // - a
        //  - b          <--- current line
        // it maybe a new child of the list.
        //
        // Empty list items can have multiple blanklines
        //
        // -             <--- 1st item is an empty thus "offset" is unknown
        //
        //
        //   -           <--- current line
        //
        // -> 1 list with 2 blank items
        //
        // So if the last item is an empty, it maybe a new child of the list.

        let offset = last_offset(arena, node_ref);
        let last_is_empty = arena[node_ref]
            .last_child()
            .is_some_and(|r| !arena[r].has_children());
        let (indent, _) = indent_width(&line, reader.line_offset());

        if indent < offset || last_is_empty {
            if indent < 4 {
                if let Some(parse_result) = parse_list_item(&line) {
                    if parse_result.marker.start.saturating_sub(offset) < 4 {
                        let lst = as_kind_data!(arena, node_ref, List);
                        if !lst.can_continue(parse_result.marker_char, parse_result.is_ordered()) {
                            return None;
                        }
                        // Thematic Breaks take precedence over lists
                        if is_thematic_break(&line[parse_result.marker.start..], 0) {
                            let mut is_heading = false;
                            if let Some(last) = ctx.last_opened_block() {
                                if matches_kind!(arena, last, Paragraph) {
                                    if let Some(c) =
                                        matches_setext_heading_bar(&line[parse_result.marker.end..])
                                    {
                                        is_heading = c == b'-';
                                    }
                                }
                            }
                            if !is_heading {
                                return None;
                            }
                        }
                        return Some(State::HAS_CHILDREN);
                    }
                }
            }
            if !last_is_empty {
                return None;
            }
        }

        if last_is_empty && indent < offset {
            return None;
        }

        // Non empty items can not exist next to an empty list item
        // with blank lines. So we need to close the current list
        //
        // -
        //
        //   foo
        //
        // -> 1 list with 1 blank items and 1 paragraph
        if matches!(ctx.get(self.empty_list_item_with_blank_lines), Some(true)) {
            return None;
        }

        Some(State::HAS_CHILDREN)
    }

    fn close(
        &self,
        arena: &mut Arena,
        node_ref: NodeRef,
        _reader: &mut text::BasicReader,
        _ctx: &mut Context,
    ) {
        let mut c = arena[node_ref].first_child();
        let mut is_tight = true;
        while let Some(child_ref) = c {
            let gc = arena[child_ref].first_child();
            if let Some(grand_child_ref) = gc {
                if gc != arena[child_ref].last_child() {
                    let mut c1 = arena[grand_child_ref].next_sibling();
                    while let Some(child1_ref) = c1 {
                        if as_type_data!(arena, child1_ref, Block).has_blank_previous_line() {
                            is_tight = false;
                            break;
                        }
                        c1 = arena[child1_ref].next_sibling();
                    }
                }
            }
            if c != arena[node_ref].first_child()
                && as_type_data!(arena, child_ref, Block).has_blank_previous_line()
            {
                is_tight = false;
                break;
            }
            c = arena[child_ref].next_sibling();
        }
        as_kind_data_mut!(arena, node_ref, List).set_tight(is_tight);
    }

    fn can_interrupt_paragraph(&self) -> bool {
        true
    }
}

/// [`BlockParser`] for list items.
#[derive(Debug)]
pub struct ListItemParser {
    skip_list_parser: ContextKey<BoolValue>,
    empty_list_item_with_blank_lines: ContextKey<BoolValue>,
}

impl ListItemParser {
    /// Returns a new [`ListItemParser`].
    pub fn new(reg: Rc<RefCell<ContextKeyRegistry>>) -> Self {
        let skip_list_parser = reg
            .borrow_mut()
            .get_or_create::<BoolValue>(SKIP_LIST_PARSER);
        let empty_list_item_with_blank_lines = reg
            .borrow_mut()
            .get_or_create::<BoolValue>(EMPTY_LIST_ITEM_WITH_BLANK_LINES);
        Self {
            skip_list_parser,
            empty_list_item_with_blank_lines,
        }
    }
}

impl BlockParser for ListItemParser {
    fn trigger(&self) -> &[u8] {
        b"-+*0123456789"
    }

    fn open(
        &self,
        arena: &mut Arena,
        parent_ref: NodeRef,
        reader: &mut text::BasicReader,
        ctx: &mut Context,
    ) -> Option<(NodeRef, State)> {
        // In some cases, it can be parsed as a list item, but invalid as a list.
        // e.g.
        //
        // - empty list items can not interrupt paragraphs(can not start new lists)
        if !matches_kind!(arena[parent_ref], List) {
            return None;
        }

        let offset = last_offset(arena, parent_ref);
        let (line, _) = reader.peek_line_bytes()?;
        let parse_result = parse_list_item(&line)?;
        if parse_result.marker.start.saturating_sub(offset) > 3 {
            return None;
        }
        ctx.insert(self.empty_list_item_with_blank_lines, false);
        let item_offset = parse_result.offset;
        let node_ref = arena.new_node(ListItem::with_offset(parse_result.marker.end + item_offset));
        if parse_result.is_blank_content {
            return Some((node_ref, State::NO_CHILDREN));
        }
        let content = parse_result.content?;
        let (pos, padding) = indent_position(&line[content.start..], content.start, item_offset)?;
        let child = parse_result.marker.end + pos;
        reader.advance_and_set_padding(child, padding);
        Some((node_ref, State::HAS_CHILDREN))
    }

    fn cont(
        &self,
        arena: &mut Arena,
        node_ref: NodeRef,
        reader: &mut text::BasicReader,
        ctx: &mut Context,
    ) -> Option<State> {
        let Some((line, _)) = reader.peek_line_bytes() else {
            return Some(State::HAS_CHILDREN);
        };

        if is_blank(&line) {
            reader.advance_to_eol();
            return Some(State::HAS_CHILDREN);
        }
        let offset = last_offset(arena, arena[node_ref].parent().unwrap());
        let empty_item_with_blank_lines =
            matches!(ctx.get(self.empty_list_item_with_blank_lines), Some(true));
        let is_empty = !arena[node_ref].has_children() && empty_item_with_blank_lines;
        let (indent, _) = indent_width(&line, reader.line_offset());
        if (is_empty || indent < offset) && indent < 4 {
            // new list item found
            if parse_list_item(&line).is_some() {
                ctx.insert(self.skip_list_parser, true);
                return None;
            }
            if !is_empty {
                return None;
            }
        }
        let (pos, padding) = indent_position(&line, reader.line_offset(), offset)?;
        reader.advance_and_set_padding(pos, padding);

        Some(State::HAS_CHILDREN)
    }

    fn can_interrupt_paragraph(&self) -> bool {
        true
    }
}

#[derive(Debug, PartialEq, Eq)]
enum ListItemMarkerType {
    Unordered,
    Ordered,
}

struct ListItemParseResult {
    typ: ListItemMarkerType,
    marker: Range<usize>,
    marker_char: u8,
    content: Option<Range<usize>>,
    is_blank_content: bool,
    offset: usize,
    start_number: Option<u32>,
}

impl ListItemParseResult {
    fn is_ordered(&self) -> bool {
        self.typ == ListItemMarkerType::Ordered
    }
}

fn last_offset(arena: &Arena, node_ref: NodeRef) -> usize {
    if let Some(last_child_ref) = arena[node_ref].last_child() {
        if let KindData::ListItem(item) = arena[last_child_ref].kind_data() {
            return item.offset();
        }
    }
    0
}

fn parse_list_item(line: &[u8]) -> Option<ListItemParseResult> {
    let mut i = 0;
    while i < line.len() {
        let c = line[i];
        if c == b' ' {
            i += 1;
            continue;
        }
        if c == b'\t' {
            return None;
        }
        break;
    }
    if i > 3 {
        return None;
    }

    let marker_start = i;
    let marker_end: usize;
    let typ: ListItemMarkerType;
    if i < line.len() && line[i] == b'-' || line[i] == b'*' || line[i] == b'+' {
        i += 1;
        marker_end = i;
        typ = ListItemMarkerType::Unordered;
    } else if i < line.len() {
        while i < line.len() && line[i].is_ascii_digit() {
            i += 1;
        }
        if i == marker_start || i - marker_start > 9 {
            return None;
        }
        if i < line.len() && (line[i] == b'.' || line[i] == b')') {
            i += 1;
            marker_end = i;
            typ = ListItemMarkerType::Ordered;
        } else {
            return None;
        }
    } else {
        return None;
    }
    if i < line.len() && line[i] != b'\n' {
        let (w, _) = indent_width(&line[i..], 0);
        if w == 0 {
            return None;
        }
    }
    let start_number = if typ == ListItemMarkerType::Ordered {
        let num_str = str::from_utf8(&line[marker_start..marker_end - 1]).ok()?;
        Some(num_str.parse::<u32>().ok()?)
    } else {
        None
    };
    if i >= line.len() {
        return Some(ListItemParseResult {
            typ,
            marker: marker_start..marker_end,
            marker_char: line[marker_end - 1],
            content: None,
            is_blank_content: true,
            offset: 1,
            start_number,
        });
    }
    let content_start = i;
    let mut content_end = line.len();
    if line[content_end - 1] == b'\n' && line[i] != b'\n' {
        content_end -= 1;
    }
    let is_blank_content = is_blank(&line[content_start..content_end]);
    Some(ListItemParseResult {
        typ,
        marker: marker_start..marker_end,
        marker_char: line[marker_end - 1],
        content: Some(content_start..content_end),
        is_blank_content,
        offset: if is_blank_content {
            1
        } else {
            let (offset, _) = indent_width(&line[content_start..content_end], content_start);
            if offset > 4 {
                // offseted codeblock
                1
            } else {
                offset
            }
        },
        start_number,
    })
}