tftio-kb 2.5.4

Personal knowledge base — typed AST with org-mode as projection, SQLite-backed
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
//! Org-mode text → AST parser using hand-written recursive descent.
//!
//! Parses org syntax into the canonical [`Document`] AST. Covers every
//! constructor that the generator produces so round-trip is well-defined.

use tftio_org::ast::{
    Block, Checkbox, Document, Inline, ListItem, ListType, LogEntry, PlanningEntry, TableCell, Tag,
    Timestamp, Title,
};

/// Parse error with position context.
#[derive(Debug, Clone)]
pub struct ParseError {
    /// Human-readable description of the parse failure.
    pub message: String,
}

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

impl std::error::Error for ParseError {}

/// Parse an org-mode document string into a [`Document`].
///
/// # Errors
///
/// Returns `ParseError` if the input cannot be parsed.
pub fn parse_document(input: &str) -> Result<Document, ParseError> {
    parse_document_with_residue(input).map(|(doc, _residue)| doc)
}

/// Parse an org-mode document, also returning the content of input lines
/// that no block claimed.
///
/// A file whose residue is empty lost no content during parsing, even if
/// it does not round-trip byte-for-byte: every source line is represented
/// in some block. Blank lines are never residue. Lines inside quote
/// blocks are not tracked.
///
/// # Errors
///
/// Returns `ParseError` if the input cannot be parsed.
pub fn parse_document_with_residue(input: &str) -> Result<(Document, Vec<String>), ParseError> {
    let lines: Vec<&str> = input.lines().collect();
    let mut residue = Vec::new();
    let (blocks, _) = parse_blocks(&lines, 0, &mut residue)?;
    Ok((Document { blocks }, residue))
}

type ParseResult<T> = Result<(T, usize), ParseError>;

/// Parse a sequence of blocks starting at `pos`. Returns parsed blocks and new position.
///
/// Unrecognized non-blank lines are appended to `residue`.
#[allow(
    clippy::unnecessary_wraps,
    reason = "mirrors the fallible `ParseResult` shape of the sibling `try_parse_*` combinators for uniform composition"
)]
fn parse_blocks(lines: &[&str], pos: usize, residue: &mut Vec<String>) -> ParseResult<Vec<Block>> {
    let mut blocks = Vec::new();
    let mut i = pos;
    while i < lines.len() {
        let Some(&line) = lines.get(i) else { break };
        if line.is_empty() {
            // Blank lines are represented explicitly for faithful spacing.
            blocks.push(Block::BlankLine);
            i += 1;
            continue;
        }

        if let Some(Ok((block, next))) = try_parse_heading(lines, i, residue)
            .or_else(|| try_parse_property_drawer(lines, i))
            .or_else(|| try_parse_logbook_drawer(lines, i))
            .or_else(|| try_parse_src_block(lines, i))
            .or_else(|| try_parse_example_block(lines, i))
            .or_else(|| try_parse_quote_block(lines, i))
            .or_else(|| try_parse_list(lines, i))
            .or_else(|| try_parse_table(lines, i))
            .or_else(|| try_parse_planning(i, line))
            .or_else(|| try_parse_comment(i, line))
            .or_else(|| try_parse_keyword(i, line))
            .or_else(|| try_parse_horizontal_rule(i, line))
            .or_else(|| try_parse_paragraph(lines, i))
        {
            blocks.push(block);
            i = next;
        } else {
            // Unrecognized line — record as residue (dropped content).
            if !line.is_empty() {
                residue.push(line.to_string());
            }
            i += 1;
        }
    }
    Ok((blocks, i))
}

