mindtape-eval 0.2.0

Typst evaluation and task extraction for MindTape
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
//! Write-back functionality for modifying `.typ` files.
//!
//! This module provides safe mutation of Typst files while preserving
//! formatting, comments, and surrounding content. It uses the `typst-syntax`
//! crate to parse files and locate specific tasks by ID, then performs
//! targeted text replacements.
//!
//! ## Operations
//!
//! - **Checkbox toggle**: `toggle_task_checkbox` (M3.1)
//! - **Due date**: `set_task_due` / `remove_task_due` (M3.2)
//! - **Tags**: `add_task_tag` / `remove_task_tag` (M3.2)

use std::path::Path;
use thiserror::Error;
use typst_syntax::{LinkedNode, Source, SyntaxKind};

/// Errors that can occur during write-back operations.
#[derive(Debug, Error)]
pub enum WriteError {
    /// The source file could not be read.
    #[error("file read error: {0}")]
    File(String),

    /// The task ID was not found in the file.
    #[error("task not found: {0}")]
    TaskNotFound(String),

    /// The task node is malformed or cannot be modified.
    #[error("invalid task structure: {0}")]
    InvalidTask(String),

    /// A date string could not be parsed.
    #[error("invalid date: {0}")]
    InvalidDate(String),
}

/// Load a `.typ` file and parse it into a `Source`.
///
/// # Errors
/// Returns `Err` if the file cannot be read.
pub fn load_source(path: &Path) -> Result<Source, WriteError> {
    std::fs::read_to_string(path)
        .map_err(|e| WriteError::File(e.to_string()))
        .map(|content| Source::detached(&content))
}

/// Find a task's `ListItem` node in the syntax tree by searching for its ID.
///
/// Walks the entire tree looking for list items that contain `#id("...")` metadata.
/// Returns the `LinkedNode` for the first matching list item.
///
/// # Errors
/// Returns `None` if no matching task is found.
pub fn find_task_node<'a>(
    source: &'a Source,
    root: &LinkedNode<'a>,
    task_id: &str,
) -> Option<LinkedNode<'a>> {
    // Walk the tree looking for ListItem nodes
    walk_tree(root, &mut |node| {
        if node.kind() == SyntaxKind::ListItem {
            // Extract text of this list item using source range
            let range = node.range();
            let text = &source.text()[range];

            // Look for #id("...") pattern
            if let Some(id) = extract_id_from_text(text)
                && id == task_id
            {
                return Some(node.clone());
            }
        }
        None
    })
}

/// Walk the syntax tree depth-first, calling `visitor` on each node.
/// Returns the first `Some(T)` value returned by the visitor.
fn walk_tree<'a, T>(
    node: &LinkedNode<'a>,
    visitor: &mut dyn FnMut(LinkedNode<'a>) -> Option<T>,
) -> Option<T> {
    // Try current node
    if let Some(result) = visitor(node.clone()) {
        return Some(result);
    }

    // Recurse into children
    for child in node.children() {
        if let Some(result) = walk_tree(&child, visitor) {
            return Some(result);
        }
    }

    None
}

/// Extract the task ID from a text string containing `#id("...")`.
///
/// Simple pattern matching for the ID — looks for `#id("` followed by
/// characters until the closing `")`.
fn extract_id_from_text(text: &str) -> Option<String> {
    let prefix = "#id(\"";
    let suffix = "\")";

    if let Some(start) = text.find(prefix) {
        let id_start = start + prefix.len();
        if let Some(end) = text[id_start..].find(suffix) {
            return Some(text[id_start..id_start + end].to_string());
        }
    }

    None
}

