markdown-org-extract 0.15.0

Library and CLI for extracting tasks from markdown files with Emacs Org-mode support
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
//! Rendering tasks and agendas as markdown or HTML.
//!
//! These functions produce the text the CLI writes to `--output`; embedders
//! that build their own UI can ignore them and read the structures directly.
//! Headings are sanitised here: characters that render as nothing but reorder
//! or hide surrounding text are dropped rather than passed through.

use std::fmt::Write;

use crate::types::{ClockEntry, DayAgenda, Task, TaskWithOffset};

/// Characters that render as nothing yet change how the surrounding text is
/// displayed: the bidirectional overrides / isolates, which can reorder a
/// heading so it reads differently from the bytes it contains, and the
/// zero-width space, which can hide a word boundary. Dropped from rendered
/// output so what the reader sees matches what the note says.
fn is_invisible_formatting(ch: char) -> bool {
    matches!(ch,
        '\u{200b}'                  // ZERO WIDTH SPACE
        | '\u{200e}' | '\u{200f}'   // LRM, RLM
        | '\u{202a}'..='\u{202e}'   // LRE, RLE, PDF, LRO, RLO
        | '\u{2066}'..='\u{2069}'   // LRI, RLI, FSI, PDI
    )
}

/// Escape markdown special characters in plain text. Used for headings and
/// labels that originate from user input — keeps formatting from being broken
/// or hijacked (e.g. a heading containing `*` would otherwise render as italic).
/// Invisible bidirectional formatting is dropped for the same reason it is
/// dropped from HTML output: it rewrites how the line reads without showing up
/// in it.
fn md_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '\\' | '`' | '*' | '_' | '#' | '[' | ']' | '<' | '>' | '|' => {
                out.push('\\');
                out.push(ch);
            }
            c if is_invisible_formatting(c) => {}
            _ => out.push(ch),
        }
    }
    out
}

/// Escape HTML special characters in pre-existing text content.
/// Also drops C0 control characters (except `\t \n \r`), DEL, and the
/// invisible bidirectional formatting characters, to protect downstream
/// renderers from null bytes and from glyphs that silently reorder the text
/// sneaked through markdown.
fn html_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            '\t' | '\n' | '\r' => out.push(ch),
            c if (c as u32) < 0x20 || c == '\u{7f}' => {}
            c if is_invisible_formatting(c) => {}
            _ => out.push(ch),
        }
    }
    out
}

fn offset_suffix(days_offset: Option<i64>) -> Option<String> {
    days_offset.map(|offset| {
        if offset > 0 {
            format!(" (in {offset} days)")
        } else {
            format!(" ({} days ago)", -offset)
        }
    })
}

/// Common formatting strategy for one output format (Markdown or HTML).
///
/// All `render_*` entry points delegate field traversal to `write_task`, which
/// drives this trait's methods. Adding a new `Task` field means touching
/// `write_task` once instead of four renderers.
trait TaskFormat {
    fn doc_open(&self, title: &str) -> String;
    fn doc_close(&self, out: &mut String);
    fn day_header(&self, out: &mut String, date: &str);
    fn section(&self, out: &mut String, title: &str);
    fn after_section(&self, out: &mut String);
    fn task_heading(&self, out: &mut String, level: u8, heading: &str, days_offset: Option<i64>);
    /// Single `Label: value` field. `code` requests inline-code wrapping
    /// for formats that support it (Markdown); HTML ignores the hint.
    fn field(&self, out: &mut String, label: &str, value: &str, code: bool);
    fn clocks_open(&self, out: &mut String);
    fn clock_complete(&self, out: &mut String, start: &str, end: &str, duration: Option<&str>);
    fn clock_active(&self, out: &mut String, start: &str);
    fn clocks_close(&self, out: &mut String);
    fn content(&self, out: &mut String, body: &str);
}

struct MdFormat;
struct HtmlFormat;

impl TaskFormat for MdFormat {
    fn doc_open(&self, title: &str) -> String {
        format!("# {title}\n\n")
    }
    fn doc_close(&self, _out: &mut String) {}