fn try_parse_heading(
    lines: &[&str],
    pos: usize,
    residue: &mut Vec<String>,
) -> Option<ParseResult<Block>> {
    let line = *lines.get(pos)?;
    if !line.starts_with('*') {
        return None;
    }

    let raw_level = line.chars().take_while(|c| *c == '*').count();
    // Require at least one space after stars for a valid heading
    if raw_level >= line.len() || !line[raw_level..].starts_with(' ') {
        return None;
    }
    let level: u8 = u8::try_from(raw_level.min(255)).unwrap_or(u8::MAX);
    let rest = line[raw_level..].trim();

    // Parse tags at end: "Title :tag1:tag2:"
    let (title_str, tags) = rest.rfind(" :").map_or((rest, vec![]), |tag_start| {
        let tag_part = &rest[tag_start + 1..];
        if tag_part.starts_with(':') && tag_part.ends_with(':') && tag_part.len() > 2 {
            let title = rest[..tag_start].trim();
            let tags: Vec<Tag> = tag_part[1..tag_part.len() - 1]
                .split(':')
                .filter(|t| !t.is_empty())
                .map(|t| Tag(t.to_string()))
                .collect();
            (title, tags)
        } else {
            (rest, vec![])
        }
    });

    let title = Title(title_str.to_string());

    // Collect children (blocks at higher indentation level)
    let mut children = Vec::new();
    let mut next = pos + 1;
    while next < lines.len() && !lines.get(next).is_some_and(|l| l.starts_with('*')) {
        // Gather child blocks that start on this or later lines up to the
        // next blank-line-separated block or next heading.
        let Some(&line) = lines.get(next) else { break };
        if line.is_empty() {
            children.push(Block::BlankLine);
            next += 1;
            continue;
        }
        // Try to parse the next item as a child block
        let mut consumed = false;
        for child_parser in &[
            try_parse_property_drawer,
            try_parse_logbook_drawer,
            try_parse_src_block,
            try_parse_example_block,
            try_parse_quote_block,
            try_parse_list,
            try_parse_table,
        ] {
            if let Some(Ok((child_block, new_pos))) = child_parser(lines, next) {
                children.push(child_block);
                next = new_pos;
                consumed = true;
                break;
            }
        }
        if !consumed {
            // Try paragraph
            if let Some(Ok((para, new_pos))) = try_parse_paragraph(lines, next) {
                children.push(para);
                next = new_pos;
            } else {
                // Unrecognized child line — record as residue.
                if let Some(&child) = lines.get(next)
                    && !child.is_empty()
                {
                    residue.push(child.to_string());
                }
                next += 1;
            }
        }
    }

    Some(Ok((
        Block::Heading {
            level,
            title,
            tags,
            children,
        },
        next,
    )))
}

fn try_parse_property_drawer(lines: &[&str], pos: usize) -> Option<ParseResult<Block>> {
    if lines.get(pos)?.trim() != ":PROPERTIES:" {
        return None;
    }
    let mut entries = Vec::new();
    let mut i = pos + 1;
    while i < lines.len() {
        let Some(line) = lines.get(i).map(|l| l.trim()) else {
            break;
        };
        if line == ":END:" {
            return Some(Ok((Block::PropertyDrawer { entries }, i + 1)));
        }
        if let Some(stripped) = line.strip_prefix(':')
            && let Some(colon_pos) = stripped.find(':')
        {
            let key = &stripped[..colon_pos];
            // Value kept verbatim (leading padding included) so aligned
            // drawers round-trip.
            let value = &stripped[colon_pos + 1..];
            entries.push((key.to_string(), value.to_string()));
        }
        i += 1;
    }
    Some(Ok((Block::PropertyDrawer { entries }, i)))
}

fn try_parse_logbook_drawer(lines: &[&str], pos: usize) -> Option<ParseResult<Block>> {
    if lines.get(pos)?.trim() != ":LOGBOOK:" {
        return None;
    }
    let mut entries = Vec::new();
    let mut i = pos + 1;
    while i < lines.len() {
        let Some(line) = lines.get(i).map(|l| l.trim()) else {
            break;
        };
        if line == ":END:" {
            return Some(Ok((Block::LogbookDrawer { entries }, i + 1)));
        }
        // Parse "- <timestamp> note"
        if let Some(rest) = line.strip_prefix("- ")
            && rest.starts_with('<')
            && let Some(close) = rest.find('>')
        {
            let ts = &rest[..=close];
            let note = rest[close + 1..].trim();
            entries.push(LogEntry {
                timestamp: Timestamp(ts.to_string()),
                note: note.to_string(),
            });
        }
        i += 1;
    }
    Some(Ok((Block::LogbookDrawer { entries }, i)))
}