/// Toggle the checkbox state of a task in the source text.
///
/// Finds the task by ID, determines its current checkbox state (`[ ]` or `[x]`),
/// and returns the modified source text with the checkbox toggled.
///
/// # Errors
/// Returns `Err` if the task is not found or cannot be modified.
pub fn toggle_task_checkbox(source: &Source, task_id: &str) -> Result<String, WriteError> {
    let root = LinkedNode::new(source.root());
    let task_node = find_task_node(source, &root, task_id)
        .ok_or_else(|| WriteError::TaskNotFound(task_id.to_string()))?;

    // Get the text range of this list item
    let range = task_node.range();
    let item_text = &source.text()[range.clone()];

    // Determine current checkbox state and compute replacement
    let (old_checkbox, new_checkbox) = if item_text.trim_start().starts_with("- [ ]") {
        ("- [ ]", "- [x]")
    } else if item_text.trim_start().starts_with("- [x]")
        || item_text.trim_start().starts_with("- [X]")
    {
        // Handle both lowercase and uppercase X
        if item_text.trim_start().starts_with("- [x]") {
            ("- [x]", "- [ ]")
        } else {
            ("- [X]", "- [ ]")
        }
    } else {
        return Err(WriteError::InvalidTask(
            "list item does not start with checkbox".to_string(),
        ));
    };

    // Replace the checkbox (replacen preserves the rest of the line)
    let new_item_text = item_text.replacen(old_checkbox, new_checkbox, 1);

    // Reconstruct the full source
    let before = &source.text()[..range.start];
    let after = &source.text()[range.end..];
    Ok(format!("{before}{new_item_text}{after}"))
}

// ---------------------------------------------------------------------------
// M3.2 — Task property updates
// ---------------------------------------------------------------------------

/// Apply a text transformation to a task's `ListItem` text, returning the
/// modified full source.
fn modify_task_text(
    source: &Source,
    task_id: &str,
    modify: impl FnOnce(&str) -> Result<String, WriteError>,
) -> Result<String, WriteError> {
    let root = LinkedNode::new(source.root());
    let task_node = find_task_node(source, &root, task_id)
        .ok_or_else(|| WriteError::TaskNotFound(task_id.to_string()))?;

    let range = task_node.range();
    let item_text = &source.text()[range.clone()];
    let new_item_text = modify(item_text)?;

    let before = &source.text()[..range.start];
    let after = &source.text()[range.end..];
    Ok(format!("{before}{new_item_text}{after}"))
}

/// Set or update the due date on a task.
///
/// If the task already has a `#due(...)` call, it is replaced.
/// Otherwise a new one is inserted before `#id("...")`.
///
/// `date_str` must be in `YYYY-MM-DD` format.
///
/// # Errors
/// Returns `Err` if the task is not found, the date is invalid, or the task
/// has no `#id(...)` for insertion.
pub fn set_task_due(source: &Source, task_id: &str, date_str: &str) -> Result<String, WriteError> {
    let args = format_typst_date_args(date_str)?;
    let replacement = format!("#due({args})");

    modify_task_text(source, task_id, |text| {
        if let Some((start, end)) = find_due_span(text) {
            // Replace existing due call
            Ok(format!("{}{replacement}{}", &text[..start], &text[end..]))
        } else if let Some(insert) = find_property_insert_point(text) {
            // Insert before #id(...): "...text {replacement} #id(...)"
            Ok(format!(
                "{}{replacement} {}",
                &text[..insert],
                &text[insert..]
            ))
        } else {
            Err(WriteError::InvalidTask(
                "task has no #id() — cannot determine insertion point".to_string(),
            ))
        }
    })
}

/// Set or update the start date on a task.
///
/// If the task already has a `#start(...)` call, it is replaced.
/// Otherwise a new one is inserted before `#id("...")`.
///
/// `date_str` must be in `YYYY-MM-DD` format.
///
/// # Errors
/// Returns `Err` if the task is not found, the date is invalid, or the task
/// has no `#id(...)` for insertion.
pub fn set_task_start(
    source: &Source,
    task_id: &str,
    date_str: &str,
) -> Result<String, WriteError> {
    let args = format_typst_date_args(date_str)?;
    let replacement = format!("#start({args})");

    modify_task_text(source, task_id, |text| {
        if let Some((start, end)) = find_start_span(text) {
            Ok(format!("{}{replacement}{}", &text[..start], &text[end..]))
        } else if let Some(insert) = find_property_insert_point(text) {
            Ok(format!(
                "{}{replacement} {}",
                &text[..insert],
                &text[insert..]
            ))
        } else {
            Err(WriteError::InvalidTask(
                "task has no #id() — cannot determine insertion point".to_string(),
            ))
        }
    })
}

