calepin 0.0.17

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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
mod fingerprint;
mod image_meta;
mod staging;

use anyhow::{anyhow, Context, Result};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
use xxhash_rust::xxh3::xxh3_64;

use crate::config::{CalepinConfig, ExecutablePaths};
use crate::typst::execute::{EnginePool, ExecutionConfig};
use crate::typst::introspect::preprocess_metadata;
use crate::typst::io::{ensure_parent, write_if_changed};
use crate::typst::model::{ChunkResultDocument, ChunkSpec, EngineName, LayoutPaths};
use crate::typst::paths::{artifact_reference, project_relative_path, resolve_layout};
use crate::typst::query::{parse_chunks_with_warnings, parse_setup_config};
use crate::typst::results::{build_results_document, write_results};
use crate::typst::runtime::write_runtime_with_syntax_theme;
use crate::typst::source_rewrite::write_staged_source;
use crate::typst::sync::write_page_sync;
use crate::typst::version::assert_supported_typst;
use crate::utils::progress::Progress;

const PAGE_META_FILE: &str = "page-meta.json";

use fingerprint::{preprocess_cache_hit, preprocess_fingerprint, write_preprocess_fingerprint};
use image_meta::write_image_meta;
use staging::{notebook_template_context, write_query_source, write_render_wrapper};

pub(crate) use image_meta::image_meta_relative_path;

#[derive(Debug, Clone)]
pub struct PreprocessOptions {
    pub input: PathBuf,
    pub root: Option<PathBuf>,
    pub config: Option<PathBuf>,
    pub display_root: Option<PathBuf>,
    pub quiet: bool,
    pub status: bool,
    pub progress: bool,
    pub timeout: Option<u64>,
    pub sync_pages: bool,
    /// CLI-level theme selection. `None` allows document setup and then
    /// `fallback_theme` to decide.
    pub theme: Option<crate::theme::ThemeSelection>,
    pub fallback_theme: crate::theme::ThemeSelection,
    pub html_syntax_theme: Option<crate::html::HtmlSyntaxTheme>,
    /// `key=value` document-parameter overrides from the CLI (`-P`).
    pub param_overrides: Vec<String>,
}

#[derive(Debug)]
pub struct PreprocessOutput {
    pub layout: LayoutPaths,
    pub executables: ExecutablePaths,
    pub fingerprint: u64,
    pub theme: crate::theme::ThemeSelection,
}

#[derive(Debug)]
pub struct PreprocessPlan {
    pub layout: LayoutPaths,
    pub executables: ExecutablePaths,
    pub fingerprint: u64,
    chunks: Vec<ChunkSpec>,
    cwd: PathBuf,
    timeout: Option<Duration>,
    quiet: bool,
    status: bool,
    progress: bool,
    sync_pages: bool,
    display_root: Option<PathBuf>,
    params: serde_json::Value,
    theme: crate::theme::ThemeSelection,
}

pub fn preprocess(options: PreprocessOptions) -> Result<PreprocessOutput> {
    let plan = prepare_preprocess_plan(options)?;
    execute_preprocess_plan(plan)
}

pub fn preprocess_cached(options: PreprocessOptions) -> Result<PreprocessOutput> {
    let plan = prepare_preprocess_plan(options)?;
    if preprocess_plan_cache_hit(&plan)? {
        if !plan.quiet && plan.status {
            eprintln!("[cache] {}", display_input(&plan));
        }
        return Ok(preprocess_cached_output(plan));
    }
    execute_preprocess_plan(plan)
}

pub fn preprocess_plan_cache_hit(plan: &PreprocessPlan) -> Result<bool> {
    preprocess_cache_hit(&plan.layout, plan.fingerprint)
}

pub fn preprocess_plan_chunk_count(plan: &PreprocessPlan) -> usize {
    plan.chunks.len()
}

pub fn preprocess_cached_output(plan: PreprocessPlan) -> PreprocessOutput {
    PreprocessOutput {
        layout: plan.layout,
        executables: plan.executables,
        fingerprint: plan.fingerprint,
        theme: plan.theme,
    }
}

