presenterm 0.16.1

A terminal slideshow presentation tool
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
use super::{BuildError, BuildResult};
use crate::{
    code::{
        execute::LanguageSnippetExecutor,
        snippet::{
            ExternalFile, Highlight, HighlightContext, HighlightGroup, HighlightMutator, HighlightedLine, PtyArgs,
            Snippet, SnippetExecArgs, SnippetExecution, SnippetExecutorSpec, SnippetLanguage, SnippetLine,
            SnippetParser, SnippetRepr, SnippetSplitter,
        },
    },
    markdown::elements::SourcePosition,
    presentation::builder::{PresentationBuilder, error::InvalidPresentation},
    render::{
        operation::{AsRenderOperations, RenderAsyncStartPolicy, RenderOperation},
        properties::WindowSize,
    },
    theme::{Alignment, CodeBlockStyle},
    third_party::ThirdPartyRenderRequest,
    ui::execution::{
        RunAcquireTerminalSnippet, RunImageSnippet, SnippetExecutionDisabledOperation, SnippetOutputOperation,
        disabled::ExecutionType,
        output::{ExecIndicator, ExecIndicatorStyle, RunSnippetTrigger, SnippetHandle, WrappedSnippetHandle},
        pty::{PtySnippetHandle, PtySnippetOutputOperation, RunPtySnippetTrigger},
        validator::ValidateSnippetOperation,
    },
};
use itertools::Itertools;
use std::{cell::RefCell, rc::Rc};

impl PresentationBuilder<'_, '_> {
    pub(crate) fn push_code(&mut self, info: String, code: String, source_position: SourcePosition) -> BuildResult {
        let mut snippet = SnippetParser::parse(info, code)
            .map_err(|e| self.invalid_presentation(source_position, InvalidPresentation::Snippet(e.to_string())))?;
        if matches!(snippet.language, SnippetLanguage::File) {
            snippet = self.load_external_snippet(snippet, source_position)?;
        }
        if self.theme.code.line_numbers {
            snippet.attributes.line_numbers = true;
        }
        if self.options.auto_render_languages.contains(&snippet.language) {
            snippet.attributes.execution = SnippetExecution::Render;
        }
        // Ids can only be used in `+exec` snippets.
        if snippet.attributes.id.is_some()
            && !matches!(
                snippet.attributes.execution,
                SnippetExecution::Exec(SnippetExecArgs { repr: SnippetRepr::SnippetOutput, .. })
            )
        {
            return Err(self.invalid_presentation(source_position, InvalidPresentation::SnippetIdNonExec));
        }

        self.push_differ(snippet.contents.clone());
        // Redraw slide if attributes change
        self.push_differ(format!("{:?}", snippet.attributes));

        if let Some(spec) = &snippet.attributes.validate {
            // Take the execution spec if we use the default one, otherwise use the one provided.
            // This allows using `rust +exec:foo +validate` and using `foo` as the executor.
            let spec = match (spec, &snippet.attributes.execution) {
                (SnippetExecutorSpec::Default, SnippetExecution::Exec(args)) => &args.spec,
                _ => spec,
            };
            let executor = self.snippet_executor.language_executor(&snippet.language, spec)?;
            self.push_validator(&snippet, &executor);
        }

        match &snippet.attributes.execution {
            SnippetExecution::None => {
                self.push_code_lines(&snippet);
            }
            SnippetExecution::Render => {
                self.push_rendered_code(snippet, source_position)?;
            }
            SnippetExecution::Exec(args) if !self.is_execution_allowed(args) => {
                self.push_code_lines(&snippet);
                let mut exec_type = match args.repr {
                    SnippetRepr::Image => ExecutionType::Image,
                    SnippetRepr::ExecReplace => ExecutionType::ExecReplace,
                    SnippetRepr::SnippetOutput | SnippetRepr::AcquireTerminal => ExecutionType::Execute,
                };
                if args.auto {
                    exec_type = ExecutionType::ExecReplace;
                }
                self.push_execution_disabled_operation(exec_type);
            }
            SnippetExecution::Exec(args) => {
                let executor = self.snippet_executor.language_executor(&snippet.language, &args.spec)?;
                match args.repr {
                    SnippetRepr::Image => {
                        self.push_code_as_image(snippet, executor)?;
                    }
                    SnippetRepr::ExecReplace => match &args.pty {
                        Some(args) => {
                            let args = args.clone();
                            self.push_replace_pty_code_execution(snippet, executor, args)?;
                        }
                        None => {
                            self.push_replace_code_execution(snippet, executor)?;
                        }
                    },
                    SnippetRepr::AcquireTerminal => {
                        let block_length = self.push_code_lines(&snippet);
                        self.push_acquire_terminal_execution(snippet, block_length, executor)?;
                    }
                    SnippetRepr::SnippetOutput => {
                        let block_length = self.push_code_lines(&snippet);
                        let policy = if args.auto {
                            RenderAsyncStartPolicy::Automatic
                        } else {
                            RenderAsyncStartPolicy::OnDemand
                        };
                        let handle: WrappedSnippetHandle = match &args.pty {
                            Some(args) => PtySnippetHandle::new(snippet.clone(), executor, policy, args.clone()).into(),
                            None => SnippetHandle::new(snippet.clone(), executor, policy).into(),
                        };
                        self.chunk_operations.push(RenderOperation::RenderAsync(handle.build_trigger().into()));

                        let alignment = self.code_style(&snippet).alignment;
                        self.push_indicator(handle.clone(), block_length, alignment);
                        match snippet.attributes.id.clone() {
                            Some(id) => {
                                if self.executable_snippets.insert(id.clone(), handle).is_some() {
                                    return Err(self.invalid_presentation(
                                        source_position,
                                        InvalidPresentation::SnippetAlreadyExists(id),
                                    ));
                                }
                            }
                            None => {
                                self.push_line_break();
                                match handle {
                                    WrappedSnippetHandle::Normal(handle) => {
                                        self.push_code_execution(block_length, handle, alignment)?;
                                    }
                                    WrappedSnippetHandle::Pty(handle) => self.push_pty_code_execution(handle)?,
                                }
                            }
                        }
                    }
                }
            }
        };
        Ok(())
    }

