Debian Codegraph @

src/parser/mod.rs

raw
1 #[cfg(feature = "attributes")]
2 mod attributes;
3 mod autolink;
4 mod inlines;
5 pub mod options;
6 #[cfg(feature = "phoenix_heex")]
7 pub mod phoenix_heex;
8 #[cfg(feature = "shortcodes")]
9 pub mod shortcodes;
10 mod table;
11
12 use std::borrow::Cow;
13 use std::cmp::{Ordering, min};
14 use std::collections::{HashMap, VecDeque};
15 use std::fmt::Debug;
16 use std::mem;
17 use std::str;
18
19 use crate::Arena;
20 use crate::ctype::{isdigit, isspace};
21 use crate::entity;
22 use crate::node_matches;
23 use crate::nodes::{
24 self, AlertType, Ast, ListDelimType, ListType, Node, NodeAlert, NodeBlockDirective,
25 NodeCodeBlock, NodeDescriptionItem, NodeFootnoteDefinition, NodeHeading, NodeHtmlBlock,
26 NodeList, NodeMultilineBlockQuote, NodeTaskItem, NodeValue, Sourcepos,
27 };
28 use crate::parser::inlines::RefMap;
29 pub use crate::parser::options::Options;
30 use crate::scanners;
31 use crate::strings::{self, Case, split_off_front_matter};
32
33 const TAB_STOP: usize = 4;
34 const CODE_INDENT: usize = 4;
35
36 // Very deeply nested lists can cause quadratic performance issues.
37 // This constant is used in open_new_blocks() to limit the nesting
38 // depth. It is unlikely that a non-contrived markdown document will
39 // be nested this deeply.
40 const MAX_LIST_DEPTH: usize = 100;
41
42 /// Parse a Markdown document to an AST.
43 ///
44 /// See the documentation of the crate root for an example.
45 pub fn parse_document<'a>(arena: &'a Arena<'a>, md: &str, options: &Options) -> Node<'a> {
46 let root = arena.alloc(
47 Ast {
48 value: NodeValue::Document,
49 content: String::new(),
50 sourcepos: (1, 1, 1, 1).into(),
51 #[cfg(feature = "attributes")]
52 attrs: None,
53 open: true,
54 last_line_blank: false,
55 table_visited: false,
56 line_offsets: Vec::new(),
57 }
58 .into(),
59 );
60 let document = Parser::new(arena, root, options).parse(md);
61 if options.parse.sourcepos_chars {
62 convert_sourcepos_columns_to_chars(document, md);
63 }
64 document
65 }
66
67 /// Convert all byte-based column values in the AST's sourcepos to char-based.
68 fn convert_sourcepos_columns_to_chars(document: Node<'_>, md: &str) {
69 let lines: Vec<&str> = md.lines().collect();
70
71 let convert = |lc: &mut nodes::LineColumn| {
72 if lc.column == 0 {
73 return;
74 }
75 if let Some(line) = lines.get(lc.line.wrapping_sub(1)) {
76 lc.column = byte_col_to_char_col(line, lc.column);
77 }
78 };
79
80 for node in document.descendants() {
81 let mut ast = node.data_mut();
82 convert(&mut ast.sourcepos.start);
83 convert(&mut ast.sourcepos.end);
84 }
85 }
86
87 /// Convert a 1-based byte column index to a 1-based char column index for the given line.
88 fn byte_col_to_char_col(line: &str, byte_col: usize) -> usize {
89 // If the byte column points past the end of the line (e.g. position
90 // after the final byte, such as softbreak/newline positions),
91 // map it to the position after the last Unicode character.
92 if byte_col > line.len() {
93 return line.chars().count() + 1;
94 }
95
96 // Count all chars whose start byte offset is <= byte_idx.
97 // Since `char_indices()` yields (byte_offset_of_char_start, char),
98 // `take_while` includes exactly the chars that start at or before `byte_idx`.
99 let byte_idx = byte_col - 1;
100 line.char_indices()
101 .take_while(|&(i, _)| i <= byte_idx)
102 .count()
103 }
104
105 /// Return whether the byte at the given offset passes the callback.
106 ///
107 /// Returns `false` if the offset is out of bounds.
108 fn byte_matches<F>(bytes: &[u8], offset: usize, predicate: F) -> bool
109 where
110 F: Fn(u8) -> bool,
111 {
112 bytes.get(offset).is_some_and(|&b| predicate(b))
113 }
114
115 pub struct Parser<'a, 'o, 'c> {
116 arena: &'a Arena<'a>,
117 options: &'o Options<'c>,
118 refmap: RefMap,
119 footnote_defs: inlines::FootnoteDefs<'a>,
120 root: Node<'a>,
121 current: Node<'a>,
122 line_number: usize,
123 offset: usize,
124 column: usize,
125 thematic_break_kill_pos: usize,
126 first_nonspace: usize,
127 first_nonspace_column: usize,
128 indent: usize,
129 blank: bool,
130 partially_consumed_tab: bool,
131 curline_len: usize,
132 curline_end_col: usize,
133 last_line_length: usize,
134 total_size: usize,
135 #[cfg(feature = "phoenix_heex")]
136 heex_block_depth: usize,
137 }
138
139 /// A reference link's resolved details.
140 #[derive(Clone, Debug)]
141 pub struct ResolvedReference {
142 /// The destination URL of the reference link.
143 pub url: String,
144
145 /// The text of the link.
146 pub title: String,
147 }
148
149 struct FootnoteDefinition<'a> {
150 ix: Option<u32>,
151 node: Node<'a>,
152 name: String,
153 total_references: u32,
154 }
155
156 impl<'a, 'o, 'c> Parser<'a, 'o, 'c>
157 where
158 'c: 'o,
159 {
160 fn new(arena: &'a Arena<'a>, root: Node<'a>, options: &'o Options<'c>) -> Self {
161 Parser {
162 arena,
163 options,
164 refmap: RefMap::new(),
165 footnote_defs: inlines::FootnoteDefs::new(),
166 root,
167 current: root,
168 line_number: 0,
169 offset: 0,
170 column: 0,
171 thematic_break_kill_pos: 0,
172 first_nonspace: 0,
173 first_nonspace_column: 0,
174 indent: 0,
175 blank: false,
176 partially_consumed_tab: false,
177 curline_len: 0,
178 curline_end_col: 0,
179 last_line_length: 0,
180 total_size: 0,
181 #[cfg(feature = "phoenix_heex")]
182 heex_block_depth: 0,
183 }
184 }
185
186 fn parse(mut self, mut s: &str) -> Node<'a> {
187 if let Some(delimiter) = &self.options.extension.front_matter_delimiter {
188 if let Some((front_matter, rest)) = split_off_front_matter(s, delimiter) {
189 self.handle_front_matter(front_matter, delimiter);
190 s = rest;
191 }
192 }
193
194 let s = s;
195 let sb = s.as_bytes();
196
197 let end = s.len();
198 self.total_size = end;
199
200 let mut ix = 0;
201 let matcher = jetscii::bytes!(b'\r', b'\n');
202
203 while ix < end {
204 let mut eol = match matcher.find(&sb[ix..]) {
205 Some(offset) => ix + offset,
206 None => end,
207 };
208 if eol < end {
209 if sb[eol] == b'\r' {
210 eol += 1;
211 if eol < end && sb[eol] == b'\n' {
212 eol += 1;
213 }
214 } else if sb[eol] == b'\n' {
215 eol += 1;
216 }
217 }
218
219 self.process_line(&s[ix..eol]);
220
221 ix = eol;
222 }
223
224 self.finalize_document();
225 self.postprocess_text_nodes(self.root);
226 self.root
227 }
228
229 fn handle_front_matter(&mut self, front_matter: &str, delimiter: &str) {
230 let lines = front_matter
231 .as_bytes()
232 .iter()
233 .filter(|b| **b == b'\n')
234 .count();
235
236 let stripped_front_matter = strings::remove_trailing_blank_lines_slice(front_matter);
237 let stripped_lines = stripped_front_matter
238 .as_bytes()
239 .iter()
240 .filter(|b| **b == b'\n')
241 .count();
242
243 let node = self.add_child(
244 self.root,
245 NodeValue::FrontMatter(front_matter.to_string()),
246 1,
247 );
248 self.finalize(node).unwrap();
249
250 node.data_mut().sourcepos = Sourcepos {
251 start: nodes::LineColumn { line: 1, column: 1 },
252 end: nodes::LineColumn {
253 line: 1 + stripped_lines,
254 column: delimiter.len(),
255 },
256 };
257 self.line_number += lines;
258 }
259
260 fn process_line(&mut self, line: &str) {
261 let bytes = line.as_bytes();
262
263 self.curline_len = line.len();
264 self.curline_end_col = line.len();
265 if self.curline_end_col > 0 && bytes[self.curline_end_col - 1] == b'\n' {
266 self.curline_end_col -= 1;
267 }
268 if self.curline_end_col > 0 && bytes[self.curline_end_col - 1] == b'\r' {
269 self.curline_end_col -= 1;
270 }
271
272 self.offset = 0;
273 self.column = 0;
274 self.first_nonspace = 0;
275 self.first_nonspace_column = 0;
276 self.indent = 0;
277 self.thematic_break_kill_pos = 0;
278 self.blank = false;
279 self.partially_consumed_tab = false;
280
281 if self.line_number == 0 && line.len() >= 3 && line.starts_with('\u{feff}') {
282 self.offset += 3;
283 }
284
285 self.line_number += 1;
286
287 if let Some((last_matched_container, all_matched)) = self.check_open_blocks(line) {
288 let mut container = last_matched_container;
289 let current = self.current;
290 self.open_new_blocks(&mut container, line, all_matched);
291
292 if current.same_node(self.current) {
293 self.add_text_to_container(container, last_matched_container, line);
294 }
295 }
296
297 self.last_line_length = self.curline_end_col;
298
299 self.curline_len = 0;
300 self.curline_end_col = 0;
301 }
302
303 ///////////////////////
304 // Check open blocks //
305 ///////////////////////
306
307 fn check_open_blocks(&mut self, line: &str) -> Option<(Node<'a>, bool)> {
308 let (all_matched, mut container) = self.check_open_blocks_inner(self.root, line)?;
309
310 if !all_matched {
311 container = container.parent().unwrap();
312 }
313
314 Some((container, all_matched))
315 }
316
317 fn check_open_blocks_inner(
318 &mut self,
319 mut container: Node<'a>,
320 line: &str,
321 ) -> Option<(bool, Node<'a>)> {
322 let mut all_matched = false;
323
324 loop {
325 if !container.last_child_is_open() {
326 all_matched = true;
327 break;
328 }
329 container = container.last_child().unwrap();
330 let ast = &mut container.data_mut();
331
332 self.find_first_nonspace(line);
333
334 match ast.value {
335 NodeValue::BlockQuote => {
336 if !self.parse_block_quote_prefix(line) {
337 break;
338 }
339 }
340 NodeValue::Item(ref nl) => {
341 if !self.parse_node_item_prefix(line, container, nl) {
342 break;
343 }
344 }
345 NodeValue::DescriptionItem(ref di) => {
346 if !self.parse_description_item_prefix(line, container, di) {
347 break;
348 }
349 }
350 NodeValue::CodeBlock(..) => {
351 if !self.parse_code_block_prefix(line, container, ast)? {
352 break;
353 }
354 }
355 NodeValue::HtmlBlock(ref nhb) => {
356 if !self.parse_html_block_prefix(nhb.block_type) {
357 break;
358 }
359 }
360 NodeValue::Paragraph => {
361 if self.blank {
362 break;
363 }
364 }
365 NodeValue::Table(..) => {
366 if !table::matches(&line[self.first_nonspace..], self.options.extension.spoiler)
367 {
368 break;
369 }
370 }
371 NodeValue::Heading(..)
372 | NodeValue::TableRow(..)
373 | NodeValue::TableCell
374 | NodeValue::Subtext => {
375 break;
376 }
377 NodeValue::FootnoteDefinition(..) => {
378 if !self.parse_footnote_definition_block_prefix(line) {
379 break;
380 }
381 }
382 NodeValue::MultilineBlockQuote(..) => {
383 self.parse_multiline_block_quote_prefix(line, container, ast)?;
384 }
385 NodeValue::Alert(ref alert) => {
386 if alert.multiline {
387 self.parse_multiline_block_quote_prefix(line, container, ast)?;
388 } else if !self.parse_block_quote_prefix(line) {
389 break;
390 }
391 }
392 NodeValue::BlockDirective(..) => {
393 self.parse_block_directive_prefix(line, container, ast)?;
394 }
395 _ => {}
396 }
397 }
398
399 Some((all_matched, container))
400 }
401
402 fn find_first_nonspace(&mut self, line: &str) {
403 let mut chars_to_tab = TAB_STOP - (self.column % TAB_STOP);
404 let bytes = line.as_bytes();
405
406 if self.first_nonspace <= self.offset {
407 self.first_nonspace = self.offset;
408 self.first_nonspace_column = self.column;
409
410 loop {
411 match bytes.get(self.first_nonspace) {
412 Some(b' ') => {
413 self.first_nonspace += 1;
414 self.first_nonspace_column += 1;
415 chars_to_tab -= 1;
416 if chars_to_tab == 0 {
417 chars_to_tab = TAB_STOP;
418 }
419 }
420 Some(b'\t') => {
421 self.first_nonspace += 1;
422 self.first_nonspace_column += chars_to_tab;
423 chars_to_tab = TAB_STOP;
424 }
425 _ => break,
426 }
427 }
428 }
429
430 self.indent = self.first_nonspace_column - self.column;
431 self.blank = bytes
432 .get(self.first_nonspace)
433 .is_none_or(|&b| strings::is_line_end_char(b));
434 }
435
436 fn parse_block_quote_prefix(&mut self, line: &str) -> bool {
437 let bytes = line.as_bytes();
438 let indent = self.indent;
439
440 // When already inside a blockquote, always treat `>` as a blockquote marker,
441 // even if it's a lone `>` (which represents a blank line in the blockquote).
442 // This allows multi-paragraph blockquotes without requiring a space after `>`.
443 if indent <= 3 && bytes.get(self.first_nonspace) == Some(&b'>') {
444 self.advance_offset(line, indent + 1, true);
445
446 if byte_matches(bytes, self.offset, strings::is_space_or_tab) {
447 self.advance_offset(line, 1, true);
448 }
449
450 return true;
451 }
452
453 false
454 }
455
456 fn is_greentext(&self, line: &str) -> bool {
457 if !self.options.extension.greentext {
458 return false;
459 }
460
461 !byte_matches(
462 line.as_bytes(),
463 self.first_nonspace + 1,
464 strings::is_space_or_tab,
465 )
466 }
467
468 fn parse_node_item_prefix(&mut self, line: &str, container: Node<'a>, nl: &NodeList) -> bool {
469 if self.indent >= nl.marker_offset + nl.padding {
470 self.advance_offset(line, nl.marker_offset + nl.padding, true);
471 true
472 } else if self.blank && container.first_child().is_some() {
473 let offset = self.first_nonspace - self.offset;
474 self.advance_offset(line, offset, false);
475 true
476 } else {
477 false
478 }
479 }
480
481 fn parse_description_item_prefix(
482 &mut self,
483 line: &str,
484 container: Node<'a>,
485 di: &NodeDescriptionItem,
486 ) -> bool {
487 if self.indent >= di.marker_offset + di.padding {
488 self.advance_offset(line, di.marker_offset + di.padding, true);
489 true
490 } else if self.blank && container.first_child().is_some() {
491 let offset = self.first_nonspace - self.offset;
492 self.advance_offset(line, offset, false);
493 true
494 } else {
495 false
496 }
497 }
498
499 fn parse_code_block_prefix(
500 &mut self,
501 line: &str,
502 container: Node<'a>,
503 ast: &mut Ast,
504 ) -> Option<bool> {
505 let (fenced, fence_char, fence_length, fence_offset) = match ast.value {
506 NodeValue::CodeBlock(ref ncb) => (
507 ncb.fenced,
508 ncb.fence_char,
509 ncb.fence_length,
510 ncb.fence_offset,
511 ),
512 _ => unreachable!(),
513 };
514
515 if !fenced {
516 if self.indent >= CODE_INDENT {
517 self.advance_offset(line, CODE_INDENT, true);
518 return Some(true);
519 } else if self.blank {
520 let offset = self.first_nonspace - self.offset;
521 self.advance_offset(line, offset, false);
522 return Some(true);
523 }
524 return Some(false);
525 }
526
527 let bytes = line.as_bytes();
528 let matched = if self.indent <= 3 && bytes.get(self.first_nonspace) == Some(&fence_char) {
529 scanners::close_code_fence(&line[self.first_nonspace..]).unwrap_or(0)
530 } else {
531 0
532 };
533
534 if matched >= fence_length {
535 let NodeValue::CodeBlock(ref mut ncb) = ast.value else {
536 unreachable!();
537 };
538 ncb.closed = true;
539 self.advance_offset(line, matched, false);
540 self.current = self.finalize_borrowed(container, ast).unwrap();
541 return None;
542 }
543
544 let mut i = fence_offset;
545 while i > 0 && byte_matches(bytes, self.offset, strings::is_space_or_tab) {
546 self.advance_offset(line, 1, true);
547 i -= 1;
548 }
549 Some(true)
550 }
551
552 fn parse_html_block_prefix(&self, t: u8) -> bool {
553 match t {
554 1..=5 => true,
555 6 | 7 => !self.blank,
556 _ => unreachable!(),
557 }
558 }
559
560 fn parse_footnote_definition_block_prefix(&mut self, line: &str) -> bool {
561 if self.indent >= 4 {
562 self.advance_offset(line, 4, true);
563 true
564 } else {
565 line == "\n" || line == "\r\n"
566 }
567 }
568
569 fn parse_multiline_block_quote_prefix(
570 &mut self,
571 line: &str,
572 container: Node<'a>,
573 ast: &mut Ast,
574 ) -> Option<()> {
575 // XXX: refactoring revealed that, unlike parse_code_block_prefix, this
576 // function never fails to match without signalling 'should_continue'
577 // (which is a `Some(false)` in that function). Is that odd?
578
579 let (fence_length, fence_offset) = match ast.value {
580 NodeValue::MultilineBlockQuote(ref node_value) => {
581 (node_value.fence_length, node_value.fence_offset)
582 }
583 NodeValue::Alert(ref node_value) => (node_value.fence_length, node_value.fence_offset),
584 _ => unreachable!(),
585 };
586
587 let bytes = line.as_bytes();
588 let matched = if self.indent <= 3 && bytes.get(self.first_nonspace) == Some(&b'>') {
589 scanners::close_multiline_block_quote_fence(&line[self.first_nonspace..]).unwrap_or(0)
590 } else {
591 0
592 };
593
594 if matched >= fence_length {
595 self.advance_offset(line, matched, false);
596
597 // The last child, like an indented codeblock, could be left open.
598 // Make sure it's finalized.
599 if container.last_child_is_open() {
600 let mut child = container.last_child().unwrap();
601 // Descend to the deepest-last open child before finalizing it.
602 // Stop descending when encountering a `List` node because
603 // list structure must be finalized at the item level. This
604 // ensures nested open children (e.g. indented code blocks)
605 // are closed first while avoiding descending into lists.
606 while child.last_child_is_open() && !node_matches!(child, NodeValue::List(..)) {
607 child = child.last_child().unwrap();
608 }
609 let child_ast = &mut child.data_mut();
610
611 self.finalize_borrowed(child, child_ast).unwrap();
612 }
613
614 self.fix_zero_end_columns(container);
615
616 self.current = self.finalize_borrowed(container, ast).unwrap();
617 return None;
618 }
619
620 let mut i = fence_offset;
621 while i > 0 && byte_matches(bytes, self.offset, strings::is_space_or_tab) {
622 self.advance_offset(line, 1, true);
623 i -= 1;
624 }
625 Some(())
626 }
627
628 fn parse_block_directive_prefix(
629 &mut self,
630 line: &str,
631 container: Node<'a>,
632 ast: &mut Ast,
633 ) -> Option<()> {
634 let (fence_length, fence_offset) = match ast.value {
635 NodeValue::BlockDirective(ref nbd) => (nbd.fence_length, nbd.fence_offset),
636 _ => unreachable!(),
637 };
638
639 let bytes = line.as_bytes();
640 let matched = if self.indent <= 3 && bytes.get(self.first_nonspace) == Some(&b':') {
641 scanners::close_block_directive_fence(&line[self.first_nonspace..]).unwrap_or(0)
642 } else {
643 0
644 };
645
646 if matched >= fence_length {
647 self.advance_offset(line, matched, false);
648
649 // The last child, like an indented codeblock, could be left open.
650 // Make sure it's finalized.
651 if container.last_child_is_open() {
652 let mut child = container.last_child().unwrap();
653 // Descend to the deepest-last open child before finalizing it.
654 // Stop descending when encountering a `List` node because
655 // list structure must be finalized at the item level. This
656 // ensures nested open children (e.g. indented code blocks)
657 // are closed first while avoiding descending into lists.
658 while child.last_child_is_open() && !node_matches!(child, NodeValue::List(..)) {
659 child = child.last_child().unwrap();
660 }
661 let child_ast = &mut child.data_mut();
662
663 self.finalize_borrowed(child, child_ast).unwrap();
664 }
665
666 self.fix_zero_end_columns(container);
667
668 self.current = self.finalize_borrowed(container, ast).unwrap();
669 return None;
670 }
671
672 let mut i = fence_offset;
673 while i > 0 && byte_matches(bytes, self.offset, strings::is_space_or_tab) {
674 self.advance_offset(line, 1, true);
675 i -= 1;
676 }
677 Some(())
678 }
679
680 // Walk the subtree rooted at each child of `container` in post-order
681 // and, where a node's end column is zero, attempt to adopt a
682 // non-zero end column from its deepest-last descendant; otherwise
683 // fall back to the node's start position.
684 // Returns a candidate end position for `container` if found.
685 fn fix_zero_end_columns(&mut self, container: Node<'a>) -> Option<nodes::LineColumn> {
686 // explicit stack for post-order traversal: (node, visited)
687 let mut stack: Vec<(Node<'a>, bool)> = Vec::new();
688
689 for ch in container.children() {
690 stack.push((ch, false));
691
692 while let Some((node, visited)) = stack.pop() {
693 if !visited {
694 stack.push((node, true));
695 for c in node.children() {
696 stack.push((c, false));
697 }
698 } else {
699 let end_col = node.data().sourcepos.end.column;
700 if end_col == 0 {
701 if let Some(mut last_desc) = node.last_child() {
702 while let Some(ld) = last_desc.last_child() {
703 last_desc = ld;
704 }
705 let pos = last_desc.data().sourcepos.end;
706 if pos.column != 0 {
707 node.data_mut().sourcepos.end = pos;
708 continue;
709 }
710 }
711 // fallback to start position (better than column 0)
712 let mut ast = node.data_mut();
713 ast.sourcepos.end = ast.sourcepos.start;
714 }
715 }
716 }
717 }
718
719 // Compute a candidate end position for the container by looking at
720 // its last child. Return it only if it has a non-zero column; the
721 // caller can fall back to the container's start position if desired.
722 //
723 // We originally looked at the deepest-last descendant, but there
724 // may be intermediate containers that are larger than it, which we
725 // should use instead. If looking just at the last child isn't
726 // enough in some circumstances, we should consider using the widest
727 // of the last descendants.
728 if let Some(last_desc) = container.last_child() {
729 let last_end = last_desc.data().sourcepos.end;
730 if last_end.column != 0 {
731 return Some(last_end);
732 }
733 }
734 None
735 }
736
737 /////////////////////
738 // Open new blocks //
739 /////////////////////
740
741 fn open_new_blocks(&mut self, container: &mut Node<'a>, line: &str, all_matched: bool) {
742 let mut maybe_lazy = node_matches!(self.current, NodeValue::Paragraph);
743 let mut depth = 0;
744
745 while !node_matches!(
746 container,
747 NodeValue::CodeBlock(..) | NodeValue::HtmlBlock(..)
748 ) && !{
749 #[cfg(feature = "phoenix_heex")]
750 {
751 node_matches!(container, NodeValue::HeexBlock(..))
752 }
753 #[cfg(not(feature = "phoenix_heex"))]
754 {
755 false
756 }
757 } {
758 depth += 1;
759 self.find_first_nonspace(line);
760 let indented = self.indent >= CODE_INDENT;
761
762 if !((!indented
763 && (self.handle_block_directive(container, line)
764 || self.handle_alert(container, line)
765 || self.handle_multiline_blockquote(container, line)
766 || self.handle_blockquote(container, line)
767 || self.handle_atx_heading(container, line)
768 || self.handle_atx_subtext(container, line)
769 || self.handle_code_fence(container, line)
770 || self.handle_heex_directive_block(container, line)
771 || self.handle_heex_expression_block(container, line)
772 || self.handle_heex_block(container, line)
773 || self.handle_html_block(container, line)
774 || self.handle_setext_heading(container, line)
775 || self.handle_thematic_break(container, line, all_matched)
776 || self.handle_footnote(container, line, depth)
777 || self.handle_description_list(container, line)))
778 || self.handle_list(container, line, indented, depth)
779 || self.handle_code_block(container, line, indented, maybe_lazy)
780 || self.handle_table(container, line, indented))
781 {
782 break;
783 }
784
785 if container.data().value.accepts_lines() {
786 break;
787 }
788
789 maybe_lazy = false;
790 }
791 }
792
793 fn handle_block_directive(&mut self, container: &mut Node<'a>, line: &str) -> bool {
794 let Some(matched) = self.detect_block_directive(line) else {
795 return false;
796 };
797
798 let first_nonspace = self.first_nonspace;
799 let offset = self.offset;
800
801 let info_start = first_nonspace + matched;
802 let mut info_end = info_start;
803 while info_end < line.len() && !strings::is_line_end_char(line.as_bytes()[info_end]) {
804 info_end += 1;
805 }
806
807 let mut info = entity::unescape_html(&line[info_start..info_end]);
808 strings::trim_cow(&mut info);
809 let mut info = info.into_owned();
810 strings::unescape(&mut info);
811
812 let nbd = NodeBlockDirective {
813 fence_length: matched,
814 fence_offset: first_nonspace - offset,
815 info,
816 };
817
818 *container = self.add_child(
819 container,
820 NodeValue::BlockDirective(Box::new(nbd)),
821 self.first_nonspace + 1,
822 );
823
824 let line_to_consume = line.len() - offset;
825 self.advance_offset(line, line_to_consume, false);
826
827 true
828 }
829
830 fn detect_block_directive(&self, line: &str) -> Option<usize> {
831 if self.options.extension.block_directive {
832 scanners::open_block_directive_fence(&line[self.first_nonspace..])
833 } else {
834 None
835 }
836 }
837
838 fn handle_alert(&mut self, container: &mut Node<'a>, line: &str) -> bool {
839 let Some(alert_type) = self.detect_alert(line) else {
840 return false;
841 };
842
843 let alert_startpos = self.first_nonspace;
844 let mut title_startpos = self.first_nonspace;
845 let mut fence_length = 0;
846
847 let bytes = line.as_bytes();
848 // The checks made here co-operate with the alert_start scanner for soundness.
849 while bytes[title_startpos] != b']' {
850 if bytes[title_startpos] == b'>' {
851 fence_length += 1
852 }
853 title_startpos += 1;
854 }
855 title_startpos += 1;
856
857 if fence_length == 2
858 || (fence_length >= 3 && !self.options.extension.multiline_block_quotes)
859 {
860 return false;
861 }
862
863 // anything remaining on this line is considered an alert title
864 let mut title = entity::unescape_html(&line[title_startpos..]);
865 strings::trim_cow(&mut title);
866 let mut title = title.into_owned();
867 strings::unescape(&mut title);
868
869 let na = NodeAlert {
870 alert_type,
871 multiline: fence_length >= 3,
872 fence_length,
873 fence_offset: self.first_nonspace - self.offset,
874 title: if title.is_empty() { None } else { Some(title) },
875 };
876
877 let offset = self.curline_len - self.offset - strings::newlines_of(line);
878 self.advance_offset(line, offset, false);
879
880 *container = self.add_child(
881 container,
882 NodeValue::Alert(Box::new(na)),
883 alert_startpos + 1,
884 );
885
886 true
887 }
888
889 fn detect_alert(&self, line: &str) -> Option<AlertType> {
890 if self.options.extension.alerts && line.as_bytes().get(self.first_nonspace) == Some(&b'>')
891 {
892 scanners::alert_start(&line[self.first_nonspace..])
893 } else {
894 None
895 }
896 }
897
898 fn handle_multiline_blockquote(&mut self, container: &mut Node<'a>, line: &str) -> bool {
899 let Some(matched) = self.detect_multiline_blockquote(line) else {
900 return false;
901 };
902
903 let first_nonspace = self.first_nonspace;
904 let offset = self.offset;
905 let nmbc = NodeMultilineBlockQuote {
906 fence_length: matched,
907 fence_offset: first_nonspace - offset,
908 };
909
910 *container = self.add_child(
911 container,
912 NodeValue::MultilineBlockQuote(nmbc),
913 self.first_nonspace + 1,
914 );
915
916 self.advance_offset(line, first_nonspace + matched - offset, false);
917
918 true
919 }
920
921 fn detect_multiline_blockquote(&self, line: &str) -> Option<usize> {
922 if self.options.extension.multiline_block_quotes {
923 scanners::open_multiline_block_quote_fence(&line[self.first_nonspace..])
924 } else {
925 None
926 }
927 }
928
929 fn handle_blockquote(&mut self, container: &mut Node<'a>, line: &str) -> bool {
930 if !self.detect_blockquote(line) {
931 return false;
932 }
933
934 let blockquote_startpos = self.first_nonspace;
935
936 let offset = self.first_nonspace + 1 - self.offset;
937 self.advance_offset(line, offset, false);
938 if byte_matches(line.as_bytes(), self.offset, strings::is_space_or_tab) {
939 self.advance_offset(line, 1, true);
940 }
941 *container = self.add_child(container, NodeValue::BlockQuote, blockquote_startpos + 1);
942
943 true
944 }
945
946 fn detect_blockquote(&self, line: &str) -> bool {
947 line.as_bytes().get(self.first_nonspace) == Some(&b'>') && !self.is_greentext(line)
948 }
949
950 fn handle_atx_heading(&mut self, container: &mut Node<'a>, line: &str) -> bool {
951 let Some(matched) = self.detect_atx_heading(line) else {
952 return false;
953 };
954
955 let heading_startpos = self.first_nonspace;
956 let offset = self.offset;
957 self.advance_offset(line, heading_startpos + matched - offset, false);
958 *container = self.add_child(
959 container,
960 NodeValue::Heading(NodeHeading::default()),
961 heading_startpos + 1,
962 );
963
964 let bytes = line.as_bytes();
965 let mut hashpos = bytes[self.first_nonspace..]
966 .iter()
967 .position(|&c| c == b'#')
968 .unwrap()
969 + self.first_nonspace;
970 let mut level = 0;
971 while hashpos < bytes.len() && bytes[hashpos] == b'#' {
972 level += 1;
973 hashpos += 1;
974 }
975
976 let container_ast = &mut container.data_mut();
977 container_ast.value = NodeValue::Heading(NodeHeading {
978 level,
979 setext: false,
980 closed: false,
981 });
982
983 true
984 }
985
986 fn detect_atx_heading(&self, line: &str) -> Option<usize> {
987 scanners::atx_heading_start(&line[self.first_nonspace..])
988 }
989
990 fn handle_atx_subtext(&mut self, container: &mut Node<'a>, line: &str) -> bool {
991 let Some(matched) = self.detect_atx_subtext(line) else {
992 return false;
993 };
994
995 let heading_startpos = self.first_nonspace;
996 let offset = self.offset;
997 self.advance_offset(line, heading_startpos + matched - offset, false);
998 *container = self.add_child(container, NodeValue::Subtext, heading_startpos + 1);
999
1000 let container_ast = &mut container.data_mut();
1001 container_ast.value = NodeValue::Subtext;
1002
1003 true
1004 }
1005
1006 fn detect_atx_subtext(&self, line: &str) -> Option<usize> {
1007 if self.options.extension.subtext {
1008 scanners::atx_subtext_start(&line[self.first_nonspace..])
1009 } else {
1010 None
1011 }
1012 }
1013
1014 fn handle_code_fence(&mut self, container: &mut Node<'a>, line: &str) -> bool {
1015 let Some(matched) = self.detect_code_fence(line) else {
1016 return false;
1017 };
1018
1019 let first_nonspace = self.first_nonspace;
1020 let offset = self.offset;
1021 let ncb = NodeCodeBlock {
1022 fenced: true,
1023 fence_char: line.as_bytes()[first_nonspace],
1024 fence_length: matched,
1025 fence_offset: first_nonspace - offset,
1026 info: String::new(),
1027 literal: String::new(),
1028 closed: false,
1029 };
1030 *container = self.add_child(
1031 container,
1032 NodeValue::CodeBlock(Box::new(ncb)),
1033 self.first_nonspace + 1,
1034 );
1035 self.advance_offset(line, first_nonspace + matched - offset, false);
1036
1037 true
1038 }
1039
1040 fn detect_code_fence(&self, line: &str) -> Option<usize> {
1041 scanners::open_code_fence(&line[self.first_nonspace..])
1042 }
1043
1044 fn handle_html_block(&mut self, container: &mut Node<'a>, line: &str) -> bool {
1045 let Some(matched) = self.detect_html_block(container, line) else {
1046 return false;
1047 };
1048
1049 let nhb = NodeHtmlBlock {
1050 block_type: matched as u8,
1051 literal: String::new(),
1052 };
1053
1054 *container = self.add_child(
1055 container,
1056 NodeValue::HtmlBlock(nhb),
1057 self.first_nonspace + 1,
1058 );
1059
1060 true
1061 }
1062
1063 fn detect_html_block(&self, container: Node<'a>, line: &str) -> Option<usize> {
1064 scanners::html_block_start(&line[self.first_nonspace..]).or_else(|| {
1065 if !node_matches!(container, NodeValue::Paragraph) {
1066 scanners::html_block_start_7(&line[self.first_nonspace..])
1067 } else {
1068 None
1069 }
1070 })
1071 }
1072
1073 #[cfg(feature = "phoenix_heex")]
1074 fn handle_heex_block(&mut self, container: &mut Node<'a>, line: &str) -> bool {
1075 let Some(tag_name_len) = self.detect_heex_block(line) else {
1076 return false;
1077 };
1078
1079 let tag_name =
1080 line[self.first_nonspace + 1..=self.first_nonspace + tag_name_len].to_string();
1081
1082 let nhb = phoenix_heex::NodeHeexBlock {
1083 literal: String::new(),
1084 node: phoenix_heex::HeexNode::Tag(tag_name),
1085 };
1086
1087 self.heex_block_depth = 0;
1088
1089 *container = self.add_child(
1090 container,
1091 NodeValue::HeexBlock(Box::new(nhb)),
1092 self.first_nonspace + 1,
1093 );
1094
1095 true
1096 }
1097
1098 #[cfg(not(feature = "phoenix_heex"))]
1099 fn handle_heex_block(&mut self, _container: &mut Node<'a>, _line: &str) -> bool {
1100 false
1101 }
1102
1103 #[cfg(feature = "phoenix_heex")]
1104 fn detect_heex_block(&self, line: &str) -> Option<usize> {
1105 if !self.options.extension.phoenix_heex {
1106 return None;
1107 }
1108
1109 let tag_name_len = scanners::phoenix_opening_tag(&line[self.first_nonspace..])?;
1110 let tag_name = &line[self.first_nonspace + 1..=self.first_nonspace + tag_name_len];
1111
1112 if let Some(end_pos) =
1113 scanners::phoenix_closing_tag_end(&line[self.first_nonspace..], tag_name)
1114 {
1115 let after_closing = &line[self.first_nonspace + end_pos..];
1116 if !after_closing.trim().is_empty() {
1117 return None;
1118 }
1119 }
1120
1121 if let Some(end_pos) = scanners::phoenix_self_closing_tag_end(&line[self.first_nonspace..])
1122 {
1123 let after_closing = &line[self.first_nonspace + end_pos..];
1124 if !after_closing.trim().is_empty() {
1125 return None;
1126 }
1127 }
1128
1129 Some(tag_name_len)
1130 }
1131
1132 #[cfg(feature = "phoenix_heex")]
1133 fn is_heex_opening_self_closing_tag(&self, line: &str, expected_tag_name: &str) -> bool {
1134 let Some(tag_name_len) = scanners::phoenix_opening_tag(&line[self.first_nonspace..]) else {
1135 return false;
1136 };
1137
1138 let line_tag_name = &line[self.first_nonspace + 1..=self.first_nonspace + tag_name_len];
1139
1140 if line_tag_name != expected_tag_name {
1141 return false;
1142 }
1143
1144 let bytes = &line.as_bytes()[self.first_nonspace..];
1145 let mut end = bytes.len();
1146 while end > 0 && strings::is_line_end_char(bytes[end - 1]) {
1147 end -= 1;
1148 }
1149
1150 end >= 2 && bytes[end - 2] == b'/' && bytes[end - 1] == b'>'
1151 }
1152
1153 #[cfg(feature = "phoenix_heex")]
1154 fn is_heex_opening_same_name_tag(&self, line: &str, tag_name: &str) -> bool {
1155 if let Some(opening_len) = scanners::phoenix_opening_tag(&line[self.first_nonspace..]) {
1156 let opening_name = &line[self.first_nonspace + 1..=self.first_nonspace + opening_len];
1157 opening_name == tag_name && !self.is_heex_opening_self_closing_tag(line, tag_name)
1158 } else {
1159 false
1160 }
1161 }
1162
1163 #[cfg(feature = "phoenix_heex")]
1164 fn heex_tag_matches_end(&mut self, line: &str, tag_name: &str) -> bool {
1165 if self.is_heex_opening_same_name_tag(line, tag_name) {
1166 self.heex_block_depth += 1;
1167 }
1168
1169 let matched = if let Some(closing_tag_name_len) =
1170 scanners::phoenix_block_closing_tag(&line[self.first_nonspace..])
1171 {
1172 let closing_tag_name =
1173 &line[self.first_nonspace + 2..self.first_nonspace + 2 + closing_tag_name_len];
1174 if closing_tag_name == tag_name {
1175 self.heex_block_depth = self.heex_block_depth.saturating_sub(1);
1176 true
1177 } else {
1178 false
1179 }
1180 } else if self.is_heex_opening_self_closing_tag(line, tag_name) {
1181 true
1182 } else if scanners::phoenix_closing_tag_end(&line[self.first_nonspace..], tag_name)
1183 .is_some()
1184 {
1185 self.heex_block_depth = self.heex_block_depth.saturating_sub(1);
1186 true
1187 } else {
1188 false
1189 };
1190
1191 matched && self.heex_block_depth == 0
1192 }
1193
1194 #[cfg(feature = "phoenix_heex")]
1195 fn handle_heex_directive_block(&mut self, container: &mut Node<'a>, line: &str) -> bool {
1196 if !self.detect_heex_directive_block(container, line) {
1197 return false;
1198 }
1199
1200 let bytes = &line.as_bytes()[self.first_nonspace..];
1201 let node = if bytes.len() >= 4 && bytes[2] == b'!' && bytes[3] == b'-' {
1202 phoenix_heex::HeexNode::MultilineComment
1203 } else if bytes.len() >= 3 && bytes[2] == b'#' {
1204 phoenix_heex::HeexNode::Comment
1205 } else {
1206 phoenix_heex::HeexNode::Directive
1207 };
1208
1209 let nhb = phoenix_heex::NodeHeexBlock {
1210 literal: String::new(),
1211 node,
1212 };
1213
1214 *container = self.add_child(
1215 container,
1216 NodeValue::HeexBlock(Box::new(nhb)),
1217 self.first_nonspace + 1,
1218 );
1219
1220 true
1221 }
1222
1223 #[cfg(not(feature = "phoenix_heex"))]
1224 fn handle_heex_directive_block(&mut self, _container: &mut Node<'a>, _line: &str) -> bool {
1225 false
1226 }
1227
1228 #[cfg(feature = "phoenix_heex")]
1229 fn detect_heex_directive_block(&self, container: Node<'a>, line: &str) -> bool {
1230 if !self.options.extension.phoenix_heex {
1231 return false;
1232 }
1233
1234 if node_matches!(container, NodeValue::HeexBlock(..)) {
1235 return false;
1236 }
1237
1238 if self.first_nonspace > 0 {
1239 let before = &line.as_bytes()[..self.first_nonspace];
1240 if before
1241 .iter()
1242 .any(|&b| !strings::is_space_or_tab(b) && !strings::is_line_end_char(b))
1243 {
1244 return false;
1245 }
1246 }
1247
1248 if scanners::phoenix_block_directive_start(&line[self.first_nonspace..]).is_none() {
1249 return false;
1250 }
1251
1252 if node_matches!(container, NodeValue::Paragraph) {
1253 !scanners::phoenix_block_directive_end(&line[self.first_nonspace..])
1254 } else {
1255 true
1256 }
1257 }
1258
1259 #[cfg(feature = "phoenix_heex")]
1260 fn handle_heex_expression_block(&mut self, container: &mut Node<'a>, line: &str) -> bool {
1261 if !self.detect_heex_expression_block(container, line) {
1262 return false;
1263 }
1264
1265 let nhb = phoenix_heex::NodeHeexBlock {
1266 literal: String::new(),
1267 node: phoenix_heex::HeexNode::Expression,
1268 };
1269
1270 *container = self.add_child(
1271 container,
1272 NodeValue::HeexBlock(Box::new(nhb)),
1273 self.first_nonspace + 1,
1274 );
1275
1276 true
1277 }
1278
1279 #[cfg(not(feature = "phoenix_heex"))]
1280 fn handle_heex_expression_block(&mut self, _container: &mut Node<'a>, _line: &str) -> bool {
1281 false
1282 }
1283
1284 #[cfg(feature = "phoenix_heex")]
1285 fn has_unclosed_heex_directive(&self, node: Node<'a>) -> bool {
1286 let content = &node.data().content;
1287
1288 if !content.as_bytes().contains(&b'<') {
1289 return false;
1290 }
1291
1292 let bytes = content.as_bytes();
1293 let len = bytes.len();
1294
1295 let mut i = 0;
1296 let mut in_directive = false;
1297 let mut in_comment = false;
1298
1299 while i < len {
1300 if i + 1 < len && bytes[i] == b'<' && bytes[i + 1] == b'%' {
1301 in_directive = true;
1302 if (i + 2 < len && bytes[i + 2] == b'#')
1303 || (i + 3 < len && bytes[i + 2] == b'!' && bytes[i + 3] == b'-')
1304 {
1305 in_comment = true;
1306 }
1307 i += 2;
1308 } else if in_directive && i + 1 < len && bytes[i] == b'%' && bytes[i + 1] == b'>' {
1309 in_directive = false;
1310 in_comment = false;
1311 i += 2;
1312 } else if in_directive
1313 && in_comment
1314 && i + 3 < len
1315 && bytes[i] == b'-'
1316 && bytes[i + 1] == b'-'
1317 && bytes[i + 2] == b'%'
1318 && bytes[i + 3] == b'>'
1319 {
1320 in_directive = false;
1321 in_comment = false;
1322 i += 4;
1323 } else {
1324 i += 1;
1325 }
1326 }
1327
1328 in_directive
1329 }
1330
1331 #[cfg(feature = "phoenix_heex")]
1332 fn detect_heex_expression_block(&self, container: Node<'a>, line: &str) -> bool {
1333 if !self.options.extension.phoenix_heex {
1334 return false;
1335 }
1336
1337 if node_matches!(container, NodeValue::HeexBlock(..)) {
1338 return false;
1339 }
1340
1341 if self.first_nonspace > 0 {
1342 let before = &line.as_bytes()[..self.first_nonspace];
1343 if before
1344 .iter()
1345 .any(|&b| !strings::is_space_or_tab(b) && !strings::is_line_end_char(b))
1346 {
1347 return false;
1348 }
1349 }
1350
1351 if scanners::phoenix_block_expression_start(&line[self.first_nonspace..]).is_none() {
1352 return false;
1353 }
1354
1355 if node_matches!(container, NodeValue::Paragraph) {
1356 !scanners::phoenix_block_expression_end(&line[self.first_nonspace..])
1357 } else {
1358 true
1359 }
1360 }
1361
1362 fn handle_setext_heading(&mut self, container: &mut Node<'a>, line: &str) -> bool {
1363 let Some(sc) = self.detect_setext_heading(container, line) else {
1364 return false;
1365 };
1366
1367 let has_content = {
1368 let mut ast = container.data_mut();
1369 self.resolve_reference_link_definitions(&mut ast.content)
1370 };
1371 if has_content {
1372 container.data_mut().value = NodeValue::Heading(NodeHeading {
1373 level: match sc {
1374 scanners::SetextChar::Equals => 1,
1375 scanners::SetextChar::Hyphen => 2,
1376 },
1377 setext: true,
1378 closed: false,
1379 });
1380 let adv = line.len() - strings::newlines_of(line) - self.offset;
1381 self.advance_offset(line, adv, false);
1382 }
1383
1384 true
1385 }
1386
1387 fn detect_setext_heading(
1388 &self,
1389 container: Node<'a>,
1390 line: &str,
1391 ) -> Option<scanners::SetextChar> {
1392 if node_matches!(container, NodeValue::Paragraph) && !self.options.parse.ignore_setext {
1393 scanners::setext_heading_line(&line[self.first_nonspace..])
1394 } else {
1395 None
1396 }
1397 }
1398
1399 fn handle_thematic_break(
1400 &mut self,
1401 container: &mut Node<'a>,
1402 line: &str,
1403 all_matched: bool,
1404 ) -> bool {
1405 let Some(_matched) = self.detect_thematic_break(container, line, all_matched) else {
1406 return false;
1407 };
1408
1409 *container = self.add_child(container, NodeValue::ThematicBreak, self.first_nonspace + 1);
1410
1411 let adv = line.len() - strings::newlines_of(line) - self.offset;
1412 container.data_mut().sourcepos.end = (self.line_number, adv).into();
1413 self.advance_offset(line, adv, false);
1414
1415 true
1416 }
1417
1418 fn detect_thematic_break(
1419 &mut self,
1420 container: Node<'a>,
1421 line: &str,
1422 all_matched: bool,
1423 ) -> Option<usize> {
1424 if !matches!(
1425 (&container.data().value, all_matched),
1426 (&NodeValue::Paragraph, false)
1427 ) && self.thematic_break_kill_pos <= self.first_nonspace
1428 {
1429 let (offset, found) = self.scan_thematic_break_inner(line);
1430 if !found {
1431 self.thematic_break_kill_pos = offset;
1432 None
1433 } else {
1434 Some(offset)
1435 }
1436 } else {
1437 None
1438 }
1439 }
1440
1441 fn scan_thematic_break_inner(&self, line: &str) -> (usize, bool) {
1442 let mut i = self.first_nonspace;
1443
1444 if i >= line.len() {
1445 return (i, false);
1446 }
1447
1448 let bytes = line.as_bytes();
1449 let b = bytes[i];
1450 if b != b'*' && b != b'_' && b != b'-' {
1451 return (i, false);
1452 }
1453
1454 let mut count = 1;
1455 let mut nextb;
1456 loop {
1457 i += 1;
1458 if i >= line.len() {
1459 nextb = 255;
1460 break;
1461 }
1462 nextb = bytes[i];
1463
1464 if nextb == b {
1465 count += 1;
1466 } else if nextb != b' ' && nextb != b'\t' {
1467 break;
1468 }
1469 }
1470
1471 if count >= 3 && (nextb == 255 || nextb == b'\r' || nextb == b'\n') {
1472 ((i - self.first_nonspace) + 1, true)
1473 } else {
1474 (i, false)
1475 }
1476 }
1477
1478 fn handle_footnote(&mut self, container: &mut Node<'a>, line: &str, depth: usize) -> bool {
1479 let Some(matched) = self.detect_footnote(line, depth) else {
1480 return false;
1481 };
1482
1483 let mut c = &line[self.first_nonspace + 2..self.first_nonspace + matched];
1484 c = c.split(']').next().unwrap();
1485 let offset = self.first_nonspace + matched - self.offset;
1486 self.advance_offset(line, offset, false);
1487 *container = self.add_child(
1488 container,
1489 NodeValue::FootnoteDefinition(NodeFootnoteDefinition {
1490 name: c.to_string(),
1491 total_references: 0,
1492 }),
1493 self.first_nonspace + 1,
1494 );
1495
1496 true
1497 }
1498
1499 fn detect_footnote(&self, line: &str, depth: usize) -> Option<usize> {
1500 if self.options.extension.footnotes && depth < MAX_LIST_DEPTH {
1501 scanners::footnote_definition(&line[self.first_nonspace..])
1502 } else {
1503 None
1504 }
1505 }
1506
1507 fn handle_description_list(&mut self, container: &mut Node<'a>, line: &str) -> bool {
1508 let Some(matched) = self.detect_description_list(container, line) else {
1509 return false;
1510 };
1511
1512 let offset = self.first_nonspace + matched - self.offset;
1513 self.advance_offset(line, offset, false);
1514 if byte_matches(line.as_bytes(), self.offset, strings::is_space_or_tab) {
1515 self.advance_offset(line, 1, true);
1516 }
1517
1518 true
1519 }
1520
1521 fn detect_description_list(&mut self, container: &mut Node<'a>, line: &str) -> Option<usize> {
1522 if self.options.extension.description_lists {
1523 if let Some(matched) = scanners::description_item_start(&line[self.first_nonspace..]) {
1524 if self.parse_desc_list_details(container, matched) {
1525 return Some(matched);
1526 }
1527 }
1528 }
1529 None
1530 }
1531
1532 fn parse_desc_list_details(&mut self, container: &mut Node<'a>, matched: usize) -> bool {
1533 let mut tight = false;
1534 let last_child = match container.last_child() {
1535 Some(lc) => lc,
1536 None => {
1537 // Happens when the detail line is directly after the term,
1538 // without a blank line between.
1539 if !node_matches!(container, NodeValue::Paragraph) {
1540 // If the container is not a paragraph, then this can't
1541 // be a description list item.
1542 return false;
1543 }
1544
1545 let Some(parent) = container.parent() else {
1546 return false;
1547 };
1548
1549 tight = true;
1550 *container = parent;
1551 container.last_child().unwrap()
1552 }
1553 };
1554
1555 if node_matches!(last_child, NodeValue::Paragraph) {
1556 // We have found the details after the paragraph for the term.
1557 //
1558 // This paragraph is moved as a child of a new DescriptionTerm node.
1559 //
1560 // If the node before the paragraph is a description list, the item
1561 // is added to it. If not, create a new list.
1562
1563 last_child.detach();
1564 let last_child_sourcepos = last_child.data().sourcepos;
1565
1566 let list = match container.last_child() {
1567 Some(lc) if node_matches!(lc, NodeValue::DescriptionList) => {
1568 reopen_ast_nodes(lc);
1569 lc
1570 }
1571 _ => {
1572 let list = self.add_child(
1573 container,
1574 NodeValue::DescriptionList,
1575 self.first_nonspace + 1,
1576 );
1577 list.data_mut().sourcepos.start = last_child_sourcepos.start;
1578 list
1579 }
1580 };
1581
1582 let metadata = NodeDescriptionItem {
1583 marker_offset: self.indent,
1584 padding: matched,
1585 tight,
1586 };
1587
1588 let item = self.add_child(
1589 list,
1590 NodeValue::DescriptionItem(metadata),
1591 self.first_nonspace + 1,
1592 );
1593 item.data_mut().sourcepos.start = last_child_sourcepos.start;
1594 let term = self.add_child(item, NodeValue::DescriptionTerm, self.first_nonspace + 1);
1595 let details =
1596 self.add_child(item, NodeValue::DescriptionDetails, self.first_nonspace + 1);
1597
1598 term.data_mut().sourcepos.start = last_child_sourcepos.start;
1599
1600 term.append(last_child);
1601
1602 *container = details;
1603
1604 true
1605 } else if node_matches!(last_child, NodeValue::DescriptionItem(..)) {
1606 let parent = last_child.parent().unwrap();
1607 let tight = match last_child.data().value {
1608 NodeValue::DescriptionItem(ref ndi) => ndi.tight,
1609 _ => false,
1610 };
1611
1612 let metadata = NodeDescriptionItem {
1613 marker_offset: self.indent,
1614 padding: matched,
1615 tight,
1616 };
1617
1618 let item = self.add_child(
1619 parent,
1620 NodeValue::DescriptionItem(metadata),
1621 self.first_nonspace + 1,
1622 );
1623
1624 let details =
1625 self.add_child(item, NodeValue::DescriptionDetails, self.first_nonspace + 1);
1626
1627 *container = details;
1628
1629 true
1630 } else {
1631 false
1632 }
1633 }
1634
1635 fn handle_list(
1636 &mut self,
1637 container: &mut Node<'a>,
1638 line: &str,
1639 indented: bool,
1640 depth: usize,
1641 ) -> bool {
1642 let Some((matched, mut nl)) = self.detect_list(container, line, indented, depth) else {
1643 return false;
1644 };
1645
1646 let offset = self.first_nonspace + matched - self.offset;
1647 self.advance_offset(line, offset, false);
1648 let (save_partially_consumed_tab, save_offset, save_column) =
1649 (self.partially_consumed_tab, self.offset, self.column);
1650
1651 let bytes = line.as_bytes();
1652 while self.column - save_column <= 5
1653 && byte_matches(bytes, self.offset, strings::is_space_or_tab)
1654 {
1655 self.advance_offset(line, 1, true);
1656 }
1657
1658 let i = self.column - save_column;
1659 if !(1..5).contains(&i) || byte_matches(bytes, self.offset, strings::is_line_end_char) {
1660 nl.padding = matched + 1;
1661 self.offset = save_offset;
1662 self.column = save_column;
1663 self.partially_consumed_tab = save_partially_consumed_tab;
1664 if i > 0 {
1665 self.advance_offset(line, 1, true);
1666 }
1667 } else {
1668 nl.padding = matched + i;
1669 }
1670
1671 nl.marker_offset = self.indent;
1672
1673 if match container.data().value {
1674 NodeValue::List(ref mnl) => !lists_match(&nl, mnl),
1675 _ => true,
1676 } {
1677 *container = self.add_child(container, NodeValue::List(nl), self.first_nonspace + 1);
1678 }
1679
1680 *container = self.add_child(container, NodeValue::Item(nl), self.first_nonspace + 1);
1681
1682 true
1683 }
1684
1685 fn detect_list(
1686 &self,
1687 container: Node<'a>,
1688 line: &str,
1689 indented: bool,
1690 depth: usize,
1691 ) -> Option<(usize, NodeList)> {
1692 if (!indented || node_matches!(container, NodeValue::List(..)))
1693 && self.indent < 4
1694 && depth < MAX_LIST_DEPTH
1695 {
1696 parse_list_marker(
1697 line,
1698 self.first_nonspace,
1699 node_matches!(container, NodeValue::Paragraph),
1700 )
1701 } else {
1702 None
1703 }
1704 }
1705
1706 fn handle_code_block(
1707 &mut self,
1708 container: &mut Node<'a>,
1709 line: &str,
1710 indented: bool,
1711 maybe_lazy: bool,
1712 ) -> bool {
1713 if !self.detect_code_block(indented, maybe_lazy) {
1714 return false;
1715 }
1716
1717 self.advance_offset(line, CODE_INDENT, true);
1718 let ncb = NodeCodeBlock {
1719 fenced: false,
1720 fence_char: 0,
1721 fence_length: 0,
1722 fence_offset: 0,
1723 info: String::new(),
1724 literal: String::new(),
1725 closed: true,
1726 };
1727 *container = self.add_child(
1728 container,
1729 NodeValue::CodeBlock(Box::new(ncb)),
1730 self.offset + 1,
1731 );
1732
1733 true
1734 }
1735
1736 fn detect_code_block(&self, indented: bool, maybe_lazy: bool) -> bool {
1737 indented && !maybe_lazy && !self.blank
1738 }
1739
1740 fn handle_table(&mut self, container: &mut Node<'a>, line: &str, indented: bool) -> bool {
1741 let Some((new_container, replace, mark_visited)) =
1742 self.detect_table(container, line, indented)
1743 else {
1744 return false;
1745 };
1746
1747 if replace {
1748 container.insert_after(new_container);
1749 container.detach();
1750 *container = new_container;
1751 } else {
1752 *container = new_container;
1753 }
1754 if mark_visited {
1755 container.data_mut().table_visited = true;
1756 }
1757
1758 true
1759 }
1760
1761 fn detect_table(
1762 &mut self,
1763 container: Node<'a>,
1764 line: &str,
1765 indented: bool,
1766 ) -> Option<(Node<'a>, bool, bool)> {
1767 if !indented && self.options.extension.table {
1768 table::try_opening_block(self, container, line)
1769 } else {
1770 None
1771 }
1772 }
1773
1774 //////////
1775 // Core //
1776 //////////
1777
1778 fn advance_offset(&mut self, line: &str, mut count: usize, columns: bool) {
1779 let bytes = line.as_bytes();
1780 while count > 0 {
1781 match bytes[self.offset] {
1782 b'\t' => {
1783 let chars_to_tab = TAB_STOP - (self.column % TAB_STOP);
1784 if columns {
1785 self.partially_consumed_tab = chars_to_tab > count;
1786 let chars_to_advance = min(count, chars_to_tab);
1787 self.column += chars_to_advance;
1788 if !self.partially_consumed_tab {
1789 self.offset += 1;
1790 };
1791 count -= chars_to_advance;
1792 } else {
1793 self.partially_consumed_tab = false;
1794 self.column += chars_to_tab;
1795 self.offset += 1;
1796 count -= 1;
1797 }
1798 }
1799 _ => {
1800 self.partially_consumed_tab = false;
1801 self.offset += 1;
1802 self.column += 1;
1803 count -= 1;
1804 }
1805 }
1806 }
1807 }
1808
1809 fn add_child(
1810 &mut self,
1811 mut parent: Node<'a>,
1812 value: NodeValue,
1813 start_column: usize,
1814 ) -> Node<'a> {
1815 while !parent.can_contain_type(&value) {
1816 parent = self.finalize(parent).unwrap();
1817 }
1818
1819 assert!(start_column > 0);
1820
1821 let child = Ast::new(value, (self.line_number, start_column).into());
1822 let node = self.arena.alloc(child.into());
1823 parent.append(node);
1824 node
1825 }
1826
1827 fn add_text_to_container(
1828 &mut self,
1829 mut container: Node<'a>,
1830 last_matched_container: Node<'a>,
1831 line: &str,
1832 ) {
1833 self.find_first_nonspace(line);
1834
1835 if self.blank {
1836 if let Some(last_child) = container.last_child() {
1837 last_child.data_mut().last_line_blank = true;
1838 }
1839 }
1840
1841 container.data_mut().last_line_blank = self.blank
1842 && match container.data().value {
1843 NodeValue::BlockQuote
1844 | NodeValue::Heading(..)
1845 | NodeValue::ThematicBreak
1846 | NodeValue::Subtext => false,
1847 NodeValue::CodeBlock(ref ncb) => !ncb.fenced,
1848 NodeValue::Item(..) => {
1849 container.first_child().is_some()
1850 || container.data().sourcepos.start.line != self.line_number
1851 }
1852 NodeValue::MultilineBlockQuote(..) => false,
1853 NodeValue::Alert(..) => false,
1854 _ => true,
1855 };
1856
1857 let mut tmp = container;
1858 while let Some(parent) = tmp.parent() {
1859 parent.data_mut().last_line_blank = false;
1860 tmp = parent;
1861 }
1862
1863 if !self.current.same_node(last_matched_container)
1864 && container.same_node(last_matched_container)
1865 && !self.blank
1866 && (!self.options.extension.greentext
1867 || !node_matches!(container, NodeValue::BlockQuote | NodeValue::Document))
1868 && node_matches!(self.current, NodeValue::Paragraph)
1869 {
1870 self.add_line(self.current, line);
1871 } else {
1872 while !self.current.same_node(last_matched_container) {
1873 self.current = self.finalize(self.current).unwrap();
1874 }
1875
1876 let add_text_result = match container.data().value {
1877 NodeValue::CodeBlock(..) => AddTextResult::LiteralText,
1878 NodeValue::HtmlBlock(ref nhb) => AddTextResult::HtmlBlock(nhb.block_type),
1879 #[cfg(feature = "phoenix_heex")]
1880 NodeValue::HeexBlock(ref nhb) => AddTextResult::HeexBlock(nhb.clone()),
1881 _ => AddTextResult::Otherwise,
1882 };
1883
1884 match add_text_result {
1885 AddTextResult::LiteralText => {
1886 self.add_line(container, line);
1887 }
1888 AddTextResult::HtmlBlock(block_type) => {
1889 self.add_line(container, line);
1890
1891 let matches_end_condition = match block_type {
1892 1 => scanners::html_block_end_1(&line[self.first_nonspace..]),
1893 2 => scanners::html_block_end_2(&line[self.first_nonspace..]),
1894 3 => scanners::html_block_end_3(&line[self.first_nonspace..]),
1895 4 => scanners::html_block_end_4(&line[self.first_nonspace..]),
1896 5 => scanners::html_block_end_5(&line[self.first_nonspace..]),
1897 _ => false,
1898 };
1899
1900 if matches_end_condition {
1901 container = self.finalize(container).unwrap();
1902 }
1903 }
1904 #[cfg(feature = "phoenix_heex")]
1905 AddTextResult::HeexBlock(nhb) => {
1906 self.add_line(container, line);
1907
1908 let matches_end = match nhb.node {
1909 phoenix_heex::HeexNode::Tag(ref tag_name) => {
1910 self.heex_tag_matches_end(line, tag_name)
1911 }
1912 phoenix_heex::HeexNode::Directive => {
1913 scanners::phoenix_block_directive_end(&line[self.first_nonspace..])
1914 }
1915 phoenix_heex::HeexNode::Comment => {
1916 scanners::phoenix_block_comment_end(&line[self.first_nonspace..])
1917 }
1918 phoenix_heex::HeexNode::MultilineComment => {
1919 scanners::phoenix_block_multiline_comment_end(
1920 &line[self.first_nonspace..],
1921 )
1922 }
1923 phoenix_heex::HeexNode::Expression => {
1924 scanners::phoenix_block_expression_end(&line[self.first_nonspace..])
1925 }
1926 };
1927
1928 if matches_end {
1929 container = self.finalize(container).unwrap();
1930 }
1931 }
1932 _ => {
1933 if self.blank {
1934 // do nothing
1935 } else if container.data().value.accepts_lines() {
1936 let mut line = line;
1937 if let NodeValue::Heading(ref mut nh) = container.data_mut().value {
1938 if !nh.setext {
1939 let (new_line, closed) = strings::chop_trailing_hashes(line);
1940 line = new_line;
1941 nh.closed = closed;
1942 }
1943 };
1944
1945 #[cfg(feature = "phoenix_heex")]
1946 let preserve_heex_whitespace = if self.options.extension.phoenix_heex {
1947 node_matches!(container, NodeValue::Paragraph)
1948 && self.has_unclosed_heex_directive(container)
1949 } else {
1950 false
1951 };
1952 #[cfg(not(feature = "phoenix_heex"))]
1953 let preserve_heex_whitespace = false;
1954
1955 let count = self.first_nonspace - self.offset;
1956
1957 // In some cases the `chop_trailing_hashes` above
1958 // can leave the line shorter than the recorded
1959 // `first_nonspace` This happens with ATX headers
1960 // containing no header text, multiple spaces and
1961 // trailing hashes, e.g
1962 //
1963 // ### ###
1964 //
1965 // In this case `first_nonspace` indexes into the
1966 // second set of hashes, while `chop_trailing_hashtags`
1967 // truncates `line` to just `###` (the first three
1968 // hashes). In this case there's no text to add, and no
1969 // further processing to be done.
1970 let have_line_text = self.first_nonspace <= line.len();
1971
1972 if have_line_text {
1973 if !preserve_heex_whitespace {
1974 self.advance_offset(line, count, false);
1975 }
1976 self.add_line(container, line);
1977 }
1978 } else {
1979 container = self.add_child(
1980 container,
1981 NodeValue::Paragraph,
1982 self.first_nonspace + 1,
1983 );
1984 let count = self.first_nonspace - self.offset;
1985 self.advance_offset(line, count, false);
1986 self.add_line(container, line);
1987 }
1988 }
1989 }
1990
1991 self.current = container;
1992 }
1993 }
1994
1995 fn add_line(&mut self, node: Node<'a>, line: &str) {
1996 let mut ast = node.data_mut();
1997 assert!(ast.open);
1998 if self.partially_consumed_tab {
1999 self.offset += 1;
2000 let chars_to_tab = TAB_STOP - (self.column % TAB_STOP);
2001 ast.content.reserve(chars_to_tab);
2002 for _ in 0..chars_to_tab {
2003 ast.content.push(' ');
2004 }
2005 }
2006 if self.offset < line.len() {
2007 // Since whitespace is stripped off the beginning of lines, we need
2008 // to keep track of how much was stripped off. This allows us to
2009 // properly calculate inline sourcepos during inline processing.
2010 ast.line_offsets.push(self.offset);
2011
2012 ast.content.push_str(&line[self.offset..]);
2013 }
2014 }
2015
2016 fn finalize_document(&mut self) {
2017 while !self.current.same_node(self.root) {
2018 self.current = self.finalize(self.current).unwrap();
2019 }
2020
2021 self.finalize(self.root);
2022
2023 self.refmap.max_ref_size = self.total_size.min(100000);
2024
2025 self.process_inlines();
2026
2027 if self.options.extension.footnotes {
2028 // Append auto-generated inline footnote definitions
2029 if self.options.extension.inline_footnotes {
2030 self.root.extend(self.footnote_defs.take());
2031 }
2032
2033 self.process_footnotes();
2034 }
2035
2036 self.propagate_list_sourcepos(self.root);
2037 }
2038
2039 // Walk the tree and fix lists using their
2040 // deepest-last descendant end where available.
2041 fn propagate_list_sourcepos(&mut self, root: Node<'a>) {
2042 // Post-order traversal using an explicit stack: (node, visited)
2043 let mut stack: Vec<(Node<'a>, bool)> = Vec::new();
2044 stack.push((root, false));
2045
2046 while let Some((node, visited)) = stack.pop() {
2047 if !visited {
2048 stack.push((node, true));
2049 for ch in node.children() {
2050 stack.push((ch, false));
2051 }
2052 } else {
2053 // Use a short-lived shared borrow to inspect descendants,
2054 // then take a mutable borrow only when we need to update the
2055 // node. This avoids RefCell borrow conflicts.
2056 if matches!(node.data().value, NodeValue::List(..)) {
2057 let mut max_end = node.data().sourcepos.end;
2058 for d in node.descendants() {
2059 let de = d.data().sourcepos.end;
2060 if de.column == 0 {
2061 continue;
2062 }
2063 if de.line > max_end.line
2064 || (de.line == max_end.line && de.column > max_end.column)
2065 {
2066 max_end = de;
2067 }
2068 }
2069
2070 if max_end.column != 0 {
2071 let mut ast = node.data_mut();
2072 ast.sourcepos.end = max_end;
2073 }
2074 }
2075 }
2076 }
2077 }
2078
2079 fn finalize(&mut self, node: Node<'a>) -> Option<Node<'a>> {
2080 self.finalize_borrowed(node, &mut node.data_mut())
2081 }
2082
2083 fn resolve_reference_link_definitions(&mut self, content: &mut String) -> bool {
2084 let mut pos = 0;
2085 let mut rrs = vec![];
2086
2087 let bytes = content.as_bytes();
2088 while pos < content.len() && bytes[pos] == b'[' {
2089 if let Some((offset, rr)) = self.parse_reference_inline(&content[pos..]) {
2090 pos += offset;
2091 rrs.extend(rr);
2092 } else {
2093 break;
2094 }
2095 }
2096
2097 for (lab, rr) in rrs {
2098 self.refmap.map.entry(lab).or_insert(rr);
2099 }
2100
2101 if pos != 0 {
2102 strings::remove_from_start(content, pos);
2103 }
2104
2105 !strings::is_blank(content)
2106 }
2107
2108 fn finalize_borrowed(&mut self, node: Node<'a>, ast: &mut Ast) -> Option<Node<'a>> {
2109 assert!(ast.open);
2110 ast.open = false;
2111
2112 let content = &mut ast.content;
2113 let parent = node.parent();
2114
2115 if self.curline_len == 0 {
2116 ast.sourcepos.end = (self.line_number, self.last_line_length).into();
2117 } else if match ast.value {
2118 NodeValue::Document => true,
2119 NodeValue::CodeBlock(ref ncb) => ncb.fenced && ncb.closed,
2120 NodeValue::MultilineBlockQuote(..) => true,
2121 NodeValue::BlockDirective(..) => true,
2122 _ => false,
2123 } {
2124 ast.sourcepos.end = (self.line_number, self.curline_end_col).into();
2125 } else if matches!(
2126 ast.value,
2127 NodeValue::ThematicBreak | NodeValue::TableRow(..) | NodeValue::Table(..)
2128 ) {
2129 // sourcepos.end set by itself or managed below.
2130 } else {
2131 ast.sourcepos.end = (self.line_number - 1, self.last_line_length).into();
2132 }
2133
2134 match ast.value {
2135 NodeValue::DescriptionList
2136 | NodeValue::DescriptionItem(..)
2137 | NodeValue::DescriptionTerm
2138 | NodeValue::DescriptionDetails => {
2139 self.fix_zero_end_columns(node);
2140 }
2141 NodeValue::Paragraph => {
2142 let has_content = self.resolve_reference_link_definitions(content);
2143 if !has_content {
2144 node.detach();
2145 }
2146 }
2147 NodeValue::CodeBlock(ref mut ncb) => {
2148 if !ncb.fenced {
2149 strings::remove_trailing_blank_lines(content);
2150 content.push('\n');
2151 } else {
2152 let mut pos = 0;
2153 while pos < content.len() {
2154 if strings::is_line_end_char(content.as_bytes()[pos]) {
2155 break;
2156 }
2157 pos += 1;
2158 }
2159
2160 let mut info = entity::unescape_html(&content[..pos]);
2161 strings::trim_cow(&mut info);
2162 let mut info = info.into_owned();
2163 strings::unescape(&mut info);
2164
2165 #[cfg(feature = "attributes")]
2166 if self.options.extension.fenced_code_attributes {
2167 if let Some(attrs) = attributes::parse_off(&mut info) {
2168 ast.attrs = Some(Box::new(attrs));
2169 }
2170 }
2171
2172 if info.is_empty() {
2173 ncb.info = self
2174 .options
2175 .parse
2176 .default_info_string
2177 .as_ref()
2178 .map_or(info, |s| s.clone());
2179 } else {
2180 ncb.info = info;
2181 }
2182
2183 if content.as_bytes().get(pos) == Some(&b'\r') {
2184 pos += 1;
2185 }
2186 if content.as_bytes().get(pos) == Some(&b'\n') {
2187 pos += 1;
2188 }
2189
2190 strings::remove_from_start(content, pos);
2191 }
2192 mem::swap(&mut ncb.literal, content);
2193 }
2194 NodeValue::HtmlBlock(ref mut nhb) => {
2195 let trimmed = strings::remove_trailing_blank_lines_slice(content);
2196 let (num_lines, last_line_len) = strings::count_newlines(trimmed);
2197 let end_line = ast.sourcepos.start.line + num_lines;
2198 let end_col = ast.line_offsets.get(num_lines).copied().unwrap_or(0) + last_line_len;
2199 ast.sourcepos.end = (end_line, end_col).into();
2200
2201 mem::swap(&mut nhb.literal, content);
2202 }
2203 #[cfg(feature = "phoenix_heex")]
2204 NodeValue::HeexBlock(ref mut nhb) => {
2205 let trimmed = strings::remove_trailing_blank_lines_slice(content);
2206 let (num_lines, last_line_len) = strings::count_newlines(trimmed);
2207 let end_line = ast.sourcepos.start.line + num_lines;
2208 let end_col = ast.line_offsets.get(num_lines).copied().unwrap_or(0) + last_line_len;
2209 ast.sourcepos.end = (end_line, end_col).into();
2210
2211 mem::swap(&mut nhb.literal, content);
2212 }
2213 NodeValue::List(ref mut nl) => {
2214 if let Some(candidate_end) = self.fix_zero_end_columns(node) {
2215 ast.sourcepos.end = candidate_end;
2216 }
2217 nl.tight = self.determine_list_tight(node);
2218 }
2219 NodeValue::FootnoteDefinition(_) => {
2220 if let Some(candidate_end) = self.fix_zero_end_columns(node) {
2221 ast.sourcepos.end = candidate_end;
2222 }
2223 }
2224 NodeValue::Heading(_) =>
2225 {
2226 #[cfg(feature = "attributes")]
2227 if self.options.extension.header_attributes {
2228 if let Some(attrs) = attributes::parse_off(content) {
2229 ast.attrs = Some(Box::new(attrs));
2230 }
2231 }
2232 }
2233 _ => (),
2234 }
2235
2236 parent
2237 }
2238
2239 fn determine_list_tight(&self, node: Node<'a>) -> bool {
2240 let mut ch = node.first_child();
2241
2242 while let Some(item) = ch {
2243 if item.data().last_line_blank && item.next_sibling().is_some() {
2244 return false;
2245 }
2246
2247 let mut subch = item.first_child();
2248 while let Some(subitem) = subch {
2249 if (item.next_sibling().is_some() || subitem.next_sibling().is_some())
2250 && subitem.ends_with_blank_line()
2251 {
2252 return false;
2253 }
2254 subch = subitem.next_sibling();
2255 }
2256
2257 ch = item.next_sibling();
2258 }
2259
2260 true
2261 }
2262
2263 fn process_inlines(&mut self) {
2264 for node in self.root.descendants() {
2265 if node.data().value.contains_inlines() {
2266 self.parse_inlines(node);
2267 }
2268 }
2269 }
2270
2271 fn parse_inlines(&mut self, node: Node<'a>) {
2272 let mut node_data = node.data_mut();
2273
2274 let mut content = mem::take(&mut node_data.content);
2275 strings::rtrim(&mut content);
2276
2277 let line = node_data.sourcepos.start.line;
2278
2279 let delimiter_arena = typed_arena::Arena::new();
2280 let mut subj = inlines::Subject::new(
2281 self.arena,
2282 self.options,
2283 content,
2284 line,
2285 &mut self.refmap,
2286 &mut self.footnote_defs,
2287 &delimiter_arena,
2288 0,
2289 );
2290
2291 while subj.parse_inline(node, &mut node_data) {}
2292 subj.process_emphasis(0);
2293 subj.clear_brackets();
2294 }
2295
2296 fn process_footnotes(&mut self) {
2297 // TODO: combine find_footnote_definitions and find_footnote_references into one pass!
2298 let mut fd_map = HashMap::new();
2299 Self::find_footnote_definitions(self.root, &mut fd_map);
2300
2301 let mut next_ix = 0;
2302 self.find_footnote_references(&mut fd_map, &mut next_ix);
2303
2304 let mut fds = fd_map.into_values().collect::<Vec<_>>();
2305 fds.sort_unstable_by(|a, b| a.ix.cmp(&b.ix));
2306 for fd in fds {
2307 if fd.ix.is_some() {
2308 let NodeValue::FootnoteDefinition(ref mut nfd) = fd.node.data_mut().value else {
2309 unreachable!()
2310 };
2311 nfd.name = fd.name.to_string();
2312 nfd.total_references = fd.total_references;
2313 if !self.options.parse.leave_footnote_definitions {
2314 self.root.append(fd.node);
2315 }
2316 } else if !self.options.parse.leave_footnote_definitions {
2317 fd.node.detach();
2318 }
2319 }
2320 }
2321
2322 fn find_footnote_definitions(
2323 root: Node<'a>,
2324 map: &mut HashMap<String, FootnoteDefinition<'a>>,
2325 ) {
2326 let mut stack = vec![root];
2327 while let Some(node) = stack.pop() {
2328 match node.data().value {
2329 NodeValue::FootnoteDefinition(ref nfd) => {
2330 map.insert(
2331 strings::normalize_label(&nfd.name, Case::Fold),
2332 FootnoteDefinition {
2333 ix: None,
2334 node,
2335 name: strings::normalize_label(&nfd.name, Case::Preserve),
2336 total_references: 0,
2337 },
2338 );
2339 }
2340 _ => {
2341 stack.extend(node.reverse_children());
2342 }
2343 }
2344 }
2345 }
2346
2347 fn find_footnote_references(
2348 &mut self,
2349 map: &mut HashMap<String, FootnoteDefinition>,
2350 ixp: &mut u32,
2351 ) {
2352 let mut stack = vec![self.root];
2353 while let Some(node) = stack.pop() {
2354 let mut ast = node.data_mut();
2355 let sp = ast.sourcepos;
2356 match ast.value {
2357 NodeValue::FootnoteReference(ref mut nfr) => {
2358 let normalized = strings::normalize_label(&nfr.name, Case::Fold);
2359 if let Some(ref mut footnote) = map.get_mut(&normalized) {
2360 let ix = match footnote.ix {
2361 Some(ix) => ix,
2362 None => {
2363 *ixp += 1;
2364 footnote.ix = Some(*ixp);
2365 *ixp
2366 }
2367 };
2368 footnote.total_references += 1;
2369 nfr.ref_num = footnote.total_references;
2370 nfr.ix = ix;
2371 nfr.name = strings::normalize_label(&footnote.name, Case::Preserve);
2372 } else {
2373 // Restore the nodes as they were-ish. We restore each
2374 // Text node as it was found, preserving the sourcepos
2375 // spans. This is important for accurate sourcepos
2376 // tracking; we assert when 'consuming' sourcepos
2377 // lengths in post-processing that either the span
2378 // length matches the byte count of the string (meaning
2379 // we can reliably subset them both), or that we're
2380 // consuming a whole span. Trying to consume part of a
2381 // span without a matching length is undefined, and we
2382 // will crash; see Spx::consume.
2383 //
2384 // See HACK comment in
2385 // `inlines::Subject::handle_close_bracket` for the
2386 // producer of these values.
2387 assert!(!nfr.texts.is_empty());
2388 let mut lc = sp.start;
2389 let mut target = node;
2390
2391 let mut texts = mem::take(&mut nfr.texts);
2392 texts.insert(0, ("[".into(), 1));
2393 texts.push(("]".into(), 1));
2394
2395 for (text, span) in &mut texts {
2396 let inl = self.arena.alloc(
2397 Ast::new_with_sourcepos(
2398 NodeValue::Text(mem::take(text).into()),
2399 (lc, lc.column_add(*span as isize - 1)).into(),
2400 )
2401 .into(),
2402 );
2403 target.insert_after(inl);
2404 target = inl;
2405 lc = lc.column_add(*span as isize);
2406 }
2407 node.detach();
2408 }
2409 }
2410 _ => {
2411 stack.extend(node.reverse_children());
2412 }
2413 }
2414 }
2415 }
2416
2417 fn postprocess_text_nodes(&mut self, root: Node<'a>) {
2418 let mut stack = vec![(root, false)];
2419 let mut children = vec![];
2420 let coalesce_escaped =
2421 !(self.options.parse.escaped_char_spans || self.options.render.escaped_char_spans);
2422
2423 while let Some((parent, in_bracket_context)) = stack.pop() {
2424 let mut it = parent.first_child();
2425 let mut escaped_to_coalesce = vec![];
2426
2427 while let Some(node) = it {
2428 let mut child_in_bracket_context = in_bracket_context;
2429 let mut emptied = false;
2430 let ast = &mut node.data_mut();
2431
2432 let sourcepos = ast.sourcepos;
2433 match ast.value {
2434 NodeValue::Text(ref mut text) => {
2435 let sourcepos = self.postprocess_text_node_with_context(
2436 node,
2437 sourcepos,
2438 text,
2439 in_bracket_context,
2440 );
2441 emptied = text.is_empty();
2442 ast.sourcepos = sourcepos;
2443 }
2444 NodeValue::Link(..) | NodeValue::Image(..) | NodeValue::WikiLink(..) => {
2445 // Recurse into links, images, and wikilinks to join adjacent text nodes,
2446 // but mark the context so autolinks won't be generated within them.
2447 child_in_bracket_context = true;
2448 }
2449 NodeValue::Escaped => {
2450 if coalesce_escaped {
2451 escaped_to_coalesce.push(node);
2452 }
2453 }
2454 _ => {}
2455 }
2456
2457 if !emptied {
2458 children.push((node, child_in_bracket_context));
2459 }
2460
2461 it = node.next_sibling();
2462
2463 if emptied {
2464 node.detach();
2465 }
2466 }
2467
2468 // Remove Escaped from the tree, coalescing with adjacent nodes.
2469 for node in escaped_to_coalesce {
2470 let escaped_text = node.first_child().unwrap();
2471 node.insert_before(escaped_text);
2472 node.detach();
2473
2474 let mut target = escaped_text;
2475
2476 // We only need look one left and one right, as all adjacent
2477 // Text nodes are coalesced already.
2478 if let Some(before) = target.previous_sibling() {
2479 let mut before_mut = before.data_mut();
2480 if let Some(before_text) = before_mut.value.text_mut() {
2481 let target_data = target.data();
2482 let target_text = target_data.value.text().unwrap();
2483 before_text.to_mut().push_str(target_text);
2484 before_mut.sourcepos.end = target_data.sourcepos.end;
2485 target.detach();
2486
2487 target = before;
2488 }
2489 }
2490
2491 if let Some(after) = target.next_sibling() {
2492 if let Some(after_text) = after.data().value.text() {
2493 let mut target_mut = target.data_mut();
2494 target_mut
2495 .value
2496 .text_mut()
2497 .unwrap()
2498 .to_mut()
2499 .push_str(after_text);
2500 target_mut.sourcepos.end = after.data().sourcepos.end;
2501 after.detach();
2502 }
2503 }
2504 }
2505
2506 // Push children onto work stack in reverse order so they are
2507 // traversed in order
2508 stack.extend(children.drain(..).rev());
2509 }
2510 }
2511
2512 fn postprocess_text_node_with_context(
2513 &mut self,
2514 node: Node<'a>,
2515 mut sourcepos: Sourcepos,
2516 root: &mut Cow<'static, str>,
2517 in_bracket_context: bool,
2518 ) -> Sourcepos {
2519 // Join adjacent text nodes together, then post-process.
2520 // Record the original list of sourcepos and bytecounts
2521 // for the post-processing step.
2522
2523 let mut spxv = VecDeque::new();
2524 spxv.push_back((sourcepos, root.len()));
2525 while let Some(ns) = node.next_sibling() {
2526 match ns.data().value {
2527 NodeValue::Text(ref adj) => {
2528 root.to_mut().push_str(adj);
2529 let sp = ns.data().sourcepos;
2530 spxv.push_back((sp, adj.len()));
2531 sourcepos.end.column = sp.end.column;
2532 ns.detach();
2533 }
2534 _ => break,
2535 }
2536 }
2537
2538 self.postprocess_text_node_with_context_inner(
2539 node,
2540 root,
2541 &mut sourcepos,
2542 spxv,
2543 in_bracket_context,
2544 );
2545
2546 sourcepos
2547 }
2548
2549 fn postprocess_text_node_with_context_inner(
2550 &mut self,
2551 node: Node<'a>,
2552 text: &mut Cow<'static, str>,
2553 sourcepos: &mut Sourcepos,
2554 spxv: VecDeque<(Sourcepos, usize)>,
2555 in_bracket_context: bool,
2556 ) {
2557 let mut spx = Spx(spxv);
2558 if self.options.extension.tasklist {
2559 self.process_tasklist(node, text, sourcepos, &mut spx);
2560 }
2561
2562 if self.options.extension.autolink && !in_bracket_context {
2563 autolink::process_email_autolinks(
2564 self.arena,
2565 node,
2566 text,
2567 self.options.parse.relaxed_autolinks,
2568 sourcepos,
2569 &mut spx,
2570 );
2571 }
2572 }
2573
2574 // Processes tasklist items in a text node. This function
2575 // must not detach `node`, as we iterate through siblings in
2576 // `postprocess_text_nodes_with_context` and may end up relying on it
2577 // remaining in place.
2578 //
2579 // `text` is the mutably borrowed textual content of `node`. If it is empty
2580 // after the call to `process_tasklist`, it will be properly cleaned up.
2581 fn process_tasklist(
2582 &mut self,
2583 node: Node<'a>,
2584 text: &mut Cow<'static, str>,
2585 sourcepos: &mut Sourcepos,
2586 spx: &mut Spx,
2587 ) {
2588 let (end, matched, symbol_range) = match scanners::tasklist(text) {
2589 Some(p) => p,
2590 None => return,
2591 };
2592
2593 let mut chars = matched.chars();
2594 let Some(symbol) = chars.next() else {
2595 return;
2596 };
2597
2598 // There must be at most one `char`'s worth of content in `matched`,
2599 // otherwise we ignore it.
2600 if chars.next().is_some() {
2601 return;
2602 }
2603
2604 if !self.options.parse.relaxed_tasklist_matching && !matches!(symbol, ' ' | 'x' | 'X') {
2605 return;
2606 }
2607
2608 let symbol_sourcepos: Sourcepos = (
2609 sourcepos.start.column_add(symbol_range.start as isize),
2610 // `- 1`: symbol_range is end-exclusive, but sourcepos are inclusive.
2611 sourcepos.start.column_add(symbol_range.end as isize - 1),
2612 )
2613 .into();
2614
2615 let parent = node.parent().unwrap();
2616
2617 if node_matches!(parent, NodeValue::TableCell) {
2618 if !self.options.parse.tasklist_in_table {
2619 return;
2620 }
2621
2622 if node.previous_sibling().is_some() || node.next_sibling().is_some() {
2623 return;
2624 }
2625
2626 // For now, require the task item is the only content of the table cell.
2627 // If we want to relax this later, we can.
2628 if end != text.len() {
2629 return;
2630 }
2631
2632 strings::remove_from_start(text.to_mut(), end);
2633 parent.prepend(
2634 self.arena.alloc(
2635 Ast::new_with_sourcepos(
2636 NodeValue::TaskItem(NodeTaskItem {
2637 symbol: if symbol == ' ' { None } else { Some(symbol) },
2638 symbol_sourcepos,
2639 }),
2640 *sourcepos,
2641 )
2642 .into(),
2643 ),
2644 );
2645 } else if node_matches!(parent, NodeValue::Paragraph) {
2646 if node.previous_sibling().is_some() || parent.previous_sibling().is_some() {
2647 return;
2648 }
2649
2650 let grandparent = parent.parent().unwrap();
2651 if !node_matches!(grandparent, NodeValue::Item(..)) {
2652 return;
2653 }
2654
2655 let great_grandparent = grandparent.parent().unwrap();
2656 if !node_matches!(great_grandparent, NodeValue::List(..)) {
2657 return;
2658 }
2659
2660 // These are sound only because the exact text that we've matched and
2661 // the count thereof (i.e. "end") will precisely map to characters in
2662 // the source document.
2663 strings::remove_from_start(text.to_mut(), end);
2664
2665 let adjust = spx.consume(end) + 1;
2666 assert_eq!(sourcepos.start.column, parent.data().sourcepos.start.column);
2667
2668 // See tests::fuzz::echaw9. The paragraph doesn't exist in the source,
2669 // so we remove it.
2670 if sourcepos.end.column < adjust && node.next_sibling().is_none() {
2671 parent.detach();
2672 } else {
2673 sourcepos.start.column = adjust;
2674 parent.data_mut().sourcepos.start.column = adjust;
2675 }
2676
2677 grandparent.data_mut().value = NodeValue::TaskItem(NodeTaskItem {
2678 symbol: if symbol == ' ' { None } else { Some(symbol) },
2679 symbol_sourcepos,
2680 });
2681
2682 if let NodeValue::List(list) = &mut great_grandparent.data_mut().value {
2683 list.is_task_list = true;
2684 }
2685 }
2686 }
2687
2688 fn parse_reference_inline(
2689 &self,
2690 content: &str,
2691 ) -> Option<(usize, Option<(String, ResolvedReference)>)> {
2692 let mut scanner = inlines::Scanner::new();
2693
2694 let mut lab: String = match scanner.link_label(content) {
2695 Some(lab) if !lab.is_empty() => lab.to_string(),
2696 _ => return None,
2697 };
2698
2699 if scanner.peek_byte(content) != Some(b':') {
2700 return None;
2701 }
2702
2703 scanner.pos += 1;
2704 scanner.spnl(content);
2705 let (url, matchlen) = match inlines::manual_scan_link_url(&content[scanner.pos..]) {
2706 Some((url, matchlen)) => (url.to_string(), matchlen),
2707 None => return None,
2708 };
2709 scanner.pos += matchlen;
2710
2711 let beforetitle = scanner.pos;
2712 scanner.spnl(content);
2713 let title_search = if scanner.pos == beforetitle {
2714 None
2715 } else {
2716 scanners::link_title(&content[scanner.pos..])
2717 };
2718 let title = match title_search {
2719 Some(matchlen) => {
2720 let t = &content[scanner.pos..scanner.pos + matchlen];
2721 scanner.pos += matchlen;
2722 t
2723 }
2724 _ => {
2725 scanner.pos = beforetitle;
2726 ""
2727 }
2728 };
2729
2730 scanner.skip_spaces(content);
2731 if !scanner.skip_line_end(content) {
2732 if !title.is_empty() {
2733 scanner.pos = beforetitle;
2734 scanner.skip_spaces(content);
2735 if !scanner.skip_line_end(content) {
2736 return None;
2737 }
2738 } else {
2739 return None;
2740 }
2741 }
2742
2743 lab = strings::normalize_label(&lab, Case::Fold);
2744 let mut rr = None;
2745 if !lab.is_empty() && !self.refmap.map.contains_key(&lab) {
2746 rr = Some((
2747 lab,
2748 ResolvedReference {
2749 url: strings::clean_url(&url).into(),
2750 title: strings::clean_title(title).into(),
2751 },
2752 ));
2753 }
2754 Some((scanner.pos, rr))
2755 }
2756 }
2757
2758 enum AddTextResult {
2759 LiteralText,
2760 HtmlBlock(u8),
2761 #[cfg(feature = "phoenix_heex")]
2762 HeexBlock(Box<phoenix_heex::NodeHeexBlock>),
2763 Otherwise,
2764 }
2765
2766 fn parse_list_marker(
2767 line: &str,
2768 mut pos: usize,
2769 interrupts_paragraph: bool,
2770 ) -> Option<(usize, NodeList)> {
2771 let bytes = line.as_bytes();
2772 if pos >= line.len() {
2773 return None;
2774 }
2775 let mut c = bytes[pos];
2776 let startpos = pos;
2777
2778 if c == b'*' || c == b'-' || c == b'+' {
2779 pos += 1;
2780 if !bytes.get(pos).is_none_or(|&b| isspace(b)) {
2781 return None;
2782 }
2783
2784 if interrupts_paragraph {
2785 // "However, an empty list item cannot interrupt a paragraph:"
2786 let mut i = pos;
2787 if i == bytes.len() {
2788 return None;
2789 }
2790
2791 while strings::is_space_or_tab(bytes[i]) {
2792 i += 1;
2793 if i == bytes.len() {
2794 return None;
2795 }
2796 }
2797 if strings::is_line_end_char(bytes[i]) {
2798 return None;
2799 }
2800 }
2801
2802 return Some((
2803 pos - startpos,
2804 NodeList {
2805 list_type: ListType::Bullet,
2806 marker_offset: 0,
2807 padding: 0,
2808 start: 1,
2809 delimiter: ListDelimType::Period,
2810 bullet_char: c,
2811 tight: false,
2812 is_task_list: false,
2813 },
2814 ));
2815 } else if isdigit(c) {
2816 let mut start: usize = 0;
2817 let mut digits = 0;
2818
2819 loop {
2820 start = (10 * start) + (bytes[pos] - b'0') as usize;
2821 pos += 1;
2822 digits += 1;
2823
2824 if pos == bytes.len() {
2825 return None;
2826 }
2827
2828 if !(digits < 9 && isdigit(bytes[pos])) {
2829 break;
2830 }
2831 }
2832
2833 if interrupts_paragraph && start != 1 {
2834 return None;
2835 }
2836
2837 c = bytes[pos];
2838 if c != b'.' && c != b')' {
2839 return None;
2840 }
2841
2842 pos += 1;
2843
2844 if pos == bytes.len() || !isspace(bytes[pos]) {
2845 return None;
2846 }
2847
2848 if interrupts_paragraph {
2849 let mut i = pos;
2850 while strings::is_space_or_tab(bytes[i]) {
2851 i += 1;
2852 if i == bytes.len() {
2853 return None;
2854 }
2855 }
2856 if strings::is_line_end_char(bytes[i]) {
2857 return None;
2858 }
2859 }
2860
2861 return Some((
2862 pos - startpos,
2863 NodeList {
2864 list_type: ListType::Ordered,
2865 marker_offset: 0,
2866 padding: 0,
2867 start,
2868 delimiter: if c == b'.' {
2869 ListDelimType::Period
2870 } else {
2871 ListDelimType::Paren
2872 },
2873 bullet_char: 0,
2874 tight: false,
2875 is_task_list: false,
2876 },
2877 ));
2878 }
2879
2880 None
2881 }
2882
2883 fn lists_match(list_data: &NodeList, item_data: &NodeList) -> bool {
2884 list_data.list_type == item_data.list_type
2885 && list_data.delimiter == item_data.delimiter
2886 && list_data.bullet_char == item_data.bullet_char
2887 }
2888
2889 fn reopen_ast_nodes(mut ast: Node<'_>) {
2890 loop {
2891 ast.data_mut().open = true;
2892 ast = match ast.parent() {
2893 Some(p) => p,
2894 None => return,
2895 }
2896 }
2897 }
2898
2899 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2900 pub enum AutolinkType {
2901 Uri,
2902 Email,
2903 }
2904
2905 pub(crate) struct Spx(VecDeque<(Sourcepos, usize)>);
2906
2907 impl Spx {
2908 // Sourcepos end column `e` of a node determined by advancing through `spx`
2909 // until `i` bytes of input are seen.
2910 //
2911 // For each element `(sp, x)` in `spx`:
2912 // - if remaining `i` is greater than the byte count `x`,
2913 // set `i -= x` and continue.
2914 // - if remaining `i` is equal to the byte count `x`,
2915 // set `e = sp.end.column` and finish.
2916 // - if remaining `i` is less than the byte count `x`,
2917 // assert `sp.end.column - sp.start.column + 1 == x || i == 0` (1),
2918 // set `e = sp.start.column + i - 1` and finish.
2919 //
2920 // (1) If `x` doesn't equal the range covered between the start and end column,
2921 // there's no way to determine sourcepos within the range. This is a bug if
2922 // it happens; it suggests we've matched an email autolink with some smart
2923 // punctuation in it, or worse.
2924 //
2925 // The one exception is if `i == 0`. Given nothing to consume, we can
2926 // happily restore what we popped, returning `sp.start.column - 1` for the
2927 // end column of the original node.
2928 pub(crate) fn consume(&mut self, mut rem: usize) -> usize {
2929 while let Some((sp, x)) = self.0.pop_front() {
2930 match rem.cmp(&x) {
2931 Ordering::Greater => rem -= x,
2932 Ordering::Equal => return sp.end.column,
2933 Ordering::Less => {
2934 assert!((sp.end.column - sp.start.column + 1 == x) || rem == 0);
2935 self.0.push_front((
2936 (
2937 sp.start.line,
2938 sp.start.column + rem,
2939 sp.end.line,
2940 sp.end.column,
2941 )
2942 .into(),
2943 x - rem,
2944 ));
2945 return sp.start.column + rem - 1;
2946 }
2947 }
2948 }
2949 unreachable!();
2950 }
2951 }