fn try_parse_src_block(lines: &[&str], pos: usize) -> Option<ParseResult<Block>> {
    let line = lines.get(pos)?.trim();
    if !line.starts_with("#+begin_src") {
        return None;
    }
    let language = line.strip_prefix("#+begin_src")?.trim().to_string();

    let mut i = pos + 1;
    let mut content = String::new();
    while i < lines.len() {
        let Some(&cur) = lines.get(i) else { break };
        if cur.trim() == "#+end_src" {
            // Canonical form: non-empty src bodies always end with newline
            if !content.is_empty() && !content.ends_with('\n') {
                content.push('\n');
            }
            return Some(Ok((Block::SrcBlock { language, content }, i + 1)));
        }
        if !content.is_empty() {
            content.push('\n');
        }
        content.push_str(cur);
        i += 1;
    }
    // No end marker found — treat rest as content
    Some(Ok((Block::SrcBlock { language, content }, i)))
}

fn try_parse_example_block(lines: &[&str], pos: usize) -> Option<ParseResult<Block>> {
    if lines.get(pos)?.trim() != "#+begin_example" {
        return None;
    }
    let mut i = pos + 1;
    let mut content = String::new();
    while i < lines.len() {
        let Some(&cur) = lines.get(i) else { break };
        if cur.trim() == "#+end_example" {
            if !content.is_empty() && !content.ends_with('\n') {
                content.push('\n');
            }
            return Some(Ok((Block::ExampleBlock { content }, i + 1)));
        }
        if !content.is_empty() {
            content.push('\n');
        }
        content.push_str(cur);
        i += 1;
    }
    // No end marker — treat the rest as content.
    Some(Ok((Block::ExampleBlock { content }, i)))
}

fn try_parse_quote_block(lines: &[&str], pos: usize) -> Option<ParseResult<Block>> {
    if lines.get(pos)?.trim() != "#+begin_quote" {
        return None;
    }
    let mut i = pos + 1;
    let mut child_lines = Vec::new();
    while i < lines.len() {
        let Some(&cur) = lines.get(i) else { break };
        if cur.trim() == "#+end_quote" {
            // Quote-block interiors are not residue-tracked.
            let (children, _) = parse_blocks(&child_lines, 0, &mut Vec::new()).ok()?;
            return Some(Ok((Block::QuoteBlock { children }, i + 1)));
        }
        child_lines.push(cur);
        i += 1;
    }
    None
}

fn try_parse_list(lines: &[&str], pos: usize) -> Option<ParseResult<Block>> {
    let (list_type, first_checkbox, first_rest) = match_bullet(lines.get(pos)?)?;

    let mut items: Vec<ListItem> = Vec::new();
    let mut cur_checkbox = first_checkbox;
    let mut cur_inlines = parse_inlines(first_rest);
    let mut i = pos + 1;

    while i < lines.len() {
        let Some(&line) = lines.get(i) else { break };
        if line.is_empty() {
            // A blank line ends the list.
            break;
        }
        if let Some((_lt, checkbox, rest)) = match_bullet(line) {
            // A column-0 bullet starts the next sibling item.
            items.push(ListItem {
                content: vec![Block::Paragraph {
                    inlines: std::mem::take(&mut cur_inlines),
                }],
                checkbox: cur_checkbox,
            });
            cur_checkbox = checkbox;
            cur_inlines = parse_inlines(rest);
            i += 1;
        } else if line.starts_with(' ') || line.starts_with('\t') {
            // Indented continuation of the current item — including
            // nested sub-bullets, kept verbatim as continuation text.
            cur_inlines.push(Inline::LineBreak);
            cur_inlines.extend(parse_inlines(line));
            i += 1;
        } else {
            // A column-0 non-bullet line ends the list.
            break;
        }
    }
    items.push(ListItem {
        content: vec![Block::Paragraph {
            inlines: cur_inlines,
        }],
        checkbox: cur_checkbox,
    });
    Some(Ok((Block::List { list_type, items }, i)))
}

/// If `line` starts (column 0) with a list bullet, return the list type,
/// checkbox state, and the content after the bullet and checkbox.
fn match_bullet(line: &str) -> Option<(ListType, Checkbox, &str)> {
    if let Some(rest) = line.strip_prefix("- ") {
        let (checkbox, rest) = strip_checkbox(rest);
        return Some((ListType::Unordered, checkbox, rest));
    }
    // Ordered: `N. ` for one or more digits.
    let digits = line.chars().take_while(char::is_ascii_digit).count();
    if digits > 0
        && let Some(rest) = line[digits..].strip_prefix(". ")
    {
        let ordinal: u64 = line[..digits].parse().unwrap_or(1);
        let (checkbox, rest) = strip_checkbox(rest);
        return Some((ListType::Ordered(ordinal), checkbox, rest));
    }
    None
}

