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
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
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
//! Markdown to tasks: the extraction step itself.
//!
//! A document is parsed with comrak, and every heading carrying an org-mode
//! keyword (`TODO`, `DONE`, …) becomes a [`Task`], together with the timestamp,
//! priority and clock entries found in its body.
//!
//! [`Task`]: crate::types::Task

use comrak::nodes::{AstNode, NodeValue};
use comrak::{parse_document, Arena, Options};
use regex::Regex;
use std::collections::BTreeMap;
use std::ops::Range;
use std::path::Path;
use std::sync::LazyLock;

use crate::clock::{calculate_total_minutes, extract_clocks, format_duration};
use crate::regex_limits::compile_bounded;
use crate::timestamp::{
    extract_created_normalized, extract_repeater_normalized, extract_timestamp_normalized,
    normalize_weekdays, parse_timestamp_fields_normalized,
};
use crate::types::{Priority, Task, TaskType, MAX_DIAGNOSTIC_ITEMS};

// Per-call cap on invalid-timestamp warnings reuses `MAX_DIAGNOSTIC_ITEMS` so
// both diagnostic surfaces (failed-path list and parse-warning stream) stay
// aligned: "20 entries is already noisy". The counter is owned by the caller
// -- typically `ProcessingStats::ts_warnings_emitted` for a CLI run -- so
// long-running library use cases and parallel scans do not pollute each
// other's budget. The previous process-global `AtomicUsize` was replaced as
// part of the 0.5.0 review (M1).
fn warn_invalid_timestamp(counter: &mut usize, path: &Path, line: u32, ts: &str) {
    let n = *counter;
    *counter = counter.saturating_add(1);
    if n < MAX_DIAGNOSTIC_ITEMS {
        tracing::warn!(
            file = %path.display(),
            line,
            timestamp = ts.trim(),
            "cannot parse timestamp"
        );
    } else if n == MAX_DIAGNOSTIC_ITEMS {
        tracing::warn!(
            limit = MAX_DIAGNOSTIC_ITEMS,
            "more invalid timestamps suppressed (showed first {MAX_DIAGNOSTIC_ITEMS})"
        );
    }
}

// Mirror of `warn_invalid_timestamp` for malformed `org-properties` lines
// (a line that has no `:`). The counter is owned by the caller -- typically
// `ProcessingStats::prop_warnings_emitted` for a CLI run -- so the
// per-`MAX_DIAGNOSTIC_ITEMS` cap spans the whole scan and parallel/library
// uses do not pollute each other's budget. See ADR-0020.
fn warn_invalid_property_line(counter: &mut usize, path: &Path, line: u32, raw: &str) {
    let n = *counter;
    *counter = counter.saturating_add(1);
    if n < MAX_DIAGNOSTIC_ITEMS {
        tracing::warn!(
            file = %path.display(),
            line,
            content = raw.trim(),
            "org-properties line has no ':'; skipping"
        );
    } else if n == MAX_DIAGNOSTIC_ITEMS {
        tracing::warn!(
            limit = MAX_DIAGNOSTIC_ITEMS,
            "more malformed org-properties lines suppressed (showed first {MAX_DIAGNOSTIC_ITEMS})"
        );
    }
}

/// Optional TODO/DONE/CANCELLED/CANCELED keyword anchored to the start of a
/// heading.
///
/// Matches `TODO`, `DONE`, `CANCELLED` (double-L) or `CANCELED` (single-L,
/// the upstream Emacs Org-mode spelling) followed by at least one whitespace
/// character. The double-L `CANCELLED` is listed before the single-L
/// `CANCELED` so the alternation prefers the longer spelling. Used as the
/// first step of heading parsing — see `parse_heading`.
static HEADING_TODO_RE: LazyLock<Regex> =
    LazyLock::new(|| compile_bounded(r"^(TODO|DONE|CANCELLED|CANCELED)\s+"));

/// Priority cookie `[#X]` with an optional trailing space, matching anywhere
/// in the heading text.
///
/// Mirrors emacs org-mode's `org-priority-regexp` semantics: the priority
/// cookie may appear at any position in the (remaining) heading title. The
/// value is either an uppercase ASCII letter or a one- or two-digit integer;
/// the integer range is validated by `Priority::parse` (only `0..=64` is
/// accepted).
///
/// Where the cookie sits decides only whether it is taken out of the title —
/// see `parse_heading`. It never decides whether the priority is read.
///
/// Two-digit alternatives are listed before single-digit `[0-9]` so the
/// matcher prefers the longest valid run (e.g. matches `15`, not just `1`).
static HEADING_PRIORITY_RE: LazyLock<Regex> =
    LazyLock::new(|| compile_bounded(r"\[#([A-Z]|6[0-4]|[1-5][0-9]|[0-9])\] ?"));

/// Extract tasks from markdown content with a caller-owned warning counter.
///
/// Production callers (see `main.rs::scan_files`) pass
/// `&mut ProcessingStats::ts_warnings_emitted` so the per-`MAX_DIAGNOSTIC_ITEMS`
/// cap on invalid-timestamp warnings spans every file in the run. Library
/// callers can pass their own counter to scope the budget per scan.
///
/// # Arguments
/// * `path` - Path to the markdown file. Stored verbatim in `Task.file` for output.
/// * `content` - File content (UTF-8).
/// * `mappings` - Weekday name mappings for localization.
/// * `max_tasks` - Per-file cap. Parsing stops as soon as this many tasks accumulate.
/// * `ts_warning_counter` - Mutable counter used to gate invalid-timestamp warnings.
///
/// # Returns
/// Vector of extracted tasks, capped at `max_tasks`.
pub fn extract_tasks_with_counter(
    path: &Path,
    content: &str,
    mappings: &[(&str, &str)],
    max_tasks: usize,
    ts_warning_counter: &mut usize,
    prop_warning_counter: &mut usize,
) -> Vec<Task> {
    let arena = Arena::new();
    let root = parse_document(&arena, content, &safe_comrak_options());

    let mut tasks = Vec::new();
    let mut current_heading: Option<HeadingInfo> = None;

    for node in root.children() {
        process_node(
            node,
            path,
            &mut tasks,
            &mut current_heading,
            mappings,
            ts_warning_counter,
            prop_warning_counter,
        );

        if tasks.len() >= max_tasks {
            tracing::warn!(
                file = %path.display(),
                limit = max_tasks,
                "reached per-file task limit"
            );
            break;
        }
    }

    // Flush remaining heading
    if let Some(info) = current_heading.take() {
        if let Some(task) = finalize_task(path, info, ts_warning_counter) {
            tasks.push(task);
        }
    }

    tracing::debug!(
        file = %path.display(),
        bytes = content.len(),
        tasks = tasks.len(),
        "parsed file"
    );

    tasks
}

