calepin 0.0.51

A Rust CLI for preprocessing Typst documents with executable code chunks
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
use anyhow::{anyhow, Result};
use serde_json::Value;

use crate::typst::fence_label::{metadata_node_label, raw_node_label};

#[derive(Debug, Clone, PartialEq)]
pub struct ParsedChunkSource {
    pub code: String,
    pub overrides: Vec<(String, Value)>,
    pub warnings: Vec<String>,
    pub fence_label: Option<String>,
}

pub fn parse_chunk_body_with_qmd_header(body: &Value, label: &str) -> Result<ParsedChunkSource> {
    let (raw, fence_label) = extract_raw_node_and_fence_label(body, label)?;
    let mut parsed = parse_chunk_source_with_qmd_header(
        raw.get("text")
            .and_then(Value::as_str)
            .ok_or_else(|| anyhow!("chunk `{}` raw element is missing text", label))?,
        label,
    )?;
    parsed.fence_label = fence_label;
    Ok(parsed)
}

pub fn parse_chunk_source_with_qmd_header(source: &str, label: &str) -> Result<ParsedChunkSource> {
    let mut code = String::new();
    let mut overrides = Vec::new();
    let mut warnings = Vec::new();
    let mut reading_header = true;

    for (line_num, line) in source.split_inclusive('\n').enumerate() {
        if !reading_header {
            code.push_str(line);
            continue;
        }

        let trimmed = line.trim();
        if !trimmed.starts_with("#|") {
            reading_header = false;
            code.push_str(line);
            continue;
        }

        let directive = trimmed.trim_start_matches("#|").trim();
        if directive.is_empty() {
            continue;
        }

        let (raw_key, raw_value) = directive
            .split_once(':')
            .ok_or_else(|| {
                anyhow!(
                    "chunk `{}` header line {}: malformed option declaration `{}` (expected `#| key: value`)",
                    label,
                    line_num + 1,
                    trimmed,
                )
            })?;
        let (key, did_translate) = resolve_chunk_option_name(raw_key.trim(), label, line_num + 1)?;
        if did_translate {
            warnings.push(format!(
                "chunk `{}` option `{}` was translated to `{}`",
                label,
                raw_key.trim(),
                key
            ));
        }
        let value = parse_qmd_value(raw_value.trim())?;
        overrides.push((key, value));
    }

    Ok(ParsedChunkSource {
        code,
        overrides,
        warnings,
        fence_label: None,
    })
}

pub fn validate_chunk_arguments(value: &Value, label: &str) -> Result<()> {
    let Some(value_obj) = value.as_object() else {
        return Err(anyhow!("chunk `{}` metadata is not an object", label));
    };

    for key in value_obj.keys() {
        if !is_supported_chunk_key(key) {
            return Err(anyhow!(
                "chunk `{}` has unsupported argument `{}` in calepin.chunk() arguments. Supported arguments: {}",
                label,
                key,
                supported_chunk_argument_names(),
            ));
        }
    }

    Ok(())
}

fn extract_raw_node_and_fence_label<'a>(
    node: &'a Value,
    label: &str,
) -> Result<(&'a Value, Option<String>)> {
    if is_raw_node(node) {
        return Ok((node, raw_node_label(node)?));
    }

    let Some(children) = node.get("children").and_then(Value::as_array) else {
        return Err(anyhow!(
            "chunk `{}` body must contain exactly one raw element",
            label
        ));
    };

    let mut raw_child = None;
    let mut fence_label = None;
    for child in children {
        if is_raw_node(child) {
            if raw_child.replace(child).is_some() {
                return Err(anyhow!(
                    "chunk `{}` body must contain exactly one raw element",
                    label
                ));
            }
            if let Some(raw_label) = raw_node_label(child)? {
                set_fence_label(&mut fence_label, raw_label, label)?;
            }
            continue;
        }
        if let Some(metadata_label) = metadata_node_label(child)? {
            set_fence_label(&mut fence_label, metadata_label, label)?;
            continue;
        }
        if !is_whitespace_node(child) {
            return Err(anyhow!(
                "chunk `{}` body contains extra non-whitespace markup",
                label
            ));
        }
    }

    let Some(raw_child) = raw_child else {
        return Err(anyhow!(
            "chunk `{}` body must contain exactly one raw element",
            label
        ));
    };

    Ok((raw_child, fence_label))
}

fn is_raw_node(node: &Value) -> bool {
    node.get("func").and_then(Value::as_str) == Some("raw")
}