    pub(crate) fn push_detached_code_execution(&mut self, handle: WrappedSnippetHandle) -> BuildResult {
        match handle {
            WrappedSnippetHandle::Normal(handle) => {
                let alignment = self.code_style(&handle.snippet()).alignment;
                self.push_code_execution(0, handle, alignment)
            }
            WrappedSnippetHandle::Pty(handle) => self.push_pty_code_execution(handle),
        }
    }

    fn is_execution_allowed(&self, args: &SnippetExecArgs) -> bool {
        match args.repr {
            SnippetRepr::SnippetOutput | SnippetRepr::AcquireTerminal => self.options.enable_snippet_execution,
            SnippetRepr::Image | SnippetRepr::ExecReplace => self.options.enable_snippet_execution_replace,
        }
    }

    fn push_code_lines(&mut self, snippet: &Snippet) -> u16 {
        let lines = SnippetSplitter::new(&self.theme.code, self.snippet_executor.hidden_line_prefix(&snippet.language))
            .split(snippet);
        let block_length = lines.iter().map(|line| line.width()).max().unwrap_or(0) * self.slide_font_size() as usize;
        let block_length = block_length as u16;
        let (lines, context) = self.highlight_lines(snippet, lines, block_length);
        for line in lines {
            self.chunk_operations.push(RenderOperation::RenderDynamic(Rc::new(line)));
        }
        self.chunk_operations.push(RenderOperation::SetColors(self.theme.default_style.style.colors));
        if self.options.allow_mutations && context.borrow().groups.len() > 1 {
            self.chunk_mutators.push(Box::new(HighlightMutator::new(context)));
        }
        block_length
    }

    fn push_replace_code_execution(&mut self, snippet: Snippet, executor: LanguageSnippetExecutor) -> BuildResult {
        let alignment = match self.code_style(&snippet).alignment {
            // If we're replacing the snippet output, we have center alignment and no background, use
            // center alignment but without any margins and minimum sizes so we truly center the output.
            Alignment::Center { .. } if snippet.attributes.no_background => {
                Alignment::Center { minimum_margin: Default::default(), minimum_size: 0 }
            }
            other => other,
        };
        let handle = SnippetHandle::new(snippet, executor, RenderAsyncStartPolicy::Automatic);
        self.chunk_operations.push(RenderOperation::RenderAsync(Rc::new(RunSnippetTrigger::new(handle.clone()))));
        self.push_code_execution(0, handle, alignment)
    }