    fn day_header(&self, out: &mut String, date: &str) {
        let _ = writeln!(out, "## {date}\n");
    }
    fn section(&self, out: &mut String, title: &str) {
        let _ = write!(out, "### {title}\n\n");
    }
    fn after_section(&self, out: &mut String) {
        out.push('\n');
    }

    fn task_heading(&self, out: &mut String, level: u8, heading: &str, days_offset: Option<i64>) {
        let hashes: String = "#".repeat(level as usize);
        let _ = write!(out, "{hashes} {}", md_escape(heading));
        if let Some(suffix) = offset_suffix(days_offset) {
            let _ = write!(out, "{suffix}");
        }
        out.push('\n');
    }

    fn field(&self, out: &mut String, label: &str, value: &str, code: bool) {
        if code {
            let _ = writeln!(out, "**{label}:** `{value}`");
        } else {
            let _ = writeln!(out, "**{label}:** {value}");
        }
    }

    fn clocks_open(&self, out: &mut String) {
        out.push_str("\n**Clock:**\n");
    }
    fn clock_complete(&self, out: &mut String, start: &str, end: &str, duration: Option<&str>) {
        match duration {
            Some(dur) => {
                let _ = writeln!(out, "- `{start}` → `{end}` ({dur})");
            }
            None => {
                let _ = writeln!(out, "- `{start}` → `{end}`");
            }
        }
    }
    fn clock_active(&self, out: &mut String, start: &str) {
        let _ = writeln!(out, "- `{start}` (active)");
    }
    fn clocks_close(&self, _out: &mut String) {}

    fn content(&self, out: &mut String, body: &str) {
        if body.is_empty() {
            out.push('\n');
        } else {
            let _ = write!(out, "\n{body}\n\n");
        }
    }
}

impl TaskFormat for HtmlFormat {
    fn doc_open(&self, title: &str) -> String {
        format!("<html><body><h1>{title}</h1>\n")
    }
    fn doc_close(&self, out: &mut String) {
        out.push_str("</body></html>");
    }

    fn day_header(&self, out: &mut String, date: &str) {
        let _ = writeln!(out, "<h2>{}</h2>", html_escape(date));
    }
    fn section(&self, out: &mut String, title: &str) {
        let _ = writeln!(out, "<h3>{title}</h3>");
    }
    fn after_section(&self, _out: &mut String) {}

    fn task_heading(&self, out: &mut String, level: u8, heading: &str, days_offset: Option<i64>) {
        let _ = write!(out, "<h{level}>{}", html_escape(heading));
        if let Some(suffix) = offset_suffix(days_offset) {
            let _ = write!(out, "{}", html_escape(&suffix));
        }
        let _ = writeln!(out, "</h{level}>");
    }

    fn field(&self, out: &mut String, label: &str, value: &str, _code: bool) {
        let _ = writeln!(
            out,
            "<p><strong>{label}:</strong> {}</p>",
            html_escape(value)
        );
    }

    fn clocks_open(&self, out: &mut String) {
        out.push_str("<p><strong>Clock:</strong></p>\n<ul>\n");
    }
    fn clock_complete(&self, out: &mut String, start: &str, end: &str, duration: Option<&str>) {
        match duration {
            Some(dur) => {
                let _ = writeln!(
                    out,
                    "<li>{}{} ({})</li>",
                    html_escape(start),
                    html_escape(end),
                    html_escape(dur)
                );
            }
            None => {
                let _ = writeln!(
                    out,
                    "<li>{}{}</li>",
                    html_escape(start),
                    html_escape(end)
                );
            }
        }
    }
    fn clock_active(&self, out: &mut String, start: &str) {
        let _ = writeln!(out, "<li>{} (active)</li>", html_escape(start));
    }
    fn clocks_close(&self, out: &mut String) {
        out.push_str("</ul>\n");
    }

    fn content(&self, out: &mut String, body: &str) {
        if !body.is_empty() {
            let _ = writeln!(out, "<p>{}</p>", html_escape(body));
        }
    }
}