fn set_fence_label(slot: &mut Option<String>, next: String, label: &str) -> Result<()> {
    if let Some(existing) = slot {
        return Err(anyhow!(
            "chunk `{}` has more than one trailing fence label (`{}` and `{}`)",
            label,
            existing,
            next
        ));
    }
    *slot = Some(next);
    Ok(())
}

fn is_whitespace_node(node: &Value) -> bool {
    matches!(
        node.get("func").and_then(Value::as_str),
        Some("space") | Some("linebreak")
    ) || node
        .get("text")
        .and_then(Value::as_str)
        .is_some_and(|s| s.trim().is_empty())
}

const BASE_CHUNK_KEYS: [&str; 7] = [
    "body",
    "code",
    "crossref-labels",
    "engine",
    "label",
    "kind",
    "lang",
];

fn supported_chunk_argument_names() -> String {
    let mut names: Vec<&str> = BASE_CHUNK_KEYS.to_vec();
    names.extend_from_slice(native_chunk_option_names());
    names.sort_unstable();
    names.dedup();
    names.join(", ")
}

fn is_supported_chunk_key(name: &str) -> bool {
    BASE_CHUNK_KEYS.contains(&name) || is_native_chunk_option(name)
}

fn resolve_chunk_option_name(raw_key: &str, label: &str, line_no: usize) -> Result<(String, bool)> {
    if raw_key == "label" {
        return Ok((raw_key.to_string(), false));
    }
    if let Some(canonical) = translate_chunk_option_name(raw_key) {
        return Ok((canonical.to_string(), canonical != raw_key));
    }
    if is_native_chunk_option(raw_key) {
        return Ok((raw_key.to_string(), false));
    }

    let dashed = raw_key.replace('.', "-");
    if dashed != raw_key && is_native_chunk_option(&dashed) {
        return Ok((dashed, true));
    }

    Err(anyhow!(
        "chunk `{}` header line {}: unsupported option `{}`. Supported options: {}",
        label,
        line_no,
        raw_key,
        supported_qmd_options(),
    ))
}

const CHUNK_OPTION_ALIASES: [(&str, &str); 17] = [
    ("out-width", "fig-width"),
    ("out-height", "fig-height"),
    ("out-align", "fig-align"),
    ("fig-dpi", "fig-device-dpi"),
    ("fig-format", "fig-device-format"),
    ("fig-asp", "fig-device-aspect"),
    ("fig.cap", "fig-caption"),
    ("fig.align", "fig-align"),
    ("fig-alt", "fig-alt-text"),
    ("fig-subcap", "fig-subcaptions"),
    ("tbl-cap", "tbl-caption"),
    ("lst-cap", "lst-caption"),
    ("tbl.cap", "tbl-caption"),
    ("lst.cap", "lst-caption"),
    ("fig-scap", "fig-caption"),
    ("layout-ncol", "fig-layout-columns"),
    ("layout-nrow", "fig-layout-rows"),
];

fn native_chunk_option_names() -> &'static [&'static str] {
    &[
        "echo",
        "eval",
        "error",
        "output",
        "results",
        "script",
        "warning",
        "message",
        "placeholder",
        "store-get",
        "store-set",
        "fig-device-format",
        "fig-device-dpi",
        "fig-device-width",
        "fig-device-height",
        "fig-device-aspect",
        "fig-width",
        "fig-height",
        "fig-align",
        "fig-responsive",
        "fig-link",
        "fig-caption",
        "fig-cap-location",
        "fig-alt-text",
        "fig-subcaptions",
        "fig-layout-columns",
        "fig-layout-rows",
        "tbl-caption",
        "lst-caption",
        "kind",
    ]
}

fn supported_qmd_options() -> String {
    let mut names: Vec<&str> = native_chunk_option_names().to_vec();
    names.push("label");

    names.extend(CHUNK_OPTION_ALIASES.iter().map(|(alias, _)| *alias));
    names.sort_unstable();
    names.dedup();
    names.join(", ")
}

