Skip to main content

markdown_org_extract/
parser.rs

1//! Markdown to tasks: the extraction step itself.
2//!
3//! A document is parsed with comrak, and every heading carrying an org-mode
4//! keyword (`TODO`, `DONE`, …) becomes a [`Task`], together with the timestamp,
5//! priority and clock entries found in its body.
6//!
7//! [`Task`]: crate::types::Task
8
9use comrak::nodes::{AstNode, NodeValue};
10use comrak::{parse_document, Arena, Options};
11use regex::Regex;
12use std::collections::BTreeMap;
13use std::ops::Range;
14use std::path::Path;
15use std::sync::LazyLock;
16
17use crate::clock::{calculate_total_minutes, extract_clocks, format_duration};
18use crate::regex_limits::compile_bounded;
19use crate::timestamp::{
20    extract_created_normalized, extract_repeater_normalized, extract_timestamp_normalized,
21    normalize_weekdays, parse_timestamp_fields_normalized,
22};
23use crate::types::{Priority, Task, TaskType, MAX_DIAGNOSTIC_ITEMS};
24
25// Per-call cap on invalid-timestamp warnings reuses `MAX_DIAGNOSTIC_ITEMS` so
26// both diagnostic surfaces (failed-path list and parse-warning stream) stay
27// aligned: "20 entries is already noisy". The counter is owned by the caller
28// -- typically `ProcessingStats::ts_warnings_emitted` for a CLI run -- so
29// long-running library use cases and parallel scans do not pollute each
30// other's budget. The previous process-global `AtomicUsize` was replaced as
31// part of the 0.5.0 review (M1).
32fn warn_invalid_timestamp(counter: &mut usize, path: &Path, line: u32, ts: &str) {
33    let n = *counter;
34    *counter = counter.saturating_add(1);
35    if n < MAX_DIAGNOSTIC_ITEMS {
36        tracing::warn!(
37            file = %path.display(),
38            line,
39            timestamp = ts.trim(),
40            "cannot parse timestamp"
41        );
42    } else if n == MAX_DIAGNOSTIC_ITEMS {
43        tracing::warn!(
44            limit = MAX_DIAGNOSTIC_ITEMS,
45            "more invalid timestamps suppressed (showed first {MAX_DIAGNOSTIC_ITEMS})"
46        );
47    }
48}
49
50// Mirror of `warn_invalid_timestamp` for malformed `org-properties` lines
51// (a line that has no `:`). The counter is owned by the caller -- typically
52// `ProcessingStats::prop_warnings_emitted` for a CLI run -- so the
53// per-`MAX_DIAGNOSTIC_ITEMS` cap spans the whole scan and parallel/library
54// uses do not pollute each other's budget. See ADR-0020.
55fn warn_invalid_property_line(counter: &mut usize, path: &Path, line: u32, raw: &str) {
56    let n = *counter;
57    *counter = counter.saturating_add(1);
58    if n < MAX_DIAGNOSTIC_ITEMS {
59        tracing::warn!(
60            file = %path.display(),
61            line,
62            content = raw.trim(),
63            "org-properties line has no ':'; skipping"
64        );
65    } else if n == MAX_DIAGNOSTIC_ITEMS {
66        tracing::warn!(
67            limit = MAX_DIAGNOSTIC_ITEMS,
68            "more malformed org-properties lines suppressed (showed first {MAX_DIAGNOSTIC_ITEMS})"
69        );
70    }
71}
72
73/// Optional TODO/DONE/CANCELLED/CANCELED keyword anchored to the start of a
74/// heading.
75///
76/// Matches `TODO`, `DONE`, `CANCELLED` (double-L) or `CANCELED` (single-L,
77/// the upstream Emacs Org-mode spelling) followed by at least one whitespace
78/// character. The double-L `CANCELLED` is listed before the single-L
79/// `CANCELED` so the alternation prefers the longer spelling. Used as the
80/// first step of heading parsing — see `parse_heading`.
81static HEADING_TODO_RE: LazyLock<Regex> =
82    LazyLock::new(|| compile_bounded(r"^(TODO|DONE|CANCELLED|CANCELED)\s+"));
83
84/// Priority cookie `[#X]` with an optional trailing space, matching anywhere
85/// in the heading text.
86///
87/// Mirrors emacs org-mode's `org-priority-regexp` semantics: the priority
88/// cookie may appear at any position in the (remaining) heading title. The
89/// value is either an uppercase ASCII letter or a one- or two-digit integer;
90/// the integer range is validated by `Priority::parse` (only `0..=64` is
91/// accepted).
92///
93/// Where the cookie sits decides only whether it is taken out of the title —
94/// see `parse_heading`. It never decides whether the priority is read.
95///
96/// Two-digit alternatives are listed before single-digit `[0-9]` so the
97/// matcher prefers the longest valid run (e.g. matches `15`, not just `1`).
98static HEADING_PRIORITY_RE: LazyLock<Regex> =
99    LazyLock::new(|| compile_bounded(r"\[#([A-Z]|6[0-4]|[1-5][0-9]|[0-9])\] ?"));
100
101/// Extract tasks from markdown content with a caller-owned warning counter.
102///
103/// Production callers (see `main.rs::scan_files`) pass
104/// `&mut ProcessingStats::ts_warnings_emitted` so the per-`MAX_DIAGNOSTIC_ITEMS`
105/// cap on invalid-timestamp warnings spans every file in the run. Library
106/// callers can pass their own counter to scope the budget per scan.
107///
108/// # Arguments
109/// * `path` - Path to the markdown file. Stored verbatim in `Task.file` for output.
110/// * `content` - File content (UTF-8).
111/// * `mappings` - Weekday name mappings for localization.
112/// * `max_tasks` - Per-file cap. Parsing stops as soon as this many tasks accumulate.
113/// * `ts_warning_counter` - Mutable counter used to gate invalid-timestamp warnings.
114///
115/// # Returns
116/// Vector of extracted tasks, capped at `max_tasks`.
117pub fn extract_tasks_with_counter(
118    path: &Path,
119    content: &str,
120    mappings: &[(&str, &str)],
121    max_tasks: usize,
122    ts_warning_counter: &mut usize,
123    prop_warning_counter: &mut usize,
124) -> Vec<Task> {
125    let arena = Arena::new();
126    let root = parse_document(&arena, content, &safe_comrak_options());
127
128    let mut tasks = Vec::new();
129    let mut current_heading: Option<HeadingInfo> = None;
130
131    for node in root.children() {
132        process_node(
133            node,
134            path,
135            &mut tasks,
136            &mut current_heading,
137            mappings,
138            ts_warning_counter,
139            prop_warning_counter,
140        );
141
142        if tasks.len() >= max_tasks {
143            tracing::warn!(
144                file = %path.display(),
145                limit = max_tasks,
146                "reached per-file task limit"
147            );
148            break;
149        }
150    }
151
152    // Flush remaining heading
153    if let Some(info) = current_heading.take() {
154        if let Some(task) = finalize_task(path, info, ts_warning_counter) {
155            tasks.push(task);
156        }
157    }
158
159    tracing::debug!(
160        file = %path.display(),
161        bytes = content.len(),
162        tasks = tasks.len(),
163        "parsed file"
164    );
165
166    tasks
167}
168
169/// Extract tasks from markdown content with a per-call warning budget.
170///
171/// Convenience wrapper around [`extract_tasks_with_counter`] that owns the
172/// counter for the duration of one call. Used by the unit-test suite and
173/// available to library callers that scope the invalid-timestamp warning
174/// cap per file. The production CLI (`main.rs::scan_files`) uses
175/// `extract_tasks_with_counter` directly so the cap spans the whole run.
176#[cfg_attr(not(test), allow(dead_code))]
177pub fn extract_tasks(
178    path: &Path,
179    content: &str,
180    mappings: &[(&str, &str)],
181    max_tasks: usize,
182) -> Vec<Task> {
183    let mut counter = 0_usize;
184    let mut prop_counter = 0_usize;
185    extract_tasks_with_counter(
186        path,
187        content,
188        mappings,
189        max_tasks,
190        &mut counter,
191        &mut prop_counter,
192    )
193}
194
195/// Comrak parsing options.
196///
197/// **Security note**: this is `Options::default()` deliberately. Defaults:
198/// - `render.unsafe_ = false` — raw HTML in markdown is escaped, not passed through.
199/// - `extension.tagfilter = false` (filter not applied, since unsafe HTML is already escaped).
200/// - No extensions that interpret embedded HTML or scripts are enabled.
201///
202/// **Do not enable `render.unsafe_` or `extension.tagfilter` here without a
203/// security review** — the HTML output goes through `html_escape`, but enabling
204/// raw HTML would let untrusted markdown inject arbitrary tags into the rendered
205/// page bypassing that escape.
206fn safe_comrak_options() -> Options<'static> {
207    Options::default()
208}
209
210/// Information extracted from a heading
211struct HeadingInfo {
212    heading: String,
213    task_type: Option<TaskType>,
214    priority: Option<Priority>,
215    line: u32,
216    content: String,
217    created: Option<String>,
218    timestamp: Option<String>,
219    clocks: Vec<crate::types::ClockEntry>,
220    properties: BTreeMap<String, String>,
221}
222
223/// Process a single markdown node
224fn process_node<'a>(
225    node: &'a AstNode<'a>,
226    path: &Path,
227    tasks: &mut Vec<Task>,
228    current_heading: &mut Option<HeadingInfo>,
229    mappings: &[(&str, &str)],
230    ts_warning_counter: &mut usize,
231    prop_warning_counter: &mut usize,
232) {
233    // Snapshot the borrow once — clone the value (cheap for Heading/Paragraph) and
234    // read the sourcepos line in the same scope; drop before any code that
235    // recurses into children (which take their own borrows).
236    let (value_clone, line) = {
237        let data = node.data.borrow();
238        (data.value.clone(), data.sourcepos.start.line as u32)
239    };
240    match value_clone {
241        NodeValue::Heading(_) => {
242            // Finalize previous heading first
243            if let Some(info) = current_heading.take() {
244                if let Some(task) = finalize_task(path, info, ts_warning_counter) {
245                    tasks.push(task);
246                }
247            }
248
249            let text = extract_text(node);
250            let (task_type, priority, heading) = parse_heading(&text);
251            *current_heading = Some(HeadingInfo {
252                heading,
253                task_type,
254                priority,
255                line,
256                content: String::new(),
257                created: None,
258                timestamp: None,
259                clocks: Vec::new(),
260                properties: BTreeMap::new(),
261            });
262        }
263        NodeValue::Paragraph => {
264            if let Some(ref mut info) = current_heading {
265                let (created, timestamp) = extract_timestamps_from_node(node, mappings);
266                let content = extract_paragraph_text(node);
267
268                for child in node.children() {
269                    if let NodeValue::Code(code) = &child.data.borrow().value {
270                        info.clocks.extend(extract_clocks(&code.literal));
271                    }
272                }
273
274                if created.is_some() {
275                    info.created = created;
276                }
277                if timestamp.is_some() {
278                    info.timestamp = timestamp;
279                }
280                if !content.is_empty() {
281                    if info.content.is_empty() {
282                        info.content = content;
283                    } else {
284                        info.content.push_str("\n\n");
285                        info.content.push_str(&content);
286                    }
287                }
288            }
289        }
290        NodeValue::CodeBlock(code) => {
291            if let Some(ref mut info) = current_heading {
292                // Performance: check the property-block info string first and
293                // return early on a match, so an org-properties block skips the
294                // backtick-strip / weekday-normalise / clock-extract work below.
295                // For every other code block the only added cost is this one
296                // `&str` comparison. The grep pre-filter (main.rs) is NOT widened
297                // for `org-properties`, so the set of scanned files is unchanged.
298                if code.info.trim() == "org-properties" {
299                    parse_org_properties(
300                        &code.literal,
301                        &mut info.properties,
302                        path,
303                        line,
304                        prop_warning_counter,
305                    );
306                } else {
307                    let raw = code.literal.trim();
308                    // An indented code block (4-space indent) reaches us with
309                    // the planning line still wrapped in inline-code backticks
310                    // (`    \`DEADLINE: <...>\``). Comrak strips the indent but
311                    // leaves the wrapping backticks in `code.literal`, which
312                    // would otherwise prevent the DEADLINE/SCHEDULED/CREATED
313                    // regex from anchoring on the keyword. Drop a matched
314                    // backtick pair before regex matching.
315                    let literal = strip_wrapping_backticks(raw);
316                    let normalized = normalize_weekdays(literal, mappings);
317                    let created = extract_created_normalized(&normalized);
318                    let timestamp = extract_timestamp_normalized(&normalized);
319
320                    info.clocks.extend(extract_clocks(literal));
321
322                    if created.is_some() {
323                        info.created = created;
324                    }
325                    if timestamp.is_some() {
326                        info.timestamp = timestamp;
327                    }
328                }
329            }
330        }
331        _ => {}
332    }
333}
334
335fn finalize_task(path: &Path, info: HeadingInfo, ts_warning_counter: &mut usize) -> Option<Task> {
336    if info.task_type.is_none() && info.created.is_none() && info.timestamp.is_none() {
337        return None;
338    }
339
340    let line = info.line;
341    let (ts_type, ts_date, ts_time, ts_end_time, ts_active, ts_repeater) =
342        if let Some(ref ts) = info.timestamp {
343            // `info.timestamp` is assembled from `extract_timestamp_normalized`
344            // regex captures over an already-`normalize_weekdays`d string in
345            // both `process_node` branches, so a second normalisation here
346            // would be redundant work on every task.
347            let parsed = parse_timestamp_fields_normalized(ts);
348            if parsed.1.is_none() {
349                warn_invalid_timestamp(ts_warning_counter, path, line, ts);
350            }
351            // The repeater is extracted via a second, fuller pass
352            // (`parse_org_timestamp`) rather than the light regex path above:
353            // the repeater grammar (prefix/value/unit, `wd`) lives in that
354            // parser and is not worth duplicating as another regex helper.
355            // The extra parse is timestamp-string-local and runs once per task.
356            let repeater = extract_repeater_normalized(ts);
357            (parsed.0, parsed.1, parsed.2, parsed.3, parsed.4, repeater)
358        } else {
359            (None, None, None, None, None, None)
360        };
361
362    let (clocks_opt, total_time) = if !info.clocks.is_empty() {
363        let total = calculate_total_minutes(&info.clocks).map(format_duration);
364        (Some(info.clocks), total)
365    } else {
366        (None, None)
367    };
368
369    let properties = if info.properties.is_empty() {
370        None
371    } else {
372        Some(info.properties)
373    };
374
375    Some(Task {
376        file: path.display().to_string(),
377        // Filled in by the scan when it walked several roots: the parser is
378        // given one file and has no notion of which collection it belongs to.
379        root: None,
380        line,
381        heading: info.heading,
382        content: info.content,
383        task_type: info.task_type,
384        priority: info.priority,
385        created: info.created,
386        timestamp: info.timestamp,
387        timestamp_type: ts_type,
388        timestamp_active: ts_active,
389        timestamp_date: ts_date,
390        timestamp_time: ts_time,
391        timestamp_end_time: ts_end_time,
392        timestamp_repeater: ts_repeater,
393        // Populated later by `annotate_next_occurrences` (needs the agenda
394        // reference date, which the parser does not have).
395        timestamp_next: None,
396        clocks: clocks_opt,
397        total_clock_time: total_time,
398        properties,
399    })
400}
401
402/// Parse heading text to extract task type, priority, and title.
403///
404/// Follows the emacs org-mode parser
405/// (`org-element--headline-parse-title` / `org-priority-regexp`):
406///
407/// 1. Strip an optional `TODO` / `DONE` keyword anchored at the start.
408/// 2. Search the remaining text for the first `[#X]` cookie at any position,
409///    where `X` is `A-Z` or an integer `0..=64`. If found, that becomes the
410///    priority, wherever it sits — emacs reads it the same way, through the
411///    `.*?` prefix of `org-priority-regexp`.
412/// 3. The cookie is taken **out of** the title only when it is in its canonical
413///    place: at the start of what is left, i.e. directly after the keyword, or
414///    opening the heading when there is no keyword. A cookie written anywhere
415///    else stays in the title, together with the text before it.
416/// 4. Whatever remains is trimmed and returned as the heading.
417///
418/// Step 3 is where this parser parts company with `org-element`, whose
419/// `:raw-value` drops everything up to the cookie (`goto-char (match-end 0)`).
420/// That value is not what a reader sees: `org-agenda` builds its line from
421/// `org-get-heading`, which keeps the title whole — `* TODO Buy [#A] filter`
422/// is shown as written and still sorts as an `A`. Dropping the prefix here
423/// left a trailing cookie with an empty heading and a blank agenda row. See
424/// [ADR-0002](../docs/adr/0002-supported-org-mode-subset.md).
425///
426/// A heading without TODO/DONE and without a priority cookie is returned
427/// verbatim (trimmed).
428fn parse_heading(text: &str) -> (Option<TaskType>, Option<Priority>, String) {
429    // Step 1: optional TODO/DONE prefix.
430    let (task_type, rest) = if let Some(caps) = HEADING_TODO_RE.captures(text) {
431        let kw = caps.get(1).map(|m| m.as_str()).unwrap_or("");
432        let m = caps
433            .get(0)
434            .expect("Captures::get(0) is Some when captures() succeeds");
435        (TaskType::from_keyword(kw), &text[m.end()..])
436    } else {
437        (None, text)
438    };
439    let title = rest.trim();
440
441    // Step 2: optional priority cookie anywhere in the remainder.
442    if let Some(caps) = HEADING_PRIORITY_RE.captures(title) {
443        let value = caps.get(1).map(|m| m.as_str()).unwrap_or("");
444        if let Some(priority) = Priority::parse(value) {
445            let whole = caps
446                .get(0)
447                .expect("Captures::get(0) is Some when captures() succeeds");
448            // Step 3: only a cookie opening the title is consumed by it.
449            let heading = if whole.start() == 0 {
450                title[whole.end()..].trim()
451            } else {
452                title
453            };
454            return (task_type, Some(priority), heading.to_string());
455        }
456    }
457
458    (task_type, None, title.to_string())
459}
460
461/// Leading `#` run of an ATX heading and the gap after it.
462///
463/// Capped at six hashes, which is where markdown stops treating the run as a
464/// heading, and the gap is mandatory for the same reason: `#no gap` is a
465/// paragraph. Used by `parse_heading_line`, which works on the raw file line —
466/// unlike `parse_heading`, which is handed the text comrak already stripped
467/// the hashes from.
468static HEADING_HASHES_RE: LazyLock<Regex> = LazyLock::new(|| compile_bounded(r"^(#{1,6})[ \t]+"));
469
470/// A token found on a heading line, with the byte range it occupies.
471///
472/// The range covers the token as written, framing included: a priority cookie
473/// reports `[#A]`, not `A`. Callers replacing one token slice the line around
474/// this range and keep everything else byte-for-byte.
475#[derive(Debug, Clone, PartialEq)]
476pub struct HeadingToken<T> {
477    /// Byte range within the line the token was parsed from.
478    pub range: Range<usize>,
479    /// What the token parsed to.
480    pub value: T,
481}
482
483/// A heading line as it sits in a file, located token by token.
484///
485/// This is the read half of an editing operation and the reason it lives here
486/// rather than in the editor: the keyword and cookie grammars are the ones the
487/// extractor itself applies, and a second copy of them would drift. Writing —
488/// assembling a line back from parts — is deliberately not part of this crate.
489///
490/// Unlike [`Task`], which carries the heading the agenda displays, nothing is
491/// summarised here. A heading may hold text between the keyword and the cookie
492/// (`# TODO leftover [#B] Title`): the agenda keeps that text and shows the
493/// cookie inside it, and [`title_start`] points at the text rather than past
494/// the cookie, so an editor rewriting the title neither swallows the cookie
495/// nor moves it. Replacing the cookie itself is what [`priority`] is for — its
496/// range addresses the cookie where the user wrote it.
497///
498/// [`title_start`]: HeadingLine::title_start
499/// [`priority`]: HeadingLine::priority
500/// [`Task`]: crate::types::Task
501#[derive(Debug, Clone, PartialEq)]
502pub struct HeadingLine {
503    /// Heading level, i.e. the number of leading `#` characters (1 to 6).
504    pub level: usize,
505    /// The `TODO` / `DONE` / `CANCELLED` / `CANCELED` keyword, when present.
506    pub status: Option<HeadingToken<TaskType>>,
507    /// The `[#A]` priority cookie, when present and within the accepted range.
508    pub priority: Option<HeadingToken<Priority>>,
509    /// Byte offset the title starts at, past the tokens above and the
510    /// whitespace after them. Also where a caller inserts a token the heading
511    /// does not carry yet. A cookie away from its canonical place counts as
512    /// part of the title, so the offset stops before it.
513    pub title_start: usize,
514}
515
516/// Locate the parts of a heading line, or return `None` when `line` is not a
517/// heading.
518///
519/// Applies the same keyword and priority grammars as the extraction path, so a
520/// heading the extractor reads one way cannot be rewritten another way. See
521/// [`HeadingLine`] for what the result addresses.
522///
523/// ```
524/// # use markdown_org_extract::parse_heading_line;
525/// let line = "## TODO [#A] Write the report";
526/// let heading = parse_heading_line(line).expect("a heading");
527/// assert_eq!(&line[heading.priority.expect("a cookie").range], "[#A]");
528/// ```
529pub fn parse_heading_line(line: &str) -> Option<HeadingLine> {
530    let hashes = HEADING_HASHES_RE.captures(line)?;
531    let level = hashes
532        .get(1)
533        .expect("group 1 is Some when captures() succeeds")
534        .len();
535    let after_hashes = hashes
536        .get(0)
537        .expect("Captures::get(0) is Some when captures() succeeds")
538        .end();
539
540    let (status, after_status) = match HEADING_TODO_RE.captures(&line[after_hashes..]) {
541        Some(caps) => {
542            let keyword = caps
543                .get(1)
544                .expect("group 1 is Some when captures() succeeds");
545            let whole = caps
546                .get(0)
547                .expect("Captures::get(0) is Some when captures() succeeds");
548            let token = TaskType::from_keyword(keyword.as_str()).map(|value| HeadingToken {
549                range: after_hashes + keyword.start()..after_hashes + keyword.end(),
550                value,
551            });
552            (token, after_hashes + whole.end())
553        }
554        None => (None, after_hashes),
555    };
556
557    // The cookie is searched for in the remainder, at any position, the way
558    // `parse_heading` does it — org-mode allows text before it.
559    let priority = HEADING_PRIORITY_RE
560        .captures(&line[after_status..])
561        .and_then(|caps| {
562            let value = caps
563                .get(1)
564                .expect("group 1 is Some when captures() succeeds");
565            // The cookie is `[#` + value + `]`; the regex match may also cover
566            // a trailing space, which is not part of the token.
567            let parsed = Priority::parse(value.as_str())?;
568            Some(HeadingToken {
569                range: after_status + value.start() - "[#".len()
570                    ..after_status + value.end() + "]".len(),
571                value: parsed,
572            })
573        });
574
575    // A cookie opening the remainder is a token of its own and the title
576    // starts past it; one written further along belongs to the title, which
577    // therefore starts where the keyword left off. Same rule as `parse_heading`
578    // applies to the heading it hands the agenda.
579    let after_tokens = priority
580        .as_ref()
581        .filter(|cookie| line[after_status..cookie.range.start].trim().is_empty())
582        .map_or(after_status, |cookie| cookie.range.end);
583    let title_start = after_tokens
584        + line[after_tokens..]
585            .find(|c: char| !c.is_whitespace())
586            .unwrap_or(line.len() - after_tokens);
587
588    Some(HeadingLine {
589        level,
590        status,
591        priority,
592        title_start,
593    })
594}
595
596/// Strip a matched pair of inline-code backtick fences from the trimmed
597/// content of an indented code block.
598///
599/// Markdown's indented code blocks preserve the literal source minus the
600/// leading 4-space indent, so a line like `    \`DEADLINE: <...>\`` arrives
601/// here with the wrapping backticks intact. Those wrappers are not part of
602/// the planning-line keyword grammar — they're inline-code framing that the
603/// user added to keep the line visually attached to the heading in their
604/// editor — so we peel one balanced run of backticks before regex matching.
605///
606/// Returns `s` unchanged when the wrapping is asymmetric or absent.
607fn strip_wrapping_backticks(s: &str) -> &str {
608    let bytes = s.as_bytes();
609    let n_leading = bytes.iter().take_while(|&&b| b == b'`').count();
610    if n_leading == 0 {
611        return s;
612    }
613    let n_trailing = bytes.iter().rev().take_while(|&&b| b == b'`').count();
614    // Require equal-length fences with at least one non-fence byte between
615    // them; otherwise the input is just a run of backticks and stripping
616    // would over-consume.
617    if n_trailing != n_leading || bytes.len() < 2 * n_leading + 1 {
618        return s;
619    }
620    s[n_leading..bytes.len() - n_leading].trim()
621}
622
623/// Parse the literal of an `org-properties` fenced code block into `props`,
624/// merging into any existing entries with last-wins on duplicate keys.
625///
626/// Each non-blank line is split on its first `:`: the key is the text
627/// before it (trimmed, case preserved), the value is the remainder
628/// (trimmed). An empty key or a line with no `:` is skipped and reported
629/// via `warn_invalid_property_line`, gated by the caller-owned counter so
630/// the `MAX_DIAGNOSTIC_ITEMS` budget spans the whole run. `block_start_line`
631/// is the source line of the opening fence; the per-line offset is added so
632/// warnings point near the offending line. See ADR-0020.
633fn parse_org_properties(
634    literal: &str,
635    props: &mut BTreeMap<String, String>,
636    path: &Path,
637    block_start_line: u32,
638    prop_warning_counter: &mut usize,
639) {
640    for (offset, line) in literal.lines().enumerate() {
641        if line.trim().is_empty() {
642            continue;
643        }
644        // Source line of this content line: opening fence + 1 + offset.
645        let src_line = block_start_line
646            .saturating_add(1)
647            .saturating_add(offset as u32);
648        match line.split_once(':') {
649            Some((key, value)) => {
650                let key = key.trim();
651                if key.is_empty() {
652                    warn_invalid_property_line(prop_warning_counter, path, src_line, line);
653                    continue;
654                }
655                props.insert(key.to_string(), value.trim().to_string());
656            }
657            None => {
658                warn_invalid_property_line(prop_warning_counter, path, src_line, line);
659            }
660        }
661    }
662}
663
664/// Extract timestamps (CREATED and others) from paragraph node
665fn extract_timestamps_from_node<'a>(
666    node: &'a AstNode<'a>,
667    mappings: &[(&str, &str)],
668) -> (Option<String>, Option<String>) {
669    let mut created = None;
670    let mut timestamp = None;
671
672    if let NodeValue::Paragraph = &node.data.borrow().value {
673        for child in node.children() {
674            if let NodeValue::Code(code) = &child.data.borrow().value {
675                // Normalize the literal once per inline-code node; both extractors
676                // would otherwise scan the same string in lockstep.
677                let normalized = normalize_weekdays(&code.literal, mappings);
678                if created.is_none() {
679                    created = extract_created_normalized(&normalized);
680                }
681                if timestamp.is_none() {
682                    timestamp = extract_timestamp_normalized(&normalized);
683                }
684            }
685        }
686    }
687    (created, timestamp)
688}
689
690/// Extract plain text from paragraph, including text inside Emph/Strong/Link nodes
691///
692/// Inline code is left out here, unlike in a heading: in a body paragraph it
693/// carries the planning lines and the property markers, which are read by
694/// their own extractors and would otherwise appear twice — once as data and
695/// once as prose.
696fn extract_paragraph_text<'a>(node: &'a AstNode<'a>) -> String {
697    let mut text = String::new();
698    collect_text_recursive(node, &mut text, InlineCode::Drop);
699    text.trim().to_string()
700}
701
702/// Extract all text from a heading node, including text inside Emph/Strong
703/// and the literal of an inline code span.
704fn extract_text<'a>(node: &'a AstNode<'a>) -> String {
705    let mut text = String::new();
706    collect_text_recursive(node, &mut text, InlineCode::Keep);
707    text
708}
709
710/// What [`collect_text_recursive`] does with an inline code span.
711#[derive(Clone, Copy, PartialEq, Eq)]
712enum InlineCode {
713    /// Write its literal out, so a heading keeps every word it was written
714    /// with.
715    Keep,
716    /// Skip it.
717    Drop,
718}
719
720fn collect_text_recursive<'a>(node: &'a AstNode<'a>, out: &mut String, code: InlineCode) {
721    for child in node.children() {
722        let value = child.data.borrow().value.clone();
723        match value {
724            NodeValue::Text(t) => out.push_str(&t),
725            NodeValue::Code(inline) if code == InlineCode::Keep => out.push_str(&inline.literal),
726            NodeValue::Emph | NodeValue::Strong | NodeValue::Link(_) | NodeValue::Strikethrough => {
727                collect_text_recursive(child, out, code)
728            }
729            _ => {}
730        }
731    }
732}
733
734/// The text of a markdown fragment as the agenda shows it, with the inline
735/// markup taken off.
736///
737/// This is how a heading reaches [`Task::heading`](crate::Task::heading):
738/// emphasis, strong text, links and strikethrough contribute their text, and
739/// an inline code span contributes its literal. An editor holding the raw
740/// line can therefore compare what the file says against what it was handed
741/// — `parse_heading_line` says where the title starts, and this says what it
742/// looks like once extracted.
743///
744/// ```
745/// # use markdown_org_extract::{display_text, parse_heading_line};
746/// let line = "# TODO **Отчёт** за июль";
747/// let heading = parse_heading_line(line).expect("a heading");
748/// assert_eq!(display_text(&line[heading.title_start..]), "Отчёт за июль");
749/// ```
750pub fn display_text(markdown: &str) -> String {
751    let arena = Arena::new();
752    let root = parse_document(&arena, markdown, &safe_comrak_options());
753
754    let mut text = String::new();
755    collect_block_text(root, &mut text);
756    text.trim().to_string()
757}
758
759/// Walk down to the inline content of every block and collect its text.
760///
761/// A fragment handed to [`display_text`] is parsed as a document, so its
762/// inline nodes sit under a paragraph (or a heading, when the caller passes a
763/// whole line); the leaves are the same either way.
764fn collect_block_text<'a>(node: &'a AstNode<'a>, out: &mut String) {
765    for child in node.children() {
766        let value = child.data.borrow().value.clone();
767        match value {
768            NodeValue::Paragraph | NodeValue::Heading(_) => {
769                collect_text_recursive(child, out, InlineCode::Keep)
770            }
771            _ => collect_block_text(child, out),
772        }
773    }
774}
775
776// Need clone for NodeValue match — comrak nodes are RefCell-borrowed
777// Re-import for clone derive if not present.
778
779#[cfg(test)]
780mod tests {
781    use super::*;
782    use crate::types::{CancelledSpelling, DEFAULT_MAX_TASKS};
783
784    #[test]
785    fn warn_invalid_timestamp_advances_per_call_counter() {
786        // The 0.5.0 review (M1) replaced a process-global
787        // `TS_WARNINGS_EMITTED: AtomicUsize` with a counter owned by the
788        // caller (typically `ProcessingStats::ts_warnings_emitted`).
789        // This test pins the per-call advance: each call bumps the
790        // counter by exactly one.
791        let mut counter = 0_usize;
792        let path = Path::new("t.md");
793        for i in 1..=25 {
794            warn_invalid_timestamp(&mut counter, path, i, "<bad>");
795        }
796        assert_eq!(counter, 25);
797    }
798
799    #[test]
800    fn warn_invalid_property_line_advances_per_call_counter() {
801        // Same per-call advance contract as warn_invalid_timestamp: each
802        // call bumps the caller-owned counter by exactly one, so the
803        // MAX_DIAGNOSTIC_ITEMS cap spans the whole run (ADR-0020).
804        let mut counter = 0_usize;
805        let path = Path::new("t.md");
806        for i in 1..=25 {
807            warn_invalid_property_line(&mut counter, path, i, "no-colon-here");
808        }
809        assert_eq!(counter, 25);
810    }
811
812    #[test]
813    fn warn_invalid_timestamp_counters_are_independent() {
814        // Independent counters do not pollute each other: e.g. a library
815        // consumer running two separate scans, or unit tests in the same
816        // binary, each see a fresh budget. With the previous global
817        // static this assertion would not hold across runs in one
818        // process.
819        let mut counter_a = 0_usize;
820        let mut counter_b = 0_usize;
821        let path = Path::new("t.md");
822        for _ in 0..MAX_DIAGNOSTIC_ITEMS {
823            warn_invalid_timestamp(&mut counter_a, path, 1, "<bad>");
824        }
825        warn_invalid_timestamp(&mut counter_b, path, 1, "<bad>");
826        assert_eq!(counter_a, MAX_DIAGNOSTIC_ITEMS);
827        assert_eq!(counter_b, 1);
828    }
829
830    #[test]
831    fn test_parse_heading_with_priority() {
832        let (task_type, priority, heading) = parse_heading("TODO [#A] Important task");
833        assert_eq!(task_type, Some(TaskType::Todo));
834        assert_eq!(priority, Some(Priority::A));
835        assert_eq!(heading, "Important task");
836    }
837
838    #[test]
839    fn test_parse_heading_without_priority() {
840        let (task_type, priority, heading) = parse_heading("DONE Simple task");
841        assert_eq!(task_type, Some(TaskType::Done));
842        assert_eq!(priority, None);
843        assert_eq!(heading, "Simple task");
844    }
845
846    #[test]
847    fn test_parse_heading_no_task() {
848        let (task_type, priority, heading) = parse_heading("Regular heading");
849        assert_eq!(task_type, None);
850        assert_eq!(priority, None);
851        assert_eq!(heading, "Regular heading");
852    }
853
854    // The next batch mirrors the test matrix from the bug report
855    // "markdown-org-extract: приоритет `[#X]` без TODO/DONE не распознаётся".
856    // We follow emacs org-mode semantics (`org-priority-regexp`) wherever the
857    // bug report diverged from it — concretely case 8 below.
858
859    #[test]
860    fn parse_heading_priority_without_todo() {
861        // Case 1: `### [#A] Заголовок`.
862        let (tt, p, h) = parse_heading("[#A] Заголовок");
863        assert_eq!(tt, None);
864        assert_eq!(p, Some(Priority::A));
865        assert_eq!(h, "Заголовок");
866    }
867
868    #[test]
869    fn parse_heading_todo_with_priority() {
870        // Case 2: `### TODO [#A] Заголовок`.
871        let (tt, p, h) = parse_heading("TODO [#A] Заголовок");
872        assert_eq!(tt, Some(TaskType::Todo));
873        assert_eq!(p, Some(Priority::A));
874        assert_eq!(h, "Заголовок");
875    }
876
877    #[test]
878    fn parse_heading_done_with_priority_b() {
879        // Case 3: `### DONE [#B] Заголовок`.
880        let (tt, p, h) = parse_heading("DONE [#B] Заголовок");
881        assert_eq!(tt, Some(TaskType::Done));
882        assert_eq!(p, Some(Priority::B));
883        assert_eq!(h, "Заголовок");
884    }
885
886    #[test]
887    fn parse_heading_plain_text_no_markers() {
888        // Case 4: `### Заголовок`.
889        let (tt, p, h) = parse_heading("Заголовок");
890        assert_eq!(tt, None);
891        assert_eq!(p, None);
892        assert_eq!(h, "Заголовок");
893    }
894
895    #[test]
896    fn parse_heading_todo_no_priority() {
897        // Case 5: `### TODO Заголовок`.
898        let (tt, p, h) = parse_heading("TODO Заголовок");
899        assert_eq!(tt, Some(TaskType::Todo));
900        assert_eq!(p, None);
901        assert_eq!(h, "Заголовок");
902    }
903
904    #[test]
905    fn parse_heading_numeric_priority() {
906        // Case 6: `### [#1] Заголовок`.
907        let (tt, p, h) = parse_heading("[#1] Заголовок");
908        assert_eq!(tt, None);
909        assert_eq!(p, Some(Priority::Numeric(1)));
910        assert_eq!(h, "Заголовок");
911    }
912
913    #[test]
914    fn parse_heading_extra_whitespace_around_priority() {
915        // Case 7: `###     [#A]     Заголовок` — comrak normalises the leading
916        // whitespace after the `###` marker, so the heading text reaching us
917        // starts at `[#A]`. Trailing extra spaces around the heading are
918        // trimmed.
919        let (tt, p, h) = parse_heading("[#A]     Заголовок");
920        assert_eq!(tt, None);
921        assert_eq!(p, Some(Priority::A));
922        assert_eq!(h, "Заголовок");
923    }
924
925    #[test]
926    fn parse_heading_priority_in_the_middle_org_semantics() {
927        // Case 8: `### Без приоритета и [#A] внутри`.
928        // The cookie counts wherever it sits — `org-get-priority` finds it
929        // through the `.*?` prefix of `org-priority-regexp` — but the title is
930        // left as written: that is the line emacs puts in the agenda.
931        let (tt, p, h) = parse_heading("Без приоритета и [#A] внутри");
932        assert_eq!(tt, None);
933        assert_eq!(p, Some(Priority::A));
934        assert_eq!(h, "Без приоритета и [#A] внутри");
935    }
936
937    #[test]
938    fn parse_heading_trailing_cookie_leaves_a_title_behind() {
939        // The case the two clients answered differently: a cookie written last
940        // used to take the whole title with it and leave the agenda showing an
941        // empty row.
942        let (tt, p, h) = parse_heading("TODO Заголовок с cookie в конце [#A]");
943        assert_eq!(tt, Some(TaskType::Todo));
944        assert_eq!(p, Some(Priority::A));
945        assert_eq!(h, "Заголовок с cookie в конце [#A]");
946    }
947
948    #[test]
949    fn parse_heading_two_digit_numeric_priority() {
950        let (tt, p, h) = parse_heading("[#15] Mid range");
951        assert_eq!(tt, None);
952        assert_eq!(p, Some(Priority::Numeric(15)));
953        assert_eq!(h, "Mid range");
954
955        let (tt, p, h) = parse_heading("[#64] At upper bound");
956        assert_eq!(tt, None);
957        assert_eq!(p, Some(Priority::Numeric(64)));
958        assert_eq!(h, "At upper bound");
959    }
960
961    #[test]
962    fn parse_heading_rejects_numeric_out_of_range() {
963        // `[#65]` and higher are not a valid org-mode priority. The cookie
964        // stays inside the heading text verbatim.
965        let (tt, p, h) = parse_heading("[#65] Above range");
966        assert_eq!(tt, None);
967        assert_eq!(p, None);
968        assert_eq!(h, "[#65] Above range");
969    }
970
971    #[test]
972    fn parse_heading_rejects_lowercase_priority() {
973        let (tt, p, h) = parse_heading("[#a] Lowercase");
974        assert_eq!(tt, None);
975        assert_eq!(p, None);
976        assert_eq!(h, "[#a] Lowercase");
977    }
978
979    #[test]
980    fn parse_heading_todo_then_priority_with_intervening_text() {
981        // The cookie is out of its canonical place, so it stays in the title
982        // and only the priority is taken from it. Emacs shows the same line in
983        // the agenda, cookie included.
984        let (tt, p, h) = parse_heading("TODO Купить [#A] фильтр");
985        assert_eq!(tt, Some(TaskType::Todo));
986        assert_eq!(p, Some(Priority::A));
987        assert_eq!(h, "Купить [#A] фильтр");
988    }
989
990    #[test]
991    fn parse_heading_priority_without_trailing_space() {
992        // `\] ?` makes the post-cookie space optional.
993        let (tt, p, h) = parse_heading("[#A]NoSpace");
994        assert_eq!(tt, None);
995        assert_eq!(p, Some(Priority::A));
996        assert_eq!(h, "NoSpace");
997    }
998
999    #[test]
1000    fn parse_heading_cancelled_simple() {
1001        let (tt, p, h) = parse_heading("CANCELLED Foo");
1002        assert_eq!(tt, Some(TaskType::Cancelled(CancelledSpelling::DoubleL)));
1003        assert_eq!(p, None);
1004        assert_eq!(h, "Foo");
1005    }
1006
1007    #[test]
1008    fn parse_heading_cancelled_with_priority() {
1009        let (tt, p, h) = parse_heading("CANCELLED [#A] Foo");
1010        assert_eq!(tt, Some(TaskType::Cancelled(CancelledSpelling::DoubleL)));
1011        assert_eq!(p, Some(Priority::A));
1012        assert_eq!(h, "Foo");
1013    }
1014
1015    #[test]
1016    fn parse_heading_cancelled_without_whitespace() {
1017        // No whitespace after the keyword: not recognised, stays in title.
1018        let (tt, p, h) = parse_heading("CANCELLEDFoo");
1019        assert_eq!(tt, None);
1020        assert_eq!(p, None);
1021        assert_eq!(h, "CANCELLEDFoo");
1022    }
1023
1024    #[test]
1025    fn parse_heading_cancelled_lowercase_not_recognised() {
1026        // Case-sensitive, like TODO/DONE.
1027        let (tt, p, h) = parse_heading("cancelled Foo");
1028        assert_eq!(tt, None);
1029        assert_eq!(p, None);
1030        assert_eq!(h, "cancelled Foo");
1031    }
1032
1033    #[test]
1034    fn parse_heading_todo_cancelled_first_keyword_wins() {
1035        // First keyword wins; the rest goes into the title (existing rule).
1036        let (tt, p, h) = parse_heading("TODO CANCELLED Foo");
1037        assert_eq!(tt, Some(TaskType::Todo));
1038        assert_eq!(p, None);
1039        assert_eq!(h, "CANCELLED Foo");
1040    }
1041
1042    #[test]
1043    fn parse_heading_canceled_single_l() {
1044        // Upstream Emacs Org-mode spells the keyword with a single L. See
1045        // ADR-0021; recognised alongside the double-L `CANCELLED`.
1046        let (tt, p, h) = parse_heading("CANCELED Foo");
1047        assert_eq!(tt, Some(TaskType::Cancelled(CancelledSpelling::SingleL)));
1048        assert_eq!(p, None);
1049        assert_eq!(h, "Foo");
1050    }
1051
1052    #[test]
1053    fn parse_heading_canceled_with_priority() {
1054        let (tt, p, h) = parse_heading("CANCELED [#A] Foo");
1055        assert_eq!(tt, Some(TaskType::Cancelled(CancelledSpelling::SingleL)));
1056        assert_eq!(p, Some(Priority::A));
1057        assert_eq!(h, "Foo");
1058    }
1059
1060    #[test]
1061    fn parse_heading_canceled_lowercase_not_recognised() {
1062        // Case-sensitive, like TODO/DONE/CANCELLED.
1063        let (tt, p, h) = parse_heading("canceled Foo");
1064        assert_eq!(tt, None);
1065        assert_eq!(p, None);
1066        assert_eq!(h, "canceled Foo");
1067    }
1068
1069    #[test]
1070    fn parse_heading_canceled_without_whitespace_not_recognised() {
1071        // No whitespace after the keyword: not recognised, stays in title.
1072        let (tt, p, h) = parse_heading("CANCELEDfoo");
1073        assert_eq!(tt, None);
1074        assert_eq!(p, None);
1075        assert_eq!(h, "CANCELEDfoo");
1076    }
1077
1078    #[test]
1079    fn extract_tasks_marks_scheduled_angle_bracket_as_active() {
1080        // End-to-end: a SCHEDULED line with `<...>` must surface
1081        // `timestamp_active = Some(true)` in the resulting Task, so
1082        // downstream consumers can branch on bracket form without
1083        // re-parsing the timestamp string. See ADR-0014.
1084        let content = "### TODO Pin me\n`SCHEDULED: <2026-05-21 Thu>`\n";
1085        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1086        assert_eq!(tasks.len(), 1);
1087        assert_eq!(tasks[0].timestamp_active, Some(true));
1088    }
1089
1090    #[test]
1091    fn extract_tasks_marks_missing_timestamp_active_as_none() {
1092        // Heading without a timestamp must keep `timestamp_active = None`,
1093        // matching the rule that absent optional fields skip JSON
1094        // serialisation (ADR-0015).
1095        let content = "### Project kickoff\n\n`CREATED: [2025-09-01 Mon]`\n";
1096        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1097        assert_eq!(tasks.len(), 1);
1098        assert_eq!(tasks[0].timestamp_active, None);
1099    }
1100
1101    #[test]
1102    fn extract_tasks_basic_todo_with_deadline() {
1103        let content = "\
1104### TODO [#A] Write docs\n\
1105`DEADLINE: <2025-12-10 Wed>`\n";
1106        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1107        assert_eq!(tasks.len(), 1);
1108        let t = &tasks[0];
1109        assert_eq!(t.task_type, Some(TaskType::Todo));
1110        assert_eq!(t.priority, Some(Priority::A));
1111        assert_eq!(t.heading, "Write docs");
1112        assert_eq!(t.timestamp_type, Some("DEADLINE".to_string()));
1113        assert_eq!(t.timestamp_date, Some("2025-12-10".to_string()));
1114    }
1115
1116    #[test]
1117    fn extract_tasks_extracts_emph_text_in_heading() {
1118        // Regression: previously emphasised text inside heading was dropped.
1119        let content = "### TODO **Important** task\n`DEADLINE: <2025-12-10 Wed>`\n";
1120        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1121        assert_eq!(tasks.len(), 1);
1122        assert_eq!(tasks[0].heading, "Important task");
1123    }
1124
1125    #[test]
1126    fn extract_tasks_ignores_non_task_headings_without_timestamps() {
1127        let content = "### Just a heading\n\nSome text.\n";
1128        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1129        assert!(tasks.is_empty());
1130    }
1131
1132    #[test]
1133    fn extract_tasks_keeps_created_without_todo() {
1134        // Heading without TODO/DONE keyword but with a CREATED line is still a task.
1135        let content = "### Project kickoff\n\n`CREATED: [2025-09-01 Mon]`\n";
1136        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1137        assert_eq!(tasks.len(), 1);
1138        assert_eq!(tasks[0].task_type, None);
1139        assert_eq!(tasks[0].created, Some("CREATED: [2025-09-01 Mon]".into()));
1140    }
1141
1142    #[test]
1143    fn extract_tasks_concatenates_multiple_paragraphs() {
1144        // Regression: previously only the first paragraph was kept as content.
1145        let content = "\
1146### TODO Multi-line task\n\
1147First paragraph.\n\
1148\n\
1149Second paragraph.\n\
1150";
1151        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1152        assert_eq!(tasks.len(), 1);
1153        assert!(tasks[0].content.contains("First paragraph"));
1154        assert!(tasks[0].content.contains("Second paragraph"));
1155    }
1156
1157    #[test]
1158    fn extract_tasks_extracts_clock_from_inline_code() {
1159        let content = "\
1160### TODO Track time\n\
1161`CLOCK: [2025-09-01 Mon 10:00]--[2025-09-01 Mon 11:30] => 1:30`\n\
1162";
1163        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1164        assert_eq!(tasks.len(), 1);
1165        let t = &tasks[0];
1166        assert!(t.clocks.is_some());
1167        assert_eq!(t.total_clock_time.as_deref(), Some("1:30"));
1168    }
1169
1170    #[test]
1171    fn extract_tasks_handles_done_priority() {
1172        let content = "### DONE [#B] Wrap up\n";
1173        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1174        assert_eq!(tasks.len(), 1);
1175        assert_eq!(tasks[0].task_type, Some(TaskType::Done));
1176        assert_eq!(tasks[0].priority, Some(Priority::B));
1177    }
1178
1179    #[test]
1180    fn extract_tasks_priority_without_todo_with_scheduled() {
1181        // Bug report case: priority cookie before SCHEDULED heading, no TODO.
1182        // After the fix the heading must surface as a task with priority=A and
1183        // task_type=None, since the SCHEDULED line is what makes it agenda-eligible.
1184        let content = "\
1185### [#A] Поменять резину до 16.05.2026\n\
1186`SCHEDULED: <2026-05-09 Sat>`\n";
1187        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1188        assert_eq!(tasks.len(), 1);
1189        let t = &tasks[0];
1190        assert_eq!(t.task_type, None);
1191        assert_eq!(t.priority, Some(Priority::A));
1192        assert_eq!(t.heading, "Поменять резину до 16.05.2026");
1193        assert_eq!(t.timestamp_type, Some("SCHEDULED".to_string()));
1194        assert_eq!(t.timestamp_date, Some("2026-05-09".to_string()));
1195    }
1196
1197    #[test]
1198    fn extract_tasks_numeric_priority_with_deadline() {
1199        // Numeric priority `[#1]` without TODO, with a DEADLINE line.
1200        let content = "\
1201### [#1] Numeric priority task\n\
1202`DEADLINE: <2026-05-09 Sat>`\n";
1203        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1204        assert_eq!(tasks.len(), 1);
1205        let t = &tasks[0];
1206        assert_eq!(t.task_type, None);
1207        assert_eq!(t.priority, Some(Priority::Numeric(1)));
1208        assert_eq!(t.heading, "Numeric priority task");
1209    }
1210
1211    #[test]
1212    fn extract_tasks_priority_in_middle_keeps_the_prefix() {
1213        // The cookie is read wherever it sits, and the heading reaches the
1214        // agenda as the file has it — nothing before the cookie is dropped.
1215        let content = "\
1216### Без приоритета и [#A] внутри\n\
1217`SCHEDULED: <2026-05-09 Sat>`\n";
1218        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1219        assert_eq!(tasks.len(), 1);
1220        let t = &tasks[0];
1221        assert_eq!(t.task_type, None);
1222        assert_eq!(t.priority, Some(Priority::A));
1223        assert_eq!(t.heading, "Без приоритета и [#A] внутри");
1224    }
1225
1226    #[test]
1227    fn extract_tasks_bug_report_minimal_reproduction() {
1228        // Three-heading reproduction from the bug report: priority without
1229        // TODO, TODO + priority, plain heading. SCHEDULED is wrapped in
1230        // backticks so the existing inline-code parser picks it up.
1231        let content = "\
1232### [#A] Поменять резину до 16.05.2026\n\
1233`SCHEDULED: <2026-05-09 Sat>`\n\
1234\n\
1235### TODO [#A] Поменять масло\n\
1236`SCHEDULED: <2026-05-09 Sat>`\n\
1237\n\
1238### Купить фильтр\n\
1239`SCHEDULED: <2026-05-09 Sat>`\n";
1240        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1241        assert_eq!(tasks.len(), 3);
1242
1243        assert_eq!(tasks[0].task_type, None);
1244        assert_eq!(tasks[0].priority, Some(Priority::A));
1245        assert_eq!(tasks[0].heading, "Поменять резину до 16.05.2026");
1246
1247        assert_eq!(tasks[1].task_type, Some(TaskType::Todo));
1248        assert_eq!(tasks[1].priority, Some(Priority::A));
1249        assert_eq!(tasks[1].heading, "Поменять масло");
1250
1251        assert_eq!(tasks[2].task_type, None);
1252        assert_eq!(tasks[2].priority, None);
1253        assert_eq!(tasks[2].heading, "Купить фильтр");
1254    }
1255
1256    // Regression suite for the "indented planning line" cases. A heading
1257    // followed by a 4-space-indented DEADLINE/SCHEDULED/CREATED line is
1258    // parsed by comrak as an indented code block; the timestamp must still
1259    // be recovered, whether or not the planning line is wrapped in inline
1260    // backticks. Matches what `emacs` org-agenda surfaces.
1261    // The literals below use real newlines (no `\\\n` Rust string
1262    // continuation): the continuation form would silently swallow the
1263    // four leading spaces and reduce the case to "no indent at all".
1264    #[test]
1265    fn extract_tasks_indented_inline_code_deadline() {
1266        let content = "#### Birthday\n    `DEADLINE: <2026-05-07 Thu +1y>`\n";
1267        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1268        assert_eq!(tasks.len(), 1, "task should not be dropped");
1269        let t = &tasks[0];
1270        assert_eq!(t.timestamp_type.as_deref(), Some("DEADLINE"));
1271        assert_eq!(t.timestamp_date.as_deref(), Some("2026-05-07"));
1272    }
1273
1274    #[test]
1275    fn extract_tasks_todo_indented_inline_code_deadline() {
1276        let content = "#### TODO Birthday\n    `DEADLINE: <2026-05-07 Thu +1y>`\n";
1277        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1278        assert_eq!(tasks.len(), 1);
1279        let t = &tasks[0];
1280        assert_eq!(t.task_type, Some(TaskType::Todo));
1281        assert_eq!(t.timestamp_date.as_deref(), Some("2026-05-07"));
1282    }
1283
1284    #[test]
1285    fn extract_tasks_indented_inline_code_blank_lines_between() {
1286        // Whitespace between heading and planning line (blank lines, tabs,
1287        // mixed indentation) must not block timestamp recovery.
1288        let content = "#### Birthday\n\n  \t  \n    `DEADLINE: <2026-05-07 Thu +1y>`\n";
1289        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1290        assert_eq!(tasks.len(), 1);
1291        let t = &tasks[0];
1292        assert_eq!(t.timestamp_date.as_deref(), Some("2026-05-07"));
1293    }
1294
1295    #[test]
1296    fn extract_tasks_with_ru_mappings_reproduces_cli_pipeline() {
1297        // Reproduce what `main.rs` feeds to `extract_tasks` when the default
1298        // `--locale ru,en` is in effect. Pulling the table from `cli` keeps
1299        // this test in sync with whatever `get_weekday_mappings("ru")` would
1300        // produce in production.
1301        let content = "#### TODO Birthday\n    `DEADLINE: <2026-05-07 Thu +1y>`\n";
1302        let tasks = extract_tasks(
1303            Path::new("t.md"),
1304            content,
1305            crate::locale::RU_WEEKDAY_MAPPINGS,
1306            DEFAULT_MAX_TASKS,
1307        );
1308        assert_eq!(tasks.len(), 1);
1309        let t = &tasks[0];
1310        assert_eq!(t.task_type, Some(TaskType::Todo));
1311        assert_eq!(t.timestamp_date.as_deref(), Some("2026-05-07"));
1312    }
1313
1314    #[test]
1315    fn extract_tasks_inline_code_scheduled_no_indent() {
1316        let content = "#### Followup\n`SCHEDULED: <2026-05-07 Thu>`\n";
1317        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1318        assert_eq!(tasks.len(), 1);
1319        let t = &tasks[0];
1320        assert_eq!(t.timestamp_type.as_deref(), Some("SCHEDULED"));
1321        assert_eq!(t.timestamp_date.as_deref(), Some("2026-05-07"));
1322    }
1323
1324    #[test]
1325    fn extract_tasks_indented_inline_code_created() {
1326        let content = "#### Project kickoff\n    `CREATED: [2025-09-01 Mon]`\n";
1327        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1328        assert_eq!(tasks.len(), 1);
1329        let t = &tasks[0];
1330        assert_eq!(t.created.as_deref(), Some("CREATED: [2025-09-01 Mon]"));
1331    }
1332
1333    #[test]
1334    fn extract_tasks_parses_single_property() {
1335        let content = "### TODO Ship release\n`SCHEDULED: <2026-06-01 Mon 10:00>`\n```org-properties\nGCAL_EVENT_ID: abc123/primary\n```\n";
1336        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1337        assert_eq!(tasks.len(), 1);
1338        let props = tasks[0].properties.as_ref().expect("properties present");
1339        assert_eq!(
1340            props.get("GCAL_EVENT_ID").map(String::as_str),
1341            Some("abc123/primary")
1342        );
1343        // The block must not leak into the task body content.
1344        assert!(!tasks[0].content.contains("GCAL_EVENT_ID"));
1345        assert!(!tasks[0].content.contains("org-properties"));
1346    }
1347
1348    #[test]
1349    fn extract_tasks_parses_multiple_properties() {
1350        let content =
1351            "### TODO T\n`SCHEDULED: <2026-06-01 Mon>`\n```org-properties\nA: 1\nB: 2\n```\n";
1352        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1353        let props = tasks[0].properties.as_ref().unwrap();
1354        assert_eq!(props.get("A").map(String::as_str), Some("1"));
1355        assert_eq!(props.get("B").map(String::as_str), Some("2"));
1356    }
1357
1358    #[test]
1359    fn extract_tasks_property_duplicate_keys_last_wins() {
1360        let content = "### TODO T\n`SCHEDULED: <2026-06-01 Mon>`\n```org-properties\nK: first\nK: second\n```\n";
1361        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1362        assert_eq!(
1363            tasks[0]
1364                .properties
1365                .as_ref()
1366                .unwrap()
1367                .get("K")
1368                .map(String::as_str),
1369            Some("second")
1370        );
1371    }
1372
1373    #[test]
1374    fn extract_tasks_property_empty_value_allowed() {
1375        let content = "### TODO T\n`SCHEDULED: <2026-06-01 Mon>`\n```org-properties\nK:\n```\n";
1376        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1377        assert_eq!(
1378            tasks[0]
1379                .properties
1380                .as_ref()
1381                .unwrap()
1382                .get("K")
1383                .map(String::as_str),
1384            Some("")
1385        );
1386    }
1387
1388    #[test]
1389    fn extract_tasks_property_malformed_line_skipped() {
1390        let content = "### TODO T\n`SCHEDULED: <2026-06-01 Mon>`\n```org-properties\nGOOD: x\nno colon here\n```\n";
1391        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1392        let props = tasks[0].properties.as_ref().unwrap();
1393        assert_eq!(props.get("GOOD").map(String::as_str), Some("x"));
1394        assert_eq!(props.len(), 1, "malformed line must be skipped");
1395    }
1396
1397    #[test]
1398    fn extract_tasks_empty_property_block_yields_none() {
1399        let content = "### TODO T\n`SCHEDULED: <2026-06-01 Mon>`\n```org-properties\n\n```\n";
1400        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1401        assert_eq!(tasks[0].properties, None);
1402    }
1403
1404    #[test]
1405    fn extract_tasks_property_info_with_extra_attrs_not_recognised() {
1406        // Info string must be exactly "org-properties"; extra attributes
1407        // mean it is a plain code block, not a property block.
1408        let content =
1409            "### TODO T\n`SCHEDULED: <2026-06-01 Mon>`\n```org-properties extra\nK: v\n```\n";
1410        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1411        assert_eq!(tasks[0].properties, None);
1412    }
1413
1414    #[test]
1415    fn extract_tasks_clock_code_block_unaffected_by_properties() {
1416        // A CLOCK-bearing code block on the same task is still parsed for
1417        // clocks; the org-properties block is parsed for properties.
1418        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";
1419        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1420        assert_eq!(
1421            tasks[0]
1422                .properties
1423                .as_ref()
1424                .unwrap()
1425                .get("K")
1426                .map(String::as_str),
1427            Some("v")
1428        );
1429        assert_eq!(tasks[0].total_clock_time.as_deref(), Some("1:30"));
1430    }
1431
1432    #[test]
1433    fn extract_tasks_merges_multiple_property_blocks_last_wins() {
1434        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";
1435        let tasks = extract_tasks(Path::new("t.md"), content, &[], DEFAULT_MAX_TASKS);
1436        let props = tasks[0].properties.as_ref().unwrap();
1437        assert_eq!(props.get("K").map(String::as_str), Some("two"));
1438        assert_eq!(props.get("L").map(String::as_str), Some("three"));
1439    }
1440}