/// Write one Task to `out` using the supplied format strategy.
///
/// `level` controls heading depth (2 for top-level lists, 4 for day-agenda
/// sub-sections). `include_history` toggles fields that are only meaningful in
/// the "all tasks" view -- `Created`, `Total Time`, `Clock:` -- so day agendas
/// stay focused on the schedule.
fn write_task<F: TaskFormat>(
    out: &mut String,
    task: &Task,
    days_offset: Option<i64>,
    level: u8,
    include_history: bool,
    fmt: &F,
) {
    fmt.task_heading(out, level, &task.heading, days_offset);

    let file_value = format!("{}:{}", task.file, task.line);
    fmt.field(out, "File", &file_value, true);

    if let Some(ref t) = task.task_type {
        fmt.field(out, "Type", &t.to_string(), false);
    }
    if let Some(ref p) = task.priority {
        fmt.field(out, "Priority", &p.to_string(), false);
    }
    if include_history {
        if let Some(ref c) = task.created {
            fmt.field(out, "Created", c, true);
        }
    }
    if let Some(ref ts) = task.timestamp {
        fmt.field(out, "Time", ts, true);
    }
    if include_history {
        if let Some(ref total) = task.total_clock_time {
            fmt.field(out, "Total Time", total, false);
        }
        if let Some(ref clocks) = task.clocks {
            write_clocks(out, clocks, fmt);
        }
    }

    fmt.content(out, &task.content);
}

fn write_clocks<F: TaskFormat>(out: &mut String, clocks: &[ClockEntry], fmt: &F) {
    fmt.clocks_open(out);
    for clock in clocks {
        match (&clock.end, &clock.duration) {
            (Some(end), Some(dur)) => fmt.clock_complete(out, &clock.start, end, Some(dur)),
            (Some(end), None) => fmt.clock_complete(out, &clock.start, end, None),
            (None, _) => fmt.clock_active(out, &clock.start),
        }
    }
    fmt.clocks_close(out);
}

fn write_day_section<F: TaskFormat>(
    out: &mut String,
    title: &str,
    tasks: &[TaskWithOffset],
    fmt: &F,
) {
    if tasks.is_empty() {
        return;
    }
    fmt.section(out, title);
    for two in tasks {
        write_task(out, &two.task, two.days_offset, 4, false, fmt);
    }
    fmt.after_section(out);
}

fn render_days<F: TaskFormat>(days: &[DayAgenda], fmt: &F) -> String {
    let mut output = fmt.doc_open("Agenda");

    for day in days {
        fmt.day_header(&mut output, &day.date);

        write_day_section(&mut output, "Overdue", &day.overdue, fmt);

        // "Scheduled" header is shared by timed + no-time groups: print it once
        // if either is non-empty, then list both without a second header.
        if !day.scheduled_timed.is_empty() || !day.scheduled_no_time.is_empty() {
            fmt.section(&mut output, "Scheduled");
            for two in &day.scheduled_timed {
                write_task(&mut output, &two.task, two.days_offset, 4, false, fmt);
            }
            for two in &day.scheduled_no_time {
                write_task(&mut output, &two.task, two.days_offset, 4, false, fmt);
            }
            fmt.after_section(&mut output);
        }

        write_day_section(&mut output, "Upcoming", &day.upcoming, fmt);
    }

    fmt.doc_close(&mut output);
    output
}

fn render_tasks<F: TaskFormat>(tasks: &[Task], fmt: &F) -> String {
    let mut output = fmt.doc_open("Tasks");
    for task in tasks {
        write_task(&mut output, task, None, 2, true, fmt);
    }
    fmt.doc_close(&mut output);
    output
}

/// Render day agendas as Markdown
pub fn render_days_markdown(days: &[DayAgenda]) -> String {
    render_days(days, &MdFormat)
}

/// Render day agendas as HTML
pub fn render_days_html(days: &[DayAgenda]) -> String {
    render_days(days, &HtmlFormat)
}

/// Render tasks as Markdown
pub fn render_markdown(tasks: &[Task]) -> String {
    render_tasks(tasks, &MdFormat)
}