pub(crate) fn parse_qmd_value(value: &str) -> Result<Value> {
    let value = value.trim();
    if value.eq_ignore_ascii_case("true") {
        return Ok(Value::Bool(true));
    }
    if value.eq_ignore_ascii_case("false") {
        return Ok(Value::Bool(false));
    }
    if value.eq_ignore_ascii_case("null") {
        return Ok(Value::Null);
    }
    if let Ok(int) = value.parse::<i64>() {
        return Ok(Value::from(int));
    }
    if let Ok(float) = value.parse::<f64>() {
        return Ok(Value::from(float));
    }
    if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
        return Ok(Value::String(decode_double_quoted_string(value)));
    }
    if value.starts_with('\'') && value.ends_with('\'') && value.len() >= 2 {
        return Ok(Value::String(value[1..value.len() - 1].to_string()));
    }
    if value.starts_with('[') && !value.ends_with(']') {
        return Err(anyhow!("unbalanced bracket sequence value `{value}`"));
    }
    if value.starts_with('[') && value.ends_with(']') {
        let inner = value[1..value.len() - 1].trim();
        if inner.is_empty() {
            return Ok(Value::Array(vec![]));
        }
        return Ok(Value::Array(parse_qmd_sequence_values(inner)?));
    }
    if value.starts_with('(') && !value.ends_with(')') {
        return Err(anyhow!("unbalanced parenthesized sequence value `{value}`"));
    }
    if value.starts_with('(') && value.ends_with(')') {
        let inner = value[1..value.len() - 1].trim();
        if inner.is_empty() {
            return Ok(Value::Array(vec![]));
        }
        let items = split_qmd_sequence_items(inner)?;
        if items.len() == 1 {
            return parse_qmd_value(items[0]);
        }
        return Ok(Value::Array(parse_qmd_sequence_values(inner)?));
    }
    Ok(Value::String(value.to_string()))
}

fn parse_qmd_sequence_values(inner: &str) -> Result<Vec<Value>> {
    let mut items = split_qmd_sequence_items(inner)?;
    if items.last().is_some_and(|item| item.is_empty()) {
        items.pop();
    }
    if items.iter().any(|item| item.is_empty()) {
        return Err(anyhow!("empty item in sequence value `{inner}`"));
    }
    items
        .into_iter()
        .map(|item| parse_qmd_value(item.trim()))
        .collect()
}

fn translate_chunk_option_name(name: &str) -> Option<&'static str> {
    CHUNK_OPTION_ALIASES
        .iter()
        .find_map(|(from, to)| if *from == name { Some(*to) } else { None })
}

fn is_native_chunk_option(name: &str) -> bool {
    native_chunk_option_names().contains(&name)
}

fn split_qmd_sequence_items(inner: &str) -> Result<Vec<&str>> {
    let mut items = Vec::new();
    let mut item_start = 0usize;
    let mut bracket_depth = 0usize;
    let mut paren_depth = 0usize;
    let mut quote = None;
    let mut escaped = false;

    for (idx, ch) in inner.char_indices() {
        if let Some(quote_char) = quote {
            if escaped {
                escaped = false;
                continue;
            }
            if quote_char == '"' && ch == '\\' {
                escaped = true;
                continue;
            }
            if ch == quote_char {
                quote = None;
            }
            continue;
        }

        match ch {
            '"' | '\'' => quote = Some(ch),
            '[' => bracket_depth += 1,
            ']' => {
                if bracket_depth == 0 {
                    return Err(anyhow!("unmatched `]` in sequence value `{inner}`"));
                }
                bracket_depth -= 1;
            }
            '(' => paren_depth += 1,
            ')' => {
                if paren_depth == 0 {
                    return Err(anyhow!("unmatched `)` in sequence value `{inner}`"));
                }
                paren_depth -= 1;
            }
            ',' if bracket_depth == 0 && paren_depth == 0 => {
                items.push(inner[item_start..idx].trim());
                item_start = idx + ch.len_utf8();
            }
            _ => {}
        }
    }

    if let Some(quote_char) = quote {
        return Err(anyhow!(
            "unterminated `{quote_char}` string in array value `{inner}`"
        ));
    }
    if bracket_depth != 0 {
        return Err(anyhow!(
            "unterminated nested bracket sequence in sequence value `{inner}`"
        ));
    }
    if paren_depth != 0 {
        return Err(anyhow!(
            "unterminated nested parenthesized sequence in sequence value `{inner}`"
        ));
    }

    items.push(inner[item_start..].trim());
    Ok(items)
}