    fn push_replace_pty_code_execution(
        &mut self,
        snippet: Snippet,
        executor: LanguageSnippetExecutor,
        args: PtyArgs,
    ) -> BuildResult {
        let standby = args.standby;
        let policy = if standby { RenderAsyncStartPolicy::OnDemand } else { RenderAsyncStartPolicy::Automatic };
        let handle = PtySnippetHandle::new(snippet, executor, policy, args);
        // If we're using standby mode we still need a trigger
        if standby {
            self.chunk_operations
                .push(RenderOperation::RenderAsync(WrappedSnippetHandle::from(handle.clone()).build_trigger().into()));
        }
        self.chunk_operations.push(RenderOperation::RenderAsync(Rc::new(RunPtySnippetTrigger::new(handle.clone()))));
        self.push_pty_code_execution(handle)
    }

    fn load_external_snippet(
        &mut self,
        mut code: Snippet,
        source_position: SourcePosition,
    ) -> Result<Snippet, BuildError> {
        let file: ExternalFile = serde_yaml::from_str(&code.contents)
            .map_err(|e| self.invalid_presentation(source_position, InvalidPresentation::Snippet(e.to_string())))?;
        let path = file.path;
        let base_path = self.resource_base_path();
        let contents = self.resources.external_text_file(&path, &base_path).map_err(|e| {
            self.invalid_presentation(
                source_position,
                InvalidPresentation::Snippet(format!("failed to load snippet {path:?}: {e}")),
            )
        })?;
        code.language = file.language;
        code.contents = Self::filter_lines(contents, file.start_line, file.end_line);
        Ok(code)
    }

    fn filter_lines(code: String, start: Option<usize>, end: Option<usize>) -> String {
        let start = start.map(|s| s.saturating_sub(1));
        match (start, end) {
            (None, None) => code,
            (None, Some(end)) => code.lines().take(end).join("\n"),
            (Some(start), None) => code.lines().skip(start).join("\n"),
            (Some(start), Some(end)) => code.lines().skip(start).take(end.saturating_sub(start)).join("\n"),
        }
    }

    fn push_rendered_code(&mut self, code: Snippet, source_position: SourcePosition) -> BuildResult {
        let Snippet { contents, language, attributes } = code;
        let request = match language {
            SnippetLanguage::Typst => ThirdPartyRenderRequest::Typst(contents, self.theme.typst.clone()),
            SnippetLanguage::Latex => ThirdPartyRenderRequest::Latex(contents, self.theme.typst.clone()),
            SnippetLanguage::Mermaid => ThirdPartyRenderRequest::Mermaid(contents, self.theme.mermaid.clone()),
            SnippetLanguage::D2 => ThirdPartyRenderRequest::D2(contents, self.theme.d2.clone()),
            _ => {
                return Err(self.invalid_presentation(
                    source_position,
                    InvalidPresentation::Snippet(format!("language {language:?} doesn't support rendering")),
                ));
            }
        };
        let operation = self.third_party.render(request, &self.theme, attributes.width)?;
        self.chunk_operations.push(operation);
        Ok(())
    }

    fn highlight_lines(
        &self,
        code: &Snippet,
        lines: Vec<SnippetLine>,
        block_length: u16,
    ) -> (Vec<HighlightedLine>, Rc<RefCell<HighlightContext>>) {
        let mut code_highlighter = self.highlighter.language_highlighter(&code.language);
        let style = self.code_style(code);
        let block_length = self.theme.code.alignment.adjust_size(block_length);
        let font_size = self.slide_font_size();
        let dim_style = {
            let mut highlighter = self.highlighter.language_highlighter(&SnippetLanguage::Rust);
            highlighter.style_line("//", &style).0.first().expect("no styles").style.size(font_size)
        };
        let groups = match self.options.allow_mutations {
            true => code.attributes.highlight_groups.clone(),
            false => vec![HighlightGroup::new(vec![Highlight::All])],
        };
        let context =
            Rc::new(RefCell::new(HighlightContext { groups, current: 0, block_length, alignment: style.alignment }));

        let mut output = Vec::new();
        for line in lines.into_iter() {
            let prefix = line.dim_prefix(&dim_style);
            let highlighted = line.highlight(&mut code_highlighter, &style, font_size);
            let not_highlighted = line.dim(&dim_style);
            let line_number = line.line_number;
            let context = context.clone();
            output.push(HighlightedLine {
                prefix,
                right_padding_length: line.right_padding_length * font_size as u16,
                highlighted,
                not_highlighted,
                line_number,
                context,
                block_color: dim_style.colors.background,
            });
        }
        (output, context)
    }