/// Remove the start date from a task.
///
/// If the task has no `#start(...)`, this is a no-op that returns the source
/// unchanged.
///
/// # Errors
/// Returns `Err` if the task is not found.
pub fn remove_task_start(source: &Source, task_id: &str) -> Result<String, WriteError> {
    modify_task_text(source, task_id, |text| {
        if let Some((start, end)) = find_start_span(text) {
            let (start, end) = trim_leading_space(text, start, end);
            Ok(format!("{}{}", &text[..start], &text[end..]))
        } else {
            Ok(text.to_string())
        }
    })
}

/// Set or update the rank on a task.
///
/// If the task already has a `#rank(...)` call (or alias like `#high`), it is replaced.
/// Otherwise a new one is inserted before `#id("...")`.
///
/// # Errors
/// Returns `Err` if the task is not found or has no `#id(...)` for insertion.
pub fn set_task_rank(source: &Source, task_id: &str, rank: i64) -> Result<String, WriteError> {
    let replacement = format!("#rank({rank})");

    modify_task_text(source, task_id, |text| {
        if let Some((start, end)) = find_rank_span(text) {
            Ok(format!("{}{replacement}{}", &text[..start], &text[end..]))
        } else if let Some(insert) = find_property_insert_point(text) {
            Ok(format!(
                "{}{replacement} {}",
                &text[..insert],
                &text[insert..]
            ))
        } else {
            Err(WriteError::InvalidTask(
                "task has no #id() — cannot determine insertion point".to_string(),
            ))
        }
    })
}

/// Remove the rank from a task.
///
/// If the task has no `#rank(...)`, this is a no-op that returns the source
/// unchanged.
///
/// # Errors
/// Returns `Err` if the task is not found.
pub fn remove_task_rank(source: &Source, task_id: &str) -> Result<String, WriteError> {
    modify_task_text(source, task_id, |text| {
        if let Some((start, end)) = find_rank_span(text) {
            let (start, end) = trim_leading_space(text, start, end);
            Ok(format!("{}{}", &text[..start], &text[end..]))
        } else {
            Ok(text.to_string())
        }
    })
}

/// Remove the due date from a task.
///
/// If the task has no `#due(...)`, this is a no-op that returns the source
/// unchanged.
///
/// # Errors
/// Returns `Err` if the task is not found.
pub fn remove_task_due(source: &Source, task_id: &str) -> Result<String, WriteError> {
    modify_task_text(source, task_id, |text| {
        if let Some((start, end)) = find_due_span(text) {
            let (start, end) = trim_leading_space(text, start, end);
            Ok(format!("{}{}", &text[..start], &text[end..]))
        } else {
            // No due date — return as-is
            Ok(text.to_string())
        }
    })
}

/// Add a tag to a task.
///
/// Inserts `#tag("name")` before `#id("...")`.
/// Does **not** check for duplicates — callers should verify if needed.
///
/// # Errors
/// Returns `Err` if the task is not found or has no `#id(...)`.
pub fn add_task_tag(source: &Source, task_id: &str, tag: &str) -> Result<String, WriteError> {
    let new_tag = format!("#tag(\"{tag}\")");

    modify_task_text(source, task_id, |text| {
        if let Some(insert) = find_property_insert_point(text) {
            Ok(format!("{}{new_tag} {}", &text[..insert], &text[insert..]))
        } else {
            Err(WriteError::InvalidTask(
                "task has no #id() — cannot determine insertion point".to_string(),
            ))
        }
    })
}

/// Remove a specific tag from a task.
///
/// If the tag is not present, this is a no-op that returns the source
/// unchanged.
///
/// # Errors
/// Returns `Err` if the task is not found.
pub fn remove_task_tag(source: &Source, task_id: &str, tag: &str) -> Result<String, WriteError> {
    modify_task_text(source, task_id, |text| {
        if let Some((start, end)) = find_tag_span(text, tag) {
            let (start, end) = trim_leading_space(text, start, end);
            Ok(format!("{}{}", &text[..start], &text[end..]))
        } else {
            // Tag not present — return as-is
            Ok(text.to_string())
        }
    })
}