/// Strip a leading `[ ] ` / `[X] ` checkbox marker, if present.
fn strip_checkbox(s: &str) -> (Checkbox, &str) {
    s.strip_prefix("[X] ").map_or_else(
        || {
            s.strip_prefix("[ ] ")
                .map_or((Checkbox::NoCheckbox, s), |r| (Checkbox::Unchecked, r))
        },
        |r| (Checkbox::Checked, r),
    )
}

fn try_parse_table(lines: &[&str], pos: usize) -> Option<ParseResult<Block>> {
    let first = lines.get(pos)?.trim();
    if !first.starts_with('|') || !first.ends_with('|') {
        return None;
    }
    let mut rows = Vec::new();
    let mut i = pos;
    while i < lines.len() {
        let Some(line) = lines.get(i).map(|l| l.trim()) else {
            break;
        };
        // A blank line ends the table.
        if line.is_empty() {
            break;
        }
        if line.len() < 2 || !line.starts_with('|') || !line.ends_with('|') {
            break;
        }
        // Cells are kept verbatim, padding included — column alignment
        // and separator rows (`|---+---|`) round-trip as cell content.
        let cells: Vec<TableCell> = line[1..line.len() - 1]
            .split('|')
            .map(|c| TableCell {
                inlines: parse_inlines(c),
            })
            .collect();
        rows.push(cells);
        i += 1;
    }
    if rows.is_empty() {
        return None;
    }
    Some(Ok((Block::Table { rows }, i)))
}

fn try_parse_planning(pos: usize, line: &str) -> Option<ParseResult<Block>> {
    let trimmed = line.trim();
    if !trimmed.starts_with("SCHEDULED: ")
        && !trimmed.starts_with("DEADLINE: ")
        && !trimmed.starts_with("CLOSED: ")
    {
        return None;
    }

    let mut entries = Vec::new();
    // Scan the line for keyword + timestamp pairs
    let mut remaining = trimmed;
    while !remaining.is_empty() {
        if let Some(rest) = remaining.strip_prefix("SCHEDULED: ")
            && let Some((ts, after)) = extract_timestamp(rest)
        {
            entries.push(PlanningEntry::Scheduled(Timestamp(ts)));
            remaining = after;
            continue;
        }
        if let Some(rest) = remaining.strip_prefix("DEADLINE: ")
            && let Some((ts, after)) = extract_timestamp(rest)
        {
            entries.push(PlanningEntry::Deadline(Timestamp(ts)));
            remaining = after;
            continue;
        }
        if let Some(rest) = remaining.strip_prefix("CLOSED: ")
            && let Some((ts, after)) = extract_timestamp(rest)
        {
            entries.push(PlanningEntry::Closed(Timestamp(ts)));
            remaining = after;
            continue;
        }
        break;
    }

    if entries.is_empty() {
        return None;
    }
    Some(Ok((Block::Planning { entries }, pos + 1)))
}

/// Extract a timestamp like `<2026-04-30 Thu>` from the start of `s`.
/// Returns the timestamp string and the remaining text.
fn extract_timestamp(s: &str) -> Option<(String, &str)> {
    let s = s.trim();
    if !s.starts_with('<') {
        return None;
    }
    let close = s.find('>')?;
    let ts = s[..=close].to_string();
    Some((ts, s[close + 1..].trim()))
}

fn try_parse_comment(pos: usize, line: &str) -> Option<ParseResult<Block>> {
    let trimmed = line.trim();
    trimmed.strip_prefix("# ").map(|text| {
        Ok((
            Block::Comment {
                text: text.to_string(),
            },
            pos + 1,
        ))
    })
}

/// Parse a `#+NAME: value` keyword line.
///
/// `name` is the run of non-`:`, non-whitespace characters after `#+`;
/// the character immediately after must be `:`. `value` is the verbatim
/// remainder after that `:`, leading space included. Block delimiters
/// such as `#+begin_src` have no `:` after the name and fall through.
fn try_parse_keyword(pos: usize, line: &str) -> Option<ParseResult<Block>> {
    let rest = line.strip_prefix("#+")?;
    let name_len = rest
        .find(|c: char| c == ':' || c.is_whitespace())
        .unwrap_or(rest.len());
    if name_len == 0 || rest.as_bytes().get(name_len) != Some(&b':') {
        return None;
    }
    let name = rest[..name_len].to_string();
    let value = rest[name_len + 1..].to_string();
    Some(Ok((Block::Keyword { name, value }, pos + 1)))
}

