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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! Runtime values for query evaluation.
//!
//! The value system is designed to be extensible while maintaining
//! type safety and efficient operations.

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::fmt;

/// Runtime value during query evaluation.
///
/// Values are the currency of the query language - every expression
/// produces and consumes values.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Value {
    /// Null/empty value
    Null,

    /// Boolean
    Bool(bool),

    /// Number (always f64 for simplicity, like JSON)
    Number(f64),

    /// String
    String(String),

    /// Array of values
    Array(Vec<Value>),

    /// Object/map with ordered keys
    Object(IndexMap<String, Value>),

    /// Heading element
    Heading(HeadingValue),

    /// Code block element
    Code(CodeValue),

    /// Link element
    Link(LinkValue),

    /// Image element
    Image(ImageValue),

    /// Table element
    Table(TableValue),

    /// List element
    List(ListValue),

    /// Blockquote element
    Blockquote(BlockquoteValue),

    /// Paragraph element
    Paragraph(ParagraphValue),

    /// Full document reference
    Document(DocumentValue),

    /// Front matter (YAML)
    FrontMatter(IndexMap<String, Value>),
}

impl Value {
    /// Get the kind/type of this value as a string.
    pub fn kind(&self) -> ValueKind {
        match self {
            Value::Null => ValueKind::Null,
            Value::Bool(_) => ValueKind::Bool,
            Value::Number(_) => ValueKind::Number,
            Value::String(_) => ValueKind::String,
            Value::Array(_) => ValueKind::Array,
            Value::Object(_) => ValueKind::Object,
            Value::Heading(_) => ValueKind::Heading,
            Value::Code(_) => ValueKind::Code,
            Value::Link(_) => ValueKind::Link,
            Value::Image(_) => ValueKind::Image,
            Value::Table(_) => ValueKind::Table,
            Value::List(_) => ValueKind::List,
            Value::Blockquote(_) => ValueKind::Blockquote,
            Value::Paragraph(_) => ValueKind::Paragraph,
            Value::Document(_) => ValueKind::Document,
            Value::FrontMatter(_) => ValueKind::FrontMatter,
        }
    }

    /// Check if this value is truthy.
    pub fn is_truthy(&self) -> bool {
        match self {
            Value::Null => false,
            Value::Bool(b) => *b,
            Value::Number(n) => *n != 0.0,
            Value::String(s) => !s.is_empty(),
            Value::Array(a) => !a.is_empty(),
            Value::Object(o) => !o.is_empty(),
            _ => true, // Element types are always truthy
        }
    }

    /// Try to get this value as a string.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Value::String(s) => Some(s),
            _ => None,
        }
    }

    /// Try to get this value as a number.
    pub fn as_number(&self) -> Option<f64> {
        match self {
            Value::Number(n) => Some(*n),
            _ => None,
        }
    }

    /// Try to get this value as a bool.
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Value::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// Try to get this value as an array.
    pub fn as_array(&self) -> Option<&[Value]> {
        match self {
            Value::Array(a) => Some(a),
            _ => None,
        }
    }

    /// Try to get this value as an object.
    pub fn as_object(&self) -> Option<&IndexMap<String, Value>> {
        match self {
            Value::Object(o) => Some(o),
            _ => None,
        }
    }

    /// Get a property from this value by name.
    ///
    /// This is the core property access mechanism used by `.property` syntax.
    pub fn get_property(&self, name: &str) -> Option<Value> {
        match self {
            Value::Object(obj) => obj.get(name).cloned(),
            Value::Heading(h) => h.get_property(name),
            Value::Code(c) => c.get_property(name),
            Value::Link(l) => l.get_property(name),
            Value::Image(i) => i.get_property(name),
            Value::Table(t) => t.get_property(name),
            Value::List(l) => l.get_property(name),
            Value::Document(d) => d.get_property(name),
            Value::FrontMatter(fm) => fm.get(name).cloned(),
            _ => None,
        }
    }

    /// Get the "text" representation of this value.
    ///
    /// Used by the `text` function and for plain output.
    pub fn to_text(&self) -> String {
        match self {
            Value::Null => String::new(),
            Value::Bool(b) => b.to_string(),
            Value::Number(n) => {
                if n.fract() == 0.0 {
                    (*n as i64).to_string()
                } else {
                    n.to_string()
                }
            }
            Value::String(s) => s.clone(),
            Value::Array(a) => a.iter().map(|v| v.to_text()).collect::<Vec<_>>().join("\n"),
            Value::Object(o) => serde_json::to_string(o).unwrap_or_default(),
            Value::Heading(h) => h.text.clone(),
            Value::Code(c) => c.content.clone(),
            Value::Link(l) => l.text.clone(),
            Value::Image(i) => i.alt.clone(),
            Value::Table(t) => format!("Table({}x{})", t.headers.len(), t.rows.len()),
            Value::List(l) => l
                .items
                .iter()
                .map(|i| i.content.clone())
                .collect::<Vec<_>>()
                .join("\n"),
            Value::Blockquote(b) => b.content.clone(),
            Value::Paragraph(p) => p.content.clone(),
            Value::Document(d) => d.content.clone(),
            Value::FrontMatter(fm) => serde_json::to_string(fm).unwrap_or_default(),
        }
    }

    /// Get the length of this value (for arrays, strings, objects).
    pub fn len(&self) -> Option<usize> {
        match self {
            Value::String(s) => Some(s.len()),
            Value::Array(a) => Some(a.len()),
            Value::Object(o) => Some(o.len()),
            Value::Table(t) => Some(t.rows.len()),
            Value::List(l) => Some(l.items.len()),
            _ => None,
        }
    }

    /// Check if this value is empty.
    pub fn is_empty(&self) -> bool {
        self.len().map(|l| l == 0).unwrap_or(false)
    }
}

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