// ---------------------------------------------------------------------------
// Helpers for property span detection
// ---------------------------------------------------------------------------

/// Find the byte span of a `#func(...)` call in `text`.
fn find_call_span(text: &str, prefix: &str) -> Option<(usize, usize)> {
    let start = text.find(prefix)?;
    let end = find_matching_paren(text, start + prefix.len() - 1)?;
    Some((start, end + 1))
}

fn find_due_span(text: &str) -> Option<(usize, usize)> {
    find_call_span(text, "#due(")
}
fn find_start_span(text: &str) -> Option<(usize, usize)> {
    find_call_span(text, "#start(")
}

/// Find the byte span of `#rank(...)`, `#high`, `#medium`, or `#low`.
/// Aliases only match at a word boundary (avoids e.g. `#highlight`).
fn find_rank_span(text: &str) -> Option<(usize, usize)> {
    if let Some(span) = find_call_span(text, "#rank(") {
        return Some(span);
    }
    for alias in &["#high", "#medium", "#low"] {
        if let Some(start) = text.find(alias) {
            let end = start + alias.len();
            if text
                .as_bytes()
                .get(end)
                .is_none_or(|&b| b == b' ' || b == b'#')
            {
                return Some((start, end));
            }
        }
    }
    None
}

/// Find the byte span of `#tag("name")` for a specific tag value.
fn find_tag_span(text: &str, tag: &str) -> Option<(usize, usize)> {
    let needle = format!("#tag(\"{tag}\")");
    let start = text.find(&needle)?;
    Some((start, start + needle.len()))
}

/// Find the byte offset just before `#id("...")` — the insertion point for
/// new properties.
fn find_property_insert_point(text: &str) -> Option<usize> {
    text.find("#id(\"")
}

/// If the character before `start` is a space, extend the span left by 1
/// to avoid double spaces after removal.
fn trim_leading_space(text: &str, start: usize, end: usize) -> (usize, usize) {
    if start > 0 && text.as_bytes().get(start - 1) == Some(&b' ') {
        (start - 1, end)
    } else {
        (start, end)
    }
}

/// Find the index of the closing `)` that matches the opening `(` at `open`.
///
/// Returns `None` if parentheses are unbalanced.
fn find_matching_paren(text: &str, open: usize) -> Option<usize> {
    let bytes = text.as_bytes();
    if bytes.get(open) != Some(&b'(') {
        return None;
    }
    let mut depth: u32 = 1;
    for (i, &byte) in bytes.iter().enumerate().skip(open + 1) {
        match byte {
            b'(' => depth += 1,
            b')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
    }
    None
}

/// Parse an ISO date string (`YYYY-MM-DD`) and format it as Typst
/// positional arguments `Y, M, D` (for use inside `#due(Y, M, D)`).
///
/// # Errors
/// Returns `Err(WriteError::InvalidDate)` if the string is malformed.
fn format_typst_date_args(date_str: &str) -> Result<String, WriteError> {
    let parts: Vec<&str> = date_str.split('-').collect();
    let [year_str, month_str, day_str] = parts.as_slice() else {
        return Err(WriteError::InvalidDate(format!(
            "expected YYYY-MM-DD, got \"{date_str}\""
        )));
    };

    let year: i32 = year_str
        .parse()
        .map_err(|_| WriteError::InvalidDate(format!("invalid year in \"{date_str}\"")))?;
    let month: u32 = month_str
        .parse()
        .map_err(|_| WriteError::InvalidDate(format!("invalid month in \"{date_str}\"")))?;
    let day: u32 = day_str
        .parse()
        .map_err(|_| WriteError::InvalidDate(format!("invalid day in \"{date_str}\"")))?;

    if !(1..=12).contains(&month) {
        return Err(WriteError::InvalidDate(format!(
            "month {month} out of range 1..12"
        )));
    }
    if !(1..=31).contains(&day) {
        return Err(WriteError::InvalidDate(format!(
            "day {day} out of range 1..31"
        )));
    }

    Ok(format!("{year}, {month}, {day}"))
}

#[cfg(test)]
#[path = "write_tests.rs"]
#[allow(clippy::unwrap_used)]
mod tests;