treemd 0.5.10

A markdown navigator with tree-based structural navigation and syntax highlighting
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
//! Abstract Syntax Tree types for the query language.
//!
//! The AST represents the parsed structure of a query expression.

use std::fmt;

/// A complete query consisting of one or more piped expressions.
#[derive(Debug, Clone)]
pub struct Query {
    /// The expressions connected by commas (multiple outputs)
    pub expressions: Vec<PipedExpr>,
}

impl Query {
    pub fn new(expressions: Vec<PipedExpr>) -> Self {
        Self { expressions }
    }
}

/// Expressions connected by pipes (`|`).
#[derive(Debug, Clone)]
pub struct PipedExpr {
    /// Pipeline stages executed left-to-right
    pub stages: Vec<Expr>,
}

impl PipedExpr {
    pub fn new(stages: Vec<Expr>) -> Self {
        Self { stages }
    }

    pub fn single(expr: Expr) -> Self {
        Self { stages: vec![expr] }
    }
}

/// A single expression in the query language.
#[derive(Debug, Clone)]
pub enum Expr {
    /// Identity selector: `.`
    Identity,

    /// Element selector: `.h2`, `.code`, `.link`
    Element {
        kind: ElementKind,
        filters: Vec<Filter>,
        index: Option<IndexOp>,
        span: Span,
    },

    /// Property access: `.text`, `.level`
    Property { name: String, span: Span },

    /// Function call: `count`, `select(...)`, `contains(...)`
    Function {
        name: String,
        args: Vec<Expr>,
        span: Span,
    },

    /// Object construction: `{title: .h1.text}`
    Object {
        pairs: Vec<(String, Expr)>,
        span: Span,
    },

    /// Array construction: `[.h2[].text]`
    Array { elements: Vec<Expr>, span: Span },

    /// Conditional: `if ... then ... else ... end`
    Conditional {
        condition: Box<Expr>,
        then_branch: Box<Expr>,
        else_branch: Option<Box<Expr>>,
        span: Span,
    },

    /// Hierarchy: `.h1 > .h2` (direct child) or `.h1 >> .h2` (descendant)
    Hierarchy {
        parent: Box<Expr>,
        child: Box<Expr>,
        direct: bool,
        span: Span,
    },

    /// Literal value
    Literal { value: Literal, span: Span },

    /// Binary operation: `==`, `!=`, `>`, `<`, `and`, `or`, `+`, `-`, etc.
    Binary {
        op: BinaryOp,
        left: Box<Expr>,
        right: Box<Expr>,
        span: Span,
    },

    /// Unary operation: `not`, `-`
    Unary {
        op: UnaryOp,
        expr: Box<Expr>,
        span: Span,
    },

    /// Parenthesized expression for grouping
    Group { expr: Box<Expr>, span: Span },
}

impl Expr {
    /// Get the span of this expression.
    pub fn span(&self) -> Span {
        match self {
            Expr::Identity => Span::new(0, 1),
            Expr::Element { span, .. } => *span,
            Expr::Property { span, .. } => *span,
            Expr::Function { span, .. } => *span,
            Expr::Object { span, .. } => *span,
            Expr::Array { span, .. } => *span,
            Expr::Conditional { span, .. } => *span,
            Expr::Hierarchy { span, .. } => *span,
            Expr::Literal { span, .. } => *span,
            Expr::Binary { span, .. } => *span,
            Expr::Unary { span, .. } => *span,
            Expr::Group { span, .. } => *span,
        }
    }
}

/// Element type for selectors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ElementKind {
    /// Any heading: `.h`
    Heading(Option<u8>),
    /// Code block: `.code`
    Code,
    /// Link: `.link`
    Link,
    /// Image: `.img`
    Image,
    /// Table: `.table`
    Table,
    /// List: `.list`
    List,
    /// Blockquote: `.blockquote`
    Blockquote,
    /// Paragraph: `.para`
    Paragraph,
    /// Front matter: `.frontmatter`
    FrontMatter,
}

impl ElementKind {
    /// Parse an element kind from a string.
    /// Supports multiple aliases for discoverability and convenience.
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            // Headings - multiple conventions
            "h" | "heading" | "headings" | "header" | "headers" => Some(ElementKind::Heading(None)),
            "h1" => Some(ElementKind::Heading(Some(1))),
            "h2" => Some(ElementKind::Heading(Some(2))),
            "h3" => Some(ElementKind::Heading(Some(3))),
            "h4" => Some(ElementKind::Heading(Some(4))),
            "h5" => Some(ElementKind::Heading(Some(5))),
            "h6" => Some(ElementKind::Heading(Some(6))),

            // Code blocks
            "code" | "codeblock" | "codeblocks" | "pre" => Some(ElementKind::Code),

            // Links - HTML-like and plural
            "link" | "links" | "a" | "anchor" => Some(ElementKind::Link),

            // Images
            "img" | "image" | "images" => Some(ElementKind::Image),

            // Tables
            "table" | "tables" => Some(ElementKind::Table),

            // Lists
            "list" | "lists" | "ul" | "ol" => Some(ElementKind::List),

            // Blockquotes
            "blockquote" | "blockquotes" | "quote" | "quotes" | "bq" => {
                Some(ElementKind::Blockquote)
            }

            // Paragraphs
            "para" | "paragraph" | "paragraphs" | "p" => Some(ElementKind::Paragraph),