impl From<String> for Value {
    fn from(s: String) -> Self {
        Value::String(s)
    }
}

impl From<&str> for Value {
    fn from(s: &str) -> Self {
        Value::String(s.to_string())
    }
}

impl From<f64> for Value {
    fn from(n: f64) -> Self {
        Value::Number(n)
    }
}

impl From<i64> for Value {
    fn from(n: i64) -> Self {
        Value::Number(n as f64)
    }
}

impl From<usize> for Value {
    fn from(n: usize) -> Self {
        Value::Number(n as f64)
    }
}

impl From<bool> for Value {
    fn from(b: bool) -> Self {
        Value::Bool(b)
    }
}

impl<T: Into<Value>> From<Vec<T>> for Value {
    fn from(v: Vec<T>) -> Self {
        Value::Array(v.into_iter().map(Into::into).collect())
    }
}

impl<T: Into<Value>> From<Option<T>> for Value {
    fn from(o: Option<T>) -> Self {
        match o {
            Some(v) => v.into(),
            None => Value::Null,
        }
    }
}

/// Value type enumeration for type checking and error messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueKind {
    Null,
    Bool,
    Number,
    String,
    Array,
    Object,
    Heading,
    Code,
    Link,
    Image,
    Table,
    List,
    Blockquote,
    Paragraph,
    Document,
    FrontMatter,
}

impl fmt::Display for ValueKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            ValueKind::Null => "null",
            ValueKind::Bool => "boolean",
            ValueKind::Number => "number",
            ValueKind::String => "string",
            ValueKind::Array => "array",
            ValueKind::Object => "object",
            ValueKind::Heading => "heading",
            ValueKind::Code => "code",
            ValueKind::Link => "link",
            ValueKind::Image => "image",
            ValueKind::Table => "table",
            ValueKind::List => "list",
            ValueKind::Blockquote => "blockquote",
            ValueKind::Paragraph => "paragraph",
            ValueKind::Document => "document",
            ValueKind::FrontMatter => "frontmatter",
        };
        write!(f, "{}", s)
    }
}

// ============================================================================
// Element Value Types
// ============================================================================

/// Heading element value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HeadingValue {
    pub level: u8,
    pub text: String,
    pub offset: usize,
    pub line: usize,
    /// Content under this heading (excluding subheadings)
    #[serde(skip_serializing_if = "String::is_empty")]
    pub content: String,
    /// Raw markdown of the entire section
    #[serde(skip)]
    pub raw_md: String,
    /// Index in the flat headings list (for navigation)
    #[serde(skip)]
    pub index: usize,
}

impl HeadingValue {
    pub fn get_property(&self, name: &str) -> Option<Value> {
        match name {
            "level" => Some(Value::Number(self.level as f64)),
            "text" => Some(Value::String(self.text.clone())),
            "offset" => Some(Value::Number(self.offset as f64)),
            "line" => Some(Value::Number(self.line as f64)),
            "content" => Some(Value::String(self.content.clone())),
            "md" | "markdown" => Some(Value::String(self.raw_md.clone())),
            "slug" => Some(Value::String(slugify(&self.text))),
            _ => None,
        }
    }
}

/// Code block element value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeValue {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    pub content: String,
    pub start_line: usize,
    pub end_line: usize,
}

impl CodeValue {
    pub fn get_property(&self, name: &str) -> Option<Value> {
        match name {
            "lang" | "language" => self
                .language
                .clone()
                .map(Value::String)
                .or(Some(Value::Null)),
            "text" | "content" => Some(Value::String(self.content.clone())),
            "start_line" => Some(Value::Number(self.start_line as f64)),
            "end_line" => Some(Value::Number(self.end_line as f64)),
            "lines" => Some(Value::Number(self.content.lines().count() as f64)),
            _ => None,
        }
    }
}

/// Link element value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinkValue {
    pub text: String,
    pub url: String,
    #[serde(rename = "type")]
    pub link_type: LinkType,
    pub offset: usize,
}

