Skip to main content

mq_markdown/
node.rs

1use crate::node::attr_value::{
2    AttrValue,
3    attr_keys::{self, CHILDREN},
4};
5use itertools::Itertools;
6use smol_str::SmolStr;
7use std::{
8    borrow::Cow,
9    fmt::{self, Display},
10};
11
12type ColorPair<'a> = (Cow<'a, str>, Cow<'a, str>);
13
14mod attr;
15pub use attr::SetAttrError;
16pub mod attr_value;
17mod render;
18pub(crate) use render::{
19    for_html, indent_lines, list_own_prefix_width, reindent_all_lines, render_before, render_cell_values,
20    render_values_block, separated_from, values_to_string,
21};
22use render::{render_link_destination, render_link_title};
23#[cfg(test)]
24mod tests;
25
26/// Color theme for rendering markdown nodes with optional ANSI escape codes.
27///
28/// Each field is a tuple of `(prefix, suffix)` ANSI escape code strings that
29/// wrap the corresponding markdown element during colored rendering.
30#[derive(Debug, Clone, Default)]
31pub struct ColorTheme<'a> {
32    /// Style for headings.
33    pub heading: ColorPair<'a>,
34    /// Style for code blocks.
35    pub code: ColorPair<'a>,
36    /// Style for inline code.
37    pub code_inline: ColorPair<'a>,
38    /// Style for emphasis.
39    pub emphasis: ColorPair<'a>,
40    /// Style for strong text.
41    pub strong: ColorPair<'a>,
42    /// Style for link text.
43    pub link: ColorPair<'a>,
44    /// Style for link destinations.
45    pub link_url: ColorPair<'a>,
46    /// Style for images.
47    pub image: ColorPair<'a>,
48    /// Style for block quote markers.
49    pub blockquote_marker: ColorPair<'a>,
50    /// Style for strikethrough.
51    pub delete: ColorPair<'a>,
52    /// Style for thematic breaks.
53    pub horizontal_rule: ColorPair<'a>,
54    /// Style for HTML.
55    pub html: ColorPair<'a>,
56    /// Style for front matter.
57    pub frontmatter: ColorPair<'a>,
58    /// Style for list markers.
59    pub list_marker: ColorPair<'a>,
60    /// Style for table separators.
61    pub table_separator: ColorPair<'a>,
62    /// Style for math.
63    pub math: ColorPair<'a>,
64}
65
66const EMPTY: Cow<'_, str> = Cow::Borrowed("");
67#[cfg(feature = "color")]
68const RESET: Cow<'_, str> = Cow::Borrowed("\x1b[0m");
69
70impl ColorTheme<'_> {
71    /// A theme that adds no styling.
72    pub const PLAIN: ColorTheme<'static> = ColorTheme {
73        heading: (EMPTY, EMPTY),
74        code: (EMPTY, EMPTY),
75        code_inline: (EMPTY, EMPTY),
76        emphasis: (EMPTY, EMPTY),
77        strong: (EMPTY, EMPTY),
78        link: (EMPTY, EMPTY),
79        link_url: (EMPTY, EMPTY),
80        image: (EMPTY, EMPTY),
81        blockquote_marker: (EMPTY, EMPTY),
82        delete: (EMPTY, EMPTY),
83        horizontal_rule: (EMPTY, EMPTY),
84        html: (EMPTY, EMPTY),
85        frontmatter: (EMPTY, EMPTY),
86        list_marker: (EMPTY, EMPTY),
87        table_separator: (EMPTY, EMPTY),
88        math: (EMPTY, EMPTY),
89    };
90
91    /// The default ANSI colored theme.
92    #[cfg(feature = "color")]
93    pub const COLORED: ColorTheme<'static> = ColorTheme {
94        heading: (Cow::Borrowed("\x1b[1m\x1b[36m"), RESET),
95        code: (Cow::Borrowed("\x1b[32m"), RESET),
96        code_inline: (Cow::Borrowed("\x1b[32m"), RESET),
97        emphasis: (Cow::Borrowed("\x1b[3m\x1b[33m"), RESET),
98        strong: (Cow::Borrowed("\x1b[1m"), RESET),
99        link: (Cow::Borrowed("\x1b[4m\x1b[34m"), RESET),
100        link_url: (Cow::Borrowed("\x1b[34m"), RESET),
101        image: (Cow::Borrowed("\x1b[35m"), RESET),
102        blockquote_marker: (Cow::Borrowed("\x1b[2m"), RESET),
103        delete: (Cow::Borrowed("\x1b[31m\x1b[2m"), RESET),
104        horizontal_rule: (Cow::Borrowed("\x1b[2m"), RESET),
105        html: (Cow::Borrowed("\x1b[2m"), RESET),
106        frontmatter: (Cow::Borrowed("\x1b[2m"), RESET),
107        list_marker: (Cow::Borrowed("\x1b[33m"), RESET),
108        table_separator: (Cow::Borrowed("\x1b[2m"), RESET),
109        math: (Cow::Borrowed("\x1b[32m"), RESET),
110    };
111
112    /// Creates a color theme from the `MQ_COLORS` environment variable.
113    #[cfg(feature = "color")]
114    pub fn from_env() -> ColorTheme<'static> {
115        match std::env::var("MQ_COLORS") {
116            Ok(v) if !v.is_empty() => ColorTheme::parse_colors(&v),
117            _ => Self::COLORED,
118        }
119    }
120
121    /// Parses a color configuration string into a `ColorTheme`.
122    ///
123    /// The format is `key=SGR:key=SGR:...` where each key corresponds to a
124    /// markdown element and the value is a semicolon-separated list of SGR
125    /// parameters. Unspecified keys use the default colored theme values.
126    /// Invalid entries are silently ignored.
127    #[cfg(feature = "color")]
128    pub fn parse_colors(spec: &str) -> ColorTheme<'static> {
129        let mut theme = Self::COLORED;
130
131        for entry in spec.split(':') {
132            let Some((key, sgr)) = entry.split_once('=') else {
133                continue;
134            };
135
136            if !Self::is_valid_sgr(sgr) {
137                continue;
138            }
139
140            let prefix = Cow::Owned(format!("\x1b[{}m", sgr));
141            let pair = (prefix, RESET);
142
143            match key {
144                "heading" => theme.heading = pair,
145                "code" => theme.code = pair,
146                "code_inline" => theme.code_inline = pair,
147                "emphasis" => theme.emphasis = pair,
148                "strong" => theme.strong = pair,
149                "link" => theme.link = pair,
150                "link_url" => theme.link_url = pair,
151                "image" => theme.image = pair,
152                "blockquote" => theme.blockquote_marker = pair,
153                "delete" => theme.delete = pair,
154                "hr" => theme.horizontal_rule = pair,
155                "html" => theme.html = pair,
156                "frontmatter" => theme.frontmatter = pair,
157                "list" => theme.list_marker = pair,
158                "table" => theme.table_separator = pair,
159                "math" => theme.math = pair,
160                _ => {}
161            }
162        }
163
164        theme
165    }
166
167    /// Validates that a string contains only valid SGR parameters
168    /// (semicolon-separated numbers).
169    #[cfg(feature = "color")]
170    fn is_valid_sgr(sgr: &str) -> bool {
171        !sgr.is_empty() && sgr.split(';').all(|part| part.parse::<u8>().is_ok())
172    }
173}
174
175pub(crate) type Level = u8;
176
177/// Options for writing nodes as Markdown.
178#[derive(Debug, Clone, PartialEq)]
179pub struct RenderOptions {
180    /// Bullet marker for lists. `None` keeps each list's original marker (`-` if unknown).
181    pub list_style: Option<ListStyle>,
182    /// How link destinations are wrapped.
183    pub link_url_style: UrlSurroundStyle,
184    /// How link titles are quoted.
185    pub link_title_style: TitleSurroundStyle,
186    /// Write for MDX: text that MDX would read as an expression or as ESM is escaped.
187    pub mdx: bool,
188    /// Pad table cells to a common column width. When `false`, cells are written as is
189    /// and the delimiter row uses the shortest valid markers.
190    pub table_padding: bool,
191}
192
193impl Default for RenderOptions {
194    fn default() -> Self {
195        Self {
196            list_style: None,
197            link_url_style: UrlSurroundStyle::default(),
198            link_title_style: TitleSurroundStyle::default(),
199            mdx: false,
200            table_padding: true,
201        }
202    }
203}
204
205/// Bullet marker used when writing lists.
206#[derive(Debug, Clone, Default, PartialEq)]
207pub enum ListStyle {
208    /// `-`
209    #[default]
210    Dash,
211    /// `+`
212    Plus,
213    /// `*`
214    Star,
215}
216
217impl Display for ListStyle {
218    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
219        match self {
220            ListStyle::Dash => write!(f, "-"),
221            ListStyle::Plus => write!(f, "+"),
222            ListStyle::Star => write!(f, "*"),
223        }
224    }
225}
226
227/// The marker of a list item as it is written in the source.
228#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
229#[cfg_attr(feature = "json", derive(serde::Serialize, serde::Deserialize))]
230pub enum ListMarker {
231    /// `-`, a bullet.
232    #[cfg_attr(feature = "json", serde(rename = "-"))]
233    Dash,
234    /// `+`, a bullet.
235    #[cfg_attr(feature = "json", serde(rename = "+"))]
236    Plus,
237    /// `*`, a bullet.
238    #[cfg_attr(feature = "json", serde(rename = "*"))]
239    Star,
240    /// `.` after the number of an ordered item.
241    #[cfg_attr(feature = "json", serde(rename = "."))]
242    Period,
243    /// `)` after the number of an ordered item.
244    #[cfg_attr(feature = "json", serde(rename = ")"))]
245    Paren,
246}
247
248impl ListMarker {
249    /// The character the marker is written with.
250    pub fn as_char(self) -> char {
251        match self {
252            Self::Dash => '-',
253            Self::Plus => '+',
254            Self::Star => '*',
255            Self::Period => '.',
256            Self::Paren => ')',
257        }
258    }
259
260    /// The marker written with `char`: `-`, `+`, `*`, `.` or `)`.
261    pub fn from_char(char: char) -> Option<Self> {
262        match char {
263            '-' => Some(Self::Dash),
264            '+' => Some(Self::Plus),
265            '*' => Some(Self::Star),
266            '.' => Some(Self::Period),
267            ')' => Some(Self::Paren),
268            _ => None,
269        }
270    }
271
272    /// The bullet style of the marker, if it is a bullet.
273    pub fn style(self) -> Option<ListStyle> {
274        match self {
275            Self::Dash => Some(ListStyle::Dash),
276            Self::Plus => Some(ListStyle::Plus),
277            Self::Star => Some(ListStyle::Star),
278            Self::Period | Self::Paren => None,
279        }
280    }
281}
282
283impl From<ListStyle> for ListMarker {
284    fn from(style: ListStyle) -> Self {
285        match style {
286            ListStyle::Dash => Self::Dash,
287            ListStyle::Plus => Self::Plus,
288            ListStyle::Star => Self::Star,
289        }
290    }
291}
292
293/// The character a horizontal rule is written with in the source.
294#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
295#[cfg_attr(feature = "json", derive(serde::Serialize, serde::Deserialize))]
296pub enum HorizontalRuleMarker {
297    /// `*`
298    #[cfg_attr(feature = "json", serde(rename = "*"))]
299    Star,
300    /// `-`
301    #[cfg_attr(feature = "json", serde(rename = "-"))]
302    Dash,
303    /// `_`
304    #[cfg_attr(feature = "json", serde(rename = "_"))]
305    Underscore,
306}
307
308impl HorizontalRuleMarker {
309    /// The character the rule is written with.
310    pub fn as_char(self) -> char {
311        match self {
312            Self::Star => '*',
313            Self::Dash => '-',
314            Self::Underscore => '_',
315        }
316    }
317
318    /// The marker written with `char`: `*`, `-` or `_`.
319    pub fn from_char(char: char) -> Option<Self> {
320        match char {
321            '*' => Some(Self::Star),
322            '-' => Some(Self::Dash),
323            '_' => Some(Self::Underscore),
324            _ => None,
325        }
326    }
327}
328
329/// A link destination.
330#[derive(Debug, Clone, PartialEq, Default)]
331#[cfg_attr(
332    feature = "json",
333    derive(serde::Serialize, serde::Deserialize),
334    serde(rename_all = "camelCase")
335)]
336pub struct Url(pub(crate) String);
337
338/// How a link destination is wrapped when written.
339#[derive(Debug, Clone, PartialEq, Default)]
340pub enum UrlSurroundStyle {
341    /// Written as is.
342    #[default]
343    None,
344    /// Wrapped in `<>`.
345    Angle,
346}
347
348impl Url {
349    /// Creates a value from `value`.
350    pub fn new(value: String) -> Self {
351        Self(value)
352    }
353
354    /// The destination as written.
355    pub fn as_str(&self) -> &str {
356        &self.0
357    }
358
359    /// Writes the node as Markdown with the given options.
360    pub fn to_string_with(&self, options: &RenderOptions) -> Cow<'_, str> {
361        Cow::Owned(render_link_destination(&self.0, &options.link_url_style))
362    }
363}
364
365/// How a link title is quoted when written.
366#[derive(Debug, Clone, PartialEq, Default)]
367pub enum TitleSurroundStyle {
368    /// Wrapped in `"`.
369    #[default]
370    Double,
371    /// Wrapped in `'`.
372    Single,
373    /// Wrapped in `()`.
374    Paren,
375}
376
377/// A link title.
378#[derive(Debug, Clone, PartialEq)]
379#[cfg_attr(
380    feature = "json",
381    derive(serde::Serialize, serde::Deserialize),
382    serde(rename_all = "camelCase")
383)]
384pub struct Title(pub(crate) String);
385
386impl Display for Title {
387    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
388        write!(f, "{}", self.0)
389    }
390}
391
392impl Title {
393    /// Creates a value from `value`.
394    pub fn new(value: String) -> Self {
395        Self(value)
396    }
397
398    /// The title text.
399    pub fn to_value(&self) -> String {
400        self.0.clone()
401    }
402
403    /// Writes the node as Markdown with the given options.
404    pub fn to_string_with(&self, options: &RenderOptions) -> Cow<'_, str> {
405        Cow::Owned(render_link_title(&self.0, &options.link_title_style))
406    }
407}
408
409/// The alignment of a table column.
410#[derive(Debug, Clone, PartialEq)]
411#[cfg_attr(
412    feature = "json",
413    derive(serde::Serialize, serde::Deserialize),
414    serde(rename_all = "camelCase")
415)]
416pub enum TableAlignKind {
417    /// Left aligned.
418    Left,
419    /// Right aligned.
420    Right,
421    /// Centered.
422    Center,
423    /// No alignment given.
424    None,
425}
426
427impl From<&str> for TableAlignKind {
428    fn from(value: &str) -> Self {
429        match value {
430            "left" | ":---" => Self::Left,
431            "right" | "---:" => Self::Right,
432            "center" | ":---:" => Self::Center,
433            "---" => Self::None,
434            _ => Self::None,
435        }
436    }
437}
438
439impl Display for TableAlignKind {
440    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441        match self {
442            TableAlignKind::Left => write!(f, ":---"),
443            TableAlignKind::Right => write!(f, "---:"),
444            TableAlignKind::Center => write!(f, ":---:"),
445            TableAlignKind::None => write!(f, "---"),
446        }
447    }
448}
449
450/// A list item.
451#[derive(Debug, Clone, PartialEq, Default)]
452#[cfg_attr(
453    feature = "json",
454    derive(serde::Serialize, serde::Deserialize),
455    serde(rename_all = "camelCase", tag = "type")
456)]
457pub struct List {
458    /// The content of the item.
459    pub values: Vec<Node>,
460    /// Index of the item in its list.
461    pub index: usize,
462    /// Nesting level of the list.
463    pub level: Level,
464    /// Whether the list is ordered.
465    pub ordered: bool,
466    /// Task state: `None` if the item is not a task.
467    pub checked: Option<bool>,
468    /// Whether the whole list is loose (blank line between/within items).
469    pub spread: bool,
470    /// Starting number for an ordered list (e.g. `5` in `5. foo`); `None` means 1.
471    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
472    pub start: Option<u32>,
473    /// Source marker. `None` keeps the default of the list kind: `-` for bullets, `.` for ordered lists.
474    #[cfg_attr(feature = "json", serde(default, skip_serializing_if = "Option::is_none"))]
475    pub marker: Option<ListMarker>,
476    /// Where the node is in the source, if known.
477    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
478    pub position: Option<Position>,
479}
480
481/// A table cell.
482#[derive(Debug, Clone, PartialEq)]
483#[cfg_attr(
484    feature = "json",
485    derive(serde::Serialize, serde::Deserialize),
486    serde(rename_all = "camelCase", tag = "type")
487)]
488pub struct TableCell {
489    /// Child nodes.
490    pub values: Vec<Node>,
491    /// Index of the column.
492    pub column: usize,
493    /// Index of the row.
494    pub row: usize,
495    /// Where the node is in the source, if known.
496    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
497    pub position: Option<Position>,
498}
499
500/// A table row.
501#[derive(Debug, Clone, PartialEq)]
502#[cfg_attr(
503    feature = "json",
504    derive(serde::Serialize, serde::Deserialize),
505    serde(rename_all = "camelCase", tag = "type")
506)]
507pub struct TableRow {
508    /// Child nodes.
509    pub values: Vec<Node>,
510    /// Where the node is in the source, if known.
511    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
512    pub position: Option<Position>,
513}
514
515/// The delimiter row of a table, giving the column alignments.
516#[derive(Debug, Clone, PartialEq)]
517#[cfg_attr(
518    feature = "json",
519    derive(serde::Serialize, serde::Deserialize),
520    serde(rename_all = "camelCase", tag = "type")
521)]
522pub struct TableAlign {
523    /// Alignment of each column.
524    pub align: Vec<TableAlignKind>,
525    /// Where the node is in the source, if known.
526    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
527    pub position: Option<Position>,
528}
529
530/// A sequence of nodes with no wrapper.
531#[derive(Debug, Clone, PartialEq)]
532#[cfg_attr(
533    feature = "json",
534    derive(serde::Serialize, serde::Deserialize),
535    serde(rename_all = "camelCase", tag = "type")
536)]
537pub struct Fragment {
538    /// Child nodes.
539    pub values: Vec<Node>,
540}
541
542/// A code block.
543#[derive(Debug, Clone, PartialEq, Default)]
544#[cfg_attr(
545    feature = "json",
546    derive(serde::Serialize, serde::Deserialize),
547    serde(rename_all = "camelCase", tag = "type")
548)]
549pub struct Code {
550    /// The code.
551    pub value: String,
552    /// The language of the info string.
553    pub lang: Option<String>,
554    /// Where the node is in the source, if known.
555    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
556    pub position: Option<Position>,
557    /// The rest of the info string after the language.
558    pub meta: Option<String>,
559    /// Whether the block is fenced rather than indented.
560    pub fence: bool,
561}
562
563/// An inline image.
564#[derive(Debug, Clone, PartialEq)]
565#[cfg_attr(
566    feature = "json",
567    derive(serde::Serialize, serde::Deserialize),
568    serde(rename_all = "camelCase", tag = "type")
569)]
570pub struct Image {
571    /// The alternative text.
572    pub alt: String,
573    /// The destination.
574    pub url: String,
575    /// The title, if any.
576    pub title: Option<String>,
577    /// Where the node is in the source, if known.
578    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
579    pub position: Option<Position>,
580}
581
582/// A reference-style image.
583#[derive(Debug, Clone, PartialEq, Default)]
584#[cfg_attr(
585    feature = "json",
586    derive(serde::Serialize, serde::Deserialize),
587    serde(rename_all = "camelCase", tag = "type")
588)]
589pub struct ImageRef {
590    /// The alternative text.
591    pub alt: String,
592    /// The normalized identifier of the reference.
593    pub ident: String,
594    /// The identifier as written in the source.
595    pub label: Option<String>,
596    /// Where the node is in the source, if known.
597    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
598    pub position: Option<Position>,
599}
600/// An inline link.
601#[derive(Debug, Clone, PartialEq)]
602#[cfg_attr(
603    feature = "json",
604    derive(serde::Serialize, serde::Deserialize),
605    serde(rename_all = "camelCase", tag = "type")
606)]
607pub struct Link {
608    /// The destination.
609    pub url: Url,
610    /// The title, if any.
611    pub title: Option<Title>,
612    /// Child nodes.
613    pub values: Vec<Node>,
614    /// Where the node is in the source, if known.
615    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
616    pub position: Option<Position>,
617}
618
619/// An Obsidian-style callout (admonition): `> [!TYPE]` or `> [!TYPE] title`.
620#[cfg(feature = "callout")]
621#[derive(Debug, Clone, PartialEq, Default)]
622#[cfg_attr(
623    feature = "json",
624    derive(serde::Serialize, serde::Deserialize),
625    serde(rename_all = "camelCase", tag = "type")
626)]
627pub struct Callout {
628    /// The callout type as written, e.g. `"NOTE"` or `"warning"`.
629    pub kind: String,
630    /// The fold marker right after `[!TYPE]`: `+` for open and `-` for folded.
631    #[cfg_attr(feature = "json", serde(default, skip_serializing_if = "Option::is_none"))]
632    pub fold: Option<char>,
633    /// Optional custom title after the `[!TYPE]` marker.
634    pub title: Option<String>,
635    /// Body content nodes (the lines after the header).
636    pub values: Vec<Node>,
637    /// Where the node is in the source, if known.
638    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
639    pub position: Option<Position>,
640}
641
642/// An Obsidian-style file embed: `![[target]]` or `![[target|display]]`.
643#[cfg(feature = "embed")]
644#[derive(Debug, Clone, PartialEq, Default)]
645#[cfg_attr(
646    feature = "json",
647    derive(serde::Serialize, serde::Deserialize),
648    serde(rename_all = "camelCase", tag = "type")
649)]
650pub struct Embed {
651    /// The target file or note name (e.g. `"image.png"`, `"note.md"`).
652    pub target: String,
653    /// Optional display hint after `|` (size for images, heading for notes).
654    pub display: Option<String>,
655    /// Where the node is in the source, if known.
656    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
657    pub position: Option<Position>,
658}
659
660/// An Obsidian-style wikilink: `[[target]]` or `[[target|text]]`.
661#[cfg(feature = "wikilink")]
662#[derive(Debug, Clone, PartialEq, Default)]
663#[cfg_attr(
664    feature = "json",
665    derive(serde::Serialize, serde::Deserialize),
666    serde(rename_all = "camelCase", tag = "type")
667)]
668pub struct WikiLink {
669    /// The target page or file name (e.g. `"Three laws of motion"`).
670    pub target: String,
671    /// Optional display text (the part after `|`).
672    pub text: Option<String>,
673    /// Where the node is in the source, if known.
674    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
675    pub position: Option<Position>,
676}
677
678/// A footnote reference.
679#[derive(Debug, Clone, PartialEq, Default)]
680#[cfg_attr(
681    feature = "json",
682    derive(serde::Serialize, serde::Deserialize),
683    serde(rename_all = "camelCase", tag = "type")
684)]
685pub struct FootnoteRef {
686    /// The normalized identifier of the reference.
687    pub ident: String,
688    /// The identifier as written in the source.
689    pub label: Option<String>,
690    /// Where the node is in the source, if known.
691    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
692    pub position: Option<Position>,
693}
694
695/// A footnote definition.
696#[derive(Debug, Clone, PartialEq, Default)]
697#[cfg_attr(
698    feature = "json",
699    derive(serde::Serialize, serde::Deserialize),
700    serde(rename_all = "camelCase", tag = "type")
701)]
702pub struct Footnote {
703    /// The normalized identifier of the reference.
704    pub ident: String,
705    /// Child nodes.
706    pub values: Vec<Node>,
707    /// Where the node is in the source, if known.
708    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
709    pub position: Option<Position>,
710}
711
712/// A reference-style link.
713#[derive(Debug, Clone, PartialEq, Default)]
714#[cfg_attr(
715    feature = "json",
716    derive(serde::Serialize, serde::Deserialize),
717    serde(rename_all = "camelCase", tag = "type")
718)]
719pub struct LinkRef {
720    /// The normalized identifier of the reference.
721    pub ident: String,
722    /// The identifier as written in the source.
723    pub label: Option<String>,
724    /// Child nodes.
725    pub values: Vec<Node>,
726    /// Where the node is in the source, if known.
727    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
728    pub position: Option<Position>,
729}
730
731/// The depth of a heading, from 1 to 6.
732#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
733#[cfg_attr(
734    feature = "json",
735    derive(serde::Serialize, serde::Deserialize),
736    serde(try_from = "u8", into = "u8")
737)]
738pub struct HeadingDepth(u8);
739
740impl fmt::Debug for HeadingDepth {
741    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
742        fmt::Debug::fmt(&self.0, f)
743    }
744}
745
746impl HeadingDepth {
747    /// Depth 1.
748    pub const H1: Self = Self(1);
749    /// Depth 2.
750    pub const H2: Self = Self(2);
751    /// Depth 3.
752    pub const H3: Self = Self(3);
753    /// Depth 4.
754    pub const H4: Self = Self(4);
755    /// Depth 5.
756    pub const H5: Self = Self(5);
757    /// Depth 6.
758    pub const H6: Self = Self(6);
759
760    /// The depth `depth`, if it is from 1 to 6.
761    pub const fn new(depth: u8) -> Option<Self> {
762        if depth >= 1 && depth <= 6 {
763            Some(Self(depth))
764        } else {
765            None
766        }
767    }
768
769    /// The depth nearest to `depth` from 1 to 6.
770    pub fn saturating(depth: i64) -> Self {
771        Self(depth.clamp(1, 6) as u8)
772    }
773
774    /// The depth as a number.
775    pub const fn get(self) -> u8 {
776        self.0
777    }
778
779    /// The depth `levels` deeper, if that is still at most 6.
780    pub fn checked_add(self, levels: u8) -> Option<Self> {
781        self.0.checked_add(levels).and_then(Self::new)
782    }
783
784    /// The depth `levels` shallower, or 1 when that is less.
785    pub fn saturating_sub(self, levels: u8) -> Self {
786        Self(self.0.saturating_sub(levels).max(1))
787    }
788}
789
790impl Default for HeadingDepth {
791    fn default() -> Self {
792        Self::H1
793    }
794}
795
796impl TryFrom<u8> for HeadingDepth {
797    type Error = InvalidHeadingDepth;
798
799    fn try_from(depth: u8) -> Result<Self, Self::Error> {
800        Self::new(depth).ok_or(InvalidHeadingDepth(depth))
801    }
802}
803
804impl From<HeadingDepth> for u8 {
805    fn from(depth: HeadingDepth) -> Self {
806        depth.0
807    }
808}
809
810impl PartialEq<u8> for HeadingDepth {
811    fn eq(&self, other: &u8) -> bool {
812        self.0 == *other
813    }
814}
815
816impl PartialEq<HeadingDepth> for u8 {
817    fn eq(&self, other: &HeadingDepth) -> bool {
818        *self == other.0
819    }
820}
821
822impl PartialOrd<u8> for HeadingDepth {
823    fn partial_cmp(&self, other: &u8) -> Option<std::cmp::Ordering> {
824        self.0.partial_cmp(other)
825    }
826}
827
828impl PartialOrd<HeadingDepth> for u8 {
829    fn partial_cmp(&self, other: &HeadingDepth) -> Option<std::cmp::Ordering> {
830        self.partial_cmp(&other.0)
831    }
832}
833
834impl From<HeadingDepth> for usize {
835    fn from(depth: HeadingDepth) -> Self {
836        usize::from(depth.0)
837    }
838}
839
840impl From<HeadingDepth> for i64 {
841    fn from(depth: HeadingDepth) -> Self {
842        i64::from(depth.0)
843    }
844}
845
846impl Display for HeadingDepth {
847    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
848        self.0.fmt(f)
849    }
850}
851
852/// A heading depth outside of 1 to 6.
853#[derive(Debug, Clone, Copy, PartialEq, Eq)]
854pub struct InvalidHeadingDepth(pub u8);
855
856impl Display for InvalidHeadingDepth {
857    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
858        write!(f, "heading depth {} is not from 1 to 6", self.0)
859    }
860}
861
862impl std::error::Error for InvalidHeadingDepth {}
863
864/// A heading.
865#[derive(Debug, Clone, PartialEq, Default)]
866#[cfg_attr(
867    feature = "json",
868    derive(serde::Serialize, serde::Deserialize),
869    serde(rename_all = "camelCase", tag = "type")
870)]
871pub struct Heading {
872    /// The depth of the heading.
873    pub depth: HeadingDepth,
874    /// Child nodes.
875    pub values: Vec<Node>,
876    /// Where the node is in the source, if known.
877    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
878    pub position: Option<Position>,
879}
880
881/// A link reference definition.
882#[derive(Debug, Clone, PartialEq, Default)]
883#[cfg_attr(
884    feature = "json",
885    derive(serde::Serialize, serde::Deserialize),
886    serde(rename_all = "camelCase", tag = "type")
887)]
888pub struct Definition {
889    /// Where the node is in the source, if known.
890    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
891    pub position: Option<Position>,
892    /// The destination of the definition.
893    pub url: Url,
894    /// The title, if any.
895    pub title: Option<Title>,
896    /// The normalized identifier of the reference.
897    pub ident: String,
898    /// The identifier as written in the source.
899    pub label: Option<String>,
900}
901/// Plain text.
902#[derive(Debug, Clone, PartialEq)]
903#[cfg_attr(
904    feature = "json",
905    derive(serde::Serialize, serde::Deserialize),
906    serde(rename_all = "camelCase", tag = "type")
907)]
908pub struct Text {
909    /// The text.
910    pub value: String,
911    /// Where the node is in the source, if known.
912    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
913    pub position: Option<Position>,
914}
915
916/// Raw HTML.
917#[derive(Debug, Clone, PartialEq)]
918#[cfg_attr(
919    feature = "json",
920    derive(serde::Serialize, serde::Deserialize),
921    serde(rename_all = "camelCase", tag = "type")
922)]
923pub struct Html {
924    /// The HTML source.
925    pub value: String,
926    /// Where the node is in the source, if known.
927    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
928    pub position: Option<Position>,
929}
930
931/// TOML front matter.
932#[derive(Debug, Clone, PartialEq)]
933#[cfg_attr(
934    feature = "json",
935    derive(serde::Serialize, serde::Deserialize),
936    serde(rename_all = "camelCase", tag = "type")
937)]
938pub struct Toml {
939    /// The TOML source.
940    pub value: String,
941    /// Where the node is in the source, if known.
942    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
943    pub position: Option<Position>,
944}
945
946/// YAML front matter.
947#[derive(Debug, Clone, PartialEq)]
948#[cfg_attr(
949    feature = "json",
950    derive(serde::Serialize, serde::Deserialize),
951    serde(rename_all = "camelCase", tag = "type")
952)]
953pub struct Yaml {
954    /// The YAML source.
955    pub value: String,
956    /// Where the node is in the source, if known.
957    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
958    pub position: Option<Position>,
959}
960
961/// Inline code.
962#[derive(Debug, Clone, PartialEq)]
963#[cfg_attr(
964    feature = "json",
965    derive(serde::Serialize, serde::Deserialize),
966    serde(rename_all = "camelCase", tag = "type")
967)]
968pub struct CodeInline {
969    /// The content.
970    pub value: SmolStr,
971    /// Where the node is in the source, if known.
972    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
973    pub position: Option<Position>,
974}
975
976/// Inline math.
977#[derive(Debug, Clone, PartialEq)]
978#[cfg_attr(
979    feature = "json",
980    derive(serde::Serialize, serde::Deserialize),
981    serde(rename_all = "camelCase", tag = "type")
982)]
983pub struct MathInline {
984    /// The content.
985    pub value: SmolStr,
986    /// Where the node is in the source, if known.
987    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
988    pub position: Option<Position>,
989}
990
991/// A math block.
992#[derive(Debug, Clone, PartialEq)]
993#[cfg_attr(
994    feature = "json",
995    derive(serde::Serialize, serde::Deserialize),
996    serde(rename_all = "camelCase", tag = "type")
997)]
998pub struct Math {
999    /// The LaTeX source.
1000    pub value: String,
1001    /// Where the node is in the source, if known.
1002    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1003    pub position: Option<Position>,
1004}
1005
1006/// A block-level MDX expression.
1007#[derive(Debug, Clone, PartialEq)]
1008#[cfg_attr(
1009    feature = "json",
1010    derive(serde::Serialize, serde::Deserialize),
1011    serde(rename_all = "camelCase", tag = "type")
1012)]
1013pub struct MdxFlowExpression {
1014    /// The source of the expression.
1015    pub value: SmolStr,
1016    /// Where the node is in the source, if known.
1017    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1018    pub position: Option<Position>,
1019}
1020
1021/// A block-level JSX element.
1022#[derive(Debug, Clone, PartialEq)]
1023#[cfg_attr(
1024    feature = "json",
1025    derive(serde::Serialize, serde::Deserialize),
1026    serde(rename_all = "camelCase", tag = "type")
1027)]
1028pub struct MdxJsxFlowElement {
1029    /// The child nodes.
1030    pub children: Vec<Node>,
1031    /// Where the node is in the source, if known.
1032    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1033    pub position: Option<Position>,
1034    /// The element name, or `None` for a fragment.
1035    pub name: Option<String>,
1036    /// The attributes of the element.
1037    pub attributes: Vec<MdxAttributeContent>,
1038}
1039
1040#[derive(Debug, Clone, PartialEq)]
1041#[cfg_attr(
1042    feature = "json",
1043    derive(serde::Serialize, serde::Deserialize),
1044    serde(rename_all = "camelCase", tag = "type", content = "value")
1045)]
1046/// An attribute of a JSX element: a property such as `a="b"`, or an expression such as `{...props}`.
1047pub enum MdxAttributeContent {
1048    /// An expression such as `{...props}`.
1049    Expression(SmolStr),
1050    /// A property such as `a="b"`.
1051    Property(MdxJsxAttribute),
1052}
1053
1054#[derive(Debug, Clone, PartialEq)]
1055#[cfg_attr(
1056    feature = "json",
1057    derive(serde::Serialize, serde::Deserialize),
1058    serde(rename_all = "camelCase", tag = "type")
1059)]
1060/// A property of a JSX element, with the value it has after its quotes or braces.
1061pub struct MdxJsxAttribute {
1062    /// The name of the property.
1063    pub name: SmolStr,
1064    /// The value, or `None` for a property with none.
1065    pub value: Option<MdxAttributeValue>,
1066}
1067
1068#[derive(Debug, Clone, PartialEq)]
1069#[cfg_attr(
1070    feature = "json",
1071    derive(serde::Serialize, serde::Deserialize),
1072    serde(rename_all = "camelCase", tag = "type", content = "value")
1073)]
1074/// The value of a JSX property: a string, or an expression in braces.
1075pub enum MdxAttributeValue {
1076    /// An expression in braces.
1077    Expression(SmolStr),
1078    /// A string.
1079    Literal(SmolStr),
1080}
1081
1082/// An inline JSX element.
1083#[derive(Debug, Clone, PartialEq)]
1084#[cfg_attr(
1085    feature = "json",
1086    derive(serde::Serialize, serde::Deserialize),
1087    serde(rename_all = "camelCase", tag = "type")
1088)]
1089pub struct MdxJsxTextElement {
1090    /// The child nodes.
1091    pub children: Vec<Node>,
1092    /// Where the node is in the source, if known.
1093    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1094    pub position: Option<Position>,
1095    /// The element name, or `None` for a fragment.
1096    pub name: Option<SmolStr>,
1097    /// The attributes of the element.
1098    pub attributes: Vec<MdxAttributeContent>,
1099}
1100
1101/// An inline MDX expression.
1102#[derive(Debug, Clone, PartialEq)]
1103#[cfg_attr(
1104    feature = "json",
1105    derive(serde::Serialize, serde::Deserialize),
1106    serde(rename_all = "camelCase", tag = "type")
1107)]
1108pub struct MdxTextExpression {
1109    /// The source of the expression.
1110    pub value: SmolStr,
1111    /// Where the node is in the source, if known.
1112    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1113    pub position: Option<Position>,
1114}
1115
1116/// MDX ESM `import` or `export`.
1117#[derive(Debug, Clone, PartialEq)]
1118#[cfg_attr(
1119    feature = "json",
1120    derive(serde::Serialize, serde::Deserialize),
1121    serde(rename_all = "camelCase", tag = "type")
1122)]
1123pub struct MdxJsEsm {
1124    /// The source of the statements.
1125    pub value: SmolStr,
1126    /// Where the node is in the source, if known.
1127    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1128    pub position: Option<Position>,
1129}
1130
1131/// A block quote.
1132#[derive(Debug, Clone, PartialEq)]
1133#[cfg_attr(
1134    feature = "json",
1135    derive(serde::Serialize, serde::Deserialize),
1136    serde(rename_all = "camelCase", tag = "type")
1137)]
1138pub struct Blockquote {
1139    /// Child nodes.
1140    pub values: Vec<Node>,
1141    /// Where the node is in the source, if known.
1142    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1143    pub position: Option<Position>,
1144}
1145
1146/// Strikethrough text.
1147#[derive(Debug, Clone, PartialEq)]
1148#[cfg_attr(
1149    feature = "json",
1150    derive(serde::Serialize, serde::Deserialize),
1151    serde(rename_all = "camelCase", tag = "type")
1152)]
1153pub struct Delete {
1154    /// Child nodes.
1155    pub values: Vec<Node>,
1156    /// Where the node is in the source, if known.
1157    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1158    pub position: Option<Position>,
1159}
1160
1161/// Emphasized text.
1162#[derive(Debug, Clone, PartialEq)]
1163#[cfg_attr(
1164    feature = "json",
1165    derive(serde::Serialize, serde::Deserialize),
1166    serde(rename_all = "camelCase", tag = "type")
1167)]
1168pub struct Emphasis {
1169    /// Child nodes.
1170    pub values: Vec<Node>,
1171    /// Where the node is in the source, if known.
1172    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1173    pub position: Option<Position>,
1174}
1175
1176/// Strongly emphasized text.
1177#[derive(Debug, Clone, PartialEq)]
1178#[cfg_attr(
1179    feature = "json",
1180    derive(serde::Serialize, serde::Deserialize),
1181    serde(rename_all = "camelCase", tag = "type")
1182)]
1183pub struct Strong {
1184    /// Child nodes.
1185    pub values: Vec<Node>,
1186    /// Where the node is in the source, if known.
1187    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1188    pub position: Option<Position>,
1189}
1190
1191/// A hard line break.
1192#[derive(Debug, Clone, PartialEq)]
1193#[cfg_attr(
1194    feature = "json",
1195    derive(serde::Serialize, serde::Deserialize),
1196    serde(rename_all = "camelCase", tag = "type")
1197)]
1198pub struct Break {
1199    /// Where the node is in the source, if known.
1200    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1201    pub position: Option<Position>,
1202}
1203
1204/// A thematic break.
1205#[derive(Debug, Clone, PartialEq)]
1206#[cfg_attr(
1207    feature = "json",
1208    derive(serde::Serialize, serde::Deserialize),
1209    serde(rename_all = "camelCase", tag = "type")
1210)]
1211pub struct HorizontalRule {
1212    /// Source marker. `None` renders as `***`.
1213    #[cfg_attr(feature = "json", serde(default, skip_serializing_if = "Option::is_none"))]
1214    pub marker: Option<HorizontalRuleMarker>,
1215    /// Where the node is in the source, if known.
1216    #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1217    pub position: Option<Position>,
1218}
1219
1220/// A Markdown node.
1221#[derive(Debug, Clone, Default)]
1222#[cfg_attr(
1223    feature = "json",
1224    derive(serde::Serialize, serde::Deserialize),
1225    serde(rename_all = "camelCase", untagged)
1226)]
1227pub enum Node {
1228    /// A block quote.
1229    Blockquote(Blockquote),
1230    /// A hard line break.
1231    Break(Break),
1232    /// An Obsidian-style callout.
1233    #[cfg(feature = "callout")]
1234    Callout(Callout),
1235    /// An Obsidian-style file embed.
1236    #[cfg(feature = "embed")]
1237    Embed(Embed),
1238    /// A link reference definition.
1239    Definition(Definition),
1240    /// Strikethrough text.
1241    Delete(Delete),
1242    /// A heading.
1243    Heading(Heading),
1244    /// Emphasized text.
1245    Emphasis(Emphasis),
1246    /// A footnote definition.
1247    Footnote(Footnote),
1248    /// A footnote reference.
1249    FootnoteRef(FootnoteRef),
1250    /// Raw HTML.
1251    Html(Html),
1252    /// YAML front matter.
1253    Yaml(Yaml),
1254    /// TOML front matter.
1255    Toml(Toml),
1256    /// An inline image.
1257    Image(Image),
1258    /// A reference-style image.
1259    ImageRef(ImageRef),
1260    /// Inline code.
1261    CodeInline(CodeInline),
1262    /// Inline math.
1263    MathInline(MathInline),
1264    /// An inline link.
1265    Link(Link),
1266    /// A reference-style link.
1267    LinkRef(LinkRef),
1268    /// An Obsidian-style wikilink.
1269    #[cfg(feature = "wikilink")]
1270    WikiLink(WikiLink),
1271    /// A math block.
1272    Math(Math),
1273    /// A list item.
1274    List(List),
1275    /// The delimiter row of a table, giving the column alignments.
1276    TableAlign(TableAlign),
1277    /// A table row.
1278    TableRow(TableRow),
1279    /// A table cell.
1280    TableCell(TableCell),
1281    /// A code block.
1282    Code(Code),
1283    /// Strongly emphasized text.
1284    Strong(Strong),
1285    /// A thematic break.
1286    HorizontalRule(HorizontalRule),
1287    /// A block-level MDX expression.
1288    MdxFlowExpression(MdxFlowExpression),
1289    /// A block-level JSX element.
1290    MdxJsxFlowElement(MdxJsxFlowElement),
1291    /// An inline JSX element.
1292    MdxJsxTextElement(MdxJsxTextElement),
1293    /// An inline MDX expression.
1294    MdxTextExpression(MdxTextExpression),
1295    /// MDX ESM `import` or `export`.
1296    MdxJsEsm(MdxJsEsm),
1297    /// Plain text.
1298    Text(Text),
1299    /// A sequence of nodes with no wrapper.
1300    Fragment(Fragment),
1301    /// An empty node.
1302    #[default]
1303    Empty,
1304}
1305
1306impl PartialEq for Node {
1307    fn eq(&self, other: &Self) -> bool {
1308        self.to_string() == other.to_string()
1309    }
1310}
1311
1312impl PartialOrd for Node {
1313    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1314        let (self_node, other_node) = (self, other);
1315        let self_pos = self_node.position();
1316        let other_pos = other_node.position();
1317
1318        match (self_pos, other_pos) {
1319            (Some(self_pos), Some(other_pos)) => match self_pos.start.line.cmp(&other_pos.start.line) {
1320                std::cmp::Ordering::Equal => self_pos.start.column.partial_cmp(&other_pos.start.column),
1321                ordering => Some(ordering),
1322            },
1323            (Some(_), None) => Some(std::cmp::Ordering::Less),
1324            (None, Some(_)) => Some(std::cmp::Ordering::Greater),
1325            (None, None) => Some(self.name().cmp(&other.name())),
1326        }
1327    }
1328}
1329
1330/// A span of the source.
1331#[derive(Debug, Clone, PartialEq)]
1332#[cfg_attr(
1333    feature = "json",
1334    derive(serde::Serialize, serde::Deserialize),
1335    serde(rename_all = "camelCase")
1336)]
1337pub struct Position {
1338    /// Where the node starts.
1339    pub start: Point,
1340    /// Where the node ends.
1341    pub end: Point,
1342}
1343
1344/// A location in the source.
1345#[derive(Debug, Clone, PartialEq, Eq)]
1346#[cfg_attr(
1347    feature = "json",
1348    derive(serde::Serialize, serde::Deserialize),
1349    serde(rename_all = "camelCase")
1350)]
1351pub struct Point {
1352    /// The one-based line.
1353    pub line: u32,
1354    /// The one-based column, counted in UTF-16 code units. A tab is one column.
1355    pub column: u32,
1356}
1357
1358impl From<String> for Node {
1359    fn from(value: String) -> Self {
1360        Self::Text(Text { value, position: None })
1361    }
1362}
1363
1364impl From<&str> for Node {
1365    fn from(value: &str) -> Self {
1366        Self::Text(Text {
1367            value: value.to_string(),
1368            position: None,
1369        })
1370    }
1371}
1372
1373impl Display for Node {
1374    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1375        write!(f, "{}", self.to_string_with(&RenderOptions::default()))
1376    }
1377}
1378
1379impl Node {
1380    /// Maps this node and its fragment descendants, cloning the input tree first.
1381    pub fn map_values<E, F>(&self, f: &mut F) -> Result<Node, E>
1382    where
1383        E: std::error::Error,
1384        F: FnMut(&Node) -> Result<Node, E>,
1385    {
1386        self.clone().map_values_into(f)
1387    }
1388
1389    /// Maps this node and its fragment descendants, consuming the input tree.
1390    ///
1391    /// Prefer this over [`Self::map_values`] when the caller owns the node and does not need to
1392    /// retain an unchanged copy.
1393    pub fn map_values_into<E, F>(self, f: &mut F) -> Result<Node, E>
1394    where
1395        E: std::error::Error,
1396        F: FnMut(&Node) -> Result<Node, E>,
1397    {
1398        Self::_map_values(self, f)
1399    }
1400
1401    /// Maps this node and its fragment descendants, giving the callback ownership of each node.
1402    ///
1403    /// This is useful when a transform must retain an unchanged fallback node without cloning it
1404    /// again after the callback returns. The traversal continues through a fragment returned by
1405    /// the callback, matching [`Self::map_values_into`]'s behavior.
1406    pub fn map_values_into_owned<E, F>(self, f: &mut F) -> Result<Node, E>
1407    where
1408        E: std::error::Error,
1409        F: FnMut(Node) -> Result<Node, E>,
1410    {
1411        Self::_map_values_owned(self, f)
1412    }
1413
1414    fn _map_values<E, F>(node: Node, f: &mut F) -> Result<Node, E>
1415    where
1416        E: std::error::Error,
1417        F: FnMut(&Node) -> Result<Node, E>,
1418    {
1419        match f(&node)? {
1420            Node::Fragment(mut v) => {
1421                let values = v
1422                    .values
1423                    .into_iter()
1424                    .map(|node| Self::_map_values(node, f))
1425                    .collect::<Result<Vec<_>, _>>();
1426                match values {
1427                    Ok(values) => {
1428                        v.values = values;
1429                        Ok(Node::Fragment(v))
1430                    }
1431                    Err(e) => Err(e),
1432                }
1433            }
1434            node => Ok(node),
1435        }
1436    }
1437
1438    fn _map_values_owned<E, F>(node: Node, f: &mut F) -> Result<Node, E>
1439    where
1440        E: std::error::Error,
1441        F: FnMut(Node) -> Result<Node, E>,
1442    {
1443        match f(node)? {
1444            Node::Fragment(mut v) => {
1445                let values = v
1446                    .values
1447                    .into_iter()
1448                    .map(|node| Self::_map_values_owned(node, f))
1449                    .collect::<Result<Vec<_>, _>>();
1450                match values {
1451                    Ok(values) => {
1452                        v.values = values;
1453                        Ok(Node::Fragment(v))
1454                    }
1455                    Err(e) => Err(e),
1456                }
1457            }
1458            node => Ok(node),
1459        }
1460    }
1461
1462    /// Converts a clone of this node into a fragment of its children.
1463    pub fn to_fragment(&self) -> Node {
1464        self.clone().into_fragment()
1465    }
1466
1467    /// Converts this node into a fragment, preserving its children without cloning them.
1468    ///
1469    /// Leaf nodes become [`Node::Empty`]. This is the consuming counterpart to
1470    /// [`Self::to_fragment`].
1471    pub fn into_fragment(mut self) -> Node {
1472        if let Some(values) = self.fragment_values_mut() {
1473            return Self::Fragment(Fragment {
1474                values: std::mem::take(values),
1475            });
1476        }
1477        match self {
1478            node @ Node::Fragment(_) => node,
1479            _ => Self::Empty,
1480        }
1481    }
1482
1483    /// Replaces the children of this node with those of `fragment`.
1484    pub fn apply_fragment(&mut self, fragment: Node) {
1485        Self::_apply_fragment(self, fragment)
1486    }
1487
1488    fn _apply_fragment(node: &mut Node, fragment: Node) {
1489        let (Some(values), Node::Fragment(Fragment { values: new_values })) = (node.fragment_values_mut(), fragment)
1490        else {
1491            return;
1492        };
1493        let new_values = values
1494            .iter()
1495            .zip(new_values)
1496            .map(|(current_value, new_value)| {
1497                if new_value.is_empty() {
1498                    current_value.clone()
1499                } else if new_value.is_fragment() {
1500                    let mut current_value = current_value.clone();
1501                    Self::_apply_fragment(&mut current_value, new_value);
1502                    current_value
1503                } else {
1504                    new_value
1505                }
1506            })
1507            .collect::<Vec<_>>();
1508        *values = new_values;
1509    }
1510
1511    /// The children of a node that has them, which [`Self::set_children`] replaces.
1512    fn children_mut(&mut self) -> Option<&mut Vec<Node>> {
1513        match self {
1514            Node::Footnote(Footnote { values, .. })
1515            | Node::Link(Link { values, .. })
1516            | Node::Heading(Heading { values, .. })
1517            | Node::List(List { values, .. })
1518            | Node::TableCell(TableCell { values, .. })
1519            | Node::TableRow(TableRow { values, .. })
1520            | Node::Strong(Strong { values, .. })
1521            | Node::Blockquote(Blockquote { values, .. })
1522            | Node::Delete(Delete { values, .. })
1523            | Node::Emphasis(Emphasis { values, .. })
1524            | Node::Fragment(Fragment { values }) => Some(values),
1525            #[cfg(feature = "callout")]
1526            Node::Callout(Callout { values, .. }) => Some(values),
1527            Node::MdxJsxFlowElement(MdxJsxFlowElement { children, .. })
1528            | Node::MdxJsxTextElement(MdxJsxTextElement { children, .. }) => Some(children),
1529            _ => None,
1530        }
1531    }
1532
1533    /// The children that a fragment made from this node holds, and that applying a fragment maps onto.
1534    fn fragment_values_mut(&mut self) -> Option<&mut Vec<Node>> {
1535        match self {
1536            Node::List(List { values, .. })
1537            | Node::TableCell(TableCell { values, .. })
1538            | Node::TableRow(TableRow { values, .. })
1539            | Node::Link(Link { values, .. })
1540            | Node::Footnote(Footnote { values, .. })
1541            | Node::LinkRef(LinkRef { values, .. })
1542            | Node::Heading(Heading { values, .. })
1543            | Node::Blockquote(Blockquote { values, .. })
1544            | Node::Delete(Delete { values, .. })
1545            | Node::Emphasis(Emphasis { values, .. })
1546            | Node::Strong(Strong { values, .. }) => Some(values),
1547            #[cfg(feature = "callout")]
1548            Node::Callout(Callout { values, .. }) => Some(values),
1549            _ => None,
1550        }
1551    }
1552
1553    /// The children whose value [`Self::into_with_children_value`] replaces and whose text position
1554    /// [`Self::clear_text_position_at`] clears.
1555    fn editable_values_mut(&mut self) -> Option<&mut Vec<Node>> {
1556        match self {
1557            Node::Blockquote(Blockquote { values, .. })
1558            | Node::Delete(Delete { values, .. })
1559            | Node::Emphasis(Emphasis { values, .. })
1560            | Node::List(List { values, .. })
1561            | Node::TableCell(TableCell { values, .. })
1562            | Node::Strong(Strong { values, .. })
1563            | Node::LinkRef(LinkRef { values, .. })
1564            | Node::Heading(Heading { values, .. }) => Some(values),
1565            #[cfg(feature = "callout")]
1566            Node::Callout(Callout { values, .. }) => Some(values),
1567            Node::MdxJsxFlowElement(MdxJsxFlowElement { children, .. })
1568            | Node::MdxJsxTextElement(MdxJsxTextElement { children, .. }) => Some(children),
1569            _ => None,
1570        }
1571    }
1572
1573    /// Returns the child nodes, or the node itself if it has none.
1574    pub fn node_values(&self) -> Vec<Node> {
1575        match self {
1576            Self::Blockquote(v) => v.values.clone(),
1577            Self::Delete(v) => v.values.clone(),
1578            Self::Heading(h) => h.values.clone(),
1579            Self::Emphasis(v) => v.values.clone(),
1580            Self::List(l) => l.values.clone(),
1581            Self::Strong(v) => v.values.clone(),
1582            #[cfg(feature = "callout")]
1583            Self::Callout(v) => v.values.clone(),
1584            _ => vec![self.clone()],
1585        }
1586    }
1587
1588    /// Returns the child at `index`, if any.
1589    pub fn find_at_index(&self, index: usize) -> Option<Node> {
1590        match self {
1591            Self::Blockquote(v) => v.values.get(index).cloned(),
1592            Self::Delete(v) => v.values.get(index).cloned(),
1593            Self::Emphasis(v) => v.values.get(index).cloned(),
1594            Self::Strong(v) => v.values.get(index).cloned(),
1595            Self::Heading(v) => v.values.get(index).cloned(),
1596            Self::List(v) => v.values.get(index).cloned(),
1597            Self::TableCell(v) => v.values.get(index).cloned(),
1598            Self::TableRow(v) => v.values.get(index).cloned(),
1599            #[cfg(feature = "callout")]
1600            Self::Callout(v) => v.values.get(index).cloned(),
1601            _ => None,
1602        }
1603    }
1604
1605    /// Returns the text content of the node.
1606    pub fn value(&self) -> String {
1607        match self {
1608            Self::Blockquote(v) => values_to_value(&v.values),
1609            Self::Definition(d) => d.url.as_str().to_string(),
1610            Self::Delete(v) => values_to_value(&v.values),
1611            Self::Heading(h) => values_to_value(&h.values),
1612            Self::Emphasis(v) => values_to_value(&v.values),
1613            Self::Footnote(f) => values_to_value(&f.values),
1614            Self::FootnoteRef(f) => f.ident.clone(),
1615            Self::Html(v) => v.value.clone(),
1616            Self::Yaml(v) => v.value.clone(),
1617            Self::Toml(v) => v.value.clone(),
1618            Self::Image(i) => i.url.clone(),
1619            Self::ImageRef(i) => i.ident.clone(),
1620            Self::CodeInline(v) => v.value.to_string(),
1621            Self::MathInline(v) => v.value.to_string(),
1622            Self::Link(l) => l.url.as_str().to_string(),
1623            Self::LinkRef(l) => l.ident.clone(),
1624            #[cfg(feature = "wikilink")]
1625            Self::WikiLink(w) => w.text.clone().unwrap_or_else(|| w.target.clone()),
1626            #[cfg(feature = "callout")]
1627            Self::Callout(v) => values_to_value(&v.values),
1628            #[cfg(feature = "embed")]
1629            Self::Embed(e) => e.display.clone().unwrap_or_else(|| e.target.clone()),
1630            Self::Math(v) => v.value.clone(),
1631            Self::List(l) => values_to_value(&l.values),
1632            Self::TableCell(c) => values_to_value(&c.values),
1633            Self::TableRow(c) => values_to_value(&c.values),
1634            Self::Code(c) => c.value.clone(),
1635            Self::Strong(v) => values_to_value(&v.values),
1636            Self::Text(t) => t.value.clone(),
1637            Self::Break { .. } => String::new(),
1638            Self::TableAlign(_) => String::new(),
1639            Self::MdxFlowExpression(mdx) => mdx.value.to_string(),
1640            Self::MdxJsxFlowElement(mdx) => values_to_value(&mdx.children),
1641            Self::MdxTextExpression(mdx) => mdx.value.to_string(),
1642            Self::MdxJsxTextElement(mdx) => values_to_value(&mdx.children),
1643            Self::MdxJsEsm(mdx) => mdx.value.to_string(),
1644            Self::HorizontalRule { .. } => String::new(),
1645            Self::Fragment(v) => values_to_value(&v.values),
1646            Self::Empty => String::new(),
1647        }
1648    }
1649
1650    /// Returns the node name, such as `"heading"` or `"code"`.
1651    pub fn name(&self) -> SmolStr {
1652        match self {
1653            Self::Blockquote(_) => "blockquote".into(),
1654            Self::Break { .. } => "break".into(),
1655            Self::Definition(_) => "definition".into(),
1656            Self::Delete(_) => "delete".into(),
1657            Self::Heading(Heading { depth, .. }) => match depth.get() {
1658                1 => "h1".into(),
1659                2 => "h2".into(),
1660                3 => "h3".into(),
1661                4 => "h4".into(),
1662                5 => "h5".into(),
1663                _ => "h6".into(),
1664            },
1665            Self::Emphasis(_) => "emphasis".into(),
1666            Self::Footnote(_) => "footnote".into(),
1667            Self::FootnoteRef(_) => "footnoteref".into(),
1668            Self::Html(_) => "html".into(),
1669            Self::Yaml(_) => "yaml".into(),
1670            Self::Toml(_) => "toml".into(),
1671            Self::Image(_) => "image".into(),
1672            Self::ImageRef(_) => "image_ref".into(),
1673            Self::CodeInline(_) => "code_inline".into(),
1674            Self::MathInline(_) => "math_inline".into(),
1675            Self::Link(_) => "link".into(),
1676            Self::LinkRef(_) => "link_ref".into(),
1677            #[cfg(feature = "wikilink")]
1678            Self::WikiLink(_) => "wikilink".into(),
1679            #[cfg(feature = "callout")]
1680            Self::Callout(_) => "callout".into(),
1681            #[cfg(feature = "embed")]
1682            Self::Embed(_) => "embed".into(),
1683            Self::Math(_) => "math".into(),
1684            Self::List(_) => "list".into(),
1685            Self::TableAlign(_) => "table_align".into(),
1686            Self::TableRow(_) => "table_row".into(),
1687            Self::TableCell(_) => "table_cell".into(),
1688            Self::Code(_) => "code".into(),
1689            Self::Strong(_) => "strong".into(),
1690            Self::HorizontalRule { .. } => "Horizontal_rule".into(),
1691            Self::MdxFlowExpression(_) => "mdx_flow_expression".into(),
1692            Self::MdxJsxFlowElement(_) => "mdx_jsx_flow_element".into(),
1693            Self::MdxJsxTextElement(_) => "mdx_jsx_text_element".into(),
1694            Self::MdxTextExpression(_) => "mdx_text_expression".into(),
1695            Self::MdxJsEsm(_) => "mdx_js_esm".into(),
1696            Self::Text(_) => "text".into(),
1697            Self::Fragment(_) | Self::Empty => "".into(),
1698        }
1699    }
1700
1701    /// Get the children nodes of the current node.
1702    pub fn children(&self) -> Vec<Node> {
1703        match self.attr(CHILDREN) {
1704            Some(AttrValue::Array(children)) => children,
1705            _ => Vec::new(),
1706        }
1707    }
1708
1709    /// Sets the children nodes of the current node, if the node supports children.
1710    /// Nodes without children (e.g. `Text`, `Code`, `Image`) are left unchanged.
1711    pub fn set_children(&mut self, children: Vec<Node>) {
1712        if let Some(values) = self.children_mut() {
1713            *values = children;
1714        }
1715    }
1716
1717    /// Sets the position of the node.
1718    pub fn set_position(&mut self, pos: Option<Position>) {
1719        match self {
1720            Self::Blockquote(v) => v.position = pos,
1721            Self::Definition(d) => d.position = pos,
1722            Self::Delete(v) => v.position = pos,
1723            Self::Heading(h) => h.position = pos,
1724            Self::Emphasis(v) => v.position = pos,
1725            Self::Footnote(f) => f.position = pos,
1726            Self::FootnoteRef(f) => f.position = pos,
1727            Self::Html(v) => v.position = pos,
1728            Self::Yaml(v) => v.position = pos,
1729            Self::Toml(v) => v.position = pos,
1730            Self::Image(i) => i.position = pos,
1731            Self::ImageRef(i) => i.position = pos,
1732            Self::CodeInline(v) => v.position = pos,
1733            Self::MathInline(v) => v.position = pos,
1734            Self::Link(l) => l.position = pos,
1735            Self::LinkRef(l) => l.position = pos,
1736            #[cfg(feature = "wikilink")]
1737            Self::WikiLink(w) => w.position = pos,
1738            #[cfg(feature = "callout")]
1739            Self::Callout(c) => c.position = pos,
1740            #[cfg(feature = "embed")]
1741            Self::Embed(e) => e.position = pos,
1742            Self::Math(v) => v.position = pos,
1743            Self::Code(c) => c.position = pos,
1744            Self::TableCell(c) => c.position = pos,
1745            Self::TableRow(r) => r.position = pos,
1746            Self::TableAlign(c) => c.position = pos,
1747            Self::List(l) => l.position = pos,
1748            Self::Strong(s) => s.position = pos,
1749            Self::MdxFlowExpression(m) => m.position = pos,
1750            Self::MdxTextExpression(m) => m.position = pos,
1751            Self::MdxJsEsm(m) => m.position = pos,
1752            Self::MdxJsxFlowElement(m) => m.position = pos,
1753            Self::MdxJsxTextElement(m) => m.position = pos,
1754            Self::Break(b) => b.position = pos,
1755            Self::HorizontalRule(h) => h.position = pos,
1756            Self::Text(t) => t.position = pos,
1757            Self::Fragment(_) | Self::Empty => {}
1758        }
1759    }
1760
1761    /// Returns the position of the node, if known.
1762    pub fn position(&self) -> Option<Position> {
1763        match self {
1764            Self::Blockquote(v) => v.position.clone(),
1765            Self::Definition(d) => d.position.clone(),
1766            Self::Delete(v) => v.position.clone(),
1767            Self::Heading(h) => h.position.clone(),
1768            Self::Emphasis(v) => v.position.clone(),
1769            Self::Footnote(f) => f.position.clone(),
1770            Self::FootnoteRef(f) => f.position.clone(),
1771            Self::Html(v) => v.position.clone(),
1772            Self::Yaml(v) => v.position.clone(),
1773            Self::Toml(v) => v.position.clone(),
1774            Self::Image(i) => i.position.clone(),
1775            Self::ImageRef(i) => i.position.clone(),
1776            Self::CodeInline(v) => v.position.clone(),
1777            Self::MathInline(v) => v.position.clone(),
1778            Self::Link(l) => l.position.clone(),
1779            Self::LinkRef(l) => l.position.clone(),
1780            #[cfg(feature = "wikilink")]
1781            Self::WikiLink(w) => w.position.clone(),
1782            #[cfg(feature = "callout")]
1783            Self::Callout(c) => c.position.clone(),
1784            #[cfg(feature = "embed")]
1785            Self::Embed(e) => e.position.clone(),
1786            Self::Math(v) => v.position.clone(),
1787            Self::Code(c) => c.position.clone(),
1788            Self::TableCell(c) => c.position.clone(),
1789            Self::TableRow(r) => r.position.clone(),
1790            Self::TableAlign(c) => c.position.clone(),
1791            Self::List(l) => l.position.clone(),
1792            Self::Strong(s) => s.position.clone(),
1793            Self::MdxFlowExpression(m) => m.position.clone(),
1794            Self::MdxTextExpression(m) => m.position.clone(),
1795            Self::MdxJsEsm(m) => m.position.clone(),
1796            Self::MdxJsxFlowElement(m) => m.position.clone(),
1797            Self::MdxJsxTextElement(m) => m.position.clone(),
1798            Self::Break(b) => b.position.clone(),
1799            Self::Text(t) => t.position.clone(),
1800            Self::HorizontalRule(h) => h.position.clone(),
1801            Self::Fragment(v) => {
1802                let positions: Vec<Position> = v.values.iter().filter_map(|node| node.position()).collect();
1803
1804                match (positions.first(), positions.last()) {
1805                    (Some(start), Some(end)) => Some(Position {
1806                        start: start.start.clone(),
1807                        end: end.end.clone(),
1808                    }),
1809                    _ => None,
1810                }
1811            }
1812            Self::Empty => None,
1813        }
1814    }
1815
1816    /// Recursively clears position information from this node and all of its children.
1817    /// Useful for shrinking structured output (JSON, YAML, etc.) when source spans
1818    /// aren't needed, since `Position` accounts for most of a serialized node's size.
1819    pub fn strip_positions(&mut self) {
1820        self.set_position(None);
1821        let mut children = self.children();
1822        if !children.is_empty() {
1823            for child in children.iter_mut() {
1824                child.strip_positions();
1825            }
1826            self.set_children(children);
1827        }
1828    }
1829
1830    fn clear_position_at(values: &mut [Node], index: usize) {
1831        if let Some(slot) = values.get_mut(index) {
1832            slot.clear_text_position_at(0);
1833        }
1834    }
1835
1836    /// Clears the position of just the `Text` leaf that `into_with_value` /
1837    /// `into_with_children_value` would write into at `index`, leaving this node and other
1838    /// descendants untouched. Used to stop the renderer re-escaping an already-escaped leaf.
1839    pub fn clear_text_position_at(&mut self, index: usize) {
1840        if let Self::Text(text) = self {
1841            text.position = None;
1842        } else if let Some(values) = self.editable_values_mut() {
1843            Self::clear_position_at(values, index);
1844        }
1845    }
1846
1847    /// Returns `true` if this node is empty.
1848    pub fn is_empty(&self) -> bool {
1849        matches!(self, Self::Empty)
1850    }
1851
1852    /// Returns `true` if this node is a fragment.
1853    pub fn is_fragment(&self) -> bool {
1854        matches!(self, Self::Fragment(_))
1855    }
1856
1857    /// Returns `true` if this node is a fragment with no nodes.
1858    pub fn is_empty_fragment(&self) -> bool {
1859        if let Self::Fragment(_) = self {
1860            Self::_fragment_inner_nodes(self).is_empty()
1861        } else {
1862            false
1863        }
1864    }
1865
1866    fn _fragment_inner_nodes(node: &Node) -> Vec<Node> {
1867        if let Self::Fragment(fragment) = node {
1868            fragment.values.iter().flat_map(Self::_fragment_inner_nodes).collect()
1869        } else if node.is_empty() {
1870            Vec::new()
1871        } else {
1872            vec![node.clone()]
1873        }
1874    }
1875
1876    /// Returns `true` if this node is inline code.
1877    pub fn is_inline_code(&self) -> bool {
1878        matches!(self, Self::CodeInline(_))
1879    }
1880
1881    /// Returns `true` if this node is inline math.
1882    pub fn is_inline_math(&self) -> bool {
1883        matches!(self, Self::MathInline(_))
1884    }
1885
1886    /// Returns `true` if this node is strongly emphasized text.
1887    pub fn is_strong(&self) -> bool {
1888        matches!(self, Self::Strong(_))
1889    }
1890
1891    /// Returns `true` if this node is a list item.
1892    pub fn is_list(&self) -> bool {
1893        matches!(self, Self::List(_))
1894    }
1895
1896    /// Returns `true` if this node is emphasized text.
1897    pub fn is_emphasis(&self) -> bool {
1898        matches!(self, Self::Emphasis(_))
1899    }
1900
1901    /// Returns `true` if this node is a strikethrough.
1902    pub fn is_delete(&self) -> bool {
1903        matches!(self, Self::Delete(_))
1904    }
1905
1906    /// Returns `true` if this node is a link.
1907    pub fn is_link(&self) -> bool {
1908        #[cfg(feature = "wikilink")]
1909        {
1910            matches!(self, Self::Link(_) | Self::WikiLink(_))
1911        }
1912        #[cfg(not(feature = "wikilink"))]
1913        {
1914            matches!(self, Self::Link(_))
1915        }
1916    }
1917
1918    /// Returns `true` if this node is a reference-style link.
1919    pub fn is_link_ref(&self) -> bool {
1920        matches!(self, Self::LinkRef(_))
1921    }
1922
1923    /// Returns `true` if this node is an Obsidian-style wikilink (`[[target]]`).
1924    #[cfg(feature = "wikilink")]
1925    pub fn is_wikilink(&self) -> bool {
1926        matches!(self, Self::WikiLink(_))
1927    }
1928
1929    /// Returns `true` if this node is an Obsidian-style callout (`> [!TYPE]`).
1930    #[cfg(feature = "callout")]
1931    pub fn is_callout(&self) -> bool {
1932        matches!(self, Self::Callout(_))
1933    }
1934
1935    /// Returns `true` if this node is an Obsidian-style embed (`![[target]]`).
1936    #[cfg(feature = "embed")]
1937    pub fn is_embed(&self) -> bool {
1938        matches!(self, Self::Embed(_))
1939    }
1940
1941    /// Returns `true` if this node is a text node.
1942    pub fn is_text(&self) -> bool {
1943        matches!(self, Self::Text(_))
1944    }
1945
1946    /// Returns `true` if this node is an image.
1947    pub fn is_image(&self) -> bool {
1948        matches!(self, Self::Image(_))
1949    }
1950
1951    /// Returns `true` if this node is a thematic break.
1952    pub fn is_horizontal_rule(&self) -> bool {
1953        matches!(self, Self::HorizontalRule { .. })
1954    }
1955
1956    /// Returns `true` if this node is a block quote.
1957    pub fn is_blockquote(&self) -> bool {
1958        matches!(self, Self::Blockquote(_))
1959    }
1960
1961    /// True for the nodes that make up the text of a paragraph.
1962    pub(crate) fn is_paragraph_text(&self) -> bool {
1963        #[cfg(feature = "wikilink")]
1964        if matches!(self, Self::WikiLink(_)) {
1965            return true;
1966        }
1967        #[cfg(feature = "embed")]
1968        if matches!(self, Self::Embed(_)) {
1969            return true;
1970        }
1971        matches!(
1972            self,
1973            Self::Text(_)
1974                | Self::Emphasis(_)
1975                | Self::Strong(_)
1976                | Self::Delete(_)
1977                | Self::CodeInline(_)
1978                | Self::MathInline(_)
1979                | Self::Link(_)
1980                | Self::LinkRef(_)
1981                | Self::Image(_)
1982                | Self::ImageRef(_)
1983                | Self::FootnoteRef(_)
1984                | Self::Html(_)
1985                | Self::MdxJsxTextElement(_)
1986                | Self::MdxTextExpression(_)
1987        )
1988    }
1989
1990    /// True for block quotes and (when enabled) Obsidian-style callouts.
1991    pub(crate) fn is_blockquote_like(&self) -> bool {
1992        match self {
1993            Self::Blockquote(_) => true,
1994            #[cfg(feature = "callout")]
1995            Self::Callout(_) => true,
1996            _ => false,
1997        }
1998    }
1999
2000    /// Returns `true` if this node is a raw HTML node.
2001    pub fn is_html(&self) -> bool {
2002        matches!(self, Self::Html { .. })
2003    }
2004
2005    /// Returns `true` if this node is a footnote definition.
2006    pub fn is_footnote(&self) -> bool {
2007        matches!(self, Self::Footnote(_))
2008    }
2009
2010    /// Returns `true` if this node is a block-level JSX element.
2011    pub fn is_mdx_jsx_flow_element(&self) -> bool {
2012        matches!(self, Self::MdxJsxFlowElement(MdxJsxFlowElement { .. }))
2013    }
2014
2015    /// Returns `true` if this node is an MDX ESM statement.
2016    pub fn is_mdx_js_esm(&self) -> bool {
2017        matches!(self, Self::MdxJsEsm(MdxJsEsm { .. }))
2018    }
2019
2020    /// Returns `true` if this node is TOML front matter.
2021    pub fn is_toml(&self) -> bool {
2022        matches!(self, Self::Toml { .. })
2023    }
2024
2025    /// Returns `true` if this node is YAML front matter.
2026    pub fn is_yaml(&self) -> bool {
2027        matches!(self, Self::Yaml { .. })
2028    }
2029
2030    /// Returns `true` if this node is a hard line break.
2031    pub fn is_break(&self) -> bool {
2032        matches!(self, Self::Break { .. })
2033    }
2034
2035    /// Returns `true` if this node is an inline MDX expression.
2036    pub fn is_mdx_text_expression(&self) -> bool {
2037        matches!(self, Self::MdxTextExpression(MdxTextExpression { .. }))
2038    }
2039
2040    /// Returns `true` if this node is a footnote reference.
2041    pub fn is_footnote_ref(&self) -> bool {
2042        matches!(self, Self::FootnoteRef { .. })
2043    }
2044
2045    /// Returns `true` if this node is a reference-style image.
2046    pub fn is_image_ref(&self) -> bool {
2047        matches!(self, Self::ImageRef(_))
2048    }
2049
2050    /// Returns `true` if this node is an inline JSX element.
2051    pub fn is_mdx_jsx_text_element(&self) -> bool {
2052        matches!(self, Self::MdxJsxTextElement(MdxJsxTextElement { .. }))
2053    }
2054
2055    /// Returns `true` if this node is a math block.
2056    pub fn is_math(&self) -> bool {
2057        matches!(self, Self::Math(_))
2058    }
2059
2060    /// Returns `true` if this node is a block-level MDX expression.
2061    pub fn is_mdx_flow_expression(&self) -> bool {
2062        matches!(self, Self::MdxFlowExpression(MdxFlowExpression { .. }))
2063    }
2064
2065    /// Returns `true` if this node is a link reference definition.
2066    pub fn is_definition(&self) -> bool {
2067        matches!(self, Self::Definition(_))
2068    }
2069
2070    /// Returns `true` if this node is a table delimiter row.
2071    pub fn is_table_align(&self) -> bool {
2072        matches!(self, Self::TableAlign(_))
2073    }
2074
2075    /// Returns `true` if this node is a code block, of language `lang` when given.
2076    pub fn is_code(&self, lang: Option<SmolStr>) -> bool {
2077        if let Self::Code(Code { lang: node_lang, .. }) = &self {
2078            if lang.is_none() {
2079                true
2080            } else {
2081                node_lang.clone().unwrap_or_default() == lang.unwrap_or_default()
2082            }
2083        } else {
2084            false
2085        }
2086    }
2087
2088    /// Returns `true` if this node is a heading, of depth `depth` when given.
2089    pub fn is_heading(&self, depth: Option<u8>) -> bool {
2090        if let Self::Heading(Heading {
2091            depth: heading_depth, ..
2092        }) = &self
2093        {
2094            depth.is_none_or(|depth| heading_depth.get() == depth)
2095        } else {
2096            false
2097        }
2098    }
2099
2100    fn replace_value_at(values: &mut [Node], index: usize, value: &str) {
2101        if let Some(slot) = values.get_mut(index) {
2102            let node = std::mem::replace(slot, Self::Empty);
2103            *slot = node.into_with_value(value);
2104        }
2105    }
2106
2107    /// Returns a clone of this node with its value replaced.
2108    pub fn with_value(&self, value: &str) -> Self {
2109        self.clone().into_with_value(value)
2110    }
2111
2112    /// Replaces this node's value while consuming the original tree.
2113    ///
2114    /// Prefer this over [`Self::with_value`] when the caller owns the node and does not need an
2115    /// unchanged copy.
2116    pub fn into_with_value(self, value: &str) -> Self {
2117        match self {
2118            Self::Blockquote(mut v) => {
2119                Self::replace_value_at(&mut v.values, 0, value);
2120
2121                Self::Blockquote(v)
2122            }
2123            Self::Delete(mut v) => {
2124                Self::replace_value_at(&mut v.values, 0, value);
2125
2126                Self::Delete(v)
2127            }
2128            Self::Emphasis(mut v) => {
2129                Self::replace_value_at(&mut v.values, 0, value);
2130
2131                Self::Emphasis(v)
2132            }
2133            Self::Html(mut html) => {
2134                html.value = value.to_string();
2135                Self::Html(html)
2136            }
2137            Self::Yaml(mut yaml) => {
2138                yaml.value = value.to_string();
2139                Self::Yaml(yaml)
2140            }
2141            Self::Toml(mut toml) => {
2142                toml.value = value.to_string();
2143                Self::Toml(toml)
2144            }
2145            Self::CodeInline(mut code) => {
2146                code.value = value.into();
2147                Self::CodeInline(code)
2148            }
2149            Self::MathInline(mut math) => {
2150                math.value = value.into();
2151                Self::MathInline(math)
2152            }
2153            Self::Math(mut math) => {
2154                math.value = value.to_string();
2155                Self::Math(math)
2156            }
2157            Self::List(mut v) => {
2158                Self::replace_value_at(&mut v.values, 0, value);
2159
2160                Self::List(v)
2161            }
2162            Self::TableCell(mut v) => {
2163                Self::replace_value_at(&mut v.values, 0, value);
2164
2165                Self::TableCell(v)
2166            }
2167            Self::TableRow(mut row) => {
2168                row.values = row
2169                    .values
2170                    .into_iter()
2171                    .zip(value.split(","))
2172                    .map(|(cell, value)| cell.into_with_value(value))
2173                    .collect::<Vec<_>>();
2174
2175                Self::TableRow(row)
2176            }
2177            Self::Strong(mut v) => {
2178                Self::replace_value_at(&mut v.values, 0, value);
2179
2180                Self::Strong(v)
2181            }
2182            Self::Code(mut code) => {
2183                code.value = value.to_string();
2184                Self::Code(code)
2185            }
2186            Self::Image(mut image) => {
2187                image.url = value.to_string();
2188                Self::Image(image)
2189            }
2190            Self::ImageRef(mut image) => {
2191                image.ident = value.to_string();
2192                image.label = Some(value.to_string());
2193                Self::ImageRef(image)
2194            }
2195            Self::Link(mut link) => {
2196                link.url = Url(value.to_string());
2197                Self::Link(link)
2198            }
2199            Self::LinkRef(mut v) => {
2200                v.label = Some(value.to_string());
2201                v.ident = value.to_string();
2202                Self::LinkRef(v)
2203            }
2204            Self::Footnote(mut footnote) => {
2205                footnote.ident = value.to_string();
2206                Self::Footnote(footnote)
2207            }
2208            Self::FootnoteRef(mut footnote) => {
2209                footnote.ident = value.to_string();
2210                footnote.label = Some(value.to_string());
2211                Self::FootnoteRef(footnote)
2212            }
2213            Self::Heading(mut v) => {
2214                Self::replace_value_at(&mut v.values, 0, value);
2215
2216                Self::Heading(v)
2217            }
2218            Self::Definition(mut def) => {
2219                def.url = Url(value.to_string());
2220                Self::Definition(def)
2221            }
2222            node @ Self::Break { .. } => node,
2223            node @ Self::TableAlign(_) => node,
2224            node @ Self::HorizontalRule { .. } => node,
2225            Self::Text(mut text) => {
2226                text.value = value.to_string();
2227                Self::Text(text)
2228            }
2229            Self::MdxFlowExpression(mut mdx) => {
2230                mdx.value = value.into();
2231                Self::MdxFlowExpression(mdx)
2232            }
2233            Self::MdxTextExpression(mut mdx) => {
2234                mdx.value = value.into();
2235                Self::MdxTextExpression(mdx)
2236            }
2237            Self::MdxJsEsm(mut mdx) => {
2238                mdx.value = value.into();
2239                Self::MdxJsEsm(mdx)
2240            }
2241            Self::MdxJsxFlowElement(mut mdx) => {
2242                Self::replace_value_at(&mut mdx.children, 0, value);
2243
2244                Self::MdxJsxFlowElement(MdxJsxFlowElement {
2245                    name: mdx.name,
2246                    attributes: mdx.attributes,
2247                    children: mdx.children,
2248                    ..mdx
2249                })
2250            }
2251            Self::MdxJsxTextElement(mut mdx) => {
2252                Self::replace_value_at(&mut mdx.children, 0, value);
2253
2254                Self::MdxJsxTextElement(MdxJsxTextElement {
2255                    name: mdx.name,
2256                    attributes: mdx.attributes,
2257                    children: mdx.children,
2258                    ..mdx
2259                })
2260            }
2261            node @ Self::Fragment(_) | node @ Self::Empty => node,
2262            #[cfg(feature = "wikilink")]
2263            Self::WikiLink(mut w) => {
2264                if w.text.is_some() {
2265                    w.text = Some(value.to_string());
2266                } else {
2267                    w.target = value.to_string();
2268                }
2269                Self::WikiLink(w)
2270            }
2271            #[cfg(feature = "callout")]
2272            Self::Callout(mut c) => {
2273                Self::replace_value_at(&mut c.values, 0, value);
2274                Self::Callout(c)
2275            }
2276            #[cfg(feature = "embed")]
2277            Self::Embed(mut e) => {
2278                if e.display.is_some() {
2279                    e.display = Some(value.to_string());
2280                } else {
2281                    e.target = value.to_string();
2282                }
2283                Self::Embed(e)
2284            }
2285        }
2286    }
2287
2288    /// Returns a clone of this node with the selected child's value replaced.
2289    pub fn with_children_value(&self, value: &str, index: usize) -> Self {
2290        self.clone().into_with_children_value(value, index)
2291    }
2292
2293    /// Replaces a selected child's value while consuming the original tree.
2294    ///
2295    /// Prefer this over [`Self::with_children_value`] when the caller owns the node and does not
2296    /// need an unchanged copy.
2297    pub fn into_with_children_value(mut self, value: &str, index: usize) -> Self {
2298        if let Some(values) = self.editable_values_mut() {
2299            Self::replace_value_at(values, index, value);
2300        }
2301        self
2302    }
2303}
2304
2305fn values_to_value(values: &[Node]) -> String {
2306    values.iter().map(|value| value.value()).collect::<String>()
2307}