pub fn prepare_preprocess_plan(options: PreprocessOptions) -> Result<PreprocessPlan> {
    let mut layout = resolve_layout(&options.input, options.root.as_deref())?;
    let config = CalepinConfig::load(&layout.root, options.config.as_deref())?;
    assert_supported_typst(&config.executables.typst)?;

    let html_syntax_theme = options
        .html_syntax_theme
        .clone()
        .unwrap_or_else(crate::html::HtmlSyntaxTheme::builtin);
    write_runtime_with_syntax_theme(&layout.root, &html_syntax_theme)?;
    let staged_input = write_staged_source(&layout)?;
    let image_meta = write_image_meta(&layout)?;
    // Metadata collection runs before the final target is known. Use the
    // staged source directly; document-level HTML must be guarded by target
    // checks so paged/query passes never evaluate `html.*` calls.
    let query_source = write_query_source(&layout, &staged_input)?;
    let query_input = write_render_wrapper(&layout, &query_source, &[], None)?;
    let results_input = artifact_reference(&layout.root, &layout.results_path);
    let metadata = preprocess_metadata(
        &config.executables.typst,
        &layout,
        &query_input,
        &results_input,
    )?;
    write_page_meta(&layout, metadata.page_meta.as_ref())?;
    let setup_config = parse_setup_config(&metadata.setup_json)?;
    let setup_config = setup_config.unwrap_or_default();
    let parsed_chunks = merge_chunk_parse_results(
        metadata
            .chunk_queries
            .iter()
            .map(|chunks_json| parse_chunks_with_warnings(chunks_json, Some(setup_config.clone())))
            .collect::<Result<Vec<_>>>()?,
    )?;
    let chunks = parsed_chunks.chunks;
    if !options.quiet {
        for warning in parsed_chunks.warnings {
            cwarn!("{}", warning);
        }
    }

    // Collect unique Jupyter kernel names so the render wrapper gets their show rules.
    let jupyter_kernels: std::collections::BTreeSet<&str> = chunks
        .iter()
        .filter_map(|c| {
            if let EngineName::Jupyter(k) = &c.engine {
                Some(k.as_str())
            } else {
                None
            }
        })
        .collect();
    let params = resolve_params(&setup_config.defaults.params, &options.param_overrides)?;

    let effective_theme = options
        .theme
        .clone()
        .or(setup_config.defaults.theme_selection(&layout.root)?)
        .unwrap_or_else(|| options.fallback_theme.clone());
    let notebook_context = notebook_template_context(
        &layout,
        &staged_input,
        metadata.page_meta.clone(),
        params.clone(),
    );
    let notebook_theme = crate::theme::notebook_source(&effective_theme, &notebook_context)?;
    if !jupyter_kernels.is_empty() {
        let kernels: Vec<&str> = jupyter_kernels.into_iter().collect();
        layout.render_input =
            write_render_wrapper(&layout, &staged_input, &kernels, notebook_theme.as_ref())?;
    } else {
        layout.render_input =
            write_render_wrapper(&layout, &staged_input, &[], notebook_theme.as_ref())?;
    }

    let cwd = layout.work_dir.clone();
    let timeout = options.timeout.map(Duration::from_secs);
    let fingerprint = preprocess_fingerprint(
        &layout,
        &config.executables,
        &chunks,
        &cwd,
        timeout,
        &params,
        &effective_theme,
        image_meta.signature()?,
    )?;

    Ok(PreprocessPlan {
        layout,
        executables: config.executables,
        fingerprint,
        chunks,
        cwd,
        timeout,
        quiet: options.quiet,
        status: options.status,
        progress: options.progress,
        sync_pages: options.sync_pages,
        display_root: options.display_root,
        params,
        theme: effective_theme,
    })
}