/// Extract tasks from markdown content with a per-call warning budget.
///
/// Convenience wrapper around [`extract_tasks_with_counter`] that owns the
/// counter for the duration of one call. Used by the unit-test suite and
/// available to library callers that scope the invalid-timestamp warning
/// cap per file. The production CLI (`main.rs::scan_files`) uses
/// `extract_tasks_with_counter` directly so the cap spans the whole run.
#[cfg_attr(not(test), allow(dead_code))]
pub fn extract_tasks(
    path: &Path,
    content: &str,
    mappings: &[(&str, &str)],
    max_tasks: usize,
) -> Vec<Task> {
    let mut counter = 0_usize;
    let mut prop_counter = 0_usize;
    extract_tasks_with_counter(
        path,
        content,
        mappings,
        max_tasks,
        &mut counter,
        &mut prop_counter,
    )
}

/// Comrak parsing options.
///
/// **Security note**: this is `Options::default()` deliberately. Defaults:
/// - `render.unsafe_ = false` — raw HTML in markdown is escaped, not passed through.
/// - `extension.tagfilter = false` (filter not applied, since unsafe HTML is already escaped).
/// - No extensions that interpret embedded HTML or scripts are enabled.
///
/// **Do not enable `render.unsafe_` or `extension.tagfilter` here without a
/// security review** — the HTML output goes through `html_escape`, but enabling
/// raw HTML would let untrusted markdown inject arbitrary tags into the rendered
/// page bypassing that escape.
fn safe_comrak_options() -> Options<'static> {
    Options::default()
}

/// Information extracted from a heading
struct HeadingInfo {
    heading: String,
    task_type: Option<TaskType>,
    priority: Option<Priority>,
    line: u32,
    content: String,
    created: Option<String>,
    timestamp: Option<String>,
    clocks: Vec<crate::types::ClockEntry>,
    properties: BTreeMap<String, String>,
}

/// Process a single markdown node
fn process_node<'a>(
    node: &'a AstNode<'a>,
    path: &Path,
    tasks: &mut Vec<Task>,
    current_heading: &mut Option<HeadingInfo>,
    mappings: &[(&str, &str)],
    ts_warning_counter: &mut usize,
    prop_warning_counter: &mut usize,
) {
    // Snapshot the borrow once — clone the value (cheap for Heading/Paragraph) and
    // read the sourcepos line in the same scope; drop before any code that
    // recurses into children (which take their own borrows).
    let (value_clone, line) = {
        let data = node.data.borrow();
        (data.value.clone(), data.sourcepos.start.line as u32)
    };
    match value_clone {
        NodeValue::Heading(_) => {
            // Finalize previous heading first
            if let Some(info) = current_heading.take() {
                if let Some(task) = finalize_task(path, info, ts_warning_counter) {
                    tasks.push(task);
                }
            }

            let text = extract_text(node);
            let (task_type, priority, heading) = parse_heading(&text);
            *current_heading = Some(HeadingInfo {
                heading,
                task_type,
                priority,
                line,
                content: String::new(),
                created: None,
                timestamp: None,
                clocks: Vec::new(),
                properties: BTreeMap::new(),
            });
        }
        NodeValue::Paragraph => {
            if let Some(ref mut info) = current_heading {
                let (created, timestamp) = extract_timestamps_from_node(node, mappings);
                let content = extract_paragraph_text(node);

                for child in node.children() {
                    if let NodeValue::Code(code) = &child.data.borrow().value {
                        info.clocks.extend(extract_clocks(&code.literal));
                    }
                }

                if created.is_some() {
                    info.created = created;
                }
                if timestamp.is_some() {
                    info.timestamp = timestamp;
                }
                if !content.is_empty() {
                    if info.content.is_empty() {
                        info.content = content;
                    } else {
                        info.content.push_str("\n\n");
                        info.content.push_str(&content);
                    }
                }
            }
        }
        NodeValue::CodeBlock(code) => {
            if let Some(ref mut info) = current_heading {
                // Performance: check the property-block info string first and
                // return early on a match, so an org-properties block skips the
                // backtick-strip / weekday-normalise / clock-extract work below.
                // For every other code block the only added cost is this one
                // `&str` comparison. The grep pre-filter (main.rs) is NOT widened
                // for `org-properties`, so the set of scanned files is unchanged.
                if code.info.trim() == "org-properties" {
                    parse_org_properties(
                        &code.literal,
                        &mut info.properties,
                        path,
                        line,
                        prop_warning_counter,
                    );
                } else {
                    let raw = code.literal.trim();
                    // An indented code block (4-space indent) reaches us with
                    // the planning line still wrapped in inline-code backticks
                    // (`    \`DEADLINE: <...>\``). Comrak strips the indent but
                    // leaves the wrapping backticks in `code.literal`, which
                    // would otherwise prevent the DEADLINE/SCHEDULED/CREATED
                    // regex from anchoring on the keyword. Drop a matched
                    // backtick pair before regex matching.
                    let literal = strip_wrapping_backticks(raw);
                    let normalized = normalize_weekdays(literal, mappings);
                    let created = extract_created_normalized(&normalized);
                    let timestamp = extract_timestamp_normalized(&normalized);

                    info.clocks.extend(extract_clocks(literal));

                    if created.is_some() {
                        info.created = created;
                    }
                    if timestamp.is_some() {
                        info.timestamp = timestamp;
                    }
                }
            }
        }
        _ => {}
    }
}

fn finalize_task(path: &Path, info: HeadingInfo, ts_warning_counter: &mut usize) -> Option<Task> {
    if info.task_type.is_none() && info.created.is_none() && info.timestamp.is_none() {
        return None;
    }

    let line = info.line;
    let (ts_type, ts_date, ts_time, ts_end_time, ts_active, ts_repeater) =
        if let Some(ref ts) = info.timestamp {
            // `info.timestamp` is assembled from `extract_timestamp_normalized`
            // regex captures over an already-`normalize_weekdays`d string in
            // both `process_node` branches, so a second normalisation here
            // would be redundant work on every task.
            let parsed = parse_timestamp_fields_normalized(ts);
            if parsed.1.is_none() {
                warn_invalid_timestamp(ts_warning_counter, path, line, ts);
            }
            // The repeater is extracted via a second, fuller pass
            // (`parse_org_timestamp`) rather than the light regex path above:
            // the repeater grammar (prefix/value/unit, `wd`) lives in that
            // parser and is not worth duplicating as another regex helper.
            // The extra parse is timestamp-string-local and runs once per task.
            let repeater = extract_repeater_normalized(ts);
            (parsed.0, parsed.1, parsed.2, parsed.3, parsed.4, repeater)
        } else {
            (None, None, None, None, None, None)
        };

    let (clocks_opt, total_time) = if !info.clocks.is_empty() {
        let total = calculate_total_minutes(&info.clocks).map(format_duration);
        (Some(info.clocks), total)
    } else {
        (None, None)
    };

    let properties = if info.properties.is_empty() {
        None
    } else {
        Some(info.properties)
    };

    Some(Task {
        file: path.display().to_string(),
        // Filled in by the scan when it walked several roots: the parser is
        // given one file and has no notion of which collection it belongs to.
        root: None,
        line,
        heading: info.heading,
        content: info.content,
        task_type: info.task_type,
        priority: info.priority,
        created: info.created,
        timestamp: info.timestamp,
        timestamp_type: ts_type,
        timestamp_active: ts_active,
        timestamp_date: ts_date,
        timestamp_time: ts_time,
        timestamp_end_time: ts_end_time,
        timestamp_repeater: ts_repeater,
        // Populated later by `annotate_next_occurrences` (needs the agenda
        // reference date, which the parser does not have).
        timestamp_next: None,
        clocks: clocks_opt,
        total_clock_time: total_time,
        properties,
    })
}

