1use std::collections::{BTreeMap, VecDeque};
59use std::fmt::Write as _;
60
61use miette::bail;
62
63use crate::glyphs::GLYPHS;
64use crate::lang::{flat_nodes, InnerKind, Language as _};
65use crate::lift::escape_html;
66use crate::machine::html::{element_id, selector, top_level, Defined};
67use crate::machine::{Answer, HtmlMachine, Machine as _};
68use crate::multi::{Languages, MetaLanguages, Multi};
69use crate::prelude::*;
70use crate::qterm::QTerm;
71
72pub const MAX_GENERATION: usize = 8;
78
79pub const STYLE_ID: &str = "quilt-cells";
82
83pub const NO_VALUE: &[&str] = &["None", "undefined"];
87
88pub const DEFAULT_STYLE: &str = r"
91.quilt-cell { --quilt-accent: #8250df; --quilt-line: #d0d7de; --quilt-ink: #1f2328; --quilt-paper: #fff; --quilt-mute: #57606a;
92 border: 1px solid var(--quilt-line); border-left: 4px solid var(--quilt-accent); border-radius: 6px;
93 margin: 1rem 0; padding: 0; background: var(--quilt-paper); color: var(--quilt-ink); font-size: .95rem; overflow: hidden; }
94.quilt-cell > .quilt-lang { font: 600 .7rem/1 ui-monospace, SFMono-Regular, Menlo, monospace; text-transform: uppercase;
95 letter-spacing: .08em; color: var(--quilt-accent); padding: .45rem .75rem 0; }
96.quilt-cell > .quilt-src { margin: 0; padding: .45rem .75rem .6rem; overflow-x: auto; font: .85rem/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; }
97.quilt-cell > .quilt-out { display: block; border-top: 1px dashed var(--quilt-line); padding: .5rem .75rem; }
98.quilt-cell .quilt-stdout, .quilt-cell .quilt-value { margin: 0; font: .85rem/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; }
99.quilt-cell .quilt-value { color: #0550ae; }
100.quilt-cell > .quilt-stderr, .quilt-cell > .quilt-error { margin: 0; border-top: 1px dashed var(--quilt-line); padding: .5rem .75rem;
101 font: .8rem/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; }
102.quilt-cell > .quilt-stderr { color: #7d4e00; background: #fff8c5; }
103.quilt-cell > .quilt-error { color: #a40e26; background: #ffebe9; }
104.quilt-cell.quilt-failed { --quilt-accent: #cf222e; }
105.quilt-cell.quilt-generated { border-left-style: dashed; }
106.quilt-cell.quilt-pending { --quilt-accent: #8c959f; }
107.quilt-cell .quilt-glyph { color: #bc4c00; font-weight: 700; }
108.quilt-cell.quilt-py, .quilt-cell.quilt-python { --quilt-accent: #3572a5; }
109.quilt-cell.quilt-sql, .quilt-cell.quilt-mysql { --quilt-accent: #e38c00; }
110.quilt-cell.quilt-bash, .quilt-cell.quilt-zsh { --quilt-accent: #4e9a06; }
111.quilt-cell.quilt-ts, .quilt-cell.quilt-typescript { --quilt-accent: #3178c6; }
112.quilt-cell.quilt-html { --quilt-accent: #e34c26; }
113@media (prefers-color-scheme: dark) {
114 .quilt-cell { --quilt-line: #3d444d; --quilt-ink: #e6edf3; --quilt-paper: #161b22; --quilt-mute: #9198a1; }
115 .quilt-cell .quilt-value { color: #79c0ff; }
116 .quilt-cell > .quilt-stderr { color: #e3b341; background: #2b2411; }
117 .quilt-cell > .quilt-error { color: #ff7b72; background: #2d1214; }
118}
119";
120
121#[derive(Debug, Clone)]
125pub struct Cell {
126 pub id: usize,
128 pub lang: Box<str>,
130 pub generation: usize,
133 pub src: String,
135 pub ran: bool,
138 pub value: Option<Box<str>>,
140 pub stdout: Box<str>,
141 pub stderr: Box<str>,
142 pub error: Option<String>,
144 pub edits: Vec<String>,
146 pub spawned: Vec<usize>,
148}
149
150impl Cell {
151 #[must_use]
153 pub fn pending(id: usize, lang: &str, src: &str, generation: usize) -> Cell {
154 Cell {
155 id,
156 lang: lang.into(),
157 generation,
158 src: src.to_string(),
159 ran: false,
160 value: None,
161 stdout: Box::default(),
162 stderr: Box::default(),
163 error: None,
164 edits: Vec::new(),
165 spawned: Vec::new(),
166 }
167 }
168
169 #[must_use]
170 pub fn failed(&self) -> bool {
171 self.error.is_some()
172 }
173
174 #[must_use]
176 pub fn element_id(&self) -> String {
177 cell_element_id(self.id)
178 }
179}
180
181const CELL_ID_PREFIX: &str = "quilt-cell-";
184
185#[must_use]
187pub fn cell_element_id(id: usize) -> String {
188 format!("{CELL_ID_PREFIX}{id}")
189}
190
191#[must_use]
193pub fn cell_id(element_id: &str) -> Option<usize> {
194 element_id.strip_prefix(CELL_ID_PREFIX)?.parse().ok()
195}
196
197fn first_quote(term: &Arc<QTerm>) -> Option<Arc<QTerm>> {
200 match &**term {
201 QTerm::Quote { term, .. } => Some(term.clone()),
202 QTerm::Tuple { terms, .. } => terms.iter().find_map(first_quote),
203 QTerm::Unquote { .. } => None,
204 }
205}
206
207struct Planted {
209 id: usize,
210 lang: Box<str>,
211 body: Arc<QTerm>,
212 generation: usize,
213}
214
215#[derive(Debug, Clone)]
219pub struct CellDef {
220 pub id: usize,
221 pub lang: Box<str>,
223 pub src: String,
225 pub generation: usize,
228}
229
230#[derive(Debug, Clone)]
232pub struct Program {
233 pub kind: InnerKind,
235 pub resolved: String,
238 pub program: String,
241 pub term: Arc<QTerm>,
244}
245
246#[derive(Debug, Clone, PartialEq, Eq)]
253pub enum Change {
254 Define { id: String, html: String },
256 Insert { after: String, html: String },
258 Append { html: String },
260 Remove { id: String },
262}
263
264#[derive(Debug, Clone)]
266pub struct Rendered {
267 pub html: String,
268 pub cells: Vec<Cell>,
269}
270
271impl Rendered {
272 #[must_use]
274 pub fn failures(&self) -> Vec<&Cell> {
275 self.cells.iter().filter(|c| c.failed()).collect()
276 }
277}
278
279pub fn run<LS: Languages, MS: MetaLanguages>(
281 multi: &mut Multi<LS, MS>,
282 src: &str,
283) -> Result<Rendered> {
284 let mut notebook = Notebook::open(multi, src)?;
285 notebook.run_pending();
286 Ok(notebook.finish())
287}
288
289pub struct Notebook<'m, LS: Languages, MS: MetaLanguages> {
296 multi: &'m mut Multi<LS, MS>,
297 page: HtmlMachine,
298 cells: Vec<Cell>,
299 defs: BTreeMap<usize, CellDef>,
302 queue: VecDeque<Planted>,
303 spawned: Vec<Planted>,
306 changes: Vec<Change>,
308 next_id: usize,
309}
310
311impl<'m, LS: Languages, MS: MetaLanguages> Notebook<'m, LS, MS> {
312 pub fn new(multi: &'m mut Multi<LS, MS>) -> Self {
314 Notebook {
315 multi,
316 page: HtmlMachine::default(),
317 cells: Vec::new(),
318 defs: BTreeMap::new(),
319 queue: VecDeque::new(),
320 spawned: Vec::new(),
321 changes: Vec::new(),
322 next_id: 1,
323 }
324 }
325
326 pub fn open(multi: &'m mut Multi<LS, MS>, src: &str) -> Result<Self> {
329 let mut nb = Self::new(multi);
330 let doc = nb.multi.parse_chain(&["html"], src)?;
331 let planted = nb.plant(&doc, 0);
332 nb.page = HtmlMachine::new(&planted);
333 nb.queue.extend(nb.spawned.drain(..));
334 nb.ensure_style();
335 Ok(nb)
336 }
337
338 pub fn feed_source(&mut self, src: &str) -> Result<Vec<usize>> {
342 let frag = self.multi.parse_chain(&["html"], src)?;
343 let planted = self.plant(&frag, 0);
344 for node in top_level(&planted) {
345 self.define(&node);
346 }
347 self.queue.extend(self.spawned.drain(..));
348 let first = self.cells.len();
349 self.run_pending();
350 Ok(self.cells[first..].iter().map(|c| c.id).collect())
351 }
352
353 pub fn run_pending(&mut self) {
355 while let Some(planted) = self.queue.pop_front() {
356 self.run_planted(&planted);
357 }
358 }
359
360 #[must_use]
362 pub fn page(&self) -> &HtmlMachine {
363 &self.page
364 }
365
366 #[must_use]
368 pub fn cells(&self) -> &[Cell] {
369 &self.cells
370 }
371
372 #[must_use]
374 pub fn render(&self) -> String {
375 self.page.document().coparse()
376 }
377
378 #[must_use]
380 pub fn finish(self) -> Rendered {
381 Rendered {
382 html: self.render(),
383 cells: self.cells,
384 }
385 }
386
387 #[must_use]
396 pub fn cell_defs(&self) -> Vec<&CellDef> {
397 let mut placed: Vec<&CellDef> = self
398 .page
399 .ids()
400 .iter()
401 .filter_map(|id| cell_id(id))
402 .filter_map(|id| self.defs.get(&id))
403 .collect();
404 let loose: Vec<&CellDef> = self
407 .defs
408 .values()
409 .filter(|d| !placed.iter().any(|p| p.id == d.id))
410 .collect();
411 placed.extend(loose);
412 placed
413 }
414
415 #[must_use]
417 pub fn cell_def(&self, id: usize) -> Option<&CellDef> {
418 self.defs.get(&id)
419 }
420
421 #[must_use]
423 pub fn cell(&self, id: usize) -> Option<&Cell> {
424 self.cells.iter().find(|c| c.id == id)
425 }
426
427 #[must_use]
430 pub fn cell_figure(&self, id: usize) -> Option<String> {
431 self.page.find(&cell_element_id(id)).map(|el| el.coparse())
432 }
433
434 pub fn take_changes(&mut self) -> Vec<Change> {
438 std::mem::take(&mut self.changes)
439 }
440
441 pub fn add_cell(&mut self, lang: &str, src: &str, after: Option<&str>) -> Result<usize> {
450 let id = self.next_id;
451 self.next_id += 1;
452 let cell = Cell::pending(id, lang, src, 0);
453 let figure = self.figure_term(&cell, "")?;
454 match after {
455 Some(anchor) if self.page.insert_after(anchor, &figure) => {
456 let html = self.cell_figure(id).unwrap_or_else(|| figure.coparse());
457 self.changes.push(Change::Insert {
458 after: anchor.to_string(),
459 html,
460 });
461 }
462 _ => {
463 self.define(&figure);
464 }
465 }
466 self.defs.insert(
467 id,
468 CellDef {
469 id,
470 lang: lang.into(),
471 src: src.to_string(),
472 generation: 0,
473 },
474 );
475 Ok(id)
476 }
477
478 pub fn set_cell(&mut self, id: usize, lang: Option<&str>, src: &str) -> Result<()> {
482 let def = self
483 .defs
484 .get_mut(&id)
485 .ok_or_else(|| miette!("this page has no cell {id}"))?;
486 if let Some(lang) = lang {
487 def.lang = lang.into();
488 }
489 def.src = src.to_string();
490 let (lang, generation) = (def.lang.clone(), def.generation);
491 self.cells.retain(|c| c.id != id);
492 let cell = Cell::pending(id, &lang, src, generation);
493 let figure = self.figure_term(&cell, "")?;
494 self.define(&figure);
495 Ok(())
496 }
497
498 pub fn remove_cell(&mut self, id: usize) -> Result<()> {
502 if self.defs.remove(&id).is_none() {
503 bail!("this page has no cell {id}");
504 }
505 self.cells.retain(|c| c.id != id);
506 let element = cell_element_id(id);
507 if self.page.remove(&element) {
508 self.changes.push(Change::Remove { id: element });
509 }
510 Ok(())
511 }
512
513 pub fn run_cell(&mut self, id: usize) -> Result<()> {
520 match self.planted(id)? {
521 Ok(planted) => self.run_planted(&planted),
522 Err((planted, e)) => self.land(&planted, Err(e)),
523 }
524 self.run_pending();
525 Ok(())
526 }
527
528 pub fn expand_cell(&mut self, id: usize) -> Result<Program> {
532 let def = self.def(id)?;
533 let body = self.parse_cell_body(&def.lang, &def.src)?;
534 self.program(&def.lang, &body, def.generation)
535 }
536
537 pub fn expand_source(&mut self, lang: &str, src: &str) -> Result<Program> {
541 let body = self.parse_cell_body(lang, src)?;
542 self.program(lang, &body, 0)
543 }
544
545 pub fn define_html(&mut self, html: &str) -> Result<Option<String>> {
550 let frag = self.parse_html(html)?;
551 let mut defined = None;
552 for node in top_level(&frag) {
553 self.define(&node);
554 defined = defined.or_else(|| element_id(&node));
555 }
556 Ok(defined)
557 }
558
559 pub fn land_cell(&mut self, id: usize, outcome: Result<Answer>) -> Result<()> {
564 let planted = match self.planted(id)? {
565 Ok(planted) | Err((planted, _)) => planted,
566 };
567 self.land(&planted, outcome);
568 self.run_pending();
569 Ok(())
570 }
571
572 pub fn feed_lang(&mut self, lang: &str, kind: InnerKind, src: &str) -> Result<Answer> {
578 self.multi.feed_on(lang, kind, src)
579 }
580
581 pub fn park_machine(&mut self, lang: &str, machine: Box<dyn crate::machine::Machine>) {
590 let key = self.multi.langs.canonical(lang).to_string();
591 self.multi.machines.insert(&key, machine);
592 }
593
594 #[must_use]
596 pub fn has_machine(&self, lang: &str) -> bool {
597 self.multi
598 .machines
599 .contains(self.multi.langs.canonical(lang))
600 }
601
602 #[must_use]
606 pub fn site_html(&self) -> String {
607 self.page
608 .document_without(&|id| cell_id(id).is_some() || id == STYLE_ID)
609 .coparse()
610 }
611
612 #[allow(clippy::type_complexity)]
617 fn planted(
618 &mut self,
619 id: usize,
620 ) -> Result<std::result::Result<Planted, (Planted, miette::Report)>> {
621 let def = self.def(id)?;
622 let CellDef {
623 lang,
624 src,
625 generation,
626 ..
627 } = def;
628 Ok(match self.parse_cell_body(&lang, &src) {
629 Ok(body) => Ok(Planted {
630 id,
631 lang,
632 body,
633 generation,
634 }),
635 Err(e) => Err((
636 Planted {
637 id,
638 lang,
639 body: leaf("text", &src),
640 generation,
641 },
642 e,
643 )),
644 })
645 }
646
647 fn def(&self, id: usize) -> Result<CellDef> {
648 self.defs
649 .get(&id)
650 .cloned()
651 .ok_or_else(|| miette!("this page has no cell {id}"))
652 }
653
654 fn parse_cell_body(&mut self, lang: &str, src: &str) -> Result<Arc<QTerm>> {
657 let wrapped = format!("{lang}↖{src}↗");
658 let doc = self
659 .multi
660 .parse_chain(&["html"], &wrapped)
661 .map_err(|e| e.with_source_code(wrapped.clone()))?;
662 first_quote(&doc).ok_or_else(|| miette!("a cell of {lang} must be readable as `{lang}↖…↗`"))
663 }
664
665 fn ensure_style(&mut self) {
667 if self.page.find(STYLE_ID).is_some() {
668 return;
669 }
670 let style = format!("<style id=\"{STYLE_ID}\">{DEFAULT_STYLE}</style>");
671 if let Ok(style) = self.parse_html(&style) {
672 self.define(&style);
673 }
674 }
675
676 fn define(&mut self, node: &Arc<QTerm>) -> Defined {
683 let defined = self.page.define(node);
684 let id = element_id(node);
685 let html = id
686 .as_deref()
687 .and_then(|id| self.page.find(id))
688 .map_or_else(|| node.coparse(), |el| el.coparse());
689 self.changes.push(match (id, defined) {
690 (Some(id), Defined::Replaced) => Change::Define { id, html },
691 _ => Change::Append { html },
692 });
693 defined
694 }
695
696 fn parse_html(&mut self, src: &str) -> Result<Arc<QTerm>> {
699 self.multi
700 .get_lang_mut("html")?
701 .parse_as(None, &flat_nodes(src))
702 }
703
704 fn plant(&mut self, term: &Arc<QTerm>, generation: usize) -> Arc<QTerm> {
707 match &**term {
708 QTerm::Quote {
709 lang, term: body, ..
710 } => {
711 let id = self.next_id;
712 self.next_id += 1;
713 self.defs.insert(
714 id,
715 CellDef {
716 id,
717 lang: lang.clone(),
718 src: cell_source(lang, body),
719 generation,
720 },
721 );
722 self.spawned.push(Planted {
723 id,
724 lang: lang.clone(),
725 body: body.clone(),
726 generation,
727 });
728 self.placeholder(id, lang)
729 }
730 QTerm::Tuple { tag, terms, cmds } => {
731 let terms: Vec<_> = terms.iter().map(|t| self.plant(t, generation)).collect();
732 tuple(tag, &terms, cmds)
733 }
734 QTerm::Unquote { .. } => term.clone(),
736 }
737 }
738
739 fn placeholder(&mut self, id: usize, lang: &str) -> Arc<QTerm> {
741 let html = format!(
742 "<figure class=\"quilt-cell quilt-pending\" id=\"{}\" data-lang=\"{lang}\"></figure>",
743 cell_element_id(id)
744 );
745 self.parse_html(&html).unwrap_or_else(|_| leaf("text", ""))
746 }
747
748 fn run_planted(&mut self, planted: &Planted) {
750 let outcome = self.execute(&planted.lang, &planted.body, planted.generation);
751 self.land(planted, outcome);
752 }
753
754 fn land(&mut self, planted: &Planted, outcome: Result<Answer>) {
763 let Planted {
764 id,
765 lang,
766 body,
767 generation,
768 } = planted;
769 let (id, generation) = (*id, *generation);
770 let mut cell = Cell {
771 id,
772 lang: lang.clone(),
773 generation,
774 src: cell_source(lang, body),
775 ran: true,
776 value: None,
777 stdout: Box::default(),
778 stderr: Box::default(),
779 error: None,
780 edits: Vec::new(),
781 spawned: Vec::new(),
782 };
783 let mut slot: Vec<Arc<QTerm>> = Vec::new();
785 match outcome {
786 Ok(answer) => {
787 cell.stdout = match &answer.value {
790 Some(value) => without_answer_line(&answer.stdout, value).into(),
791 None => answer.stdout,
792 };
793 cell.stderr = answer.stderr;
794 cell.value = answer.value;
795 let stdout = cell.stdout.to_string();
796 let mut nodes = self.output_nodes(&stdout, "quilt-stdout", generation);
797 if let Some(value) = cell.value.clone() {
798 if !NO_VALUE.contains(&value.trim()) {
799 nodes.extend(self.output_nodes(&value, "quilt-value", generation));
800 }
801 }
802 for node in nodes {
803 match element_id(&node) {
806 Some(id) if self.page.find(&id).is_some() => {
807 self.define(&node);
808 cell.edits.push(id);
809 }
810 _ => slot.push(node),
811 }
812 }
813 }
814 Err(e) => cell.error = Some(render_error(&e)),
815 }
816 cell.spawned = self.spawned.iter().map(|p| p.id).collect();
818 let spawned: Vec<Planted> = self.spawned.drain(..).collect();
819 for planted in spawned.into_iter().rev() {
820 self.queue.push_front(planted);
821 }
822 self.place(&cell, &slot);
823 match self.cells.iter_mut().find(|c| c.id == id) {
826 Some(slot) => *slot = cell,
827 None => self.cells.push(cell),
828 }
829 }
830
831 fn execute(&mut self, lang: &str, body: &Arc<QTerm>, generation: usize) -> Result<Answer> {
834 let program = self.program(lang, body, generation)?;
835 self.feed(lang, &program)
836 }
837
838 fn program(&mut self, lang: &str, body: &Arc<QTerm>, generation: usize) -> Result<Program> {
844 if generation > MAX_GENERATION {
845 bail!(
846 "cell generation {generation} is past the limit of {MAX_GENERATION}: cells kept \
847 creating cells"
848 );
849 }
850 let resolved = self.resolve_refs(lang, body, 1)?;
851 let src = cell_source(lang, &resolved);
852 let with_src = |e: miette::Report| e.with_source_code(src.clone());
853 let term = self.multi.parse_chain(&[lang], &src).map_err(with_src)?;
854 let term = if self.multi.get_meta(lang).is_ok() {
857 self.multi.expand_lang(lang, &term).map_err(with_src)?
858 } else {
859 term
860 };
861 let kind = self.multi.classify_for_feed(lang, &term)?;
862 Ok(Program {
863 kind,
864 resolved: src,
865 program: term.coparse(),
866 term,
867 })
868 }
869
870 fn feed(&mut self, lang: &str, program: &Program) -> Result<Answer> {
873 if lang == "html" {
874 return self.feed_page(program.kind, &program.term);
875 }
876 self.multi.machine(lang)?.feed(program.kind, &program.term)
877 }
878
879 fn feed_page(&mut self, kind: InnerKind, term: &Arc<QTerm>) -> Result<Answer> {
885 let nodes = top_level(term);
886 let query =
887 kind == InnerKind::Expr || matches!(nodes.as_slice(), [one] if selector(one).is_some());
888 if query {
889 return self.page.feed(kind, term);
890 }
891 for node in &nodes {
892 self.define(node);
893 }
894 Ok(Answer::default())
895 }
896
897 fn resolve_refs(&self, lang: &str, term: &Arc<QTerm>, depth: usize) -> Result<Arc<QTerm>> {
902 Ok(match &**term {
903 QTerm::Quote {
904 tag,
905 index,
906 lang: qlang,
907 term: inner,
908 cmds,
909 span,
910 repr,
911 } => arc(QTerm::Quote {
912 tag: tag.clone(),
913 index: *index,
914 lang: qlang.clone(),
915 term: self.resolve_refs(lang, inner, depth + usize::from(*index))?,
916 cmds: cmds.clone(),
917 span: span.clone(),
918 repr: *repr,
919 }),
920 QTerm::Unquote {
921 tag,
922 index,
923 lang: ulang,
924 term: inner,
925 cmds,
926 span,
927 } => {
928 if usize::from(*index) >= depth {
929 let text = inner.coparse();
930 let text = text.trim();
931 let spliced = match text.strip_prefix('#') {
932 Some(id) if !id.is_empty() && !id.contains(char::is_whitespace) => {
933 let value = self.page.text(id).ok_or_else(|| {
934 miette!(
935 "the page has no element with id {id:?} for `↙{text}↘` to read"
936 )
937 })?;
938 string_literal(lang, &value)
939 }
940 _ => text.to_string(),
941 };
942 leaf("text", &spliced)
943 } else {
944 arc(QTerm::Unquote {
945 tag: tag.clone(),
946 index: *index,
947 lang: ulang.clone(),
948 term: self.resolve_refs(lang, inner, depth - usize::from(*index))?,
949 cmds: cmds.clone(),
950 span: span.clone(),
951 })
952 }
953 }
954 QTerm::Tuple { tag, terms, cmds } => {
955 let terms = terms
956 .iter()
957 .map(|t| self.resolve_refs(lang, t, depth))
958 .collect::<Result<Vec<_>>>()?;
959 tuple(tag, &terms, cmds)
960 }
961 })
962 }
963
964 fn output_nodes(
968 &mut self,
969 text: &str,
970 plain_class: &str,
971 generation: usize,
972 ) -> Vec<Arc<QTerm>> {
973 let text = text.trim_end_matches(['\n', '\r']);
974 if text.trim().is_empty() {
975 return Vec::new();
976 }
977 let markup = text.contains('<') || text.chars().any(|c| GLYPHS.contains(&c));
978 if markup {
979 if let Ok(frag) = self.multi.parse_chain(&["html"], text) {
980 let planted = self.plant(&frag, generation + 1);
981 return top_level(&planted);
982 }
983 }
984 vec![self.pre(plain_class, text)]
985 }
986
987 fn pre(&mut self, class: &str, text: &str) -> Arc<QTerm> {
989 let escaped = escape_html(text);
990 self.parse_html(&format!("<pre class=\"{class}\">{escaped}</pre>"))
991 .unwrap_or_else(|_| leaf("text", &escaped))
992 }
993
994 fn place(&mut self, cell: &Cell, slot: &[Arc<QTerm>]) {
997 let slot_html = slot
998 .iter()
999 .map(|n| n.coparse())
1000 .collect::<Vec<_>>()
1001 .join("\n");
1002 if let Ok(figure) = self.figure_term(cell, &slot_html) {
1003 self.define(&figure);
1004 }
1005 }
1006
1007 fn figure_term(&mut self, cell: &Cell, slot_html: &str) -> Result<Arc<QTerm>> {
1011 self.parse_html(&figure_html(cell, slot_html)).or_else(|_| {
1012 let escaped = format!(
1013 "<pre class=\"quilt-stdout\">{}</pre>",
1014 escape_html(slot_html)
1015 );
1016 self.parse_html(&figure_html(cell, &escaped))
1017 })
1018 }
1019}
1020
1021fn figure_html(cell: &Cell, slot_html: &str) -> String {
1026 let mut classes = format!("quilt-cell quilt-{}", cell.lang);
1027 if cell.generation > 0 {
1028 classes.push_str(" quilt-generated");
1029 }
1030 if cell.failed() {
1031 classes.push_str(" quilt-failed");
1032 }
1033 if !cell.ran {
1034 classes.push_str(" quilt-pending");
1035 }
1036 let mut h = String::new();
1037 let _ = writeln!(
1038 h,
1039 "<figure class=\"{classes}\" id=\"{}\" data-lang=\"{}\" data-generation=\"{}\">",
1040 cell.element_id(),
1041 cell.lang,
1042 cell.generation
1043 );
1044 let _ = writeln!(
1045 h,
1046 "<figcaption class=\"quilt-lang\">{}</figcaption>",
1047 cell.lang
1048 );
1049 let _ = writeln!(
1050 h,
1051 "<pre class=\"quilt-src\"><code>{}</code></pre>",
1052 highlight(&cell.src)
1053 );
1054 if !slot_html.is_empty() {
1055 let _ = writeln!(h, "<output class=\"quilt-out\">\n{slot_html}\n</output>");
1056 }
1057 let stderr = cell.stderr.trim_end();
1058 if !stderr.trim().is_empty() {
1059 let _ = writeln!(
1060 h,
1061 "<pre class=\"quilt-stderr\">{}</pre>",
1062 escape_html(stderr)
1063 );
1064 }
1065 if let Some(error) = &cell.error {
1066 let _ = writeln!(
1067 h,
1068 "<pre class=\"quilt-error\">{}</pre>",
1069 escape_html(error.trim_end())
1070 );
1071 }
1072 h.push_str("</figure>");
1073 h
1074}
1075
1076fn highlight(src: &str) -> String {
1079 let mut out = String::with_capacity(src.len());
1080 for c in escape_html(src).chars() {
1081 if GLYPHS.contains(&c) {
1082 let _ = write!(out, "<span class=\"quilt-glyph\">{c}</span>");
1083 } else {
1084 out.push(c);
1085 }
1086 }
1087 out
1088}
1089
1090fn string_literal(lang: &str, s: &str) -> String {
1094 match lang {
1095 "python" | "py" | "typescript" | "ts" => {
1096 format!("\"{}\"", crate::lift::py_dquote_escape(s))
1097 }
1098 "bash" | "zsh" => format!("\"{}\"", crate::lift::sh_dquote_escape(s)),
1099 "sql" => format!("'{}'", crate::lift::sql_squote_escape(s)),
1100 "mysql" | "mariadb" => format!("'{}'", crate::lift::mysql_squote_escape(s)),
1101 "rust" | "rs" => format!("{s:?}"),
1102 _ => s.to_string(),
1103 }
1104}
1105
1106fn cell_source(lang: &str, body: &Arc<QTerm>) -> String {
1113 let quoted = quote(
1114 "cell",
1115 1,
1116 lang,
1117 body.clone(),
1118 &[
1119 crate::term::cmd(crate::strcmd::write("↖")),
1120 crate::term::HOLE,
1121 crate::term::cmd(crate::strcmd::write("↗")),
1122 ],
1123 );
1124 let text = quoted.coparse_quilt();
1125 text.strip_prefix('↖')
1126 .and_then(|t| t.strip_suffix('↗'))
1127 .map_or(text.clone(), str::to_string)
1128}
1129
1130fn without_answer_line(stdout: &str, value: &str) -> String {
1133 let trimmed = stdout.trim_end();
1134 match trimmed.rfind('\n') {
1135 Some(at) if trimmed[at + 1..].trim() == value => trimmed[..at].to_string(),
1136 None if trimmed.trim() == value => String::new(),
1137 _ => stdout.to_string(),
1138 }
1139}
1140
1141fn render_error(e: &miette::Report) -> String {
1146 let diagnostic: &dyn miette::Diagnostic = e.as_ref();
1147 if diagnostic.labels().is_some() && diagnostic.source_code().is_some() {
1148 let handler =
1149 miette::GraphicalReportHandler::new_themed(miette::GraphicalTheme::unicode_nocolor())
1150 .with_width(96);
1151 let mut out = String::new();
1152 if handler.render_report(&mut out, diagnostic).is_ok() {
1153 return out;
1154 }
1155 }
1156 e.chain()
1157 .map(ToString::to_string)
1158 .collect::<Vec<_>>()
1159 .join("\n")
1160}
1161
1162#[cfg(test)]
1165mod tests {
1166 use super::*;
1167
1168 #[test]
1169 fn string_literals_follow_each_language() {
1170 assert_eq!(string_literal("py", "a\"b"), "\"a\\\"b\"");
1171 assert_eq!(string_literal("bash", "$x"), "\"\\$x\"");
1172 assert_eq!(string_literal("sql", "it's"), "'it''s'");
1173 assert_eq!(string_literal("html", "<b>"), "<b>");
1174 }
1175
1176 #[test]
1177 fn the_answer_line_is_shown_once() {
1178 assert_eq!(without_answer_line("hi\n42\n", "42"), "hi");
1179 assert_eq!(without_answer_line("42", "42"), "");
1180 assert_eq!(without_answer_line("hi\n", "42"), "hi\n");
1181 }
1182
1183 #[test]
1184 fn highlight_marks_glyphs_and_escapes_markup() {
1185 assert_eq!(
1186 highlight("<b>↖x↗"),
1187 "<b><span class=\"quilt-glyph\">↖</span>x<span class=\"quilt-glyph\">↗</span>"
1188 );
1189 }
1190}