/// Render tasks as HTML
pub fn render_html(tasks: &[Task]) -> String {
    render_tasks(tasks, &HtmlFormat)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{CancelledSpelling, Priority, TaskType};

    #[test]
    fn test_html_escape() {
        assert_eq!(html_escape("<script>"), "&lt;script&gt;");
        assert_eq!(html_escape("A & B"), "A &amp; B");
    }

    #[test]
    fn test_html_escape_strips_control_chars() {
        assert_eq!(html_escape("A\u{0000}B"), "AB");
        assert_eq!(html_escape("A\u{0007}B"), "AB"); // BEL
        assert_eq!(html_escape("A\u{007f}B"), "AB"); // DEL
        assert_eq!(html_escape("line1\nline2\tx"), "line1\nline2\tx");
    }

    #[test]
    fn escapes_drop_invisible_bidi_formatting() {
        // A heading carrying RLO reads back-to-front while the bytes say
        // otherwise; a zero-width space hides a word boundary. Both render as
        // nothing, so neither renderer may pass them through.
        let sneaky = "safe\u{202e}txt.exe\u{202c}\u{200b}end\u{2066}x\u{2069}";
        assert_eq!(html_escape(sneaky), "safetxt.exeendx");
        assert_eq!(md_escape(sneaky), "safetxt.exeendx");
        // Ordinary text, including non-Latin scripts, is untouched.
        assert_eq!(html_escape("Отчёт за июль"), "Отчёт за июль");
        assert_eq!(md_escape("Отчёт за июль"), "Отчёт за июль");
    }

    #[test]
    fn test_render_markdown_basic() {
        let tasks = vec![Task {
            file: "test.md".to_string(),
            root: None,
            line: 1,
            heading: "Test Task".to_string(),
            content: "Description".to_string(),
            task_type: Some(TaskType::Todo),
            priority: Some(Priority::A),
            created: None,
            timestamp: None,
            timestamp_type: None,
            timestamp_active: None,
            timestamp_date: None,
            timestamp_time: None,
            timestamp_end_time: None,
            timestamp_repeater: None,
            timestamp_next: None,
            clocks: None,
            total_clock_time: None,
            properties: None,
        }];

        let output = render_markdown(&tasks);
        assert!(output.contains("# Tasks"));
        assert!(output.contains("## Test Task"));
        assert!(output.contains("**Type:** TODO"));
        assert!(output.contains("**Priority:** A"));
    }

    #[test]
    fn test_md_escape_specials() {
        assert_eq!(md_escape("plain"), "plain");
        assert_eq!(md_escape("a*b"), "a\\*b");
        assert_eq!(md_escape("a_b"), "a\\_b");
        assert_eq!(md_escape("# hi"), "\\# hi");
        assert_eq!(md_escape("[link]"), "\\[link\\]");
        assert_eq!(md_escape("<tag>"), "\\<tag\\>");
        assert_eq!(md_escape("a|b"), "a\\|b");
        assert_eq!(md_escape("`code`"), "\\`code\\`");
        assert_eq!(md_escape("back\\slash"), "back\\\\slash");
    }

    #[test]
    fn test_render_markdown_escapes_heading() {
        let tasks = vec![Task {
            file: "test.md".to_string(),
            root: None,
            line: 1,
            heading: "Fix *important* [#issue]".to_string(),
            content: String::new(),
            task_type: None,
            priority: None,
            created: None,
            timestamp: None,
            timestamp_type: None,
            timestamp_active: None,
            timestamp_date: None,
            timestamp_time: None,
            timestamp_end_time: None,
            timestamp_repeater: None,
            timestamp_next: None,
            clocks: None,
            total_clock_time: None,
            properties: None,
        }];
        let out = render_markdown(&tasks);
        assert!(
            out.contains("## Fix \\*important\\* \\[\\#issue\\]"),
            "heading must be escaped: {out}"
        );
    }

    fn fixture_task() -> Task {
        Task {
            file: "notes.md".to_string(),
            root: None,
            line: 42,
            heading: "Test task".to_string(),
            content: "Body text.".to_string(),
            task_type: Some(TaskType::Todo),
            priority: Some(Priority::A),
            created: Some("CREATED: [2025-09-01 Mon]".to_string()),
            timestamp: Some("DEADLINE: <2025-10-01 Wed>".to_string()),
            timestamp_type: Some("DEADLINE".to_string()),
            timestamp_active: Some(true),
            timestamp_date: Some("2025-10-01".to_string()),
            timestamp_time: None,
            timestamp_end_time: None,
            timestamp_repeater: None,
            timestamp_next: None,
            clocks: None,
            total_clock_time: None,
            properties: None,
        }
    }

    #[test]
    fn snapshot_render_markdown_full_task() {
        let out = render_markdown(&[fixture_task()]);
        let expected = "# Tasks\n\n\
## Test task\n\
**File:** `notes.md:42`\n\
**Type:** TODO\n\
**Priority:** A\n\
**Created:** `CREATED: [2025-09-01 Mon]`\n\
**Time:** `DEADLINE: <2025-10-01 Wed>`\n\
\n\
Body text.\n\n";
        assert_eq!(out, expected);
    }

    #[test]
    fn snapshot_render_html_full_task() {
        let out = render_html(&[fixture_task()]);
        let expected = "<html><body><h1>Tasks</h1>\n\
<h2>Test task</h2>\n\
<p><strong>File:</strong> notes.md:42</p>\n\
<p><strong>Type:</strong> TODO</p>\n\
<p><strong>Priority:</strong> A</p>\n\
<p><strong>Created:</strong> CREATED: [2025-09-01 Mon]</p>\n\
<p><strong>Time:</strong> DEADLINE: &lt;2025-10-01 Wed&gt;</p>\n\
<p>Body text.</p>\n\
</body></html>";
        assert_eq!(out, expected);
    }

    #[test]
    fn render_task_cancelled_json_serialises_correctly() {
        // ADR-0015 wire contract: the cancelled TaskType variant must serialise
        // to the JSON string "CANCELLED" via the hand-written `Serialize` impl,
        // preserving the original double-L spelling (ADR-0021).
        let mut task = fixture_task();
        task.heading = "Foo".to_string();
        task.task_type = Some(TaskType::Cancelled(CancelledSpelling::DoubleL));

        let rendered = serde_json::to_string(&task).expect("Task serialises");
        assert!(
            rendered.contains(r#""task_type":"CANCELLED""#),
            "expected task_type CANCELLED in JSON, got: {rendered}",
        );
    }

    #[test]
    fn render_task_canceled_single_l_json_preserves_spelling() {
        // ADR-0021: the single-L spelling is preserved, not normalised to
        // double-L. ADR-0015 wire contract: the cancelled TaskType variant
        // serialises to a plain JSON string ("CANCELED") via the hand-written
        // `Serialize` impl.
        let mut task = fixture_task();
        task.heading = "Foo".to_string();
        task.task_type = Some(TaskType::Cancelled(CancelledSpelling::SingleL));

        let rendered = serde_json::to_string(&task).expect("Task serialises");
        assert!(
            rendered.contains(r#""task_type":"CANCELED""#),
            "expected task_type CANCELED (single-L) in JSON, got: {rendered}",
        );
        assert!(
            !rendered.contains(r#""task_type":"CANCELLED""#),
            "single-L spelling must not be normalised to double-L, got: {rendered}",
        );
    }

    #[test]
    fn test_render_html_escapes() {
        let tasks = vec![Task {
            file: "<script>.md".to_string(),
            root: None,
            line: 1,
            heading: "Test & Task".to_string(),
            content: String::new(),
            task_type: None,
            priority: None,
            created: None,
            timestamp: None,
            timestamp_type: None,
            timestamp_active: None,
            timestamp_date: None,
            timestamp_time: None,
            timestamp_end_time: None,
            timestamp_repeater: None,
            timestamp_next: None,
            clocks: None,
            total_clock_time: None,
            properties: None,
        }];

        let output = render_html(&tasks);
        assert!(output.contains("&lt;script&gt;"));
        assert!(output.contains("Test &amp; Task"));
    }
}