/// Parse heading text to extract task type, priority, and title.
///
/// Follows the emacs org-mode parser
/// (`org-element--headline-parse-title` / `org-priority-regexp`):
///
/// 1. Strip an optional `TODO` / `DONE` keyword anchored at the start.
/// 2. Search the remaining text for the first `[#X]` cookie at any position,
///    where `X` is `A-Z` or an integer `0..=64`. If found, that becomes the
///    priority, wherever it sits — emacs reads it the same way, through the
///    `.*?` prefix of `org-priority-regexp`.
/// 3. The cookie is taken **out of** the title only when it is in its canonical
///    place: at the start of what is left, i.e. directly after the keyword, or
///    opening the heading when there is no keyword. A cookie written anywhere
///    else stays in the title, together with the text before it.
/// 4. Whatever remains is trimmed and returned as the heading.
///
/// Step 3 is where this parser parts company with `org-element`, whose
/// `:raw-value` drops everything up to the cookie (`goto-char (match-end 0)`).
/// That value is not what a reader sees: `org-agenda` builds its line from
/// `org-get-heading`, which keeps the title whole — `* TODO Buy [#A] filter`
/// is shown as written and still sorts as an `A`. Dropping the prefix here
/// left a trailing cookie with an empty heading and a blank agenda row. See
/// [ADR-0002](../docs/adr/0002-supported-org-mode-subset.md).
///
/// A heading without TODO/DONE and without a priority cookie is returned
/// verbatim (trimmed).
fn parse_heading(text: &str) -> (Option<TaskType>, Option<Priority>, String) {
    // Step 1: optional TODO/DONE prefix.
    let (task_type, rest) = if let Some(caps) = HEADING_TODO_RE.captures(text) {
        let kw = caps.get(1).map(|m| m.as_str()).unwrap_or("");
        let m = caps
            .get(0)
            .expect("Captures::get(0) is Some when captures() succeeds");
        (TaskType::from_keyword(kw), &text[m.end()..])
    } else {
        (None, text)
    };
    let title = rest.trim();

    // Step 2: optional priority cookie anywhere in the remainder.
    if let Some(caps) = HEADING_PRIORITY_RE.captures(title) {
        let value = caps.get(1).map(|m| m.as_str()).unwrap_or("");
        if let Some(priority) = Priority::parse(value) {
            let whole = caps
                .get(0)
                .expect("Captures::get(0) is Some when captures() succeeds");
            // Step 3: only a cookie opening the title is consumed by it.
            let heading = if whole.start() == 0 {
                title[whole.end()..].trim()
            } else {
                title
            };
            return (task_type, Some(priority), heading.to_string());
        }
    }

    (task_type, None, title.to_string())
}

/// Leading `#` run of an ATX heading and the gap after it.
///
/// Capped at six hashes, which is where markdown stops treating the run as a
/// heading, and the gap is mandatory for the same reason: `#no gap` is a
/// paragraph. Used by `parse_heading_line`, which works on the raw file line —
/// unlike `parse_heading`, which is handed the text comrak already stripped
/// the hashes from.
static HEADING_HASHES_RE: LazyLock<Regex> = LazyLock::new(|| compile_bounded(r"^(#{1,6})[ \t]+"));

/// A token found on a heading line, with the byte range it occupies.
///
/// The range covers the token as written, framing included: a priority cookie
/// reports `[#A]`, not `A`. Callers replacing one token slice the line around
/// this range and keep everything else byte-for-byte.
#[derive(Debug, Clone, PartialEq)]
pub struct HeadingToken<T> {
    /// Byte range within the line the token was parsed from.
    pub range: Range<usize>,
    /// What the token parsed to.
    pub value: T,
}

/// A heading line as it sits in a file, located token by token.
///
/// This is the read half of an editing operation and the reason it lives here
/// rather than in the editor: the keyword and cookie grammars are the ones the
/// extractor itself applies, and a second copy of them would drift. Writing —
/// assembling a line back from parts — is deliberately not part of this crate.
///
/// Unlike [`Task`], which carries the heading the agenda displays, nothing is
/// summarised here. A heading may hold text between the keyword and the cookie
/// (`# TODO leftover [#B] Title`): the agenda keeps that text and shows the
/// cookie inside it, and [`title_start`] points at the text rather than past
/// the cookie, so an editor rewriting the title neither swallows the cookie
/// nor moves it. Replacing the cookie itself is what [`priority`] is for — its
/// range addresses the cookie where the user wrote it.
///
/// [`title_start`]: HeadingLine::title_start
/// [`priority`]: HeadingLine::priority
/// [`Task`]: crate::types::Task
#[derive(Debug, Clone, PartialEq)]
pub struct HeadingLine {
    /// Heading level, i.e. the number of leading `#` characters (1 to 6).
    pub level: usize,
    /// The `TODO` / `DONE` / `CANCELLED` / `CANCELED` keyword, when present.
    pub status: Option<HeadingToken<TaskType>>,
    /// The `[#A]` priority cookie, when present and within the accepted range.
    pub priority: Option<HeadingToken<Priority>>,
    /// Byte offset the title starts at, past the tokens above and the
    /// whitespace after them. Also where a caller inserts a token the heading
    /// does not carry yet. A cookie away from its canonical place counts as
    /// part of the title, so the offset stops before it.
    pub title_start: usize,
}