    fn code_style(&self, snippet: &Snippet) -> CodeBlockStyle {
        let mut style = self.theme.code.clone();
        if snippet.attributes.no_background {
            style.background = false;
        }
        style
    }

    fn push_execution_disabled_operation(&mut self, exec_type: ExecutionType) {
        let policy = match exec_type {
            ExecutionType::ExecReplace | ExecutionType::Image => RenderAsyncStartPolicy::Automatic,
            ExecutionType::Execute => RenderAsyncStartPolicy::OnDemand,
        };
        let operation = SnippetExecutionDisabledOperation::new(
            self.theme.execution_output.status.failure_style,
            self.theme.code.alignment,
            policy,
            exec_type,
        );
        self.chunk_operations.push(RenderOperation::RenderAsync(Rc::new(operation)));
    }

    fn push_code_as_image(&mut self, snippet: Snippet, executor: LanguageSnippetExecutor) -> BuildResult {
        let operation =
            RunImageSnippet::new(snippet, executor, self.image_registry.clone(), self.theme.execution_output.status);
        let operation = RenderOperation::RenderAsync(Rc::new(operation));
        self.chunk_operations.push(operation);
        Ok(())
    }

    fn push_acquire_terminal_execution(
        &mut self,
        snippet: Snippet,
        block_length: u16,
        executor: LanguageSnippetExecutor,
    ) -> BuildResult {
        let block_length = self.theme.code.alignment.adjust_size(block_length);
        let operation = RunAcquireTerminalSnippet::new(
            snippet,
            executor,
            self.theme.execution_output.status,
            block_length,
            self.slide_font_size(),
        );
        let operation = RenderOperation::RenderAsync(Rc::new(operation));
        self.chunk_operations.push(operation);
        Ok(())
    }

    fn push_indicator<T: Into<WrappedSnippetHandle>>(&mut self, handle: T, block_length: u16, alignment: Alignment) {
        let style = ExecIndicatorStyle {
            theme: self.theme.execution_output.status,
            block_length,
            font_size: self.slide_font_size(),
            alignment,
        };
        let indicator = Rc::new(ExecIndicator::new(handle, style));
        self.chunk_operations.push(RenderOperation::RenderDynamic(indicator));
    }

    fn push_code_execution(&mut self, block_length: u16, handle: SnippetHandle, alignment: Alignment) -> BuildResult {
        let snippet = handle.snippet();
        let default_colors = self.theme.default_style.style.colors;
        let mut execution_output_style = self.theme.execution_output.clone();
        if snippet.attributes.no_background {
            execution_output_style.style.colors.background = None;
            execution_output_style.padding = Default::default();
        }
        let operation = SnippetOutputOperation::new(
            handle,
            default_colors,
            execution_output_style,
            block_length,
            alignment,
            self.slide_font_size(),
        );
        let operation = RenderOperation::RenderDynamic(Rc::new(operation));
        self.chunk_operations.push(operation);
        Ok(())
    }

    fn push_pty_code_execution(&mut self, handle: PtySnippetHandle) -> BuildResult {
        let snippet = handle.snippet();
        let mut style = self.theme.pty_output.clone();
        if snippet.attributes.no_background {
            style.style.colors.background = None;
        }
        let operation = PtySnippetOutputOperation::new(handle, style, self.slide_font_size());
        let operation = RenderOperation::RenderDynamic(Rc::new(operation));
        self.chunk_operations.push(operation);
        Ok(())
    }

    fn push_differ(&mut self, text: String) {
        self.chunk_operations.push(RenderOperation::RenderDynamic(Rc::new(Differ(text))));
    }

    fn push_validator(&mut self, snippet: &Snippet, executor: &LanguageSnippetExecutor) {
        if !self.options.validate_snippets {
            return;
        }
        let operation = ValidateSnippetOperation::new(snippet.clone(), executor.clone());
        self.chunk_operations.push(RenderOperation::RenderAsync(Rc::new(operation)));
    }
}

#[derive(Debug)]
struct Differ(String);

impl AsRenderOperations for Differ {
    fn as_render_operations(&self, _: &WindowSize) -> Vec<RenderOperation> {
        Vec::new()
    }

    fn diffable_content(&self) -> Option<&str> {
        Some(&self.0)
    }
}