fn merge_chunk_parse_results(
    results: Vec<crate::typst::query::ChunkParseResult>,
) -> Result<crate::typst::query::ChunkParseResult> {
    let mut label_index = std::collections::HashMap::new();
    let mut chunks = Vec::new();
    let mut warnings = Vec::new();

    for result in results {
        warnings.extend(result.warnings);
        for chunk in result.chunks {
            if let Some(existing_index) = label_index.get(&chunk.label).copied() {
                let existing = &chunks[existing_index];
                if !same_chunk_definition(existing, &chunk) {
                    // Auto labels are target-local: paged and HTML scans can
                    // both produce `chunk-1` for different hidden branches. The
                    // render runtime only asks for results by label, so allowing
                    // that collision would attach the wrong result. Require
                    // authors to disambiguate target-specific chunks explicitly.
                    return Err(anyhow!(
                        "chunk label `{}` resolves to different code or options across paged/html targets; add explicit labels to target-specific chunks",
                        chunk.label
                    ));
                }
                continue;
            }
            label_index.insert(chunk.label.clone(), chunks.len());
            chunks.push(chunk);
        }
    }

    Ok(crate::typst::query::ChunkParseResult { chunks, warnings })
}

fn same_chunk_definition(left: &ChunkSpec, right: &ChunkSpec) -> bool {
    left.engine == right.engine
        && left.code == right.code
        && left.exec_options == right.exec_options
        && left.display_options == right.display_options
        && left.crossref_labels == right.crossref_labels
}

pub fn execute_preprocess_plan(plan: PreprocessPlan) -> Result<PreprocessOutput> {
    execute_preprocess_plan_with_chunk_progress(plan, None)
}

pub fn execute_preprocess_plan_with_chunk_progress(
    plan: PreprocessPlan,
    chunk_progress: Option<&Progress>,
) -> Result<PreprocessOutput> {
    let staged = tempfile::Builder::new()
        .prefix("calepin-figures-")
        .tempdir()
        .context("failed to create temporary figures directory")?;
    let staged_figures_dir = staged.path().join("figures");
    std::fs::create_dir_all(&staged_figures_dir)
        .with_context(|| format!("failed to create {}", staged_figures_dir.display()))?;

    // Always write params.json when there are parameters: it is the universal
    // transport for Jupyter kernels Calepin cannot auto-bind, and a useful
    // reproducibility record. Native R/Python read their literal prelude instead.
    let params_path = write_params_file(&plan.layout, &plan.params)?;

    let execution_config = ExecutionConfig {
        cwd: plan.cwd.clone(),
        executables: plan.executables.clone(),
        timeout: plan.timeout,
        params: plan.params.clone(),
        params_path,
    };
    let mut pool = EnginePool::new(execution_config);
    let mut chunk_results: Vec<Option<ChunkResultDocument>> = vec![None; plan.chunks.len()];
    let input = display_input(&plan);
    let chunk_count = plan.chunks.len();
    let chunk_word = if chunk_count == 1 { "chunk" } else { "chunks" };
    let progress = if plan.progress {
        Some(Progress::bar(
            format!("[run] {input}: {chunk_count} {chunk_word}"),
            chunk_count as u64,
            plan.quiet,
        ))
    } else {
        if !plan.quiet && plan.status {
            eprintln!("[run] {input}: {chunk_count} {chunk_word}");
        }
        None
    };

    for (position, chunk_index) in chunks_in_engine_order(&plan.chunks).into_iter().enumerate() {
        let chunk = &plan.chunks[chunk_index];
        if let Some(progress) = &progress {
            progress.set_message(format!(
                "[run] {input}: chunk {}/{} `{}`",
                position + 1,
                chunk_count,
                chunk.label
            ));
        }
        let result = execute_chunk_live(&mut pool, chunk, &staged_figures_dir, &plan.layout)?;
        if let Some(progress) = &progress {
            progress.inc(1);
        }
        if let Some(progress) = chunk_progress {
            progress.inc(1);
        }
        chunk_results[chunk_index] = Some(result);
    }

    let chunk_results = chunk_results
        .into_iter()
        .map(|result| {
            result.context("chunk execution produced no result; this indicates a planner bug")
        })
        .collect::<Result<Vec<_>>>()?;

    publish_staged_figures(&staged_figures_dir, &plan.layout.figures_dir)?;
    let document = build_results_document(&plan.layout.input_rel, chunk_results);
    write_results(&plan.layout.results_path, &document)?;
    write_preprocess_fingerprint(&plan.layout, plan.fingerprint)?;
    if plan.sync_pages {
        if let Err(error) = write_page_sync(&plan.executables.typst, &plan.layout, &plan.chunks) {
            if !plan.quiet {
                cwarn!("page sync failed: {}", error);
            }
        }
    }
    if let Some(progress) = progress {
        progress.finish(format!("[done] {input}: {chunk_count} {chunk_word}"));
    }

    Ok(PreprocessOutput {
        layout: plan.layout,
        executables: plan.executables,
        fingerprint: plan.fingerprint,
        theme: plan.theme,
    })
}