/// Locate the parts of a heading line, or return `None` when `line` is not a
/// heading.
///
/// Applies the same keyword and priority grammars as the extraction path, so a
/// heading the extractor reads one way cannot be rewritten another way. See
/// [`HeadingLine`] for what the result addresses.
///
/// ```
/// # use markdown_org_extract::parse_heading_line;
/// let line = "## TODO [#A] Write the report";
/// let heading = parse_heading_line(line).expect("a heading");
/// assert_eq!(&line[heading.priority.expect("a cookie").range], "[#A]");
/// ```
pub fn parse_heading_line(line: &str) -> Option<HeadingLine> {
    let hashes = HEADING_HASHES_RE.captures(line)?;
    let level = hashes
        .get(1)
        .expect("group 1 is Some when captures() succeeds")
        .len();
    let after_hashes = hashes
        .get(0)
        .expect("Captures::get(0) is Some when captures() succeeds")
        .end();

    let (status, after_status) = match HEADING_TODO_RE.captures(&line[after_hashes..]) {
        Some(caps) => {
            let keyword = caps
                .get(1)
                .expect("group 1 is Some when captures() succeeds");
            let whole = caps
                .get(0)
                .expect("Captures::get(0) is Some when captures() succeeds");
            let token = TaskType::from_keyword(keyword.as_str()).map(|value| HeadingToken {
                range: after_hashes + keyword.start()..after_hashes + keyword.end(),
                value,
            });
            (token, after_hashes + whole.end())
        }
        None => (None, after_hashes),
    };

    // The cookie is searched for in the remainder, at any position, the way
    // `parse_heading` does it — org-mode allows text before it.
    let priority = HEADING_PRIORITY_RE
        .captures(&line[after_status..])
        .and_then(|caps| {
            let value = caps
                .get(1)
                .expect("group 1 is Some when captures() succeeds");
            // The cookie is `[#` + value + `]`; the regex match may also cover
            // a trailing space, which is not part of the token.
            let parsed = Priority::parse(value.as_str())?;
            Some(HeadingToken {
                range: after_status + value.start() - "[#".len()
                    ..after_status + value.end() + "]".len(),
                value: parsed,
            })
        });

    // A cookie opening the remainder is a token of its own and the title
    // starts past it; one written further along belongs to the title, which
    // therefore starts where the keyword left off. Same rule as `parse_heading`
    // applies to the heading it hands the agenda.
    let after_tokens = priority
        .as_ref()
        .filter(|cookie| line[after_status..cookie.range.start].trim().is_empty())
        .map_or(after_status, |cookie| cookie.range.end);
    let title_start = after_tokens
        + line[after_tokens..]
            .find(|c: char| !c.is_whitespace())
            .unwrap_or(line.len() - after_tokens);

    Some(HeadingLine {
        level,
        status,
        priority,
        title_start,
    })
}

/// Strip a matched pair of inline-code backtick fences from the trimmed
/// content of an indented code block.
///
/// Markdown's indented code blocks preserve the literal source minus the
/// leading 4-space indent, so a line like `    \`DEADLINE: <...>\`` arrives
/// here with the wrapping backticks intact. Those wrappers are not part of
/// the planning-line keyword grammar — they're inline-code framing that the
/// user added to keep the line visually attached to the heading in their
/// editor — so we peel one balanced run of backticks before regex matching.
///
/// Returns `s` unchanged when the wrapping is asymmetric or absent.
fn strip_wrapping_backticks(s: &str) -> &str {
    let bytes = s.as_bytes();
    let n_leading = bytes.iter().take_while(|&&b| b == b'`').count();
    if n_leading == 0 {
        return s;
    }
    let n_trailing = bytes.iter().rev().take_while(|&&b| b == b'`').count();
    // Require equal-length fences with at least one non-fence byte between
    // them; otherwise the input is just a run of backticks and stripping
    // would over-consume.
    if n_trailing != n_leading || bytes.len() < 2 * n_leading + 1 {
        return s;
    }
    s[n_leading..bytes.len() - n_leading].trim()
}

/// Parse the literal of an `org-properties` fenced code block into `props`,
/// merging into any existing entries with last-wins on duplicate keys.
///
/// Each non-blank line is split on its first `:`: the key is the text
/// before it (trimmed, case preserved), the value is the remainder
/// (trimmed). An empty key or a line with no `:` is skipped and reported
/// via `warn_invalid_property_line`, gated by the caller-owned counter so
/// the `MAX_DIAGNOSTIC_ITEMS` budget spans the whole run. `block_start_line`
/// is the source line of the opening fence; the per-line offset is added so
/// warnings point near the offending line. See ADR-0020.
fn parse_org_properties(
    literal: &str,
    props: &mut BTreeMap<String, String>,
    path: &Path,
    block_start_line: u32,
    prop_warning_counter: &mut usize,
) {
    for (offset, line) in literal.lines().enumerate() {
        if line.trim().is_empty() {
            continue;
        }
        // Source line of this content line: opening fence + 1 + offset.
        let src_line = block_start_line
            .saturating_add(1)
            .saturating_add(offset as u32);
        match line.split_once(':') {
            Some((key, value)) => {
                let key = key.trim();
                if key.is_empty() {
                    warn_invalid_property_line(prop_warning_counter, path, src_line, line);
                    continue;
                }
                props.insert(key.to_string(), value.trim().to_string());
            }
            None => {
                warn_invalid_property_line(prop_warning_counter, path, src_line, line);
            }
        }
    }
}

/// Extract timestamps (CREATED and others) from paragraph node
fn extract_timestamps_from_node<'a>(
    node: &'a AstNode<'a>,
    mappings: &[(&str, &str)],
) -> (Option<String>, Option<String>) {
    let mut created = None;
    let mut timestamp = None;

    if let NodeValue::Paragraph = &node.data.borrow().value {
        for child in node.children() {
            if let NodeValue::Code(code) = &child.data.borrow().value {
                // Normalize the literal once per inline-code node; both extractors
                // would otherwise scan the same string in lockstep.
                let normalized = normalize_weekdays(&code.literal, mappings);
                if created.is_none() {
                    created = extract_created_normalized(&normalized);
                }
                if timestamp.is_none() {
                    timestamp = extract_timestamp_normalized(&normalized);
                }
            }
        }
    }
    (created, timestamp)
}

/// Extract plain text from paragraph, including text inside Emph/Strong/Link nodes
///
/// Inline code is left out here, unlike in a heading: in a body paragraph it
/// carries the planning lines and the property markers, which are read by
/// their own extractors and would otherwise appear twice — once as data and
/// once as prose.
fn extract_paragraph_text<'a>(node: &'a AstNode<'a>) -> String {
    let mut text = String::new();
    collect_text_recursive(node, &mut text, InlineCode::Drop);
    text.trim().to_string()
}

/// Extract all text from a heading node, including text inside Emph/Strong
/// and the literal of an inline code span.
fn extract_text<'a>(node: &'a AstNode<'a>) -> String {
    let mut text = String::new();
    collect_text_recursive(node, &mut text, InlineCode::Keep);
    text
}

/// What [`collect_text_recursive`] does with an inline code span.
#[derive(Clone, Copy, PartialEq, Eq)]
enum InlineCode {
    /// Write its literal out, so a heading keeps every word it was written
    /// with.
    Keep,
    /// Skip it.
    Drop,
}