#[cfg(all(test, target_os = "linux"))]
mod tests {
    use super::*;
    use crate::{
        markdown::text_style::Color,
        presentation::builder::utils::{RunAsyncRendersPolicy, Test},
        theme::raw,
    };
    use rstest::rstest;
    use std::fs;

    #[rstest]
    #[case::no_filters(None, None, &["a", "b", "c", "d", "e"])]
    #[case::start_from_first(Some(1), None, &["a", "b", "c", "d", "e"])]
    #[case::start_from_second(Some(2), None, &["b", "c", "d", "e"])]
    #[case::start_from_end(Some(5), None, &["e"])]
    #[case::start_from_past_end(Some(6), None, &[])]
    #[case::end_last(None, Some(5), &["a", "b", "c", "d", "e"])]
    #[case::end_one_before_last(None, Some(4), &["a", "b", "c", "d"])]
    #[case::end_at_first(None, Some(1), &["a"])]
    #[case::end_at_zero(None, Some(0), &[])]
    #[case::start_and_end(Some(2), Some(3), &["b", "c"])]
    #[case::crossed(Some(2), Some(1), &[])]
    fn filter_lines(#[case] start: Option<usize>, #[case] end: Option<usize>, #[case] expected: &[&str]) {
        let code = ["a", "b", "c", "d", "e"].join("\n");
        let output = PresentationBuilder::filter_lines(code, start, end);
        let expected = expected.join("\n");
        assert_eq!(output, expected);
    }

    #[test]
    fn plain() {
        let input = "
```bash
echo hi
```";
        let lines = Test::new(input).render().rows(3).columns(7).into_lines();
        let expected = &["       ", "echo hi", "       "];
        assert_eq!(lines, expected);
    }

    #[test]
    fn external_snippet() {
        let temp = tempfile::NamedTempFile::new().expect("failed to create tempfile");
        let path = temp.path();
        fs::write(path, "echo hi").unwrap();

        let path = path.to_string_lossy();
        let input = format!(
            "
```file
path: {path}
language: bash
```
"
        );
        let lines = Test::new(input).render().rows(3).columns(7).into_lines();
        let expected = &["       ", "echo hi", "       "];
        assert_eq!(lines, expected);
    }

    #[test]
    fn line_numbers() {
        let input = "
```bash +line_numbers
hi
bye
```";
        let lines = Test::new(input).render().rows(4).columns(5).into_lines();
        let expected = &["     ", "1 hi ", "2 bye", "     "];
        assert_eq!(lines, expected);
    }

    #[test]
    fn line_numbers_via_theme() {
        let input = "---
theme:
  override:
    code:
      line_numbers: true
---

```bash
hi
bye
```";
        let lines = Test::new(input).render().rows(4).columns(5).into_lines();
        let expected = &["     ", "1 hi ", "2 bye", "     "];
        assert_eq!(lines, expected);
    }

    #[test]
    fn surroundings() {
        let input = "
---
```bash
echo hi
```
---";
        let lines = Test::new(input).render().rows(7).columns(7).into_lines();
        let expected = &[
            //
            "       ",
            "———————",
            "       ",
            "echo hi",
            "       ",
            "———————",
            "       ",
        ];
        assert_eq!(lines, expected);
    }

    #[test]
    fn padding() {
        let input = "
```bash
echo hi
```";
        let theme = raw::PresentationTheme {
            code: raw::CodeBlockStyle {
                padding: raw::PaddingRect { horizontal: Some(2), vertical: Some(1) },
                ..Default::default()
            },
            ..Default::default()
        };
        let lines = Test::new(input).theme(theme).render().rows(5).columns(13).into_lines();
        let expected = &[
            //
            "             ",
            "             ",
            "  echo hi    ",
            "             ",
            "             ",
        ];
        assert_eq!(lines, expected);
    }

    #[test]
    fn exec_no_run() {
        let input = "
```bash +exec
echo hi
```";
        let lines =
            Test::new(input).render().rows(4).columns(19).run_async_renders(RunAsyncRendersPolicy::None).into_lines();
        let expected = &[
            //
            "                   ",
            "echo hi            ",
            "                   ",
            "—— [not started] ——",
        ];
        assert_eq!(lines, expected);
    }