            // Front matter
            "frontmatter" | "fm" | "meta" | "yaml" => Some(ElementKind::FrontMatter),

            _ => None,
        }
    }

    /// Get the string representation.
    pub fn as_str(&self) -> &'static str {
        match self {
            ElementKind::Heading(None) => "h",
            ElementKind::Heading(Some(1)) => "h1",
            ElementKind::Heading(Some(2)) => "h2",
            ElementKind::Heading(Some(3)) => "h3",
            ElementKind::Heading(Some(4)) => "h4",
            ElementKind::Heading(Some(5)) => "h5",
            ElementKind::Heading(Some(6)) => "h6",
            ElementKind::Heading(Some(_)) => "h",
            ElementKind::Code => "code",
            ElementKind::Link => "link",
            ElementKind::Image => "img",
            ElementKind::Table => "table",
            ElementKind::List => "list",
            ElementKind::Blockquote => "blockquote",
            ElementKind::Paragraph => "para",
            ElementKind::FrontMatter => "frontmatter",
        }
    }
}

impl fmt::Display for ElementKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Filter for element selection.
#[derive(Debug, Clone)]
pub enum Filter {
    /// Text filter: `[text]` or `["exact text"]`
    Text {
        pattern: String,
        exact: bool,
        span: Span,
    },

    /// Regex filter: `[/pattern/]`
    Regex { pattern: String, span: Span },

    /// Type filter: `[anchor]`, `[external]` for links
    Type { type_name: String, span: Span },
}

/// Index operation for element access.
#[derive(Debug, Clone)]
pub enum IndexOp {
    /// Single index: `[0]`, `[-1]`
    Single(i64),

    /// Slice: `[0:3]`, `[:3]`, `[2:]`
    Slice {
        start: Option<i64>,
        end: Option<i64>,
    },

    /// Iterate (no index): `[]`
    Iterate,
}

/// Literal values.
#[derive(Debug, Clone)]
pub enum Literal {
    String(String),
    Number(f64),
    Bool(bool),
    Null,
}

impl fmt::Display for Literal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Literal::String(s) => write!(f, "\"{}\"", s),
            Literal::Number(n) => write!(f, "{}", n),
            Literal::Bool(b) => write!(f, "{}", b),
            Literal::Null => write!(f, "null"),
        }
    }
}

/// Binary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryOp {
    // Comparison
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,

    // Logical
    And,
    Or,

    // Arithmetic
    Add,
    Sub,
    Mul,
    Div,
    Mod,

    // String
    Concat,

    // Null coalescing
    Alt, // //
}

impl BinaryOp {
    pub fn as_str(&self) -> &'static str {
        match self {
            BinaryOp::Eq => "==",
            BinaryOp::Ne => "!=",
            BinaryOp::Lt => "<",
            BinaryOp::Le => "<=",
            BinaryOp::Gt => ">",
            BinaryOp::Ge => ">=",
            BinaryOp::And => "and",
            BinaryOp::Or => "or",
            BinaryOp::Add => "+",
            BinaryOp::Sub => "-",
            BinaryOp::Mul => "*",
            BinaryOp::Div => "/",
            BinaryOp::Mod => "%",
            BinaryOp::Concat => "+",
            BinaryOp::Alt => "//",
        }
    }

    /// Get operator precedence (higher = binds tighter).
    pub fn precedence(&self) -> u8 {
        match self {
            BinaryOp::Or => 1,
            BinaryOp::And => 2,
            BinaryOp::Eq | BinaryOp::Ne => 3,
            BinaryOp::Lt | BinaryOp::Le | BinaryOp::Gt | BinaryOp::Ge => 4,
            BinaryOp::Alt => 5,
            BinaryOp::Add | BinaryOp::Sub | BinaryOp::Concat => 6,
            BinaryOp::Mul | BinaryOp::Div | BinaryOp::Mod => 7,
        }
    }
}

impl fmt::Display for BinaryOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Unary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOp {
    Not,
    Neg,
}

impl UnaryOp {
    pub fn as_str(&self) -> &'static str {
        match self {
            UnaryOp::Not => "not",
            UnaryOp::Neg => "-",
        }
    }
}

impl fmt::Display for UnaryOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Source location span.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Span {
    pub start: usize,
    pub end: usize,
}

impl Span {
    pub fn new(start: usize, end: usize) -> Self {
        Self { start, end }
    }

    pub fn merge(self, other: Span) -> Span {
        Span {
            start: self.start.min(other.start),
            end: self.end.max(other.end),
        }
    }
}

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

    #[test]
    fn test_element_kind_from_str() {
        assert_eq!(
            ElementKind::from_str("h2"),
            Some(ElementKind::Heading(Some(2)))
        );
        assert_eq!(ElementKind::from_str("code"), Some(ElementKind::Code));
        assert_eq!(ElementKind::from_str("link"), Some(ElementKind::Link));
        assert_eq!(ElementKind::from_str("unknown"), None);
    }

    #[test]
    fn test_binary_op_precedence() {
        assert!(BinaryOp::Mul.precedence() > BinaryOp::Add.precedence());
        assert!(BinaryOp::And.precedence() > BinaryOp::Or.precedence());
        assert!(BinaryOp::Eq.precedence() > BinaryOp::And.precedence());
    }
}