fn collect_text_recursive<'a>(node: &'a AstNode<'a>, out: &mut String, code: InlineCode) {
    for child in node.children() {
        let value = child.data.borrow().value.clone();
        match value {
            NodeValue::Text(t) => out.push_str(&t),
            NodeValue::Code(inline) if code == InlineCode::Keep => out.push_str(&inline.literal),
            NodeValue::Emph | NodeValue::Strong | NodeValue::Link(_) | NodeValue::Strikethrough => {
                collect_text_recursive(child, out, code)
            }
            _ => {}
        }
    }
}

/// The text of a markdown fragment as the agenda shows it, with the inline
/// markup taken off.
///
/// This is how a heading reaches [`Task::heading`](crate::Task::heading):
/// emphasis, strong text, links and strikethrough contribute their text, and
/// an inline code span contributes its literal. An editor holding the raw
/// line can therefore compare what the file says against what it was handed
/// — `parse_heading_line` says where the title starts, and this says what it
/// looks like once extracted.
///
/// ```
/// # use markdown_org_extract::{display_text, parse_heading_line};
/// let line = "# TODO **Отчёт** за июль";
/// let heading = parse_heading_line(line).expect("a heading");
/// assert_eq!(display_text(&line[heading.title_start..]), "Отчёт за июль");
/// ```
pub fn display_text(markdown: &str) -> String {
    let arena = Arena::new();
    let root = parse_document(&arena, markdown, &safe_comrak_options());

    let mut text = String::new();
    collect_block_text(root, &mut text);
    text.trim().to_string()
}

/// Walk down to the inline content of every block and collect its text.
///
/// A fragment handed to [`display_text`] is parsed as a document, so its
/// inline nodes sit under a paragraph (or a heading, when the caller passes a
/// whole line); the leaves are the same either way.
fn collect_block_text<'a>(node: &'a AstNode<'a>, out: &mut String) {
    for child in node.children() {
        let value = child.data.borrow().value.clone();
        match value {
            NodeValue::Paragraph | NodeValue::Heading(_) => {
                collect_text_recursive(child, out, InlineCode::Keep)
            }
            _ => collect_block_text(child, out),
        }
    }
}