fn try_parse_horizontal_rule(pos: usize, line: &str) -> Option<ParseResult<Block>> {
    let trimmed = line.trim();
    if trimmed == "-----" {
        Some(Ok((Block::HorizontalRule, pos + 1)))
    } else {
        None
    }
}

fn try_parse_paragraph(lines: &[&str], pos: usize) -> Option<ParseResult<Block>> {
    if !is_paragraph_line(lines.get(pos)?) {
        return None;
    }
    // Consume consecutive paragraph lines into one block, joining them
    // with explicit `LineBreak`s so the source wrapping round-trips.
    let mut inlines = Vec::new();
    let mut i = pos;
    while let Some(&line) = lines.get(i).filter(|l| is_paragraph_line(l)) {
        if i > pos {
            inlines.push(Inline::LineBreak);
        }
        inlines.extend(parse_inlines(line));
        i += 1;
    }
    Some(Ok((Block::Paragraph { inlines }, i)))
}

/// Whether `line` can appear as paragraph content: neither blank nor the
/// start of any other block kind.
fn is_paragraph_line(line: &str) -> bool {
    if line.is_empty() {
        return false;
    }
    let trimmed = line.trim();
    // Heading: one or more `*` followed by a space.
    let stars = trimmed.chars().take_while(|c| *c == '*').count();
    if stars > 0 && trimmed[stars..].starts_with(' ') {
        return false;
    }
    if trimmed.starts_with("# ")
        || trimmed.starts_with(":PROPERTIES:")
        || trimmed.starts_with(":LOGBOOK:")
        || trimmed.starts_with("#+begin_")
        || trimmed.starts_with("SCHEDULED:")
        || trimmed.starts_with("DEADLINE:")
        || trimmed.starts_with("CLOSED:")
        || trimmed == "-----"
        || (trimmed.starts_with('|') && trimmed.ends_with('|'))
    {
        return false;
    }
    // A column-0 list bullet starts a list, not a paragraph. An indented
    // bullet has no column-0 list to join, so it stays paragraph text.
    if match_bullet(line).is_some() {
        return false;
    }
    // Keyword line `#+name:`.
    if let Some(rest) = trimmed.strip_prefix("#+") {
        let name_len = rest
            .find(|c: char| c == ':' || c.is_whitespace())
            .unwrap_or(rest.len());
        if name_len > 0 && rest.as_bytes().get(name_len) == Some(&b':') {
            return false;
        }
    }
    true
}

