marco-core 1.0.2

nom-based Markdown parser, HTML renderer, and intelligence features (highlights, diagnostics, completions) for the Marco editor.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// AST node definitions: central representation consumed by renderer and intelligence

use crate::parser::Span;
use std::collections::HashMap;

// Link reference map: stores [label]: url definitions for later resolution
#[derive(Debug, Clone, Default)]
pub struct ReferenceMap {
    // Key: normalized label (case-folded, whitespace collapsed), Value: (url, optional title)
    defs: HashMap<String, (String, Option<String>)>,
}

impl ReferenceMap {
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a link reference definition
    pub fn insert(&mut self, label: &str, url: String, title: Option<String>) {
        let normalized = normalize_label(label);
        // CommonMark: when multiple definitions normalize to the same label,
        // the first definition takes precedence.
        self.defs.entry(normalized).or_insert((url, title));
    }

    /// Lookup a link reference by label
    pub fn get(&self, label: &str) -> Option<&(String, Option<String>)> {
        let normalized = normalize_label(label);
        self.defs.get(&normalized)
    }

    /// Check if a label exists
    pub fn contains(&self, label: &str) -> bool {
        let normalized = normalize_label(label);
        self.defs.contains_key(&normalized)
    }
}

/// Normalize label according to CommonMark spec:
/// - Apply Unicode case-folding semantics (best-effort)
/// - Collapse consecutive whitespace to single space
/// - Trim leading/trailing whitespace
fn normalize_label(label: &str) -> String {
    let collapsed = label.split_whitespace().collect::<Vec<_>>().join(" ");

    // NOTE:
    // Rust doesn't provide full Unicode case-folding in std. We apply
    // to_lowercase() plus the critical sharp-s expansion so labels like
    // "ẞ" and "SS" normalize identically, matching CommonMark examples.
    let mut out = String::with_capacity(collapsed.len());
    for ch in collapsed.chars() {
        for lower in ch.to_lowercase() {
            if lower == 'ß' {
                out.push('s');
                out.push('s');
            } else {
                out.push(lower);
            }
        }
    }

    out
}

// Root document node
#[derive(Debug, Clone, Default)]
pub struct Document {
    pub children: Vec<Node>,
    pub references: ReferenceMap,
}

// Generic AST node
#[derive(Debug, Clone)]
pub struct Node {
    pub kind: NodeKind,
    pub span: Option<Span>,
    pub children: Vec<Node>,
}

/// Table column alignment (GFM tables extension).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TableAlignment {
    #[default]
    None,
    Left,
    Center,
    Right,
}

/// GitHub-style admonitions / alerts (GFM extension).
///
/// Syntax is based on blockquotes, e.g.
///
/// `> [!NOTE]`
/// `> body...`
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AdmonitionKind {
    Note,
    Tip,
    Important,
    Warning,
    Caution,
}

/// Rendering style for admonitions.
///
/// - `Alert`: Standard GitHub-style alert coloring (NOTE/TIP/WARNING/etc).
/// - `Quote`: Quote-colored styling (neutral border/colors like regular blockquotes) while
///   keeping the admonition title layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AdmonitionStyle {
    Alert,
    Quote,
}

// All node types
#[derive(Debug, Clone)]
pub enum NodeKind {
    // Block-level
    Heading {
        level: u8,
        text: String,
        /// Explicit heading id, e.g. `### Title {#custom-id}`.
        ///
        /// When present, the renderer should emit it as `id="..."` on the
        /// heading element.
        id: Option<String>,
    },
    Paragraph,
    CodeBlock {
        language: Option<String>,
        code: String,
    },
    ThematicBreak, // Horizontal rule (---, ***, ___)
    List {
        ordered: bool,
        start: Option<u32>, // Starting number for ordered lists
        tight: bool,        // No blank lines between items
    },
    ListItem,