    #[test]
    fn exec_auto() {
        let input = "
```bash +auto_exec
echo hi
```";
        let lines = Test::new(input)
            .render()
            .rows(6)
            .columns(19)
            .run_async_renders(RunAsyncRendersPolicy::OnlyAutomatic)
            .into_lines();
        let expected = &[
            //
            "                   ",
            "echo hi            ",
            "                   ",
            "——— [finished] ————",
            "                   ",
            "hi                 ",
        ];
        assert_eq!(lines, expected);
    }

    #[test]
    fn validate() {
        let input = "
```bash +validate
echo hi
```";
        let lines =
            Test::new(input).render().rows(4).columns(19).run_async_renders(RunAsyncRendersPolicy::None).into_lines();
        let expected = &["                   ", "echo hi            ", "                   ", "                   "];
        assert_eq!(lines, expected);
    }

    #[test]
    fn exec_disabled() {
        let input = "
```bash +exec
echo hi
```";
        let lines = Test::new(input).disable_exec().render().rows(6).columns(25).into_lines();
        let expected = &[
            "                         ",
            "echo hi                  ",
            "                         ",
            "snippet +exec is         ",
            "disabled, run with -x to ",
            "enable                   ",
        ];
        assert_eq!(lines, expected);
    }

    #[test]
    fn exec_replace_disabled() {
        let input = "
```bash +exec_replace
echo hi
```";
        let lines = Test::new(input).disable_exec_replace().render().rows(6).columns(25).into_lines();
        let expected = &[
            "                         ",
            "echo hi                  ",
            "                         ",
            "snippet +exec_replace is ",
            "disabled, run with -X to ",
            "enable                   ",
        ];
        assert_eq!(lines, expected);
    }

    #[test]
    fn exec() {
        let input = "
```bash +exec
echo hi
```";
        let theme = raw::PresentationTheme {
            execution_output: raw::ExecutionOutputBlockStyle {
                colors: raw::RawColors {
                    background: Some(raw::RawColor::Color(Color::new(45, 45, 45))),
                    foreground: None,
                },
                padding: raw::PaddingRect { horizontal: Some(1), vertical: Some(1) },
                ..Default::default()
            },
            ..Default::default()
        };
        let (lines, styles) = Test::new(input)
            .theme(theme)
            .render()
            .map_background(Color::new(45, 45, 45), 'x')
            .rows(8)
            .columns(16)
            .into_parts();
        let expected_lines = &[
            "                ",
            "echo hi         ",
            "                ",
            "—— [finished] ——",
            "                ",
            "                ",
            " hi             ",
            "                ",
        ];
        let expected_styles = &[
            "                ",
            "xxxxxxxxxxxxxxxx",
            "                ",
            "                ",
            "                ",
            "xxxxxxxxxxxxxxxx",
            "xxxxxxxxxxxxxxxx",
            "xxxxxxxxxxxxxxxx",
        ];
        assert_eq!(lines, expected_lines);
        assert_eq!(styles, expected_styles);
    }

    #[test]
    fn exec_font_size() {
        let input = "
<!-- font_size: 2 -->
```bash +exec
echo hi
```";
        let lines = Test::new(input).render().rows(8).columns(32).into_lines();
        let expected = &[
            "                                ",
            "e c h o   h i                   ",
            "                                ",
            "                                ",
            "— —   [ f i n i s h e d ]   — — ",
            "                                ",
            "                                ",
            "h i                             ",
        ];
        assert_eq!(lines, expected);
    }

    #[test]
    fn exec_font_size_centered() {
        let input = "
<!-- font_size: 2 -->
```bash +exec
echo hi
```";
        let theme = raw::PresentationTheme {
            code: raw::CodeBlockStyle {
                alignment: Some(raw::Alignment::Center { minimum_margin: raw::Margin::Fixed(0), minimum_size: 40 }),
                ..Default::default()
            },
            execution_output: raw::ExecutionOutputBlockStyle {
                colors: raw::RawColors {
                    background: Some(raw::RawColor::Color(Color::new(45, 45, 45))),
                    foreground: None,
                },
                padding: raw::PaddingRect { horizontal: Some(1), vertical: Some(1) },
                ..Default::default()
            },
            ..Default::default()
        };
        let (lines, styles) = Test::new(input)
            .theme(theme)
            .render()
            .map_background(Color::new(45, 45, 45), 'x')
            .rows(10)
            .columns(40)
            .into_parts();
        let expected_lines = &[
            "                                        ",
            "e c h o   h i                           ",
            "                                        ",
            "                                        ",
            "— — — —   [ f i n i s h e d ]   — — — — ",
            "                                        ",
            "                                        ",
            "                                        ",
            "                                        ",
            "  h i                                   ",
        ];
        let expected_styles = &[
            "                                        ",
            "x x x x x x x x x x x x x x x x x x x x ",
            "                                        ",
            "                                        ",
            "                                        ",
            "                                        ",
            "                                        ",
            "x x x x x x x x x x x x x x x x x x x x ",
            "                                        ",
            "x x x x x x x x x x x x x x x x x x x x ",
        ];
        assert_eq!(lines, expected_lines);
        assert_eq!(styles, expected_styles);
    }