fn page_meta_path(layout: &LayoutPaths) -> PathBuf {
    layout.sibling_path(PAGE_META_FILE)
}

fn source_fingerprint(input: &Path) -> Result<String> {
    let bytes = fs::read(input).with_context(|| format!("failed to read {}", input.display()))?;
    Ok(format!("{:016x}", xxh3_64(&bytes)))
}

/// Persists the page's `<website-metadata>` value next to its results, tagged
/// with the source content hash so readers can detect staleness.
fn write_page_meta(layout: &LayoutPaths, value: Option<&serde_json::Value>) -> Result<()> {
    let document = serde_json::json!({
        "source_xxh3": source_fingerprint(&layout.input)?,
        "value": value,
    });
    let path = page_meta_path(layout);
    write_if_changed(&path, serde_json::to_string(&document)?)
}

/// Returns the `<website-metadata>` value persisted by the last preprocess of
/// `input`, or `None` when it is missing or stale for the current content.
pub fn read_page_meta_with_root(input: &Path, root: Option<&Path>) -> Option<serde_json::Value> {
    let layout = resolve_layout(input, root).ok()?;
    let contents = fs::read_to_string(page_meta_path(&layout)).ok()?;
    let document: serde_json::Value = serde_json::from_str(&contents).ok()?;
    let current = source_fingerprint(&layout.input).ok()?;
    if document
        .get("source_xxh3")
        .and_then(serde_json::Value::as_str)
        != Some(current.as_str())
    {
        return None;
    }
    document
        .get("value")
        .cloned()
        .filter(|value| !value.is_null())
}

fn execute_chunk_live(
    pool: &mut EnginePool,
    chunk: &ChunkSpec,
    execution_figures_dir: &Path,
    layout: &LayoutPaths,
) -> Result<ChunkResultDocument> {
    pool.execute_chunk(chunk, execution_figures_dir, |path| {
        execution_artifact_reference(
            &layout.root,
            execution_figures_dir,
            &layout.figures_dir,
            path,
        )
    })
}

fn chunks_in_engine_order(chunks: &[ChunkSpec]) -> Vec<usize> {
    let mut groups: Vec<(EngineName, Vec<usize>)> = Vec::new();

    for (index, chunk) in chunks.iter().enumerate() {
        if let Some((_, chunk_indexes)) = groups
            .iter_mut()
            .find(|(engine, _)| *engine == chunk.engine)
        {
            chunk_indexes.push(index);
            continue;
        }

        groups.push((chunk.engine.clone(), vec![index]));
    }

    groups
        .into_iter()
        .flat_map(|(_, chunk_indexes)| chunk_indexes)
        .collect()
}

fn execution_artifact_reference(
    root: &Path,
    execution_figures_dir: &Path,
    final_figures_dir: &Path,
    path: &Path,
) -> String {
    let final_path = path
        .strip_prefix(execution_figures_dir)
        .map(|relative| final_figures_dir.join(relative))
        .unwrap_or_else(|_| path.to_path_buf());
    artifact_reference(root, &final_path)
}

fn display_input(plan: &PreprocessPlan) -> String {
    display_input_path(&plan.layout, plan.display_root.as_deref())
}