// Need clone for NodeValue match — comrak nodes are RefCell-borrowed
// Re-import for clone derive if not present.

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

    #[test]
    fn warn_invalid_timestamp_advances_per_call_counter() {
        // The 0.5.0 review (M1) replaced a process-global
        // `TS_WARNINGS_EMITTED: AtomicUsize` with a counter owned by the
        // caller (typically `ProcessingStats::ts_warnings_emitted`).
        // This test pins the per-call advance: each call bumps the
        // counter by exactly one.
        let mut counter = 0_usize;
        let path = Path::new("t.md");
        for i in 1..=25 {
            warn_invalid_timestamp(&mut counter, path, i, "<bad>");
        }
        assert_eq!(counter, 25);
    }

    #[test]
    fn warn_invalid_property_line_advances_per_call_counter() {
        // Same per-call advance contract as warn_invalid_timestamp: each
        // call bumps the caller-owned counter by exactly one, so the
        // MAX_DIAGNOSTIC_ITEMS cap spans the whole run (ADR-0020).
        let mut counter = 0_usize;
        let path = Path::new("t.md");
        for i in 1..=25 {
            warn_invalid_property_line(&mut counter, path, i, "no-colon-here");
        }
        assert_eq!(counter, 25);
    }

    #[test]
    fn warn_invalid_timestamp_counters_are_independent() {
        // Independent counters do not pollute each other: e.g. a library
        // consumer running two separate scans, or unit tests in the same
        // binary, each see a fresh budget. With the previous global
        // static this assertion would not hold across runs in one
        // process.
        let mut counter_a = 0_usize;
        let mut counter_b = 0_usize;
        let path = Path::new("t.md");
        for _ in 0..MAX_DIAGNOSTIC_ITEMS {
            warn_invalid_timestamp(&mut counter_a, path, 1, "<bad>");
        }
        warn_invalid_timestamp(&mut counter_b, path, 1, "<bad>");
        assert_eq!(counter_a, MAX_DIAGNOSTIC_ITEMS);
        assert_eq!(counter_b, 1);
    }

    #[test]
    fn test_parse_heading_with_priority() {
        let (task_type, priority, heading) = parse_heading("TODO [#A] Important task");
        assert_eq!(task_type, Some(TaskType::Todo));
        assert_eq!(priority, Some(Priority::A));
        assert_eq!(heading, "Important task");
    }

    #[test]
    fn test_parse_heading_without_priority() {
        let (task_type, priority, heading) = parse_heading("DONE Simple task");
        assert_eq!(task_type, Some(TaskType::Done));
        assert_eq!(priority, None);
        assert_eq!(heading, "Simple task");
    }

    #[test]
    fn test_parse_heading_no_task() {
        let (task_type, priority, heading) = parse_heading("Regular heading");
        assert_eq!(task_type, None);
        assert_eq!(priority, None);
        assert_eq!(heading, "Regular heading");
    }

    // The next batch mirrors the test matrix from the bug report
    // "markdown-org-extract: приоритет `[#X]` без TODO/DONE не распознаётся".
    // We follow emacs org-mode semantics (`org-priority-regexp`) wherever the
    // bug report diverged from it — concretely case 8 below.

    #[test]
    fn parse_heading_priority_without_todo() {
        // Case 1: `### [#A] Заголовок`.
        let (tt, p, h) = parse_heading("[#A] Заголовок");
        assert_eq!(tt, None);
        assert_eq!(p, Some(Priority::A));
        assert_eq!(h, "Заголовок");
    }

    #[test]
    fn parse_heading_todo_with_priority() {
        // Case 2: `### TODO [#A] Заголовок`.
        let (tt, p, h) = parse_heading("TODO [#A] Заголовок");
        assert_eq!(tt, Some(TaskType::Todo));
        assert_eq!(p, Some(Priority::A));
        assert_eq!(h, "Заголовок");
    }

    #[test]
    fn parse_heading_done_with_priority_b() {
        // Case 3: `### DONE [#B] Заголовок`.
        let (tt, p, h) = parse_heading("DONE [#B] Заголовок");
        assert_eq!(tt, Some(TaskType::Done));
        assert_eq!(p, Some(Priority::B));
        assert_eq!(h, "Заголовок");
    }

    #[test]
    fn parse_heading_plain_text_no_markers() {
        // Case 4: `### Заголовок`.
        let (tt, p, h) = parse_heading("Заголовок");
        assert_eq!(tt, None);
        assert_eq!(p, None);
        assert_eq!(h, "Заголовок");
    }

    #[test]
    fn parse_heading_todo_no_priority() {
        // Case 5: `### TODO Заголовок`.
        let (tt, p, h) = parse_heading("TODO Заголовок");
        assert_eq!(tt, Some(TaskType::Todo));
        assert_eq!(p, None);
        assert_eq!(h, "Заголовок");
    }

    #[test]
    fn parse_heading_numeric_priority() {
        // Case 6: `### [#1] Заголовок`.
        let (tt, p, h) = parse_heading("[#1] Заголовок");
        assert_eq!(tt, None);
        assert_eq!(p, Some(Priority::Numeric(1)));
        assert_eq!(h, "Заголовок");
    }

    #[test]
    fn parse_heading_extra_whitespace_around_priority() {
        // Case 7: `###     [#A]     Заголовок` — comrak normalises the leading
        // whitespace after the `###` marker, so the heading text reaching us
        // starts at `[#A]`. Trailing extra spaces around the heading are
        // trimmed.
        let (tt, p, h) = parse_heading("[#A]     Заголовок");
        assert_eq!(tt, None);
        assert_eq!(p, Some(Priority::A));
        assert_eq!(h, "Заголовок");
    }

    #[test]
    fn parse_heading_priority_in_the_middle_org_semantics() {
        // Case 8: `### Без приоритета и [#A] внутри`.
        // The cookie counts wherever it sits — `org-get-priority` finds it
        // through the `.*?` prefix of `org-priority-regexp` — but the title is
        // left as written: that is the line emacs puts in the agenda.
        let (tt, p, h) = parse_heading("Без приоритета и [#A] внутри");
        assert_eq!(tt, None);
        assert_eq!(p, Some(Priority::A));
        assert_eq!(h, "Без приоритета и [#A] внутри");
    }

    #[test]
    fn parse_heading_trailing_cookie_leaves_a_title_behind() {
        // The case the two clients answered differently: a cookie written last
        // used to take the whole title with it and leave the agenda showing an
        // empty row.
        let (tt, p, h) = parse_heading("TODO Заголовок с cookie в конце [#A]");
        assert_eq!(tt, Some(TaskType::Todo));
        assert_eq!(p, Some(Priority::A));
        assert_eq!(h, "Заголовок с cookie в конце [#A]");
    }

    #[test]
    fn parse_heading_two_digit_numeric_priority() {
        let (tt, p, h) = parse_heading("[#15] Mid range");
        assert_eq!(tt, None);
        assert_eq!(p, Some(Priority::Numeric(15)));
        assert_eq!(h, "Mid range");

        let (tt, p, h) = parse_heading("[#64] At upper bound");
        assert_eq!(tt, None);
        assert_eq!(p, Some(Priority::Numeric(64)));
        assert_eq!(h, "At upper bound");
    }

    #[test]
    fn parse_heading_rejects_numeric_out_of_range() {
        // `[#65]` and higher are not a valid org-mode priority. The cookie
        // stays inside the heading text verbatim.
        let (tt, p, h) = parse_heading("[#65] Above range");
        assert_eq!(tt, None);
        assert_eq!(p, None);
        assert_eq!(h, "[#65] Above range");
    }

    #[test]
    fn parse_heading_rejects_lowercase_priority() {
        let (tt, p, h) = parse_heading("[#a] Lowercase");
        assert_eq!(tt, None);
        assert_eq!(p, None);
        assert_eq!(h, "[#a] Lowercase");
    }

    #[test]
    fn parse_heading_todo_then_priority_with_intervening_text() {
        // The cookie is out of its canonical place, so it stays in the title
        // and only the priority is taken from it. Emacs shows the same line in
        // the agenda, cookie included.
        let (tt, p, h) = parse_heading("TODO Купить [#A] фильтр");
        assert_eq!(tt, Some(TaskType::Todo));
        assert_eq!(p, Some(Priority::A));
        assert_eq!(h, "Купить [#A] фильтр");
    }

    #[test]
    fn parse_heading_priority_without_trailing_space() {
        // `\] ?` makes the post-cookie space optional.
        let (tt, p, h) = parse_heading("[#A]NoSpace");
        assert_eq!(tt, None);
        assert_eq!(p, Some(Priority::A));
        assert_eq!(h, "NoSpace");
    }

    #[test]
    fn parse_heading_cancelled_simple() {
        let (tt, p, h) = parse_heading("CANCELLED Foo");
        assert_eq!(tt, Some(TaskType::Cancelled(CancelledSpelling::DoubleL)));
        assert_eq!(p, None);
        assert_eq!(h, "Foo");
    }

    #[test]
    fn parse_heading_cancelled_with_priority() {
        let (tt, p, h) = parse_heading("CANCELLED [#A] Foo");
        assert_eq!(tt, Some(TaskType::Cancelled(CancelledSpelling::DoubleL)));
        assert_eq!(p, Some(Priority::A));
        assert_eq!(h, "Foo");
    }

    #[test]
    fn parse_heading_cancelled_without_whitespace() {
        // No whitespace after the keyword: not recognised, stays in title.
        let (tt, p, h) = parse_heading("CANCELLEDFoo");
        assert_eq!(tt, None);
        assert_eq!(p, None);
        assert_eq!(h, "CANCELLEDFoo");
    }

    #[test]
    fn parse_heading_cancelled_lowercase_not_recognised() {
        // Case-sensitive, like TODO/DONE.
        let (tt, p, h) = parse_heading("cancelled Foo");
        assert_eq!(tt, None);
        assert_eq!(p, None);
        assert_eq!(h, "cancelled Foo");
    }

    #[test]
    fn parse_heading_todo_cancelled_first_keyword_wins() {
        // First keyword wins; the rest goes into the title (existing rule).
        let (tt, p, h) = parse_heading("TODO CANCELLED Foo");
        assert_eq!(tt, Some(TaskType::Todo));
        assert_eq!(p, None);
        assert_eq!(h, "CANCELLED Foo");
    }

    #[test]
    fn parse_heading_canceled_single_l() {
        // Upstream Emacs Org-mode spells the keyword with a single L. See
        // ADR-0021; recognised alongside the double-L `CANCELLED`.
        let (tt, p, h) = parse_heading("CANCELED Foo");
        assert_eq!(tt, Some(TaskType::Cancelled(CancelledSpelling::SingleL)));
        assert_eq!(p, None);
        assert_eq!(h, "Foo");
    }

    #[test]
    fn parse_heading_canceled_with_priority() {
        let (tt, p, h) = parse_heading("CANCELED [#A] Foo");
        assert_eq!(tt, Some(TaskType::Cancelled(CancelledSpelling::SingleL)));
        assert_eq!(p, Some(Priority::A));
        assert_eq!(h, "Foo");
    }

    #[test]
    fn parse_heading_canceled_lowercase_not_recognised() {
        // Case-sensitive, like TODO/DONE/CANCELLED.
        let (tt, p, h) = parse_heading("canceled Foo");
        assert_eq!(tt, None);
        assert_eq!(p, None);
        assert_eq!(h, "canceled Foo");
    }

    #[test]
    fn parse_heading_canceled_without_whitespace_not_recognised() {
        // No whitespace after the keyword: not recognised, stays in title.
        let (tt, p, h) = parse_heading("CANCELEDfoo");
        assert_eq!(tt, None);
        assert_eq!(p, None);
        assert_eq!(h, "CANCELEDfoo");
    }

    #[test]
    fn extract_tasks_marks_scheduled_angle_bracket_as_active() {
        // End-to-end: a SCHEDULED line with `<...>` must surface
        // `timestamp_active = Some(true)` in the resulting Task, so
        // downstream consumers can branch on bracket form without
        // re-parsing the timestamp string. See ADR-0014.
        let content = "### TODO Pin me\n`SCHEDULED: <2026-05-21 Thu>`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].timestamp_active, Some(true));
    }

    #[test]
    fn extract_tasks_marks_missing_timestamp_active_as_none() {
        // Heading without a timestamp must keep `timestamp_active = None`,
        // matching the rule that absent optional fields skip JSON
        // serialisation (ADR-0015).
        let content = "### Project kickoff\n\n`CREATED: [2025-09-01 Mon]`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].timestamp_active, None);
    }

    #[test]
    fn extract_tasks_basic_todo_with_deadline() {
        let content = "\
### TODO [#A] Write docs\n\
`DEADLINE: <2025-12-10 Wed>`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        let t = &tasks[0];
        assert_eq!(t.task_type, Some(TaskType::Todo));
        assert_eq!(t.priority, Some(Priority::A));
        assert_eq!(t.heading, "Write docs");
        assert_eq!(t.timestamp_type, Some("DEADLINE".to_string()));
        assert_eq!(t.timestamp_date, Some("2025-12-10".to_string()));
    }

    #[test]
    fn extract_tasks_extracts_emph_text_in_heading() {
        // Regression: previously emphasised text inside heading was dropped.
        let content = "### TODO **Important** task\n`DEADLINE: <2025-12-10 Wed>`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].heading, "Important task");
    }

    #[test]
    fn extract_tasks_ignores_non_task_headings_without_timestamps() {
        let content = "### Just a heading\n\nSome text.\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert!(tasks.is_empty());
    }

    #[test]
    fn extract_tasks_keeps_created_without_todo() {
        // Heading without TODO/DONE keyword but with a CREATED line is still a task.
        let content = "### Project kickoff\n\n`CREATED: [2025-09-01 Mon]`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].task_type, None);
        assert_eq!(tasks[0].created, Some("CREATED: [2025-09-01 Mon]".into()));
    }

    #[test]
    fn extract_tasks_concatenates_multiple_paragraphs() {
        // Regression: previously only the first paragraph was kept as content.
        let content = "\
### TODO Multi-line task\n\
First paragraph.\n\
\n\
Second paragraph.\n\
";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        assert!(tasks[0].content.contains("First paragraph"));
        assert!(tasks[0].content.contains("Second paragraph"));
    }

    #[test]
    fn extract_tasks_extracts_clock_from_inline_code() {
        let content = "\
### TODO Track time\n\
`CLOCK: [2025-09-01 Mon 10:00]--[2025-09-01 Mon 11:30] => 1:30`\n\
";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        let t = &tasks[0];
        assert!(t.clocks.is_some());
        assert_eq!(t.total_clock_time.as_deref(), Some("1:30"));
    }

    #[test]
    fn extract_tasks_handles_done_priority() {
        let content = "### DONE [#B] Wrap up\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].task_type, Some(TaskType::Done));
        assert_eq!(tasks[0].priority, Some(Priority::B));
    }

    #[test]
    fn extract_tasks_priority_without_todo_with_scheduled() {
        // Bug report case: priority cookie before SCHEDULED heading, no TODO.
        // After the fix the heading must surface as a task with priority=A and
        // task_type=None, since the SCHEDULED line is what makes it agenda-eligible.
        let content = "\
### [#A] Поменять резину до 16.05.2026\n\
`SCHEDULED: <2026-05-09 Sat>`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        let t = &tasks[0];
        assert_eq!(t.task_type, None);
        assert_eq!(t.priority, Some(Priority::A));
        assert_eq!(t.heading, "Поменять резину до 16.05.2026");
        assert_eq!(t.timestamp_type, Some("SCHEDULED".to_string()));
        assert_eq!(t.timestamp_date, Some("2026-05-09".to_string()));
    }

    #[test]
    fn extract_tasks_numeric_priority_with_deadline() {
        // Numeric priority `[#1]` without TODO, with a DEADLINE line.
        let content = "\
### [#1] Numeric priority task\n\
`DEADLINE: <2026-05-09 Sat>`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        let t = &tasks[0];
        assert_eq!(t.task_type, None);
        assert_eq!(t.priority, Some(Priority::Numeric(1)));
        assert_eq!(t.heading, "Numeric priority task");
    }

    #[test]
    fn extract_tasks_priority_in_middle_keeps_the_prefix() {
        // The cookie is read wherever it sits, and the heading reaches the
        // agenda as the file has it — nothing before the cookie is dropped.
        let content = "\
### Без приоритета и [#A] внутри\n\
`SCHEDULED: <2026-05-09 Sat>`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        let t = &tasks[0];
        assert_eq!(t.task_type, None);
        assert_eq!(t.priority, Some(Priority::A));
        assert_eq!(t.heading, "Без приоритета и [#A] внутри");
    }

    #[test]
    fn extract_tasks_bug_report_minimal_reproduction() {
        // Three-heading reproduction from the bug report: priority without
        // TODO, TODO + priority, plain heading. SCHEDULED is wrapped in
        // backticks so the existing inline-code parser picks it up.
        let content = "\
### [#A] Поменять резину до 16.05.2026\n\
`SCHEDULED: <2026-05-09 Sat>`\n\
\n\
### TODO [#A] Поменять масло\n\
`SCHEDULED: <2026-05-09 Sat>`\n\
\n\
### Купить фильтр\n\
`SCHEDULED: <2026-05-09 Sat>`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 3);

        assert_eq!(tasks[0].task_type, None);
        assert_eq!(tasks[0].priority, Some(Priority::A));
        assert_eq!(tasks[0].heading, "Поменять резину до 16.05.2026");

        assert_eq!(tasks[1].task_type, Some(TaskType::Todo));
        assert_eq!(tasks[1].priority, Some(Priority::A));
        assert_eq!(tasks[1].heading, "Поменять масло");

        assert_eq!(tasks[2].task_type, None);
        assert_eq!(tasks[2].priority, None);
        assert_eq!(tasks[2].heading, "Купить фильтр");
    }

    // Regression suite for the "indented planning line" cases. A heading
    // followed by a 4-space-indented DEADLINE/SCHEDULED/CREATED line is
    // parsed by comrak as an indented code block; the timestamp must still
    // be recovered, whether or not the planning line is wrapped in inline
    // backticks. Matches what `emacs` org-agenda surfaces.
    // The literals below use real newlines (no `\\\n` Rust string
    // continuation): the continuation form would silently swallow the
    // four leading spaces and reduce the case to "no indent at all".
    #[test]
    fn extract_tasks_indented_inline_code_deadline() {
        let content = "#### Birthday\n    `DEADLINE: <2026-05-07 Thu +1y>`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1, "task should not be dropped");
        let t = &tasks[0];
        assert_eq!(t.timestamp_type.as_deref(), Some("DEADLINE"));
        assert_eq!(t.timestamp_date.as_deref(), Some("2026-05-07"));
    }

    #[test]
    fn extract_tasks_todo_indented_inline_code_deadline() {
        let content = "#### TODO Birthday\n    `DEADLINE: <2026-05-07 Thu +1y>`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        let t = &tasks[0];
        assert_eq!(t.task_type, Some(TaskType::Todo));
        assert_eq!(t.timestamp_date.as_deref(), Some("2026-05-07"));
    }

    #[test]
    fn extract_tasks_indented_inline_code_blank_lines_between() {
        // Whitespace between heading and planning line (blank lines, tabs,
        // mixed indentation) must not block timestamp recovery.
        let content = "#### Birthday\n\n  \t  \n    `DEADLINE: <2026-05-07 Thu +1y>`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        let t = &tasks[0];
        assert_eq!(t.timestamp_date.as_deref(), Some("2026-05-07"));
    }

    #[test]
    fn extract_tasks_with_ru_mappings_reproduces_cli_pipeline() {
        // Reproduce what `main.rs` feeds to `extract_tasks` when the default
        // `--locale ru,en` is in effect. Pulling the table from `cli` keeps
        // this test in sync with whatever `get_weekday_mappings("ru")` would
        // produce in production.
        let content = "#### TODO Birthday\n    `DEADLINE: <2026-05-07 Thu +1y>`\n";
        let tasks = extract_tasks(
            Path::new("t.md"),
            content,
            crate::locale::RU_WEEKDAY_MAPPINGS,
            DEFAULT_MAX_TASKS,
        );
        assert_eq!(tasks.len(), 1);
        let t = &tasks[0];
        assert_eq!(t.task_type, Some(TaskType::Todo));
        assert_eq!(t.timestamp_date.as_deref(), Some("2026-05-07"));
    }

    #[test]
    fn extract_tasks_inline_code_scheduled_no_indent() {
        let content = "#### Followup\n`SCHEDULED: <2026-05-07 Thu>`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        let t = &tasks[0];
        assert_eq!(t.timestamp_type.as_deref(), Some("SCHEDULED"));
        assert_eq!(t.timestamp_date.as_deref(), Some("2026-05-07"));
    }

    #[test]
    fn extract_tasks_indented_inline_code_created() {
        let content = "#### Project kickoff\n    `CREATED: [2025-09-01 Mon]`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        let t = &tasks[0];
        assert_eq!(t.created.as_deref(), Some("CREATED: [2025-09-01 Mon]"));
    }

    #[test]
    fn extract_tasks_parses_single_property() {
        let content = "### TODO Ship release\n`SCHEDULED: <2026-06-01 Mon 10:00>`\n```org-properties\nGCAL_EVENT_ID: abc123/primary\n```\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks.len(), 1);
        let props = tasks[0].properties.as_ref().expect("properties present");
        assert_eq!(
            props.get("GCAL_EVENT_ID").map(String::as_str),
            Some("abc123/primary")
        );
        // The block must not leak into the task body content.
        assert!(!tasks[0].content.contains("GCAL_EVENT_ID"));
        assert!(!tasks[0].content.contains("org-properties"));
    }

    #[test]
    fn extract_tasks_parses_multiple_properties() {
        let content =
            "### TODO T\n`SCHEDULED: <2026-06-01 Mon>`\n```org-properties\nA: 1\nB: 2\n```\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        let props = tasks[0].properties.as_ref().unwrap();
        assert_eq!(props.get("A").map(String::as_str), Some("1"));
        assert_eq!(props.get("B").map(String::as_str), Some("2"));
    }

    #[test]
    fn extract_tasks_property_duplicate_keys_last_wins() {
        let content = "### TODO T\n`SCHEDULED: <2026-06-01 Mon>`\n```org-properties\nK: first\nK: second\n```\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(
            tasks[0]
                .properties
                .as_ref()
                .unwrap()
                .get("K")
                .map(String::as_str),
            Some("second")
        );
    }

    #[test]
    fn extract_tasks_property_empty_value_allowed() {
        let content = "### TODO T\n`SCHEDULED: <2026-06-01 Mon>`\n```org-properties\nK:\n```\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(
            tasks[0]
                .properties
                .as_ref()
                .unwrap()
                .get("K")
                .map(String::as_str),
            Some("")
        );
    }

    #[test]
    fn extract_tasks_property_malformed_line_skipped() {
        let content = "### TODO T\n`SCHEDULED: <2026-06-01 Mon>`\n```org-properties\nGOOD: x\nno colon here\n```\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        let props = tasks[0].properties.as_ref().unwrap();
        assert_eq!(props.get("GOOD").map(String::as_str), Some("x"));
        assert_eq!(props.len(), 1, "malformed line must be skipped");
    }

    #[test]
    fn extract_tasks_empty_property_block_yields_none() {
        let content = "### TODO T\n`SCHEDULED: <2026-06-01 Mon>`\n```org-properties\n\n```\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks[0].properties, None);
    }

    #[test]
    fn extract_tasks_property_info_with_extra_attrs_not_recognised() {
        // Info string must be exactly "org-properties"; extra attributes
        // mean it is a plain code block, not a property block.
        let content =
            "### TODO T\n`SCHEDULED: <2026-06-01 Mon>`\n```org-properties extra\nK: v\n```\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(tasks[0].properties, None);
    }

    #[test]
    fn extract_tasks_clock_code_block_unaffected_by_properties() {
        // A CLOCK-bearing code block on the same task is still parsed for
        // clocks; the org-properties block is parsed for properties.
        let content = "### TODO T\n```org-properties\nK: v\n```\n`CLOCK: [2025-09-01 Mon 10:00]--[2025-09-01 Mon 11:30] => 1:30`\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        assert_eq!(
            tasks[0]
                .properties
                .as_ref()
                .unwrap()
                .get("K")
                .map(String::as_str),
            Some("v")
        );
        assert_eq!(tasks[0].total_clock_time.as_deref(), Some("1:30"));
    }

    #[test]
    fn extract_tasks_merges_multiple_property_blocks_last_wins() {
        let content = "### TODO T\n`SCHEDULED: <2026-06-01 Mon>`\n```org-properties\nK: one\n```\n```org-properties\nK: two\nL: three\n```\n";
        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
        let props = tasks[0].properties.as_ref().unwrap();
        assert_eq!(props.get("K").map(String::as_str), Some("two"));
        assert_eq!(props.get("L").map(String::as_str), Some("three"));
    }
}