Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/eval/realise.rs

50.2 KiB, 206 runs

created by r1870400018:63508, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// SPDX-License-Identifier: Apache-2.0
2// Original work copyright (c) the Typst project authors (typst-realize, version 0.15.1).
3// Modified for Austenite: ported to Hematite's types, IR and error handling.
4// U4 owns this file: content plus styles in, an ordered element stream out, with show rules applied,
5// locations assigned and inline runs grouped. Flow calls it again for each container's body, so one call
6// realises one level, not the whole tree.
7//
8// A port of Typst 0.15's `typst-realize`: show-rule verdicts with guards, preparation (location, built-in
9// show-set styles, materialised and synthesised fields), text and regex rules over merged text runs, and
10// the grouping rules (textual, par, cites, list, enum, terms) with their priorities and interruptions.
11// A location tag is a `Pair` with `tag` set in the stream and a `tag` element in content, so tags inside
12// a paragraph stay in its body; tags inside a list or a cite group are lifted out of it (a start before
13// the group element, an end after it). This file also answers for the `Realise` family: `tag`,
14// `sequence` and `styled`, the kinds of what realisation makes and of plain content.
15
16use crate::diag::DiagnosticKind;
17use crate::eval::args::Args;
18use crate::eval::content::{
19 self,
20 native_show,
21 Content,
22 Elem,
23 ElemKind,
24 Family,
25 FieldDefault,
26 FieldId,
27 FieldSpec,
28 FieldType,
29};
30use crate::eval::fp;
31use crate::eval::locate::Location;
32use crate::eval::styles::{
33 apply_recipe,
34 error_hints,
35 Recipe,
36 RecipeIndex,
37 RecipeSlot,
38 Style,
39 StyleChain,
40 Styles,
41 Transformation,
42};
43use crate::eval::value::{
44 Label,
45 Type,
46 Value,
47};
48use crate::eval::Engine;
49use crate::syntax::Span;
50use crate::timings::{
51 Counter,
52 Phase,
53 Timings,
54};
55
56use oxedyne_fe2o3_core::prelude::*;
57use oxedyne_fe2o3_hash::fingerprint::Fingerprint;
58use oxedyne_fe2o3_hash::fingerprint::Fingerprinter;
59
60use std::sync::Arc;
61
62pub const MAX_SHOW_RULE_DEPTH: usize = 64; // Typst's own limit
63pub const MAX_GROUPING_STEPS: usize = 512; // ditto, for groups that keep producing groups
64
65/// The show rules Typst applies to an element on its way to a layout routine, which its show-rule depth counts
66/// where the element is realised: one for a shape, a stack, a pad, a transform or a `layout`, two for a list, an
67/// enumeration, a grid or a figure, where the nested list or grid begins a layer more.
68fn shows_of(kind: Option<ElemKind>) -> usize {
69 match kind {
70 Some(ElemKind::List | ElemKind::Enum | ElemKind::Grid | ElemKind::Figure)
71 => 2,
72 Some(ElemKind::Pad | ElemKind::Stack | ElemKind::Rect | ElemKind::Square | ElemKind::Circle | ElemKind::Ellipse
73 | ElemKind::Move | ElemKind::Scale | ElemKind::Rotate | ElemKind::Layout)
74 => 1,
75 _ => 0,
76 }
77}
78
79/// What the caller will do with the stream, which decides grouping.
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub enum RealiseMode {
82 Document, // page elements and pagebreaks surface; everything else as in Flow
83 Flow, // block-level: inline runs grouped into `par`, list items into `list`/`enum`/`terms`
84 Inline, // a paragraph's children: text runs merged, text/regex show rules applied
85 Math, // an equation's body
86}
87
88/// Where a located element starts and ends in the stream, for the ledger and the introspector. `Start`
89/// carries the element as prepared (location set, fields materialised).
90#[derive(Clone, Debug)]
91pub enum Tag {
92 Start(Content),
93 End(Location),
94}
95
96impl Tag {
97 /// The tag as a `tag` element, how it sits inside content such as a paragraph's body.
98 pub fn to_content(&self) -> Content {
99 match self {
100 Tag::Start(c) => Content::new(ElemKind::Tag, vec![(TAG_START, Value::Content(c.clone()))], c.span()),
101 Tag::End(l) => Content::new(ElemKind::Tag, vec![(TAG_END, Value::Location(*l))], Span::detached()),
102 }
103 }
104
105 /// The tag a `tag` element carries.
106 pub fn from_content(c: &Content) -> Option<Tag> {
107 if !c.is(ElemKind::Tag) {
108 return None;
109 }
110 match (c.get(TAG_START), c.get(TAG_END)) {
111 (Some(Value::Content(e)), _) => Some(Tag::Start(e.clone())),
112 (_, Some(Value::Location(l))) => Some(Tag::End(*l)),
113 _ => None,
114 }
115 }
116}
117
118// The `Realise` family's schemas.
119const TAG_START: FieldId = FieldId(0);
120const TAG_END: FieldId = FieldId(1);
121
122const TAG: &[FieldSpec] = &[
123 FieldSpec::named("start", FieldType::Of(Type::Content), FieldDefault::None).unsettable(),
124 FieldSpec::named("end", FieldType::Of(Type::Location), FieldDefault::None).unsettable(),
125];
126const SEQUENCE: &[FieldSpec] = &[
127 FieldSpec::required("children", FieldType::Of(Type::Array)),
128];
129const STYLED: &[FieldSpec] = &[
130 FieldSpec::required("child", FieldType::Content),
131 FieldSpec::required("styles", FieldType::Of(Type::Styles)),
132];
133
134pub fn fields(kind: ElemKind) -> &'static [FieldSpec] {
135 match kind {
136 ElemKind::Tag => TAG,
137 ElemKind::Sequence => SEQUENCE,
138 ElemKind::Styled => STYLED,
139 _ => &[],
140 }
141}
142
143/// `sequence(children)` and `styled(child, styles)` build plain content, as the functions
144/// `content.func()` returns for it do in Typst; a tag is made only by realisation.
145pub fn construct(engine: &mut Engine, kind: ElemKind, args: &mut Args) -> Outcome<Option<Content>> {
146 let span = args.span;
147 let built = match kind {
148 ElemKind::Sequence => {
149 let items = res!(args.expect::<Value>("children"));
150 let items = match items {
151 Value::Array(a) => a,
152 other => return Err(engine.error(DiagnosticKind::Type, span, fmt!(
153 "expected array, found {}", other.ty().long_name()))),
154 };
155 let mut children = Vec::with_capacity(items.len());
156 for v in items.iter() {
157 match v {
158 Value::Content(c) => children.push(c.clone()),
159 other => return Err(engine.error(DiagnosticKind::Type, span, fmt!(
160 "expected content, found {}", other.ty().long_name()))),
161 }
162 }
163 Content::sequence(children)
164 }
165 ElemKind::Styled => {
166 let child = res!(args.expect::<Value>("child"));
167 let styles = res!(args.expect::<Value>("styles"));
168 let child = res!(content::display(engine, child, span));
169 match styles {
170 Value::Styles(s) => child.styled(s),
171 other => return Err(engine.error(DiagnosticKind::Type, span, fmt!(
172 "expected styles, found {}", other.ty().long_name()))),
173 }
174 }
175 _ => return Err(engine.error(DiagnosticKind::Type, span, fmt!("`{}` is made by realisation, not called", kind.path()))),
176 };
177 res!(std::mem::take(args).finish());
178 Ok(Some(built))
179}
180
181/// One realised element and the styles it is laid out under. A tag pair has empty content and `tag` set;
182/// flow emits a ledger anchor for it and lays nothing out.
183#[derive(Clone, Debug)]
184pub struct Pair {
185 pub content: Content,
186 pub styles: StyleChain,
187 pub tag: Option<Tag>,
188}
189
190impl Pair {
191 pub fn new(content: Content, styles: StyleChain) -> Self { Self { content, styles, tag: None } }
192
193 pub fn tag(tag: Tag, styles: StyleChain) -> Self { Self { content: Content::empty(), styles, tag: Some(tag) } }
194
195 pub fn is_tag(&self) -> bool { self.tag.is_some() }
196
197 /// The pair as flow sees it: its content, the style chain it is laid out under and its tag. The
198 /// content's own location and place are in it, because flow anchors the pair by them; a span is not.
199 pub fn fingerprint(&self) -> Fingerprint {
200 let mut h = Fingerprinter::new();
201 h.write_fingerprint(self.content.fingerprint());
202 match self.content.location() {
203 Some(l) => { h.write_u8(1); h.write_u64(l.0); }
204 None => h.write_u8(0),
205 }
206 match self.content.place() {
207 Some(p) => { h.write_u8(1); h.write_u64(p.0); }
208 None => h.write_u8(0),
209 }
210 h.write_fingerprint(self.styles.fingerprint());
211 match &self.tag {
212 None => h.write_u8(0),
213 Some(Tag::Start(c)) => {
214 h.write_u8(1);
215 h.write_fingerprint(c.fingerprint());
216 match c.location() {
217 Some(l) => { h.write_u8(1); h.write_u64(l.0); }
218 None => h.write_u8(0),
219 }
220 }
221 Some(Tag::End(l)) => { h.write_u8(2); h.write_u64(l.0); }
222 }
223 h.finish()
224 }
225}
226
227/// Does a realised document set any content? Spaces, paragraph breaks, page breaks and column breaks do not,
228/// and a tag only marks a place; any other element does, though it draws nothing, as a vertical space or an
229/// empty box does. A `context` that gives nothing, a `set` rule and a `let` leave no element, and the furniture
230/// a `set page` names is laid out beside the body and is no part of it.
231pub fn sets_content(pairs: &[Pair]) -> bool {
232 pairs.iter().any(|p| !p.is_tag() && !matches!(
233 p.content.kind(),
234 Some(ElemKind::Space | ElemKind::Parbreak | ElemKind::Pagebreak | ElemKind::Colbreak),
235 ))
236}
237
238/// Realises `content` under `styles`. In `Flow` mode a body that is inline only -- no paragraph break,
239/// no block-level element -- comes back ungrouped, as Typst's fragment realisation leaves it: flow sets
240/// it as one paragraph without a `par` element, so `show par` rules do not reach it.
241pub fn realise(
242 engine: &mut Engine,
243 content: &Content,
244 styles: &StyleChain,
245 mode: RealiseMode,
246)
247 -> Outcome<Vec<Pair>>
248{
249 Ok(res!(realise_with(engine, content, styles, mode, false, false)).0)
250}
251
252/// Realises a body in `Flow` mode and says whether it is one paragraph's worth of inline elements left without
253/// a `par`: Typst's `FragmentKind::Inline`. Text with spaces between its runs (`A: B`) is such a body, so the
254/// caller cannot re-derive the verdict from the pairs alone.
255pub fn realise_fragment(
256 engine: &mut Engine,
257 content: &Content,
258 styles: &StyleChain,
259)
260 -> Outcome<(Vec<Pair>, bool)>
261{
262 realise_with(engine, content, styles, RealiseMode::Flow, false, true)
263}
264
265/// Realises as `realise` does, but leaves model elements (headings, paragraphs, lists, strong and
266/// emphasised text, figures and the like) standing where no user show rule replaces them, instead of
267/// expanding them by their built-in show, as Typst's HTML export keeps them. The structure a reader
268/// sees can then be compared with that export.
269pub fn realise_structure(
270 engine: &mut Engine,
271 content: &Content,
272 styles: &StyleChain,
273 mode: RealiseMode,
274)
275 -> Outcome<Vec<Pair>>
276{
277 Ok(res!(realise_with(engine, content, styles, mode, true, false)).0)
278}
279
280fn realise_with(
281 engine: &mut Engine,
282 content: &Content,
283 styles: &StyleChain,
284 mode: RealiseMode,
285 keep_model: bool,
286 fragment: bool,
287)
288 -> Outcome<(Vec<Pair>, bool)>
289{
290 note_call(engine, content, mode);
291 engine.timed(Phase::Realise, |engine| {
292 let mut s = State {
293 engine,
294 mode,
295 keep_model,
296 sink: Vec::new(),
297 groupings: Vec::new(),
298 outside: mode == RealiseMode::Document,
299 may_attach: false,
300 saw_parbreak: false,
301 fully_inline: false,
302 pars: 0,
303 };
304 res!(s.visit(content, styles));
305 res!(s.finish());
306 let State { engine, sink, fully_inline, pars, .. } = s;
307 if !fragment || fully_inline || pars != 1 {
308 return Ok((sink, fully_inline));
309 }
310 // A fragment whose one paragraph was closed by styles around it (`set par(..)`, `set align(..)`) is still a
311 // paragraph's worth of inline content, with no `par` of its own: Typst sets it as such, with no first-line indent.
312 let members: Vec<usize> = (0..sink.len()).filter(|i| !sink[*i].is_tag()).collect();
313 let at = match members.as_slice() {
314 [i] if sink[*i].content.is(ElemKind::Par) => *i,
315 _ => return Ok((sink, false)),
316 };
317 let body = match sink[at].content.kind().and_then(|k| k.field_id("body")).and_then(|id| sink[at].content.get(id)) {
318 Some(Value::Content(c)) => c.clone(),
319 _ => return Ok((sink, false)),
320 };
321 let (inner, _) = res!(realise_with(engine, &body, &sink[at].styles, RealiseMode::Inline, keep_model, false));
322 let mut inner = Some(inner);
323 let mut out = Vec::new();
324 for (i, pair) in sink.into_iter().enumerate() {
325 match inner.take() {
326 Some(run) if i == at => out.extend(run),
327 other => {
328 inner = other;
329 out.push(pair);
330 }
331 }
332 }
333 Ok((out, true))
334 })
335}
336
337// Gives the timing record the realise call about to be made: its mode and what the content is, and the
338// key of where it is realised, which tells a body met again from one met for the first time.
339fn note_call(engine: &mut Engine, content: &Content, mode: RealiseMode) {
340 let place = engine.locator.place().0;
341 if let Some(t) = engine.timings.as_mut() {
342 let m = match mode {
343 RealiseMode::Document => "doc",
344 RealiseMode::Flow => "flow",
345 RealiseMode::Inline => "inline",
346 RealiseMode::Math => "math",
347 };
348 let shape = shape_of(content, 0);
349 let span = content.span();
350 let key = Timings::key(&(m, place, span.file.0 as u64, span.start, span.end, &shape));
351 t.note_call(fmt!("{}/{}", m, shape), key);
352 }
353}
354
355// What the content is, for the record: an element's kind, or the kind of the first element of a sequence
356// or a styled run, as far as three levels in.
357fn shape_of(c: &Content, depth: usize) -> String {
358 match c {
359 Content::Elem(e) => e.kind.path().to_string(),
360 Content::Sequence(s) => match s.children.iter().find(|k| !k.is(ElemKind::Space)) {
361 None => "empty".to_string(),
362 Some(first) if depth < 3 => fmt!("seq>{}", shape_of(first, depth + 1)),
363 Some(_) => "seq".to_string(),
364 },
365 Content::Styled(s) => if depth < 3 { fmt!("styled>{}", shape_of(&s.child, depth + 1)) } else { "styled".to_string() },
366 }
367}
368
369/// Is the element set inline, within a paragraph, rather than as a block of its own?
370pub fn is_inline(content: &Content) -> bool {
371 Rule::Par.trigger(content, false)
372}
373
374// Grouping rules
375
376#[derive(Clone, Copy, Debug, PartialEq, Eq)]
377enum Rule {
378 Textual,
379 Par,
380 Cites,
381 List,
382 Enum,
383 Terms,
384}
385
386impl Rule {
387 fn priority(self) -> u8 {
388 match self {
389 Rule::Textual => 3,
390 Rule::Cites | Rule::List | Rule::Enum | Rule::Terms => 2,
391 Rule::Par => 1,
392 }
393 }
394
395 /// Does the element open (or continue) such a group? When the model stands unexpanded (`keep`), strong
396 /// text, emphasis and a link are phrasing content, as Typst's HTML export groups them, so they stay
397 /// in their paragraph instead of ending it.
398 fn trigger(self, c: &Content, keep: bool) -> bool {
399 let k = match c.kind() {
400 Some(k) => k,
401 None => return false,
402 };
403 match self {
404 Rule::Textual => matches!(k, ElemKind::Text | ElemKind::Linebreak | ElemKind::SmartQuote),
405 Rule::Par => match k {
406 ElemKind::Text | ElemKind::H | ElemKind::Linebreak | ElemKind::SmartQuote
407 | ElemKind::Box => true,
408 ElemKind::Strong | ElemKind::Emph | ElemKind::Link => keep,
409 // An inline equation; a block one is `block: true`.
410 ElemKind::Equation => !matches!(c.field("block"), Some(Value::Bool(true))),
411 _ => false,
412 },
413 Rule::Cites => k == ElemKind::Cite,
414 Rule::List => k == ElemKind::ListItem,
415 Rule::Enum => k == ElemKind::EnumItem,
416 Rule::Terms => k == ElemKind::TermItem,
417 }
418 }
419
420 /// May a group of this rule open inside the active group of `outer`? A textual run opens in a paragraph
421 /// group. Opened inside a list, enum, terms or cite group, which cannot hold text, it would stay in that
422 /// group and be dropped when the next item joined it and the group was built, so there the text ends the
423 /// group instead.
424 fn nests_in(self, outer: Rule) -> bool {
425 !(self == Rule::Textual && matches!(outer, Rule::Cites | Rule::List | Rule::Enum | Rule::Terms))
426 }
427
428 /// May the element sit inside such a group without opening one?
429 fn inner(self, c: &Content) -> bool {
430 match self {
431 Rule::Textual | Rule::Par | Rule::Cites => c.is(ElemKind::Space),
432 Rule::List | Rule::Enum | Rule::Terms => c.is(ElemKind::Space) || c.is(ElemKind::Parbreak),
433 }
434 }
435
436 /// Do styles on this element end such a group?
437 fn interrupted_by(self, k: ElemKind) -> bool {
438 match self {
439 Rule::Textual => true,
440 Rule::Par => matches!(k, ElemKind::Par | ElemKind::Align),
441 Rule::Cites => matches!(k, ElemKind::CiteGroup | ElemKind::Cite),
442 Rule::List => matches!(k, ElemKind::List | ElemKind::Align),
443 Rule::Enum => matches!(k, ElemKind::Enum | ElemKind::Align),
444 Rule::Terms => matches!(k, ElemKind::Terms | ElemKind::Align),
445 }
446 }
447}
448
449const LAYOUT_RULES: &[Rule] = &[Rule::Textual, Rule::Par, Rule::Cites, Rule::List, Rule::Enum, Rule::Terms];
450const PAR_RULES: &[Rule] = &[Rule::Textual, Rule::Cites, Rule::List, Rule::Enum, Rule::Terms];
451const MATH_RULES: &[Rule] = &[Rule::Cites, Rule::List, Rule::Enum, Rule::Terms];
452
453#[derive(Clone, Copy, Debug)]
454struct Grouping {
455 start: usize,
456 rule: Rule,
457}
458
459#[derive(Clone, Copy, Debug, PartialEq, Eq)]
460enum SpaceState {
461 Destructive, // a space here would be dropped: start, after a break
462 Supportive, // after content a space may follow
463 Space(usize), // a space was kept, at this index
464}
465
466/// The show step a verdict chose.
467enum Step {
468 Recipe(Arc<Recipe>, RecipeIndex),
469 Builtin,
470}
471
472struct RegexMatch {
473 offset: usize,
474 text: String,
475 index: RecipeIndex,
476 recipe: Arc<Recipe>,
477 styles: StyleChain,
478}
479
480struct State<'e> {
481 engine: &'e mut Engine,
482 mode: RealiseMode,
483 keep_model: bool, // model elements stand unexpanded (`realise_structure`)
484 sink: Vec<Pair>,
485 groupings: Vec<Grouping>,
486 outside: bool, // at the document's top level, not inside a container or show-rule output
487 may_attach: bool, // the last block was a paragraph, so `v(attach: true)` survives
488 saw_parbreak: bool,
489 fully_inline: bool, // the whole body is one paragraph's worth of inline elements (`Flow` mode)
490 pars: usize, // paragraphs the grouping has made
491}
492
493impl State<'_> {
494 fn rules(&self) -> &'static [Rule] {
495 match self.mode {
496 RealiseMode::Document | RealiseMode::Flow => LAYOUT_RULES,
497 RealiseMode::Inline => PAR_RULES,
498 RealiseMode::Math => MATH_RULES,
499 }
500 }
501
502 fn visit(&mut self, content: &Content, styles: &StyleChain) -> Outcome<()> {
503 self.engine.bump(Counter::Visits, 1);
504 // A tag carried in content (a paragraph's body) goes back into the stream where it stands.
505 if let Some(tag) = Tag::from_content(content) {
506 self.push_tag(tag, styles);
507 return Ok(());
508 }
509 if res!(self.visit_kind_rules(content, styles)) {
510 return Ok(());
511 }
512 if res!(self.visit_show_rules(content, styles)) {
513 return Ok(());
514 }
515 match content {
516 Content::Sequence(seq) => {
517 for c in &seq.children {
518 res!(self.visit(c, styles));
519 }
520 Ok(())
521 }
522 Content::Styled(st) => self.visit_styled(&st.child, &st.styles, styles, false),
523 Content::Elem(_) => self.leaf(content, styles),
524 }
525 }
526
527 /// An element no rule transforms further: grouped, filtered or pushed.
528 fn leaf(&mut self, content: &Content, styles: &StyleChain) -> Outcome<()> {
529 self.engine.bump(Counter::Leaves, 1);
530 if res!(self.visit_grouping_rules(content, styles)) {
531 return Ok(());
532 }
533 if res!(self.visit_filter_rules(content, styles)) {
534 return Ok(());
535 }
536 self.sink.push(Pair::new(content.clone(), styles.clone()));
537 Ok(())
538 }
539
540 fn push_tag(&mut self, tag: Tag, styles: &StyleChain) {
541 self.sink.push(Pair::tag(tag, styles.clone()));
542 }
543
544 // Kind rules
545
546 fn visit_kind_rules(&mut self, content: &Content, styles: &StyleChain) -> Outcome<bool> {
547 let kind = match content.kind() {
548 Some(k) => k,
549 None => return Ok(false),
550 };
551 if self.mode == RealiseMode::Math {
552 // An equation nested in maths is transparent: `#let x = $pi$; $ x $`.
553 if kind == ElemKind::Equation {
554 if let Some(Value::Content(body)) = content.field("body") {
555 let body = body.clone();
556 res!(self.visit(&body, styles));
557 return Ok(true);
558 }
559 }
560 // A maths character is a symbol and a number is text; rules run on each element alone here,
561 // not over a textual run.
562 if kind == ElemKind::Text || kind == ElemKind::Symbol {
563 if let Some(Value::Str(t)) = content.get(FieldId(0)) {
564 let t = t.clone();
565 if let Some(m) = res!(self.engine.timed(Phase::Regex, |_| find_regex_match_in_str(&t, styles))) {
566 let pair = Pair::new(content.clone(), styles.clone());
567 res!(self.visit_regex_match(vec![pair], m));
568 return Ok(true);
569 }
570 }
571 }
572 return Ok(false);
573 }
574 // Maths content outside an equation is wrapped in one.
575 if kind.family() == Family::Math && kind != ElemKind::Equation {
576 if let Some(id) = ElemKind::Equation.field_id("body") {
577 let eq = Content::new(ElemKind::Equation, vec![(id, Value::Content(content.clone()))], content.span());
578 res!(self.visit(&eq, styles));
579 return Ok(true);
580 }
581 }
582 // A symbol outside maths is text, as Typst makes it before any show rule or grouping runs. A
583 // shorthand (`--`, `...`, `~`, `-?`), an escape and a symbol value all arrive here, so they join
584 // the paragraph and the textual run they stand in, and text and regex rules reach them.
585 if kind == ElemKind::Symbol {
586 if let Some(Value::Str(t)) = content.get(FieldId(0)) {
587 let mut text = Content::text(t).with_span(content.span());
588 if let Some(label) = content.label() {
589 text = text.labelled(label.clone());
590 }
591 res!(self.visit(&text, styles));
592 return Ok(true);
593 }
594 }
595 Ok(false)
596 }
597
598 // Show rules
599
600 fn visit_show_rules(&mut self, content: &Content, styles: &StyleChain) -> Outcome<bool> {
601 match content {
602 Content::Elem(_) => self.show_elem(content, styles),
603 Content::Sequence(seq) if seq.label.is_some() => self.show_labelled(content, styles),
604 _ => Ok(false),
605 }
606 }
607
608 fn show_elem(&mut self, target: &Content, styles: &StyleChain) -> Outcome<bool> {
609 let (prepared, guards) = match target {
610 Content::Elem(e) => (e.prepared, e.guards.clone()),
611 _ => return Ok(false),
612 };
613 // The verdict: the innermost unguarded matching recipe is the step; show-set rules are collected
614 // (all of them, until the element is prepared, whichever side of the step they sit).
615 let recipes = self.engine.timed(Phase::Styles, |_| styles.recipes());
616 self.engine.bump(Counter::Shown, 1);
617 self.engine.bump(Counter::Recipes, recipes.len() as u64);
618 let (mut map, step) = res!(self.engine.timed(Phase::Show, |engine| -> Outcome<(Styles, Option<Step>)> {
619 let mut map = Styles::new();
620 let mut step = None;
621 let mut tried = 0;
622 for slot in recipes {
623 tried += 1;
624 if !res!(slot.recipe.applicable(target, styles)) {
625 continue;
626 }
627 if let Transformation::Style(set) = &slot.recipe.transform {
628 if !prepared {
629 map.apply_outer(set);
630 }
631 continue;
632 }
633 if step.is_some() || guards.contains(&slot.index) {
634 continue;
635 }
636 step = Some(Step::Recipe(slot.recipe.clone(), slot.index));
637 if prepared {
638 break;
639 }
640 }
641 engine.bump(Counter::Matched, tried);
642 Ok((map, step))
643 }));
644 let step = step.unwrap_or(Step::Builtin);
645 let mut output = target.clone();
646 let mut tags = None;
647 if !prepared {
648 self.engine.bump(Counter::Prepared, 1);
649 tags = res!(self.engine.timed(Phase::Show, |engine| prepare(engine, &mut output, &mut map, styles)));
650 }
651 let chained = styles.chain(&map);
652 // A show rule's error does not end the compile here: the element shows as nothing and the error
653 // stands for the final pass to report (Typst's `Engine::delay`).
654 let mark = self.engine.diags.len();
655 let result = match step {
656 Step::Recipe(recipe, index) => {
657 if let Content::Elem(e) = &mut output {
658 if e.is_shared() {
659 self.engine.bump(Counter::Copied, 1);
660 }
661 e.edit().guards.push(index);
662 }
663 let shown = self.engine.timed(Phase::Show, |engine| apply_recipe(engine, &recipe, output.clone(), &chained));
664 self.engine.delay(mark, target.span(), shown)
665 }
666 Step::Builtin => match self.builtin_show(&output, &chained) {
667 Ok(Some(c)) => spanned(c, output.span()),
668 Err(e) => {
669 let shown = self.engine.delay(mark, target.span(), Err::<Content, _>(e));
670 spanned(shown, output.span())
671 },
672 Ok(None) => {
673 // A primitive: flow lays it out itself. Typst shows it as a block with a layout routine,
674 // which counts toward the show-rule depth where it is realised.
675 let shows = shows_of(output.kind());
676 if shows > 0 {
677 res!(self.check_depth(output.span(), shows));
678 }
679 if let Some((start, _)) = &tags {
680 self.push_tag(start.clone(), styles);
681 }
682 res!(self.visit_styled(&output, &map, styles, true));
683 if let Some((_, end)) = tags {
684 self.push_tag(end, styles);
685 }
686 return Ok(true);
687 }
688 },
689 };
690 if let Some((start, _)) = &tags {
691 self.push_tag(start.clone(), styles);
692 }
693 res!(self.visit_output(target, &result, &map, styles));
694 if let Some((_, end)) = tags {
695 self.push_tag(end, styles);
696 }
697 Ok(true)
698 }
699
700 // The element's built-in show, or `None` for a primitive -- and for a model element when the
701 // structure is being kept.
702 fn builtin_show(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<Option<Content>> {
703 if self.keep_model && elem.kind().map(|k| k.family() == Family::Model).unwrap_or(false) {
704 return Ok(None);
705 }
706 self.engine.timed(Phase::Show, |engine| native_show(engine, elem, styles))
707 }
708
709 /// A labelled sequence meets label rules too, and is located and guarded as an element is: its
710 /// location is assigned once, and a recipe applied to it is not applied to its output again.
711 fn show_labelled(&mut self, target: &Content, styles: &StyleChain) -> Outcome<bool> {
712 let (prepared, guards) = match target {
713 Content::Sequence(seq) => (seq.location.is_some(), seq.guards.clone()),
714 _ => return Ok(false),
715 };
716 let recipes = self.engine.timed(Phase::Styles, |_| styles.recipes());
717 self.engine.bump(Counter::Shown, 1);
718 self.engine.bump(Counter::Recipes, recipes.len() as u64);
719 let (map, step) = res!(self.engine.timed(Phase::Show, |engine| -> Outcome<(Styles, Option<(Arc<Recipe>, RecipeIndex)>)> {
720 let mut map = Styles::new();
721 let mut step = None;
722 let mut tried = 0;
723 for slot in recipes {
724 tried += 1;
725 if !res!(slot.recipe.applicable(target, styles)) {
726 continue;
727 }
728 if let Transformation::Style(set) = &slot.recipe.transform {
729 if !prepared {
730 map.apply_outer(set);
731 }
732 continue;
733 }
734 if step.is_some() || guards.contains(&slot.index) {
735 continue;
736 }
737 step = Some((slot.recipe.clone(), slot.index));
738 if prepared {
739 break;
740 }
741 }
742 engine.bump(Counter::Matched, tried);
743 Ok((map, step))
744 }));
745 if prepared && step.is_none() {
746 return Ok(false);
747 }
748 let mut output = target.clone();
749 let mut tags = None;
750 // The fingerprint is read before `edit` forgets the cell, and only for a sequence yet to be located.
751 let fp = match &output {
752 Content::Sequence(seq) if seq.location.is_none() => Some(output.fingerprint()),
753 _ => None,
754 };
755 if let Content::Sequence(seq) = &mut output {
756 let seq = seq.edit();
757 if let (None, Some(fp)) = (seq.location, fp) {
758 let loc = self.engine.locator.locate(ElemKind::Sequence, fp);
759 seq.location = Some(loc);
760 tags = Some(loc);
761 }
762 if let Some((_, index)) = &step {
763 seq.guards.push(*index);
764 }
765 }
766 if tags.is_some() {
767 self.push_tag(Tag::Start(output.clone()), styles);
768 }
769 match step {
770 Some((recipe, _)) => {
771 let chained = styles.chain(&map);
772 let mark = self.engine.diags.len();
773 let shown = self.engine.timed(Phase::Show, |engine| apply_recipe(engine, &recipe, output.clone(), &chained));
774 let result = self.engine.delay(mark, target.span(), shown);
775 res!(self.visit_output(target, &result, &map, styles));
776 }
777 // No recipe: the located sequence itself, which the next visit walks into at this level,
778 // so page rules inside it still reach the page.
779 None => res!(self.visit_styled(&output, &map, styles, false)),
780 }
781 if let Some(loc) = tags {
782 self.push_tag(Tag::End(loc), styles);
783 }
784 Ok(true)
785 }
786
787 /// Visits a show rule's output under the collected show-set styles, one level deeper.
788 fn visit_output(&mut self, target: &Content, output: &Content, map: &Styles, styles: &StyleChain) -> Outcome<()> {
789 res!(self.check_depth(target.span(), 1));
790 self.engine.route += 1;
791 let prev_outside = self.outside;
792 self.outside &= target.is(ElemKind::Context);
793 let r = self.visit_styled(output, map, styles, false);
794 self.outside = prev_outside;
795 self.engine.route -= 1;
796 r
797 }
798
799 /// Typst's show-rule depth limit. The layers and show rules already entered, and `shows` more, must not pass
800 /// it: an element that Typst shows as a layout routine counts the shows it takes, though its body is laid out
801 /// later and no output is visited here.
802 fn check_depth(&mut self, span: Span, shows: usize) -> Outcome<()> {
803 if self.engine.route + shows > MAX_SHOW_RULE_DEPTH {
804 return Err(error_hints(self.engine, DiagnosticKind::Limit, span, "maximum show rule depth exceeded", &[
805 "maybe a show rule matches its own output",
806 "maybe there are too deeply nested elements",
807 ]));
808 }
809 Ok(())
810 }
811
812 // Styled content
813
814 /// Visits `child` under `local` styles pushed onto `outer`. `leaf` pushes the child without another
815 /// round of rules (it is a prepared primitive).
816 fn visit_styled(&mut self, child: &Content, local: &Styles, outer: &StyleChain, leaf: bool) -> Outcome<()> {
817 if local.is_empty() {
818 return if leaf { self.leaf(child, outer) } else { self.visit(child, outer) };
819 }
820 // `show: f` transforms the rest of its scope at once, the styles before it staying outside.
821 if let Some(i) = local.iter().position(|s| matches!(s, Style::Recipe(r) if r.selector.is_none())) {
822 let before = Styles::from_vec(local.as_slice()[..i].to_vec());
823 let after = Styles::from_vec(local.as_slice()[i + 1..].to_vec());
824 let recipe = match &local.as_slice()[i] {
825 Style::Recipe(r) => r.clone(),
826 _ => return Err(err!("selector-less recipe vanished"; Bug)),
827 };
828 let chain = outer.chain(&before);
829 let out = res!(self.engine.timed(Phase::Show, |engine| apply_recipe(engine, &recipe, child.clone().styled(after), &chain)));
830 return self.visit_styled(&out, &before, outer, false);
831 }
832 let mut pagebreak = false;
833 for style in local.iter() {
834 let p = match style {
835 Style::Property(p) => p,
836 _ => continue,
837 };
838 match p.elem {
839 ElemKind::Document if self.mode != RealiseMode::Document => {
840 return Err(self.engine.error(DiagnosticKind::Type, p.span, "document set rules are not allowed inside of containers"));
841 }
842 ElemKind::Page if self.mode != RealiseMode::Document => {
843 return Err(self.engine.error(DiagnosticKind::Type, p.span, "page configuration is not allowed inside of containers"));
844 }
845 ElemKind::Page => {
846 // Page styles break free of the show-rule cage.
847 pagebreak = true;
848 self.outside = true;
849 }
850 _ => (),
851 }
852 }
853 // Outside a container or show rule's output, the styles may be lifted to the page level.
854 let marked;
855 let local = if self.outside {
856 marked = local.outside();
857 &marked
858 } else {
859 local
860 };
861 if pagebreak {
862 // The leading break takes the styles up to and including the last page property only.
863 let last = local.as_slice().iter().rposition(|s| matches!(s, Style::Property(p) if p.elem == ElemKind::Page));
864 let relevant = match last {
865 Some(l) => Styles::from_vec(local.as_slice()[..=l].to_vec()),
866 None => local.clone(),
867 };
868 res!(self.visit(&weak_pagebreak(false), &outer.chain(&relevant)));
869 }
870 res!(self.finish_interrupted(local));
871 let chain = outer.chain(local);
872 res!(if leaf { self.leaf(child, &chain) } else { self.visit(child, &chain) });
873 res!(self.finish_interrupted(local));
874 if pagebreak {
875 res!(self.visit(&weak_pagebreak(true), outer));
876 }
877 Ok(())
878 }
879
880 /// Ends every group that the styled elements interrupt, innermost first, as long as one is. Finishing
881 /// a textual run opens the paragraph it belongs to, which no style on a text interrupts, so the
882 /// paragraph stays open across a styled run inside it.
883 fn finish_interrupted(&mut self, local: &Styles) -> Outcome<()> {
884 let mut last = None;
885 for elem in local.iter().filter_map(|s| s.element()) {
886 if last == Some(elem) {
887 continue;
888 }
889 let mut i = 0;
890 while self.groupings.iter().any(|g| g.rule.interrupted_by(elem)) {
891 res!(self.finish_innermost_grouping());
892 i += 1;
893 if i > MAX_GROUPING_STEPS {
894 return Err(self.engine.error(DiagnosticKind::Limit, Span::detached(), "maximum grouping depth exceeded"));
895 }
896 }
897 last = Some(elem);
898 }
899 Ok(())
900 }
901
902 // Grouping
903
904 fn visit_grouping_rules(&mut self, content: &Content, styles: &StyleChain) -> Outcome<bool> {
905 let keep = self.keep_model;
906 let rules = self.rules();
907 let matching = self.engine.timed(Phase::Rules, |_| rules.iter().copied().find(|r| r.trigger(content, keep)));
908 let mut i = 0;
909 while let Some(active) = self.groupings.last().copied() {
910 // A rule of higher priority nests a new group inside the active one.
911 let (nests, joins) = self.engine.timed(Phase::Rules, |_| {
912 let nests = matching.map(|r| r.priority() > active.rule.priority() && r.nests_in(active.rule)).unwrap_or(false);
913 (nests, !nests && (active.rule.trigger(content, keep) || active.rule.inner(content)))
914 });
915 if nests {
916 break;
917 }
918 if joins {
919 self.sink.push(Pair::new(content.clone(), styles.clone()));
920 return Ok(true);
921 }
922 res!(self.finish_innermost_grouping());
923 i += 1;
924 if i > MAX_GROUPING_STEPS {
925 return Err(self.engine.error(DiagnosticKind::Limit, content.span(), "maximum grouping depth exceeded"));
926 }
927 }
928 if let Some(rule) = matching {
929 self.groupings.push(Grouping { start: self.sink.len(), rule });
930 self.sink.push(Pair::new(content.clone(), styles.clone()));
931 return Ok(true);
932 }
933 Ok(false)
934 }
935
936 /// Spaces and paragraph breaks left outside every group mean nothing to block flow; attached spacing
937 /// survives only straight after a paragraph.
938 fn visit_filter_rules(&mut self, content: &Content, styles: &StyleChain) -> Outcome<bool> {
939 if matches!(self.mode, RealiseMode::Inline | RealiseMode::Math) {
940 return Ok(false);
941 }
942 if content.is(ElemKind::Space) {
943 return Ok(true);
944 }
945 if content.is(ElemKind::Parbreak) {
946 self.may_attach = false;
947 self.saw_parbreak = true;
948 return Ok(true);
949 }
950 if !self.may_attach && content.is(ElemKind::V) {
951 let attach = match ElemKind::V.field_id("attach") {
952 Some(id) => res!(styles.resolve(content, id)),
953 None => None,
954 };
955 if matches!(attach, Some(Value::Bool(true))) {
956 return Ok(true);
957 }
958 }
959 self.may_attach = content.is(ElemKind::Par);
960 Ok(false)
961 }
962
963 fn finish(&mut self) -> Outcome<()> {
964 let mut i = 0;
965 let mut inline = false;
966 while !self.groupings.is_empty() {
967 if self.is_fully_inline() {
968 inline = true;
969 self.fully_inline = true;
970 break;
971 }
972 res!(self.finish_innermost_grouping());
973 i += 1;
974 if i > MAX_GROUPING_STEPS {
975 return Err(self.engine.error(DiagnosticKind::Limit, Span::detached(), "maximum grouping depth exceeded"));
976 }
977 }
978 if inline || matches!(self.mode, RealiseMode::Inline | RealiseMode::Math) {
979 res!(self.engine.timed(Phase::Repack, |_| collapse_spaces(&mut self.sink, 0)));
980 }
981 Ok(())
982 }
983
984 /// A fragment whose whole content is one paragraph's worth of inline elements.
985 fn is_fully_inline(&self) -> bool {
986 self.mode == RealiseMode::Flow
987 && !self.saw_parbreak
988 && matches!(self.groupings.as_slice(), [g] if g.start == 0 && g.rule == Rule::Par)
989 }
990
991 fn finish_innermost_grouping(&mut self) -> Outcome<()> {
992 let g = match self.groupings.pop() {
993 Some(g) => g,
994 None => return Ok(()),
995 };
996 self.engine.bump(Counter::Finished, 1);
997 // Trailing members that did not trigger the group are not part of it.
998 let end = match self.sink[g.start..].iter().rposition(|p| !p.is_tag() && g.rule.trigger(&p.content, self.keep_model)) {
999 Some(i) => g.start + i + 1,
1000 None => g.start,
1001 };
1002 let tail = self.sink.split_off(end);
1003 match g.rule {
1004 Rule::Textual => res!(self.finish_textual(g.start)),
1005 Rule::Par => res!(self.finish_par(g.start)),
1006 Rule::Cites => res!(self.finish_cites(g.start)),
1007 Rule::List | Rule::Enum | Rule::Terms => res!(self.finish_list(g.start, g.rule)),
1008 }
1009 for p in tail {
1010 match p.tag {
1011 Some(t) => self.sink.push(Pair::tag(t, p.styles)),
1012 None => res!(self.visit(&p.content, &p.styles)),
1013 }
1014 }
1015 Ok(())
1016 }
1017
1018 fn finish_textual(&mut self, start: usize) -> Outcome<()> {
1019 self.engine.bump(Counter::Textual, 1);
1020 let run = &self.sink[start..];
1021 if let Some(m) = res!(self.engine.timed(Phase::Regex, |_| find_regex_match_in_elems(run))) {
1022 res!(self.engine.timed(Phase::Repack, |_| collapse_spaces(&mut self.sink, start)));
1023 let elems = self.sink.split_off(start);
1024 return self.visit_regex_match(elems, m);
1025 }
1026 // No match: the run is a paragraph's to group, when this realisation groups paragraphs.
1027 if self.groupings.is_empty() && self.rules().contains(&Rule::Par) {
1028 self.groupings.push(Grouping { start, rule: Rule::Par });
1029 }
1030 Ok(())
1031 }
1032
1033 /// Splits the run around the match and puts the recipe's output in its place, under a revocation of
1034 /// the recipe so it cannot match its own output.
1035 fn visit_regex_match(&mut self, elems: Vec<Pair>, m: RegexMatch) -> Outcome<()> {
1036 let (ms, me) = (m.offset, m.offset + m.text.len());
1037 let span = elems.iter().map(|p| p.content.span()).find(|s| !s.is_detached()).unwrap_or(Span::detached());
1038 let piece = Content::text(&m.text).with_span(span);
1039 let output = res!(self.engine.timed(Phase::Show, |engine| apply_recipe(engine, &m.recipe, piece, &m.styles)));
1040 let mut pending = Some(output);
1041 let revoked = m.styles.chain(&Styles::from_style(Style::Revocation(m.index)));
1042 let mut cursor = 0;
1043 for p in elems {
1044 if let Some(t) = p.tag {
1045 self.sink.push(Pair::tag(t, p.styles));
1046 continue;
1047 }
1048 let text = match (p.content.kind(), p.content.get(FieldId(0))) {
1049 (Some(ElemKind::Text | ElemKind::Symbol), Some(Value::Str(t))) => Some(t.clone()),
1050 _ => None,
1051 };
1052 let len = text.as_ref().map(|t| t.len()).unwrap_or(1);
1053 let (es, ee) = (cursor, cursor + len);
1054 if es < ms {
1055 if ee <= ms {
1056 res!(self.visit(&p.content, &p.styles));
1057 } else if let Some(t) = &text {
1058 let piece = slice_text(&p.content, t, 0, ms - es);
1059 res!(self.visit(&piece, &p.styles));
1060 }
1061 }
1062 if ms < ee {
1063 if let Some(out) = pending.take() {
1064 res!(self.visit(&out, &revoked));
1065 }
1066 }
1067 if ee > me {
1068 if es >= me {
1069 res!(self.visit(&p.content, &p.styles));
1070 } else if let Some(t) = &text {
1071 let piece = slice_text(&p.content, t, me - es, t.len());
1072 res!(self.visit(&piece, &p.styles));
1073 }
1074 }
1075 cursor = ee;
1076 }
1077 if let Some(out) = pending.take() {
1078 res!(self.visit(&out, &revoked));
1079 }
1080 Ok(())
1081 }
1082
1083 /// A paragraph keeps the tags that fall inside it in its body, as `tag` elements, so a located
1084 /// element in running text is found where it is set.
1085 fn finish_par(&mut self, start: usize) -> Outcome<()> {
1086 res!(self.engine.timed(Phase::Repack, |_| collapse_spaces(&mut self.sink, start)));
1087 let elems = self.sink.split_off(start);
1088 let span = select_span(&elems);
1089 let (body, trunk) = self.engine.timed(Phase::Repack, |_| repack(&elems));
1090 let id = res!(field(ElemKind::Par, "body"));
1091 self.pars += 1;
1092 let par = Content::new(ElemKind::Par, vec![(id, Value::Content(body))], span);
1093 self.visit(&par, &trunk)
1094 }
1095
1096 /// Adjacent citations, with only spaces between them, become one cite group.
1097 fn finish_cites(&mut self, start: usize) -> Outcome<()> {
1098 let elems = self.sink.split_off(start);
1099 let (cites, rest): (Vec<Pair>, Vec<Pair>) = elems.into_iter().partition(|p| p.content.is(ElemKind::Cite));
1100 let tags: Vec<Pair> = rest.into_iter().filter(|p| p.is_tag()).collect();
1101 let span = select_span(&cites);
1102 let trunk = StyleChain::trunk(cites.iter().map(|p| &p.styles));
1103 let children = cites.iter().map(|p| Value::Content(p.content.clone())).collect();
1104 let id = res!(field(ElemKind::CiteGroup, "children"));
1105 let group = Content::new(ElemKind::CiteGroup, vec![(id, Value::array(children))], span);
1106 self.around_tags(tags, |s| s.visit(&group, &trunk))
1107 }
1108
1109 fn finish_list(&mut self, start: usize, rule: Rule) -> Outcome<()> {
1110 let (kind, item_kind) = match rule {
1111 Rule::List => (ElemKind::List, ElemKind::ListItem),
1112 Rule::Enum => (ElemKind::Enum, ElemKind::EnumItem),
1113 _ => (ElemKind::Terms, ElemKind::TermItem),
1114 };
1115 let elems = self.sink.split_off(start);
1116 let tight = !elems.iter().any(|p| p.content.is(ElemKind::Parbreak));
1117 let (items, rest): (Vec<Pair>, Vec<Pair>) = elems.into_iter().partition(|p| p.content.is(item_kind));
1118 let tags: Vec<Pair> = rest.into_iter().filter(|p| p.is_tag()).collect();
1119 let span = select_span(&items);
1120 let trunk = StyleChain::trunk(items.iter().map(|p| &p.styles));
1121 let depth = trunk.depth();
1122 let bodies: &[&str] = match item_kind {
1123 ElemKind::TermItem => &["term", "description"],
1124 _ => &["body"],
1125 };
1126 let mut children = Vec::new();
1127 for p in &items {
1128 let local = p.styles.suffix(depth);
1129 let mut item = p.content.clone();
1130 if !local.is_empty() {
1131 for name in bodies {
1132 if let Some(id) = item_kind.field_id(name) {
1133 if let Some(Value::Content(b)) = item.get(id) {
1134 let b = b.clone().styled(local.clone());
1135 item.set(id, Value::Content(b));
1136 }
1137 }
1138 }
1139 }
1140 children.push(Value::Content(item));
1141 }
1142 let mut fields = vec![(res!(field(kind, "children")), Value::array(children))];
1143 if let Some(id) = kind.field_id("tight") {
1144 fields.push((id, Value::Bool(tight)));
1145 }
1146 let list = Content::new(kind, fields, span);
1147 self.around_tags(tags, |s| s.visit(&list, &trunk))
1148 }
1149
1150 /// Tags lifted out of a group: starts before the group's element, ends after it.
1151 fn around_tags<F: FnOnce(&mut Self) -> Outcome<()>>(&mut self, tags: Vec<Pair>, f: F) -> Outcome<()> {
1152 let (starts, ends): (Vec<Pair>, Vec<Pair>) = tags.into_iter()
1153 .partition(|p| matches!(p.tag, Some(Tag::Start(_))));
1154 self.sink.extend(starts);
1155 res!(f(self));
1156 self.sink.extend(ends);
1157 Ok(())
1158 }
1159}
1160
1161fn wants_location(e: &Elem) -> bool { e.location.is_none() && (e.kind.locatable() || e.label.is_some()) }
1162
1163fn wants_place(e: &Elem) -> bool { e.place.is_none() && e.kind.has_place() }
1164
1165/// Gives the element its location (when locatable or labelled) and copies the style chain's values
1166/// of its unset settable fields into it, so a show rule sees them; returns its tags when located.
1167fn prepare(engine: &mut Engine, target: &mut Content, map: &mut Styles, styles: &StyleChain) -> Outcome<Option<(Tag, Tag)>> {
1168 // Built-in show-set styles sit outside the user's, which override them.
1169 let builtin = res!(content::show_set(target, styles));
1170 // A location is keyed by the content's fingerprint, read before `edit` forgets the cell and only when one is
1171 // wanted. A place is keyed by the element's shell, never by what it holds.
1172 let key = match &*target {
1173 Content::Elem(e) if wants_location(e) => Some(target.fingerprint()),
1174 _ => None,
1175 };
1176 let e = match target {
1177 Content::Elem(e) => {
1178 if e.is_shared() {
1179 engine.bump(Counter::Copied, 1);
1180 }
1181 e.edit()
1182 },
1183 _ => return Ok(None),
1184 };
1185 if let Some(key) = key {
1186 e.location = Some(engine.locator.locate(e.kind, key));
1187 }
1188 // An element that lays a body out keeps one place for it however often it is laid out, and however its
1189 // body is edited. One a layouter made and gave a place already (a grid's cell) keeps that.
1190 if wants_place(e) {
1191 e.place = Some(engine.locator.next(e.kind, fp::elem_shell_fp(e)));
1192 }
1193 map.apply_outer(&builtin);
1194 let chain = styles.chain(map);
1195 res!(engine.timed(Phase::Styles, |_| -> Outcome<()> {
1196 for (i, spec) in e.kind.fields().iter().enumerate() {
1197 let id = FieldId(i as u8);
1198 if !spec.settable || e.fields.iter().any(|(f, _)| *f == id) {
1199 continue;
1200 }
1201 if let Some(v) = res!(chain.get(e.kind, id)) {
1202 e.fields.push((id, v));
1203 }
1204 }
1205 Ok(())
1206 }));
1207 res!(content::synthesise(engine, target, &chain));
1208 let loc = match target {
1209 Content::Elem(e) => {
1210 let e = e.edit();
1211 e.prepared = true;
1212 e.location
1213 }
1214 _ => None,
1215 };
1216 Ok(loc.map(|l| (Tag::Start(target.clone()), Tag::End(l))))
1217}
1218
1219/// A schema field the grouping must fill; its absence is the owning unit's gap, reported as such.
1220fn field(kind: ElemKind, name: &str) -> Outcome<FieldId> {
1221 match kind.field_id(name) {
1222 Some(id) => Ok(id),
1223 None => Err(err!("{} has no `{}` field in its schema, so realisation cannot group into it",
1224 kind.path(), name; Unimplemented)),
1225 }
1226}
1227
1228/// A weak page break, as page styles in the document's flow produce around themselves; `boundary`
1229/// marks the one after, whose styles take precedence.
1230fn weak_pagebreak(boundary: bool) -> Content {
1231 let mut fields = Vec::new();
1232 if let Some(id) = ElemKind::Pagebreak.field_id("weak") {
1233 fields.push((id, Value::Bool(true)));
1234 }
1235 if boundary {
1236 if let Some(id) = ElemKind::Pagebreak.field_id("boundary") {
1237 fields.push((id, Value::Bool(true)));
1238 }
1239 }
1240 Content::new(ElemKind::Pagebreak, fields, Span::detached())
1241}
1242
1243/// A native show's output takes the element's span where it has none of its own.
1244fn spanned(c: Content, span: Span) -> Content {
1245 if c.span().is_detached() { c.with_span(span) } else { c }
1246}
1247
1248fn slice_text(c: &Content, t: &str, from: usize, to: usize) -> Content {
1249 let mut piece = c.clone();
1250 let s = t.get(from..to).unwrap_or(t);
1251 piece.set(FieldId(0), Value::str(s));
1252 piece
1253}
1254
1255fn select_span(pairs: &[Pair]) -> Span {
1256 pairs.iter().filter(|p| !p.is_tag()).map(|p| p.content.span()).find(|s| !s.is_detached())
1257 .unwrap_or(Span::detached())
1258}
1259
1260/// Rebuilds content from grouped pairs: each run of members under one chain becomes a sequence styled
1261/// with what its chain has beyond the group's trunk, and the trunk is returned for the group itself.
1262/// A tag among them becomes a `tag` element; the trunk is taken over the members alone.
1263fn repack(pairs: &[Pair]) -> (Content, StyleChain) {
1264 let members: Vec<&Pair> = pairs.iter().filter(|p| !p.is_tag()).collect();
1265 let trunk = if members.is_empty() {
1266 StyleChain::trunk(pairs.iter().map(|p| &p.styles))
1267 } else {
1268 StyleChain::trunk(members.iter().map(|p| &p.styles))
1269 };
1270 let depth = trunk.depth();
1271 let mut children = Vec::new();
1272 let mut i = 0;
1273 while i < pairs.len() {
1274 let mut j = i + 1;
1275 while j < pairs.len() && pairs[j].styles.ptr_eq(&pairs[i].styles) {
1276 j += 1;
1277 }
1278 let run: Vec<Content> = pairs[i..j].iter().map(|p| match &p.tag {
1279 Some(t) => t.to_content(),
1280 None => p.content.clone(),
1281 }).collect();
1282 children.push(Content::sequence(run).styled(pairs[i].styles.suffix(depth)));
1283 i = j;
1284 }
1285 (Content::sequence(children), trunk)
1286}
1287
1288/// Drops spaces at the edges of a run and next to breaks: after nothing, before or after a line break,
1289/// and before a weak or fractional `h`.
1290fn collapse_spaces(sink: &mut Vec<Pair>, start: usize) -> Outcome<()> {
1291 let tail = sink.split_off(start);
1292 let mut state = SpaceState::Destructive;
1293 for p in tail {
1294 if !p.is_tag() {
1295 let c = &p.content;
1296 if c.is(ElemKind::Space) {
1297 if state != SpaceState::Supportive {
1298 continue;
1299 }
1300 state = SpaceState::Space(sink.len());
1301 } else if c.is(ElemKind::Linebreak) {
1302 destruct_space(sink, &mut state);
1303 } else if c.is(ElemKind::H) {
1304 if res!(is_weak_or_fractional(c, &p.styles)) {
1305 destruct_space(sink, &mut state);
1306 }
1307 } else {
1308 state = SpaceState::Supportive;
1309 }
1310 }
1311 sink.push(p);
1312 }
1313 destruct_space(sink, &mut state);
1314 Ok(())
1315}
1316
1317fn destruct_space(sink: &mut Vec<Pair>, state: &mut SpaceState) {
1318 if let SpaceState::Space(i) = *state {
1319 if i < sink.len() {
1320 sink.remove(i);
1321 }
1322 }
1323 *state = SpaceState::Destructive;
1324}
1325
1326fn is_weak_or_fractional(h: &Content, styles: &StyleChain) -> Outcome<bool> {
1327 let field = |name: &str| -> Outcome<Option<Value>> {
1328 match ElemKind::H.field_id(name) {
1329 Some(id) => styles.resolve(h, id),
1330 None => Ok(None),
1331 }
1332 };
1333 let amount = res!(field("amount"));
1334 let weak = res!(field("weak"));
1335 Ok(matches!(amount, Some(Value::Fraction(_))) || matches!(weak, Some(Value::Bool(true))))
1336}
1337
1338// Text and regex rules
1339
1340/// The leftmost match of any text or regex rule in a textual run. The run is read as Typst reads it --
1341/// spaces collapsed, a line break as `\n`, smart quotes as straight ones -- and searched one stretch of
1342/// equal styles at a time, since a rule cannot match across a style change.
1343fn find_regex_match_in_elems(elems: &[Pair]) -> Outcome<Option<RegexMatch>> {
1344 let mut buf = String::new();
1345 let mut base = 0;
1346 let mut current: Option<StyleChain> = None;
1347 let mut space = SpaceState::Destructive;
1348 for p in elems {
1349 if p.is_tag() {
1350 continue;
1351 }
1352 let c = &p.content;
1353 let linebreak = c.is(ElemKind::Linebreak);
1354 if linebreak {
1355 if let SpaceState::Space(_) = space {
1356 buf.pop();
1357 }
1358 }
1359 let changed = current.as_ref().map(|cur| !cur.ptr_eq(&p.styles)).unwrap_or(false);
1360 if changed && !buf.is_empty() {
1361 if let Some(cur) = &current {
1362 if let Some(m) = res!(find_regex_match_in_str(&buf, cur)) {
1363 return Ok(Some(RegexMatch { offset: base + m.offset, ..m }));
1364 }
1365 }
1366 base += buf.len();
1367 buf.clear();
1368 }
1369 current = Some(p.styles.clone());
1370 if c.is(ElemKind::Space) {
1371 if space != SpaceState::Supportive {
1372 continue;
1373 }
1374 buf.push(' ');
1375 space = SpaceState::Space(0);
1376 } else if linebreak {
1377 buf.push('\n');
1378 space = SpaceState::Destructive;
1379 } else if c.is(ElemKind::SmartQuote) {
1380 let double = match ElemKind::SmartQuote.field_id("double") {
1381 Some(id) => res!(p.styles.resolve(c, id)),
1382 None => None,
1383 };
1384 buf.push(if matches!(double, Some(Value::Bool(false))) { '\'' } else { '"' });
1385 space = SpaceState::Supportive;
1386 } else if let Some(Value::Str(t)) = c.get(FieldId(0)) {
1387 buf.push_str(t);
1388 space = SpaceState::Supportive;
1389 }
1390 }
1391 match &current {
1392 Some(cur) => Ok(res!(find_regex_match_in_str(&buf, cur)).map(|m| RegexMatch { offset: base + m.offset, ..m })),
1393 None => Ok(None),
1394 }
1395}
1396
1397/// The leftmost non-empty match of the text and regex rules in force, the innermost rule winning a tie.
1398fn find_regex_match_in_str(text: &str, styles: &StyleChain) -> Outcome<Option<RegexMatch>> {
1399 let mut best: Option<(usize, usize, &RecipeSlot)> = None;
1400 for slot in styles.recipes() {
1401 let sel = match &slot.recipe.selector {
1402 Some(s) => s,
1403 None => continue,
1404 };
1405 let (s, e) = match res!(sel.find_text(text)) {
1406 Some(m) => m,
1407 None => continue,
1408 };
1409 if s == e {
1410 continue;
1411 }
1412 if best.map(|(bs, ..)| bs <= s).unwrap_or(false) {
1413 continue;
1414 }
1415 best = Some((s, e, slot));
1416 }
1417 Ok(best.map(|(s, e, slot)| RegexMatch {
1418 offset: s,
1419 text: text[s..e].to_string(),
1420 index: slot.index,
1421 recipe: slot.recipe.clone(),
1422 styles: styles.clone(),
1423 }))
1424}
1425
1426/// The label a realised pair's content carries, for the introspector.
1427pub fn label_of(pair: &Pair) -> Option<&Label> {
1428 match &pair.tag {
1429 Some(Tag::Start(c)) => c.label(),
1430 _ => pair.content.label(),
1431 }
1432}
1433
1434#[cfg(test)]
1435mod tests {
1436 use super::*;
1437
1438 fn pair(kind: ElemKind) -> Pair {
1439 Pair::new(Content::new(kind, Vec::new(), Span::detached()), StyleChain::root())
1440 }
1441
1442 /// Nothing, spaces, breaks and tags set nothing; any other element is content, drawn or not.
1443 #[test]
1444 fn a_realised_body_sets_content_unless_it_holds_only_spaces_breaks_and_tags() {
1445 assert!(!sets_content(&[]));
1446 assert!(!sets_content(&[
1447 pair(ElemKind::Space), pair(ElemKind::Parbreak), pair(ElemKind::Pagebreak), pair(ElemKind::Colbreak),
1448 ]));
1449 let tag = Pair::tag(Tag::End(Location(1)), StyleChain::root());
1450 assert!(!sets_content(&[tag.clone(), pair(ElemKind::Space)]));
1451 assert!(sets_content(&[tag, pair(ElemKind::Space), pair(ElemKind::Linebreak)]));
1452 assert!(sets_content(&[pair(ElemKind::Parbreak), pair(ElemKind::Metadata)]));
1453 }
1454}