fn display_input_path(layout: &LayoutPaths, display_root: Option<&Path>) -> String {
    project_relative_path(display_root.unwrap_or(&layout.root), &layout.input)
}

fn publish_staged_figures(staged: &Path, final_dir: &Path) -> Result<()> {
    if !staged.exists() {
        return Ok(());
    }

    for entry in
        std::fs::read_dir(staged).with_context(|| format!("failed to read {}", staged.display()))?
    {
        let entry = entry.with_context(|| format!("failed to read {}", staged.display()))?;
        let path = entry.path();
        let target = final_dir.join(entry.file_name());
        if entry
            .file_type()
            .with_context(|| format!("failed to stat {}", path.display()))?
            .is_dir()
        {
            publish_staged_figures(&path, &target)?;
        } else {
            publish_staged_file(&path, &target)?;
        }
    }

    Ok(())
}

fn publish_staged_file(source: &Path, target: &Path) -> Result<()> {
    let bytes = std::fs::read(source)
        .with_context(|| format!("failed to read staged figure {}", source.display()))?;
    write_if_changed(target, bytes)
}

/// Write `params.json` next to `results.json` when there are parameters, and
/// return its path. Returns `None` (and removes any stale file) when empty.
fn write_params_file(layout: &LayoutPaths, params: &serde_json::Value) -> Result<Option<PathBuf>> {
    let path = layout.sibling_path("params.json");
    let is_empty = params.as_object().is_none_or(|map| map.is_empty());
    if is_empty {
        let _ = fs::remove_file(&path);
        return Ok(None);
    }
    ensure_parent(&path)?;
    let json = serde_json::to_string_pretty(params)?;
    write_if_changed(&path, json)?;
    Ok(Some(path))
}