    /// Extended definition lists (Markdown Guide / Markdown Extra-style).
    ///
    /// Rendering convention:
    /// - A `DefinitionList` contains alternating `DefinitionTerm` (`<dt>`) and
    ///   `DefinitionDescription` (`<dd>`) children.
    /// - `DefinitionTerm` should contain inline children.
    /// - `DefinitionDescription` should contain block children.
    DefinitionList,
    DefinitionTerm,
    DefinitionDescription,
    /// GFM task list checkbox marker for a list item.
    ///
    /// This is emitted by the list parser when a list item begins with
    /// `[ ]` or `[x]` / `[X]`.
    ///
    /// Rendering convention:
    /// - This node is expected to appear as the first child inside a `ListItem`.
    /// - The HTML renderer will convert it into a themed checkbox icon.
    TaskCheckbox {
        checked: bool,
    },
    Blockquote,
    /// GitHub-style admonition / alert (GFM extension).
    ///
    /// This is created by a post-parse transformation that recognizes a special
    /// first line inside a blockquote (e.g. `[!NOTE]`) and removes that marker.
    Admonition {
        kind: AdmonitionKind,
        /// Optional custom title for the admonition header.
        ///
        /// Used by extended GFM-style admonitions (e.g. `> [😂 Happy Header]`).
        title: Option<String>,
        /// Optional custom icon content (typically a Unicode emoji) for the title.
        ///
        /// Rendered as text (not SVG) and must be styled by CSS.
        icon: Option<String>,
        /// Render variant.
        style: AdmonitionStyle,
    },

    /// Marco extended tab blocks.
    ///
    /// Syntax (container + items):
    /// ```text
    /// :::tab
    /// @tab Title
    /// Content...
    /// :::
    /// ```
    ///
    /// Children convention:
    /// - A `TabGroup` contains one or more `TabItem` children.
    /// - Each `TabItem` contains block children representing the tab panel content.
    TabGroup,
    TabItem {
        title: String,
    },

    /// Marco sliders (planned Reveal.js-like syntax, rendered as a simple slideshow).
    ///
    /// Syntax:
    /// ```text
    /// @slidestart
    /// slide 1
    /// ---
    /// slide 2
    /// @slideend
    /// ```
    ///
    /// Optional timer (seconds per slide): `@slidestart:t5`.
    ///
    /// Children convention:
    /// - A `SliderDeck` contains one or more `Slide` children.
    /// - Each `Slide` contains block children representing the slide content.
    SliderDeck {
        timer_seconds: Option<u32>,
    },
    Slide {
        /// True if this slide started after a vertical separator (`--`).
        ///
        /// The current Marco viewer treats slides as a single linear sequence
        /// (left/right). This flag is preserved for future vertical navigation.
        vertical: bool,
    },
    /// GFM table (pipe table extension).
    ///
    /// Children convention:
    /// - Each child is a `TableRow`.
    /// - Each `TableRow` contains `TableCell` children.
    Table {
        alignments: Vec<TableAlignment>,
    },
    TableRow {
        header: bool,
    },
    TableCell {
        header: bool,
        alignment: TableAlignment,
    },
    HtmlBlock {
        html: String,
    }, // Block-level HTML (comments, tags, etc.)

    /// GFM-style footnote definition (extension).
    ///
    /// Syntax:
    /// - `[^label]: definition text`
    /// - Continuation lines may be indented.
    ///
    /// Rendering convention:
    /// - This node should not be rendered in place.
    /// - Instead, the renderer collects referenced footnotes and emits a
    ///   footnotes section at the end of the document.
    FootnoteDefinition {
        label: String,
    },