impl LinkValue {
    pub fn get_property(&self, name: &str) -> Option<Value> {
        match name {
            "text" => Some(Value::String(self.text.clone())),
            "url" => Some(Value::String(self.url.clone())),
            "type" => Some(Value::String(self.link_type.as_str().to_string())),
            "offset" => Some(Value::Number(self.offset as f64)),
            _ => None,
        }
    }
}

/// Link type enumeration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LinkType {
    Anchor,
    Relative,
    WikiLink,
    External,
}

impl LinkType {
    pub fn as_str(&self) -> &'static str {
        match self {
            LinkType::Anchor => "anchor",
            LinkType::Relative => "relative",
            LinkType::WikiLink => "wikilink",
            LinkType::External => "external",
        }
    }
}

/// Image element value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageValue {
    pub alt: String,
    pub src: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
}

impl ImageValue {
    pub fn get_property(&self, name: &str) -> Option<Value> {
        match name {
            "alt" | "text" => Some(Value::String(self.alt.clone())),
            "src" | "url" => Some(Value::String(self.src.clone())),
            "title" => self.title.clone().map(Value::String).or(Some(Value::Null)),
            _ => None,
        }
    }
}

/// Table element value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableValue {
    pub headers: Vec<String>,
    pub rows: Vec<Vec<String>>,
    pub alignments: Vec<String>,
}

impl TableValue {
    pub fn get_property(&self, name: &str) -> Option<Value> {
        match name {
            "headers" => Some(Value::Array(
                self.headers
                    .iter()
                    .map(|h| Value::String(h.clone()))
                    .collect(),
            )),
            "rows" => Some(Value::Array(
                self.rows
                    .iter()
                    .map(|row| Value::Array(row.iter().map(|c| Value::String(c.clone())).collect()))
                    .collect(),
            )),
            "cols" | "columns" => Some(Value::Number(self.headers.len() as f64)),
            "alignments" => Some(Value::Array(
                self.alignments
                    .iter()
                    .map(|a| Value::String(a.clone()))
                    .collect(),
            )),
            _ => None,
        }
    }
}

/// List element value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListValue {
    pub ordered: bool,
    pub items: Vec<ListItemValue>,
}

impl ListValue {
    pub fn get_property(&self, name: &str) -> Option<Value> {
        match name {
            "ordered" => Some(Value::Bool(self.ordered)),
            "items" => Some(Value::Array(
                self.items
                    .iter()
                    .map(|i| Value::String(i.content.clone()))
                    .collect(),
            )),
            "length" | "count" => Some(Value::Number(self.items.len() as f64)),
            _ => None,
        }
    }
}

/// List item value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListItemValue {
    pub content: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub checked: Option<bool>,
}

/// Blockquote element value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlockquoteValue {
    pub content: String,
}

/// Paragraph element value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParagraphValue {
    pub content: String,
}

/// Document value (root).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocumentValue {
    pub content: String,
    pub heading_count: usize,
    pub word_count: usize,
}

impl DocumentValue {
    pub fn get_property(&self, name: &str) -> Option<Value> {
        match name {
            "content" | "text" => Some(Value::String(self.content.clone())),
            "heading_count" | "headings" => Some(Value::Number(self.heading_count as f64)),
            "word_count" | "words" => Some(Value::Number(self.word_count as f64)),
            _ => None,
        }
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Generate URL-friendly slug from text.
fn slugify(text: &str) -> String {
    text.to_lowercase()
        .chars()
        .map(|c| {
            if c.is_alphanumeric() {
                c
            } else if c.is_whitespace() || c == '-' || c == '.' || c == '_' {
                '-'
            } else {
                '\0'
            }
        })
        .filter(|&c| c != '\0')
        .collect::<String>()
        .split('-')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("-")
}

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

    #[test]
    fn test_value_kind() {
        assert_eq!(Value::Null.kind(), ValueKind::Null);
        assert_eq!(Value::Bool(true).kind(), ValueKind::Bool);
        assert_eq!(Value::Number(42.0).kind(), ValueKind::Number);
        assert_eq!(Value::String("test".into()).kind(), ValueKind::String);
    }

    #[test]
    fn test_value_truthy() {
        assert!(!Value::Null.is_truthy());
        assert!(!Value::Bool(false).is_truthy());
        assert!(Value::Bool(true).is_truthy());
        assert!(!Value::Number(0.0).is_truthy());
        assert!(Value::Number(1.0).is_truthy());
        assert!(!Value::String("".into()).is_truthy());
        assert!(Value::String("hello".into()).is_truthy());
    }

    #[test]
    fn test_slugify() {
        assert_eq!(slugify("Hello World"), "hello-world");
        assert_eq!(slugify("Getting Started!"), "getting-started");
        assert_eq!(slugify("API v2.0"), "api-v2-0");
    }
}