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#[derive(Debug, Clone, Default)]
31pub struct ColorTheme<'a> {
32 pub heading: ColorPair<'a>,
34 pub code: ColorPair<'a>,
36 pub code_inline: ColorPair<'a>,
38 pub emphasis: ColorPair<'a>,
40 pub strong: ColorPair<'a>,
42 pub link: ColorPair<'a>,
44 pub link_url: ColorPair<'a>,
46 pub image: ColorPair<'a>,
48 pub blockquote_marker: ColorPair<'a>,
50 pub delete: ColorPair<'a>,
52 pub horizontal_rule: ColorPair<'a>,
54 pub html: ColorPair<'a>,
56 pub frontmatter: ColorPair<'a>,
58 pub list_marker: ColorPair<'a>,
60 pub table_separator: ColorPair<'a>,
62 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 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 #[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 #[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 #[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 #[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#[derive(Debug, Clone, PartialEq)]
179pub struct RenderOptions {
180 pub list_style: Option<ListStyle>,
182 pub link_url_style: UrlSurroundStyle,
184 pub link_title_style: TitleSurroundStyle,
186 pub mdx: bool,
188 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#[derive(Debug, Clone, Default, PartialEq)]
207pub enum ListStyle {
208 #[default]
210 Dash,
211 Plus,
213 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
229#[cfg_attr(feature = "json", derive(serde::Serialize, serde::Deserialize))]
230pub enum ListMarker {
231 #[cfg_attr(feature = "json", serde(rename = "-"))]
233 Dash,
234 #[cfg_attr(feature = "json", serde(rename = "+"))]
236 Plus,
237 #[cfg_attr(feature = "json", serde(rename = "*"))]
239 Star,
240 #[cfg_attr(feature = "json", serde(rename = "."))]
242 Period,
243 #[cfg_attr(feature = "json", serde(rename = ")"))]
245 Paren,
246}
247
248impl ListMarker {
249 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
295#[cfg_attr(feature = "json", derive(serde::Serialize, serde::Deserialize))]
296pub enum HorizontalRuleMarker {
297 #[cfg_attr(feature = "json", serde(rename = "*"))]
299 Star,
300 #[cfg_attr(feature = "json", serde(rename = "-"))]
302 Dash,
303 #[cfg_attr(feature = "json", serde(rename = "_"))]
305 Underscore,
306}
307
308impl HorizontalRuleMarker {
309 pub fn as_char(self) -> char {
311 match self {
312 Self::Star => '*',
313 Self::Dash => '-',
314 Self::Underscore => '_',
315 }
316 }
317
318 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#[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#[derive(Debug, Clone, PartialEq, Default)]
340pub enum UrlSurroundStyle {
341 #[default]
343 None,
344 Angle,
346}
347
348impl Url {
349 pub fn new(value: String) -> Self {
351 Self(value)
352 }
353
354 pub fn as_str(&self) -> &str {
356 &self.0
357 }
358
359 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#[derive(Debug, Clone, PartialEq, Default)]
367pub enum TitleSurroundStyle {
368 #[default]
370 Double,
371 Single,
373 Paren,
375}
376
377#[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 pub fn new(value: String) -> Self {
395 Self(value)
396 }
397
398 pub fn to_value(&self) -> String {
400 self.0.clone()
401 }
402
403 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#[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,
419 Right,
421 Center,
423 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#[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 pub values: Vec<Node>,
460 pub index: usize,
462 pub level: Level,
464 pub ordered: bool,
466 pub checked: Option<bool>,
468 pub spread: bool,
470 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
472 pub start: Option<u32>,
473 #[cfg_attr(feature = "json", serde(default, skip_serializing_if = "Option::is_none"))]
475 pub marker: Option<ListMarker>,
476 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
478 pub position: Option<Position>,
479}
480
481#[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 pub values: Vec<Node>,
491 pub column: usize,
493 pub row: usize,
495 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
497 pub position: Option<Position>,
498}
499
500#[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 pub values: Vec<Node>,
510 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
512 pub position: Option<Position>,
513}
514
515#[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 pub align: Vec<TableAlignKind>,
525 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
527 pub position: Option<Position>,
528}
529
530#[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 pub values: Vec<Node>,
540}
541
542#[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 pub value: String,
552 pub lang: Option<String>,
554 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
556 pub position: Option<Position>,
557 pub meta: Option<String>,
559 pub fence: bool,
561}
562
563#[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 pub alt: String,
573 pub url: String,
575 pub title: Option<String>,
577 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
579 pub position: Option<Position>,
580}
581
582#[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 pub alt: String,
592 pub ident: String,
594 pub label: Option<String>,
596 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
598 pub position: Option<Position>,
599}
600#[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 pub url: Url,
610 pub title: Option<Title>,
612 pub values: Vec<Node>,
614 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
616 pub position: Option<Position>,
617}
618
619#[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 pub kind: String,
630 #[cfg_attr(feature = "json", serde(default, skip_serializing_if = "Option::is_none"))]
632 pub fold: Option<char>,
633 pub title: Option<String>,
635 pub values: Vec<Node>,
637 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
639 pub position: Option<Position>,
640}
641
642#[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 pub target: String,
653 pub display: Option<String>,
655 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
657 pub position: Option<Position>,
658}
659
660#[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 pub target: String,
671 pub text: Option<String>,
673 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
675 pub position: Option<Position>,
676}
677
678#[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 pub ident: String,
688 pub label: Option<String>,
690 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
692 pub position: Option<Position>,
693}
694
695#[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 pub ident: String,
705 pub values: Vec<Node>,
707 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
709 pub position: Option<Position>,
710}
711
712#[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 pub ident: String,
722 pub label: Option<String>,
724 pub values: Vec<Node>,
726 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
728 pub position: Option<Position>,
729}
730
731#[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 pub const H1: Self = Self(1);
749 pub const H2: Self = Self(2);
751 pub const H3: Self = Self(3);
753 pub const H4: Self = Self(4);
755 pub const H5: Self = Self(5);
757 pub const H6: Self = Self(6);
759
760 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 pub fn saturating(depth: i64) -> Self {
771 Self(depth.clamp(1, 6) as u8)
772 }
773
774 pub const fn get(self) -> u8 {
776 self.0
777 }
778
779 pub fn checked_add(self, levels: u8) -> Option<Self> {
781 self.0.checked_add(levels).and_then(Self::new)
782 }
783
784 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#[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#[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 pub depth: HeadingDepth,
874 pub values: Vec<Node>,
876 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
878 pub position: Option<Position>,
879}
880
881#[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 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
891 pub position: Option<Position>,
892 pub url: Url,
894 pub title: Option<Title>,
896 pub ident: String,
898 pub label: Option<String>,
900}
901#[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 pub value: String,
911 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
913 pub position: Option<Position>,
914}
915
916#[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 pub value: String,
926 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
928 pub position: Option<Position>,
929}
930
931#[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 pub value: String,
941 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
943 pub position: Option<Position>,
944}
945
946#[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 pub value: String,
956 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
958 pub position: Option<Position>,
959}
960
961#[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 pub value: SmolStr,
971 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
973 pub position: Option<Position>,
974}
975
976#[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 pub value: SmolStr,
986 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
988 pub position: Option<Position>,
989}
990
991#[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 pub value: String,
1001 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1003 pub position: Option<Position>,
1004}
1005
1006#[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 pub value: SmolStr,
1016 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1018 pub position: Option<Position>,
1019}
1020
1021#[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 pub children: Vec<Node>,
1031 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1033 pub position: Option<Position>,
1034 pub name: Option<String>,
1036 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)]
1046pub enum MdxAttributeContent {
1048 Expression(SmolStr),
1050 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)]
1060pub struct MdxJsxAttribute {
1062 pub name: SmolStr,
1064 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)]
1074pub enum MdxAttributeValue {
1076 Expression(SmolStr),
1078 Literal(SmolStr),
1080}
1081
1082#[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 pub children: Vec<Node>,
1092 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1094 pub position: Option<Position>,
1095 pub name: Option<SmolStr>,
1097 pub attributes: Vec<MdxAttributeContent>,
1099}
1100
1101#[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 pub value: SmolStr,
1111 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1113 pub position: Option<Position>,
1114}
1115
1116#[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 pub value: SmolStr,
1126 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1128 pub position: Option<Position>,
1129}
1130
1131#[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 pub values: Vec<Node>,
1141 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1143 pub position: Option<Position>,
1144}
1145
1146#[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 pub values: Vec<Node>,
1156 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1158 pub position: Option<Position>,
1159}
1160
1161#[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 pub values: Vec<Node>,
1171 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1173 pub position: Option<Position>,
1174}
1175
1176#[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 pub values: Vec<Node>,
1186 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1188 pub position: Option<Position>,
1189}
1190
1191#[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 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1201 pub position: Option<Position>,
1202}
1203
1204#[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 #[cfg_attr(feature = "json", serde(default, skip_serializing_if = "Option::is_none"))]
1214 pub marker: Option<HorizontalRuleMarker>,
1215 #[cfg_attr(feature = "json", serde(skip_serializing_if = "Option::is_none"))]
1217 pub position: Option<Position>,
1218}
1219
1220#[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 Blockquote(Blockquote),
1230 Break(Break),
1232 #[cfg(feature = "callout")]
1234 Callout(Callout),
1235 #[cfg(feature = "embed")]
1237 Embed(Embed),
1238 Definition(Definition),
1240 Delete(Delete),
1242 Heading(Heading),
1244 Emphasis(Emphasis),
1246 Footnote(Footnote),
1248 FootnoteRef(FootnoteRef),
1250 Html(Html),
1252 Yaml(Yaml),
1254 Toml(Toml),
1256 Image(Image),
1258 ImageRef(ImageRef),
1260 CodeInline(CodeInline),
1262 MathInline(MathInline),
1264 Link(Link),
1266 LinkRef(LinkRef),
1268 #[cfg(feature = "wikilink")]
1270 WikiLink(WikiLink),
1271 Math(Math),
1273 List(List),
1275 TableAlign(TableAlign),
1277 TableRow(TableRow),
1279 TableCell(TableCell),
1281 Code(Code),
1283 Strong(Strong),
1285 HorizontalRule(HorizontalRule),
1287 MdxFlowExpression(MdxFlowExpression),
1289 MdxJsxFlowElement(MdxJsxFlowElement),
1291 MdxJsxTextElement(MdxJsxTextElement),
1293 MdxTextExpression(MdxTextExpression),
1295 MdxJsEsm(MdxJsEsm),
1297 Text(Text),
1299 Fragment(Fragment),
1301 #[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#[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 pub start: Point,
1340 pub end: Point,
1342}
1343
1344#[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 pub line: u32,
1354 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 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 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 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 pub fn to_fragment(&self) -> Node {
1464 self.clone().into_fragment()
1465 }
1466
1467 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 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 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 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 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 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 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 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 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 pub fn children(&self) -> Vec<Node> {
1703 match self.attr(CHILDREN) {
1704 Some(AttrValue::Array(children)) => children,
1705 _ => Vec::new(),
1706 }
1707 }
1708
1709 pub fn set_children(&mut self, children: Vec<Node>) {
1712 if let Some(values) = self.children_mut() {
1713 *values = children;
1714 }
1715 }
1716
1717 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 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 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 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 pub fn is_empty(&self) -> bool {
1849 matches!(self, Self::Empty)
1850 }
1851
1852 pub fn is_fragment(&self) -> bool {
1854 matches!(self, Self::Fragment(_))
1855 }
1856
1857 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 pub fn is_inline_code(&self) -> bool {
1878 matches!(self, Self::CodeInline(_))
1879 }
1880
1881 pub fn is_inline_math(&self) -> bool {
1883 matches!(self, Self::MathInline(_))
1884 }
1885
1886 pub fn is_strong(&self) -> bool {
1888 matches!(self, Self::Strong(_))
1889 }
1890
1891 pub fn is_list(&self) -> bool {
1893 matches!(self, Self::List(_))
1894 }
1895
1896 pub fn is_emphasis(&self) -> bool {
1898 matches!(self, Self::Emphasis(_))
1899 }
1900
1901 pub fn is_delete(&self) -> bool {
1903 matches!(self, Self::Delete(_))
1904 }
1905
1906 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 pub fn is_link_ref(&self) -> bool {
1920 matches!(self, Self::LinkRef(_))
1921 }
1922
1923 #[cfg(feature = "wikilink")]
1925 pub fn is_wikilink(&self) -> bool {
1926 matches!(self, Self::WikiLink(_))
1927 }
1928
1929 #[cfg(feature = "callout")]
1931 pub fn is_callout(&self) -> bool {
1932 matches!(self, Self::Callout(_))
1933 }
1934
1935 #[cfg(feature = "embed")]
1937 pub fn is_embed(&self) -> bool {
1938 matches!(self, Self::Embed(_))
1939 }
1940
1941 pub fn is_text(&self) -> bool {
1943 matches!(self, Self::Text(_))
1944 }
1945
1946 pub fn is_image(&self) -> bool {
1948 matches!(self, Self::Image(_))
1949 }
1950
1951 pub fn is_horizontal_rule(&self) -> bool {
1953 matches!(self, Self::HorizontalRule { .. })
1954 }
1955
1956 pub fn is_blockquote(&self) -> bool {
1958 matches!(self, Self::Blockquote(_))
1959 }
1960
1961 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 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 pub fn is_html(&self) -> bool {
2002 matches!(self, Self::Html { .. })
2003 }
2004
2005 pub fn is_footnote(&self) -> bool {
2007 matches!(self, Self::Footnote(_))
2008 }
2009
2010 pub fn is_mdx_jsx_flow_element(&self) -> bool {
2012 matches!(self, Self::MdxJsxFlowElement(MdxJsxFlowElement { .. }))
2013 }
2014
2015 pub fn is_mdx_js_esm(&self) -> bool {
2017 matches!(self, Self::MdxJsEsm(MdxJsEsm { .. }))
2018 }
2019
2020 pub fn is_toml(&self) -> bool {
2022 matches!(self, Self::Toml { .. })
2023 }
2024
2025 pub fn is_yaml(&self) -> bool {
2027 matches!(self, Self::Yaml { .. })
2028 }
2029
2030 pub fn is_break(&self) -> bool {
2032 matches!(self, Self::Break { .. })
2033 }
2034
2035 pub fn is_mdx_text_expression(&self) -> bool {
2037 matches!(self, Self::MdxTextExpression(MdxTextExpression { .. }))
2038 }
2039
2040 pub fn is_footnote_ref(&self) -> bool {
2042 matches!(self, Self::FootnoteRef { .. })
2043 }
2044
2045 pub fn is_image_ref(&self) -> bool {
2047 matches!(self, Self::ImageRef(_))
2048 }
2049
2050 pub fn is_mdx_jsx_text_element(&self) -> bool {
2052 matches!(self, Self::MdxJsxTextElement(MdxJsxTextElement { .. }))
2053 }
2054
2055 pub fn is_math(&self) -> bool {
2057 matches!(self, Self::Math(_))
2058 }
2059
2060 pub fn is_mdx_flow_expression(&self) -> bool {
2062 matches!(self, Self::MdxFlowExpression(MdxFlowExpression { .. }))
2063 }
2064
2065 pub fn is_definition(&self) -> bool {
2067 matches!(self, Self::Definition(_))
2068 }
2069
2070 pub fn is_table_align(&self) -> bool {
2072 matches!(self, Self::TableAlign(_))
2073 }
2074
2075 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 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 pub fn with_value(&self, value: &str) -> Self {
2109 self.clone().into_with_value(value)
2110 }
2111
2112 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 pub fn with_children_value(&self, value: &str, index: usize) -> Self {
2290 self.clone().into_with_children_value(value, index)
2291 }
2292
2293 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}