fn decode_double_quoted_string(value: &str) -> String {
    let inner = &value[1..value.len() - 1];
    let mut decoded = String::with_capacity(inner.len());
    let mut chars = inner.chars();
    while let Some(ch) = chars.next() {
        if ch != '\\' {
            decoded.push(ch);
            continue;
        }

        let Some(escaped) = chars.next() else {
            decoded.push('\\');
            break;
        };
        match escaped {
            '"' => decoded.push('"'),
            '\\' => decoded.push('\\'),
            'n' => decoded.push('\n'),
            'r' => decoded.push('\r'),
            't' => decoded.push('\t'),
            other => {
                decoded.push('\\');
                decoded.push(other);
            }
        }
    }
    decoded
}

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

    fn override_value<'a>(parsed: &'a ParsedChunkSource, key: &str) -> &'a Value {
        parsed
            .overrides
            .iter()
            .find_map(|(name, value)| (name == key).then_some(value))
            .unwrap_or_else(|| panic!("missing override `{key}`"))
    }

    #[test]
    fn parsed_source_exposes_named_fields() {
        let parsed =
            parse_chunk_source_with_qmd_header("#| echo: false\nprint(1)", "chunk-1").unwrap();

        assert_eq!(parsed.code, "print(1)");
        assert_eq!(override_value(&parsed, "echo"), &Value::Bool(false));
        assert!(parsed.warnings.is_empty());
        assert_eq!(parsed.fence_label, None);
    }

    #[test]
    fn parsed_body_carries_trailing_fence_label() {
        let body = json!({
            "func": "sequence",
            "children": [
                {"func": "raw", "text": "#| echo: false\nplot(1)", "block": true},
                {"func": "space"},
                {
                    "func": "metadata",
                    "label": "<calepin-fence-label>",
                    "value": {"label": "fig-trailing"}
                }
            ]
        });

        let parsed = parse_chunk_body_with_qmd_header(&body, "fig-trailing").unwrap();

        assert_eq!(parsed.code, "plot(1)");
        assert_eq!(override_value(&parsed, "echo"), &Value::Bool(false));
        assert_eq!(parsed.fence_label.as_deref(), Some("fig-trailing"));
    }

    #[test]
    fn qmd_arrays_split_only_top_level_commas() {
        let parsed = parse_qmd_value(r#"["A, with comma", ["B, nested", C], "D"]"#).unwrap();

        assert_eq!(parsed, json!(["A, with comma", ["B, nested", "C"], "D"]));
    }

    #[test]
    fn qmd_typst_arrays_support_nesting_and_singletons() {
        assert_eq!(
            parse_qmd_value(r#"("A, with comma", ("B, nested", C), ["D"])"#).unwrap(),
            json!(["A, with comma", ["B, nested", "C"], ["D"]])
        );
        assert_eq!(parse_qmd_value(r#"("only",)"#).unwrap(), json!(["only"]));
        assert_eq!(parse_qmd_value("(grouped)").unwrap(), json!("grouped"));
        assert_eq!(parse_qmd_value("()").unwrap(), json!([]));
    }

    #[test]
    fn qmd_sequences_reject_empty_and_unbalanced_nested_items() {
        for value in [
            "(first,,third)",
            "(first, (nested, second)",
            "(first, second",
            "[first, second",
        ] {
            assert!(parse_qmd_value(value).is_err(), "accepted {value}");
        }
    }

    #[test]
    fn qmd_double_quoted_strings_decode_escapes() {
        let parsed = parse_qmd_value(r#""A \"quoted\" label""#).unwrap();

        assert_eq!(parsed, Value::String("A \"quoted\" label".to_string()));
    }

    #[test]
    fn qmd_double_quoted_strings_preserve_unknown_escapes() {
        let parsed = parse_qmd_value(r#""C:\path\figure.svg""#).unwrap();

        assert_eq!(parsed, Value::String(r#"C:\path\figure.svg"#.to_string()));
    }

    #[test]
    fn qmd_header_accepts_kind_option() {
        let parsed = parse_chunk_source_with_qmd_header("#| kind: fig\nplot(1)", "fig-1").unwrap();

        assert_eq!(
            override_value(&parsed, "kind"),
            &Value::String("fig".to_string())
        );
    }

    #[test]
    fn qmd_header_accepts_script_path_and_exclusion() {
        let routed =
            parse_chunk_source_with_qmd_header("#| script: scripts/main.py\nprint(1)", "routed")
                .unwrap();
        assert_eq!(
            routed.overrides,
            vec![(
                "script".to_string(),
                Value::String("scripts/main.py".to_string())
            )]
        );

        let excluded =
            parse_chunk_source_with_qmd_header("#| script: false\nprint(2)", "excluded").unwrap();
        assert_eq!(
            excluded.overrides,
            vec![("script".to_string(), Value::Bool(false))]
        );
    }
}