    // Inline-level
    Text(String),
    /// Inline task checkbox marker (extension).
    ///
    /// This is emitted when a paragraph begins with a task marker like
    /// `[ ] ` / `[x] ` / `[X] `.
    ///
    /// Rendering convention:
    /// - The HTML renderer converts it into the same themed SVG checkbox icon
    ///   used for task list items.
    TaskCheckboxInline {
        checked: bool,
    },
    Emphasis,
    Strong,
    /// Combined strong+emphasis, e.g. `***text***` or `___text___`.
    ///
    /// This is parsed as a single inline node to avoid leaving dangling
    /// delimiters that would otherwise be treated as plain text.
    StrongEmphasis,
    /// Strikethrough (extension), e.g. `~~text~~`.
    Strikethrough,
    /// Highlight/mark (extension), e.g. `==text==`.
    Mark,
    /// Superscript (extension), e.g. `^text^`.
    Superscript,
    /// Subscript (extension), e.g. `~text~`.
    Subscript,
    Link {
        url: String,
        title: Option<String>,
    },
    /// Reference-style link placeholder (CommonMark): `[text][label]`, `[label][]`, `[label]`.
    ///
    /// These cannot be fully resolved during inline parsing because reference
    /// definitions may appear later in the document. The top-level `parse()`
    /// performs a post-processing pass that converts this into a `Link` when a
    /// matching definition exists in `Document.references`.
    ///
    /// If no matching definition is found, this should be rendered as literal
    /// bracketed text (preserving the already-parsed `children` for the first
    /// bracketed segment).
    LinkReference {
        /// Label used for reference resolution (will be normalized when looked up).
        label: String,
        /// Extra literal suffix after the first `]` (e.g. `"[]"` or `"[label]"`).
        /// Empty for shortcut reference links.
        suffix: String,
    },

    /// GFM-style footnote reference (extension), e.g. `[^label]`.
    ///
    /// Rendering convention:
    /// - If a matching `FootnoteDefinition` exists, this renders as a numbered
    ///   superscript link.
    /// - Otherwise it should fall back to literal text.
    FootnoteReference {
        label: String,
    },
    Image {
        url: String,
        alt: String,
    },
    CodeSpan(String),
    InlineHtml(String),
    HardBreak, // Two spaces + newline, or backslash + newline
    SoftBreak, // Regular newline (rendered as space in HTML)

    /// Marco extended user mentions.
    ///
    /// Syntax:
    /// - `@username[platform]`
    /// - `@username[platform](Display Name)`
    ///
    /// Rendering policy:
    /// - The renderer may convert this to an external profile link based on
    ///   a platform mapping table.
    PlatformMention {
        username: String,
        platform: String,
        display: Option<String>,
    },
    /// Inline math (LaTeX), e.g. `$E = mc^2$`.
    ///
    /// Rendering policy:
    /// - Rendered using KaTeX in inline mode.
    /// - Content is raw LaTeX source code.
    InlineMath {
        content: String,
    },

    /// Display math (LaTeX), e.g. `$$\int_0^\infty e^{-x^2} dx$$`.
    ///
    /// Rendering policy:
    /// - Rendered using KaTeX in display mode.
    /// - Content is raw LaTeX source code.
    DisplayMath {
        content: String,
    },

    /// Mermaid diagram (code block with language="mermaid").
    ///
    /// Rendering policy:
    /// - Rendered using mermaid-rs-renderer to SVG.
    /// - Content is raw Mermaid diagram source code.
    ///
    /// This is created during parsing when a fenced code block has
    /// info string "mermaid".
    MermaidDiagram {
        content: String,
    },
}

impl Document {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn len(&self) -> usize {
        self.children.len()
    }

    pub fn is_empty(&self) -> bool {
        self.children.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::ReferenceMap;

    #[test]
    fn smoke_test_reference_map_first_definition_wins() {
        let mut refs = ReferenceMap::new();
        refs.insert("foo", "https://first.example".to_string(), None);
        refs.insert("foo", "https://second.example".to_string(), None);

        let (url, title) = refs.get("foo").expect("reference not found");
        assert_eq!(url, "https://first.example");
        assert_eq!(title, &None);
    }

    #[test]
    fn smoke_test_reference_map_casefold_sharp_s() {
        let mut refs = ReferenceMap::new();
        refs.insert("SS", "/url".to_string(), None);

        let (url, _) = refs.get("").expect("reference not found");
        assert_eq!(url, "/url");
    }

    #[test]
    fn smoke_test_reference_map_whitespace_collapse() {
        let mut refs = ReferenceMap::new();
        refs.insert("Foo\n\t  bar", "/url".to_string(), None);

        assert!(refs.contains("foo bar"));
        assert!(refs.contains("  FOO   BAR  "));
    }
}