    #[test]
    fn exec_adjacent_detached_output() {
        let input = "
```bash +exec +id:foo
echo hi
```
<!-- snippet_output: foo -->";
        let lines =
            Test::new(input).render().rows(4).columns(19).run_async_renders(RunAsyncRendersPolicy::None).into_lines();
        // this should look exactly the same as if we hadn't detached the output
        let expected = &[
            //
            "                   ",
            "echo hi            ",
            "                   ",
            "—— [not started] ——",
        ];
        assert_eq!(lines, expected);
    }

    #[test]
    fn exec_detached_output() {
        let input = "
```bash +exec +id:foo
echo hi
```

bar

<!-- snippet_output: foo -->";
        let lines = Test::new(input).render().rows(8).columns(16).into_lines();
        let expected = &[
            "                ",
            "echo hi         ",
            "                ",
            "—— [finished] ——",
            "                ",
            "bar             ",
            "                ",
            "hi              ",
        ];
        assert_eq!(lines, expected);
    }

    #[test]
    fn exec_replace() {
        let input = "
```bash +exec_replace
echo hi
```";
        let lines = Test::new(input).render().rows(3).columns(7).into_lines();
        let expected = &["       ", "hi     ", "       "];
        assert_eq!(lines, expected);
    }

    #[test]
    fn snippet_exec_replace_centered() {
        let input = "
```bash +exec_replace
echo hi
```";
        let theme = raw::PresentationTheme {
            code: raw::CodeBlockStyle {
                alignment: Some(raw::Alignment::Center { minimum_margin: raw::Margin::Fixed(1), minimum_size: 1 }),
                ..Default::default()
            },
            ..Default::default()
        };
        let lines = Test::new(input).theme(theme).render().rows(3).columns(6).into_lines();
        let expected = &["      ", "  hi  ", "      "];
        assert_eq!(lines, expected);
    }

    #[test]
    fn exec_replace_font_size() {
        let input = "
<!-- font_size: 2 -->
```bash +exec_replace
echo hi
```";
        let lines = Test::new(input).render().rows(3).columns(7).into_lines();
        let expected = &["       ", "h i    ", "       "];
        assert_eq!(lines, expected);
    }

    #[test]
    fn exec_replace_long() {
        let qr = [
            "█▀▀▀▀▀█ ▄▀ ▄▀ █▀▀▀▀▀█",
            "█ ███ █ ▄▀ ▄  █ ███ █",
            "█ ▀▀▀ █ ▄▄█▀█ █ ▀▀▀ █",
            "▀▀▀▀▀▀▀ ▀ █▄█ ▀▀▀▀▀▀▀",
            "█▀▀██ ▀▀█▀  █▀ █ ▀ ▀▄",
            "▄▄██▀▄▀▀▄ █▀ ▀ ▄█▀█▀ ",
            "▀  ▀▀ ▀▀▄█▄█▄█▄▄▀ ▄ █",
            "█▀▀▀▀▀█ ▀▀ ▄█▄█▀ ▄█▀▄",
            "█ ███ █ ██▀ █  ▄█▄ ▀ ",
            "█ ▀▀▀ █ █ ▄▀ ▀  ▄██  ",
            "▀▀▀▀▀▀▀ ▀▀ ▀ ▀  ▀  ▀ ",
        ]
        .join("\n");

        let input = format!(
            r#"
```bash +exec_replace
echo "{qr}"
```
"#
        );
        let rows = 13;
        let columns = 21;
        let lines = Test::new(input).render().rows(rows).columns(columns).into_lines();
        let empty = " ".repeat(columns as usize);
        let expected: Vec<_> = [empty.as_str()].into_iter().chain(qr.lines()).chain([empty.as_str()]).collect();
        assert_eq!(lines, expected);
    }
}