/// Merge `-P key=value` CLI overrides onto the document's `setup(params: ...)`.
/// CLI values win, and inherit the same scalar typing as `#|` option values.
fn resolve_params(base: &serde_json::Value, overrides: &[String]) -> Result<serde_json::Value> {
    let mut map = match base {
        serde_json::Value::Object(map) => map.clone(),
        _ => serde_json::Map::new(),
    };
    for entry in overrides {
        let (key, raw_value) = entry
            .split_once('=')
            .ok_or_else(|| anyhow!("invalid --param `{entry}` (expected `key=value`)"))?;
        let value = crate::typst::chunk_options::parse_qmd_value(raw_value.trim())?;
        map.insert(key.trim().to_string(), value);
    }
    Ok(serde_json::Value::Object(map))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::typst::model::ResultsMode;
    use crate::typst::paths::slash_path;
    use crate::typst::testfixtures;

    #[test]
    fn page_meta_roundtrips_and_detects_stale_source() {
        let temp = tempfile::tempdir().unwrap();
        let input = temp.path().join("page.typ");
        fs::write(&input, "= Home\n").unwrap();
        let layout = resolve_layout(&input, None).unwrap();
        let value = serde_json::json!({"title": "Home", "pdf": false});

        write_page_meta(&layout, Some(&value)).unwrap();
        assert_eq!(read_page_meta_with_root(&input, None), Some(value));

        fs::write(&input, "= Changed\n").unwrap();
        assert_eq!(read_page_meta_with_root(&input, None), None);
    }

    #[test]
    fn page_meta_absent_when_document_exposes_none() {
        let temp = tempfile::tempdir().unwrap();
        let input = temp.path().join("page.typ");
        fs::write(&input, "= Home\n").unwrap();
        let layout = resolve_layout(&input, None).unwrap();

        write_page_meta(&layout, None).unwrap();

        assert_eq!(read_page_meta_with_root(&input, None), None);
    }

    #[test]
    fn cli_params_override_setup_params() {
        let base = serde_json::json!({"region": "NY", "min_count": 10});
        let resolved = resolve_params(
            &base,
            &[
                "region=CA".to_string(),
                "alpha=0.5".to_string(),
                "active=true".to_string(),
            ],
        )
        .unwrap();
        assert_eq!(
            resolved,
            serde_json::json!({"region":"CA","min_count":10,"alpha":0.5,"active":true})
        );
    }

    #[test]
    fn cli_param_without_equals_is_rejected() {
        let err = resolve_params(&serde_json::json!({}), &["bad".to_string()])
            .unwrap_err()
            .to_string();
        assert!(err.contains("bad"), "{err}");
    }

    #[test]
    fn resolve_params_with_no_overrides_returns_base() {
        let base = serde_json::json!({"a": 1});
        assert_eq!(resolve_params(&base, &[]).unwrap(), base);
    }

    #[test]
    fn query_command_uses_root_relative_input() {
        let dir = tempfile::tempdir().unwrap();
        let input = dir.path().join("paper.typ");
        std::fs::write(&input, "").unwrap();
        let layout = resolve_layout(&input, Some(dir.path())).unwrap();
        assert_eq!(slash_path(&layout.input_rel), "paper.typ");
    }

    #[test]
    fn display_input_uses_explicit_display_root() {
        let dir = tempfile::tempdir().unwrap();
        let docs = dir.path().join("docs");
        let language_dir = docs.join("fr");
        let input = language_dir.join("index.typ");
        std::fs::create_dir_all(&language_dir).unwrap();
        std::fs::write(&input, "").unwrap();
        let layout = resolve_layout(&input, Some(&language_dir)).unwrap();

        assert_eq!(display_input_path(&layout, None), "index.typ");
        let docs = std::fs::canonicalize(docs).unwrap();
        assert_eq!(display_input_path(&layout, Some(&docs)), "fr/index.typ");
    }

    #[test]
    fn preprocess_fingerprint_ignores_render_only_display_options() {
        let dir = tempfile::tempdir().unwrap();
        let layout = test_layout(dir.path());
        let executables = ExecutablePaths::defaults();
        let mut chunk = test_chunk("print(1)");

        let first = preprocess_fingerprint(
            &layout,
            &executables,
            std::slice::from_ref(&chunk),
            dir.path(),
            Some(Duration::from_secs(5)),
            &serde_json::json!({}),
            &crate::theme::ThemeSelection::Default,
            0,
        )
        .unwrap();

        chunk.display_options.echo = false;
        chunk.display_options.output = false;
        chunk.display_options.results = ResultsMode::Hide;
        chunk.display_options.fig_caption = Some("New caption".to_string());

        let second = preprocess_fingerprint(
            &layout,
            &executables,
            &[chunk],
            dir.path(),
            Some(Duration::from_secs(5)),
            &serde_json::json!({}),
            &crate::theme::ThemeSelection::Default,
            0,
        )
        .unwrap();

        assert_eq!(first, second);
    }

    #[test]
    fn preprocess_fingerprint_tracks_params() {
        let dir = tempfile::tempdir().unwrap();
        let layout = test_layout(dir.path());
        let executables = ExecutablePaths::defaults();
        let chunk = test_chunk("print(1)");
        let baseline = preprocess_fingerprint(
            &layout,
            &executables,
            std::slice::from_ref(&chunk),
            dir.path(),
            Some(Duration::from_secs(5)),
            &serde_json::json!({"region": "NY"}),
            &crate::theme::ThemeSelection::Default,
            0,
        )
        .unwrap();
        let changed = preprocess_fingerprint(
            &layout,
            &executables,
            &[chunk],
            dir.path(),
            Some(Duration::from_secs(5)),
            &serde_json::json!({"region": "CA"}),
            &crate::theme::ThemeSelection::Default,
            0,
        )
        .unwrap();
        assert_ne!(baseline, changed);
    }

    #[test]
    fn preprocess_fingerprint_tracks_execution_inputs() {
        let dir = tempfile::tempdir().unwrap();
        let layout = test_layout(dir.path());
        let executables = ExecutablePaths::defaults();
        let chunk = test_chunk("print(1)");
        let baseline = preprocess_fingerprint(
            &layout,
            &executables,
            std::slice::from_ref(&chunk),
            dir.path(),
            Some(Duration::from_secs(5)),
            &serde_json::json!({}),
            &crate::theme::ThemeSelection::Default,
            0,
        )
        .unwrap();

        let code_changed = preprocess_fingerprint(
            &layout,
            &executables,
            &[test_chunk("print(2)")],
            dir.path(),
            Some(Duration::from_secs(5)),
            &serde_json::json!({}),
            &crate::theme::ThemeSelection::Default,
            0,
        )
        .unwrap();
        assert_ne!(baseline, code_changed);

        let mut exec_changed = chunk.clone();
        exec_changed.exec_options.fig_device_dpi = 300;
        let exec_changed = preprocess_fingerprint(
            &layout,
            &executables,
            &[exec_changed],
            dir.path(),
            Some(Duration::from_secs(5)),
            &serde_json::json!({}),
            &crate::theme::ThemeSelection::Default,
            0,
        )
        .unwrap();
        assert_ne!(baseline, exec_changed);

        let mut executables_changed = executables.clone();
        executables_changed.python = PathBuf::from("python-custom");
        let executables_changed = preprocess_fingerprint(
            &layout,
            &executables_changed,
            &[chunk],
            dir.path(),
            Some(Duration::from_secs(5)),
            &serde_json::json!({}),
            &crate::theme::ThemeSelection::Default,
            0,
        )
        .unwrap();
        assert_ne!(baseline, executables_changed);
    }

    #[test]
    fn preprocess_fingerprint_tracks_theme() {
        let dir = tempfile::tempdir().unwrap();
        let layout = test_layout(dir.path());
        let executables = ExecutablePaths::defaults();
        let chunk = test_chunk("print(1)");
        let baseline = preprocess_fingerprint(
            &layout,
            &executables,
            std::slice::from_ref(&chunk),
            dir.path(),
            Some(Duration::from_secs(5)),
            &serde_json::json!({}),
            &crate::theme::ThemeSelection::Default,
            0,
        )
        .unwrap();
        let changed = preprocess_fingerprint(
            &layout,
            &executables,
            &[chunk],
            dir.path(),
            Some(Duration::from_secs(5)),
            &serde_json::json!({}),
            &crate::theme::ThemeSelection::Disabled,
            0,
        )
        .unwrap();
        assert_ne!(baseline, changed);
    }

    #[test]
    fn chunks_are_executed_grouped_by_engine() {
        let mut first_r = test_chunk("x <- 1");
        first_r.label = "r-first".to_string();
        first_r.engine = EngineName::R;

        let mut first_py = test_chunk("print(1)");
        first_py.label = "py-first".to_string();
        first_py.engine = EngineName::Python;

        let mut second_r = test_chunk("x <- 2");
        second_r.label = "r-second".to_string();
        second_r.engine = EngineName::R;

        let mut second_py = test_chunk("print(2)");
        second_py.label = "py-second".to_string();
        second_py.engine = EngineName::Python;

        let chunks = vec![first_r, first_py, second_r, second_py];
        let grouped_indices = chunks_in_engine_order(&chunks);
        let labels: Vec<&str> = grouped_indices
            .iter()
            .map(|&index| chunks[index].label.as_str())
            .collect();

        assert_eq!(labels, vec!["r-first", "r-second", "py-first", "py-second"]);
    }

    #[test]
    fn execution_artifacts_reference_final_figures_dir() {
        let root = tempfile::tempdir().unwrap();
        let staged = tempfile::tempdir().unwrap();
        let final_figures_dir = root.path().join(".calepin/paper/figures");
        let staged_artifact = staged.path().join("answer.svg");

        assert_eq!(
            execution_artifact_reference(
                root.path(),
                staged.path(),
                &final_figures_dir,
                &staged_artifact,
            ),
            "/.calepin/paper/figures/answer.svg"
        );
    }

    #[test]
    fn publish_staged_figures_copies_into_final_dir() {
        let staged = tempfile::tempdir().unwrap();
        let final_dir = tempfile::tempdir().unwrap();
        let staged_figures = staged.path().join("figures");
        std::fs::create_dir_all(staged_figures.join("nested")).unwrap();
        std::fs::write(staged_figures.join("answer.svg"), "<svg>answer</svg>").unwrap();
        std::fs::write(
            staged_figures.join("nested/detail.svg"),
            "<svg>detail</svg>",
        )
        .unwrap();

        publish_staged_figures(&staged_figures, final_dir.path()).unwrap();

        assert_eq!(
            std::fs::read_to_string(final_dir.path().join("answer.svg")).unwrap(),
            "<svg>answer</svg>"
        );
        assert_eq!(
            std::fs::read_to_string(final_dir.path().join("nested/detail.svg")).unwrap(),
            "<svg>detail</svg>"
        );
    }

    #[test]
    fn preprocess_cache_requires_results_and_matching_fingerprint() {
        let dir = tempfile::tempdir().unwrap();
        let layout = test_layout(dir.path());

        write_preprocess_fingerprint(&layout, 0x2a).unwrap();
        assert!(!preprocess_cache_hit(&layout, 0x2a).unwrap());

        std::fs::create_dir_all(layout.results_path.parent().unwrap()).unwrap();
        std::fs::write(&layout.results_path, "{}\n").unwrap();
        assert!(preprocess_cache_hit(&layout, 0x2a).unwrap());
        assert!(!preprocess_cache_hit(&layout, 0x2b).unwrap());
    }

    #[test]
    fn render_wrapper_includes_notebook_theme_before_source() {
        let dir = tempfile::tempdir().unwrap();
        let layout = test_layout(dir.path());
        let staged_input = PathBuf::from(".calepin/paper/source.typ");
        let notebook_theme = crate::theme::NotebookSource {
            source: "#let notebook-theme-marker = true\n".to_string(),
            owns_body: false,
        };

        let wrapper =
            write_render_wrapper(&layout, &staged_input, &[], Some(&notebook_theme)).unwrap();
        let contents = std::fs::read_to_string(dir.path().join(wrapper)).unwrap();

        let theme_marker = contents.find("#let notebook-theme-marker = true").unwrap();
        let source_include = contents
            .find("#include \"/.calepin/paper/source.typ\"")
            .unwrap();
        assert!(theme_marker < source_include);
    }

    #[test]
    fn render_wrapper_does_not_duplicate_template_owned_body() {
        let dir = tempfile::tempdir().unwrap();
        let layout = test_layout(dir.path());
        let staged_input = PathBuf::from(".calepin/paper/source.typ");
        let notebook_theme = crate::theme::NotebookSource {
            source: "#include \"/.calepin/paper/source.typ\"\n[#emph[Appendix]]\n".to_string(),
            owns_body: true,
        };

        let wrapper =
            write_render_wrapper(&layout, &staged_input, &[], Some(&notebook_theme)).unwrap();
        let contents = std::fs::read_to_string(dir.path().join(wrapper)).unwrap();

        assert_eq!(
            contents
                .matches("#include \"/.calepin/paper/source.typ\"")
                .count(),
            1
        );
        assert!(contents.contains("[#emph[Appendix]]"));
    }

    #[test]
    fn notebook_theme_comes_from_theme_selection() {
        let source = crate::theme::notebook_source(
            &crate::theme::ThemeSelection::Default,
            &crate::theme::NotebookTemplateContext::default(),
        )
        .unwrap()
        .unwrap();
        assert!(source.source.contains("code-block"));
        assert!(source.source.contains("_fenced-chunks-runs"));
        assert!(crate::theme::notebook_source(
            &crate::theme::ThemeSelection::Disabled,
            &crate::theme::NotebookTemplateContext::default(),
        )
        .unwrap()
        .is_none());
    }

    fn test_layout(root: &Path) -> LayoutPaths {
        testfixtures::layout(root)
    }

    fn test_chunk(code: &str) -> ChunkSpec {
        testfixtures::chunk("answer", code, ResultsMode::Verbatim)
    }
}