/// Parse inline formatting from a string.
fn parse_inlines(input: &str) -> Vec<Inline> {
    let mut inlines = Vec::new();
    let mut pos = 0;
    let chars: Vec<char> = input.chars().collect();

    // `slice(a..b)` collects an in-range char range to a String. Every call
    // site below derives its bounds from `find_closing` / `next_marker_or_end`
    // / the loop guard, so the range is always valid; an empty fallback would
    // only ever appear on a logic bug.
    let slice =
        |a: usize, b: usize| -> String { chars.get(a..b).unwrap_or_default().iter().collect() };
    let slice_from = |a: usize| -> String { chars.get(a..).unwrap_or_default().iter().collect() };

    while pos < chars.len() {
        let Some(&c) = chars.get(pos) else { break };
        match c {
            '*' => {
                if let Some(end) = find_closing(&chars, pos + 1, '*') {
                    let inner = slice(pos + 1, end);
                    inlines.push(Inline::Bold(parse_inlines(&inner)));
                    pos = end + 1;
                } else {
                    // Treat as literal
                    if let Some(end) = next_marker_or_end(&chars, pos) {
                        inlines.push(Inline::Plain(slice(pos, end)));
                        pos = end;
                    } else {
                        inlines.push(Inline::Plain(slice_from(pos)));
                        pos = chars.len();
                    }
                }
            }
            '/' => {
                if let Some(end) = find_closing(&chars, pos + 1, '/') {
                    let inner = slice(pos + 1, end);
                    inlines.push(Inline::Italic(parse_inlines(&inner)));
                    pos = end + 1;
                } else if let Some(end) = next_marker_or_end(&chars, pos) {
                    inlines.push(Inline::Plain(slice(pos, end)));
                    pos = end;
                } else {
                    inlines.push(Inline::Plain(slice_from(pos)));
                    pos = chars.len();
                }
            }
            '+' => {
                if let Some(end) = find_closing(&chars, pos + 1, '+') {
                    let inner = slice(pos + 1, end);
                    inlines.push(Inline::Strikethrough(parse_inlines(&inner)));
                    pos = end + 1;
                } else if let Some(end) = next_marker_or_end(&chars, pos) {
                    inlines.push(Inline::Plain(slice(pos, end)));
                    pos = end;
                } else {
                    inlines.push(Inline::Plain(slice_from(pos)));
                    pos = chars.len();
                }
            }
            '=' => {
                if let Some(end) = find_closing(&chars, pos + 1, '=') {
                    let code = slice(pos + 1, end);
                    inlines.push(Inline::InlineCode(code));
                    pos = end + 1;
                } else if let Some(end) = next_marker_or_end(&chars, pos) {
                    inlines.push(Inline::Plain(slice(pos, end)));
                    pos = end;
                } else {
                    inlines.push(Inline::Plain(slice_from(pos)));
                    pos = chars.len();
                }
            }
            '~' => {
                if let Some(end) = find_closing(&chars, pos + 1, '~') {
                    let verb = slice(pos + 1, end);
                    inlines.push(Inline::Verbatim(verb));
                    pos = end + 1;
                } else if let Some(end) = next_marker_or_end(&chars, pos) {
                    inlines.push(Inline::Plain(slice(pos, end)));
                    pos = end;
                } else {
                    inlines.push(Inline::Plain(slice_from(pos)));
                    pos = chars.len();
                }
            }
            '[' => {
                let (inline, next) = consume_bracket(&chars, pos);
                inlines.push(inline);
                pos = next;
            }
            _ => {
                if let Some(end) = next_marker_or_end(&chars, pos) {
                    inlines.push(Inline::Plain(slice(pos, end)));
                    pos = end;
                } else {
                    inlines.push(Inline::Plain(slice_from(pos)));
                    pos = chars.len();
                }
            }
        }
    }

    // Merge adjacent Plain inlines
    merge_adjacent_plain(&mut inlines);
    inlines
}

/// Consume a `[`-run at `pos`: an org `[[target]]` / `[[target][desc]]`
/// link, or — when the brackets do not form a well-shaped link — a plain
/// literal run up to the next inline marker. Returns the inline to emit
/// and the position after it. Never drops trailing text.
fn consume_bracket(chars: &[char], pos: usize) -> (Inline, usize) {
    // All ranges below are derived from `position(|c| c == ']')` matches or
    // the loop-verified `pos`, so they are always in bounds; an empty
    // fallback would only surface on a logic bug.
    let collect =
        |a: usize, b: usize| -> String { chars.get(a..b).unwrap_or_default().iter().collect() };
    let collect_from = |a: usize| -> String { chars.get(a..).unwrap_or_default().iter().collect() };
    let plain_to = |end: usize| Inline::Plain(collect(pos, end));
    let plain_rest = || Inline::Plain(collect_from(pos));
    let literal = || {
        next_marker_or_end(chars, pos)
            .map_or_else(|| (plain_rest(), chars.len()), |end| (plain_to(end), end))
    };

    // Not a `[[…` link opener — single bracket, literal.
    if pos + 1 >= chars.len() || chars.get(pos + 1) != Some(&'[') {
        return literal();
    }
    let start = pos + 2;
    let Some(bracket_end) = chars
        .get(start..)
        .and_then(|rest| rest.iter().position(|&c| c == ']'))
        .map(|p| start + p)
    else {
        return (plain_rest(), chars.len());
    };

    if bracket_end + 1 < chars.len() && chars.get(bracket_end + 1) == Some(&']') {
        // [[target]]
        let target = collect(start, bracket_end);
        return (
            Inline::Link {
                target,
                description: None,
            },
            bracket_end + 2,
        );
    }
    if bracket_end + 1 >= chars.len() || chars.get(bracket_end + 1) != Some(&'[') {
        // `[[…]` followed by something other than `]` or `[` — literal.
        return literal();
    }
    // [[target][description]]
    let target: String = collect(start, bracket_end);
    let desc_start = bracket_end + 2;
    match chars
        .get(desc_start..)
        .and_then(|rest| rest.iter().position(|&c| c == ']'))
        .map(|p| desc_start + p)
    {
        Some(desc_end) if desc_end + 1 < chars.len() && chars.get(desc_end + 1) == Some(&']') => {
            let description = collect(desc_start, desc_end);
            (
                Inline::Link {
                    target,
                    description: Some(description),
                },
                desc_end + 2,
            )
        }
        // Malformed `[[target][…` — literal up to the unmatched `]`.
        Some(desc_end) => (plain_to(desc_end + 1), desc_end + 1),
        None => (plain_rest(), chars.len()),
    }
}

fn find_closing(chars: &[char], start: usize, marker: char) -> Option<usize> {
    for i in start..chars.len() {
        let Some(&c) = chars.get(i) else { break };
        if c == marker && (i + 1 == chars.len() || chars.get(i + 1) != Some(&marker)) {
            return Some(i);
        }
    }
    None
}

fn next_marker_or_end(chars: &[char], pos: usize) -> Option<usize> {
    for i in pos..chars.len() {
        let Some(&c) = chars.get(i) else { break };
        if c == '*' || c == '/' || c == '+' || c == '=' || c == '~' || c == '[' {
            if i == pos {
                // Find the next different char
                continue;
            }
            return Some(i);
        }
        if c == '[' && i + 1 < chars.len() && chars.get(i + 1) == Some(&'[') {
            if i == pos {
                continue;
            }
            return Some(i);
        }
    }
    None
}

fn merge_adjacent_plain(inlines: &mut Vec<Inline>) {
    let mut i = 0;
    while i + 1 < inlines.len() {
        if let (Some(Inline::Plain(a)), Some(Inline::Plain(b))) =
            (inlines.get(i), inlines.get(i + 1))
        {
            let merged = format!("{a}{b}");
            if let Some(slot) = inlines.get_mut(i) {
                *slot = Inline::Plain(merged);
            }
            inlines.remove(i + 1);
        } else {
            i += 1;
        }
    }
}

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

    #[test]
    fn parse_heading_level_1() {
        let doc = parse_document("* Hello\n").unwrap();
        assert_eq!(
            doc.blocks[0],
            Block::Heading {
                level: 1,
                title: Title("Hello".into()),
                tags: vec![],
                children: vec![]
            }
        );
    }

    #[test]
    fn parse_heading_with_tags() {
        let doc = parse_document("** Task :rust:kb:\n").unwrap();
        if let Block::Heading {
            level,
            title,
            tags,
            children: _,
        } = &doc.blocks[0]
        {
            assert_eq!(*level, 2);
            assert_eq!(title.0, "Task");
            assert_eq!(tags.len(), 2);
            assert_eq!(tags[0].0, "rust");
            assert_eq!(tags[1].0, "kb");
        } else {
            panic!("expected heading");
        }
    }

    #[test]
    fn parse_paragraph() {
        let doc = parse_document("some text\n").unwrap();
        assert_eq!(
            doc.blocks[0],
            Block::Paragraph {
                inlines: vec![Inline::Plain("some text".into())]
            }
        );
    }

    #[test]
    fn parse_bold() {
        let doc = parse_document("*bold*\n").unwrap();
        if let Block::Paragraph { inlines } = &doc.blocks[0] {
            assert_eq!(inlines.len(), 1);
            assert_eq!(inlines[0], Inline::Bold(vec![Inline::Plain("bold".into())]));
        } else {
            panic!("expected paragraph");
        }
    }

    #[test]
    fn parse_italic() {
        let doc = parse_document("/italic/\n").unwrap();
        if let Block::Paragraph { inlines } = &doc.blocks[0] {
            assert_eq!(
                inlines[0],
                Inline::Italic(vec![Inline::Plain("italic".into())])
            );
        } else {
            panic!("expected paragraph");
        }
    }

    #[test]
    fn parse_strikethrough() {
        let doc = parse_document("+struck+\n").unwrap();
        if let Block::Paragraph { inlines } = &doc.blocks[0] {
            assert_eq!(
                inlines[0],
                Inline::Strikethrough(vec![Inline::Plain("struck".into())])
            );
        } else {
            panic!("expected paragraph");
        }
    }

    #[test]
    fn parse_link_no_description() {
        let doc = parse_document("[[https://example.com]]\n").unwrap();
        if let Block::Paragraph { inlines } = &doc.blocks[0] {
            assert_eq!(
                inlines[0],
                Inline::Link {
                    target: "https://example.com".into(),
                    description: None,
                }
            );
        } else {
            panic!("expected paragraph");
        }
    }

    #[test]
    fn parse_link_with_description() {
        let doc = parse_document("[[https://example.com][example]]\n").unwrap();
        if let Block::Paragraph { inlines } = &doc.blocks[0] {
            assert_eq!(
                inlines[0],
                Inline::Link {
                    target: "https://example.com".into(),
                    description: Some("example".into()),
                }
            );
        } else {
            panic!("expected paragraph");
        }
    }

    #[test]
    fn parse_src_block() {
        let input = "#+begin_src rust\nfn main() {}\n#+end_src\n";
        let doc = parse_document(input).unwrap();
        if let Block::SrcBlock { language, content } = &doc.blocks[0] {
            assert_eq!(language, "rust");
            assert_eq!(content, "fn main() {}\n");
        } else {
            panic!("expected src block");
        }
    }

    #[test]
    fn parse_example_block() {
        let input = "#+begin_example\n$ ls\nfoo\n#+end_example\n";
        let doc = parse_document(input).unwrap();
        assert_eq!(
            doc.blocks[0],
            Block::ExampleBlock {
                content: "$ ls\nfoo\n".into(),
            }
        );
    }

    #[test]
    fn parse_property_drawer() {
        let input = ":PROPERTIES:\n:ID: abc-123\n:END:\n";
        let doc = parse_document(input).unwrap();
        if let Block::PropertyDrawer { entries } = &doc.blocks[0] {
            assert_eq!(entries.len(), 1);
            assert_eq!(entries[0].0, "ID");
            // Value kept verbatim, including the space after the key colon.
            assert_eq!(entries[0].1, " abc-123");
        } else {
            panic!("expected property drawer");
        }
    }

    #[test]
    fn parse_list_unordered() {
        let input = "- one\n- two\n";
        let doc = parse_document(input).unwrap();
        if let Block::List { list_type, items } = &doc.blocks[0] {
            assert_eq!(*list_type, ListType::Unordered);
            assert_eq!(items.len(), 2);
        } else {
            panic!("expected list");
        }
    }

    #[test]
    fn parse_comment() {
        let doc = parse_document("# a comment\n").unwrap();
        assert_eq!(
            doc.blocks[0],
            Block::Comment {
                text: "a comment".into()
            }
        );
    }

    #[test]
    fn parse_horizontal_rule() {
        let doc = parse_document("-----\n").unwrap();
        assert_eq!(doc.blocks[0], Block::HorizontalRule);
    }

    #[test]
    fn parse_single_bracket_run_keeps_trailing_text() {
        // A `[...]` that is not a `[[link]]` must not drop the rest of
        // the line.
        let doc = parse_document("see [his] notes here\n").unwrap();
        assert_eq!(
            doc.blocks[0],
            Block::Paragraph {
                inlines: vec![Inline::Plain("see [his] notes here".into())],
            }
        );
    }

    #[test]
    fn residue_empty_when_every_line_claimed() {
        let input = "* Heading\n\nA paragraph.\n";
        let (_, residue) = parse_document_with_residue(input).unwrap();
        assert!(
            residue.is_empty(),
            "no line should be unclaimed: {residue:?}"
        );
    }

    #[test]
    fn residue_records_unparsable_block_marker() {
        // `#+begin_verse` is claimed by no block — kb models src, quote,
        // and example blocks but not verse blocks.
        let (_, residue) = parse_document_with_residue("#+begin_verse\n").unwrap();
        assert_eq!(residue, vec!["#+begin_verse".to_string()]);
    }

    #[test]
    fn residue_records_unclaimed_line_under_heading() {
        let input = "* Heading\n#+begin_verse\n";
        let (_, residue) = parse_document_with_residue(input).unwrap();
        assert_eq!(residue, vec!["#+begin_verse".to_string()]);
    }

    #[test]
    fn residue_excludes_blank_lines() {
        let (_, residue) = parse_document_with_residue("para\n\n\n").unwrap();
        assert!(
            residue.is_empty(),
            "blank lines are not residue: {residue:?}"
        );
    }
}