Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/math/process.rs

8.1 KiB, 1 run

created by r1870400018:63552, 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-library `math/ir/process.rs` and `math/ir/multiline.rs`, version 0.15.1).
3// Modified for Austenite: ported to Hematite's types, IR and error handling.
4//! Spacing between items by their classes, and linebreaks and alignment points into rows and columns: a
5//! port of Typst 0.15's `math/ir/process.rs` and `multiline.rs`.
6
7use crate::eval::styles::StyleChain;
8use crate::math::class::MathClass;
9use crate::math::item::{
10 FencedBody,
11 Item,
12 Raw,
13 Row,
14};
15use crate::math::resolve::{
16 fenced,
17 shared_sizing,
18 MEDIUM,
19 THICK,
20 THIN,
21};
22use crate::math::style::MathSize;
23use crate::syntax::Span;
24
25/// Items with their spacing decided: flat, or split into rows at linebreaks.
26pub enum Group {
27 Flat(Vec<Item>),
28 Multiline(Vec<Row>),
29}
30
31/// Spaces and splits a run of raw items. `closing`: a closing delimiter follows; `pad`: rows are padded
32/// to a common column count; `split`: alignment points split columns even without a linebreak.
33pub fn process_group(items: Vec<Raw>, styles: &StyleChain, closing: bool, pad: bool, split: bool) -> Group {
34 let pre = preprocess(items, closing, false);
35 if pre.linebreaks > 0 || (split && pre.has_align) {
36 let mut rows = Vec::new();
37 let mut row = Vec::new();
38 for raw in pre.items.into_iter().chain(std::iter::once(Raw::Linebreak)) {
39 match raw {
40 Raw::Linebreak => rows.push(split_at_align(std::mem::take(&mut row), styles)),
41 other => row.push(other),
42 }
43 }
44 if pad {
45 let n = rows.iter().map(|r: &Row| r.len()).max().unwrap_or(0);
46 for r in rows.iter_mut() {
47 r.pad_to(n, styles);
48 }
49 }
50 Group::Multiline(rows)
51 } else {
52 Group::Flat(pre.items.into_iter().filter_map(Raw::into_item).collect())
53 }
54}
55
56/// A table cell's items: linebreaks stripped (and reported), split at alignment points.
57pub fn process_table_cell(items: Vec<Raw>, styles: &StyleChain) -> (Row, bool) {
58 let pre = preprocess(items, false, true);
59 let row = if pre.has_align {
60 split_at_align(pre.items, styles)
61 } else {
62 Row(vec![Item::wrap(pre.items.into_iter().filter_map(Raw::into_item).collect(), styles)])
63 };
64 (row, pre.had_linebreaks)
65}
66
67struct Pre {
68 items: Vec<Raw>,
69 had_linebreaks: bool,
70 has_align: bool,
71 linebreaks: u32,
72}
73
74fn last_index(v: &[Raw]) -> Option<usize> { v.iter().rposition(|i| !i.is_ignorant()) }
75
76fn preprocess(items: Vec<Raw>, closing: bool, strip_linebreaks: bool) -> Pre {
77 let mut out: Vec<Raw> = Vec::with_capacity(items.len());
78 let mut last: Option<usize> = None;
79 let mut space: Option<Item> = None;
80 let mut had_linebreaks = false;
81 let mut has_align = false;
82 let mut linebreaks = 0u32;
83 for raw in items {
84 let mut item = match raw {
85 Raw::Item(Item::Tag(t)) => {
86 out.push(Raw::Item(Item::Tag(t)));
87 continue;
88 }
89 Raw::Item(Item::Space) => {
90 if last.is_some() {
91 space = Some(Item::Space);
92 }
93 continue;
94 }
95 Raw::Item(Item::Spacing(w, weak)) => {
96 last = None;
97 space = None;
98 if weak {
99 let li = last_index(&out);
100 match li.and_then(|i| out.get_mut(i)) {
101 None => continue,
102 Some(Raw::Item(Item::Spacing(pw, true))) => {
103 if *pw < w {
104 *pw = w;
105 }
106 continue;
107 }
108 Some(_) => (),
109 }
110 }
111 out.push(Raw::Item(Item::Spacing(w, weak)));
112 continue;
113 }
114 Raw::Align => {
115 has_align = true;
116 out.push(Raw::Align);
117 continue;
118 }
119 Raw::Linebreak => {
120 had_linebreaks = true;
121 if strip_linebreaks {
122 continue;
123 }
124 linebreaks += 1;
125 out.push(Raw::Linebreak);
126 space = None;
127 last = None;
128 continue;
129 }
130 Raw::Item(i) => i,
131 };
132 // A varying operator becomes binary after an operand.
133 if item.class() == MathClass::Vary {
134 if let Some(Raw::Item(prev)) = last.and_then(|i| out.get(i)) {
135 if matches!(prev.class(), MathClass::Normal | MathClass::Alphabetic | MathClass::Closing | MathClass::Fence) {
136 item.set_class(MathClass::Binary);
137 }
138 }
139 }
140 if !item.is_ignorant() {
141 if let Some(i) = last {
142 let s = match out.get_mut(i) {
143 Some(Raw::Item(prev)) => spacing(prev, space.take(), &mut item),
144 _ => None,
145 };
146 if let Some(s) = s {
147 out.insert(i + 1, Raw::Item(s));
148 }
149 }
150 last = Some(out.len());
151 }
152 out.push(Raw::Item(item));
153 }
154 // Closing punctuation takes thin space; a trailing weak space goes.
155 let mut applied = false;
156 if closing {
157 if let Some(i) = last_index(&out) {
158 if let Some(Raw::Item(item)) = out.get_mut(i) {
159 if item.rclass() == MathClass::Punctuation && item.size().map(|s| s > MathSize::Script).unwrap_or(true) {
160 item.set_rspace(Some(THIN));
161 applied = true;
162 }
163 }
164 }
165 }
166 if !applied {
167 if let Some(i) = last_index(&out) {
168 if matches!(out.get(i), Some(Raw::Item(Item::Spacing(_, true)))) {
169 out.remove(i);
170 }
171 }
172 }
173 if !closing {
174 if let Some(i) = last_index(&out) {
175 if matches!(out.get(i), Some(Raw::Linebreak)) {
176 out.remove(i);
177 linebreaks = linebreaks.saturating_sub(1);
178 }
179 }
180 }
181 Pre { items: out, had_linebreaks, has_align, linebreaks }
182}
183
184// Typst's class-pair spacing; `space` is a source space, kept only between spaced items.
185fn spacing(l: &mut Item, space: Option<Item>, r: &mut Item) -> Option<Item> {
186 use MathClass as C;
187 let script = |f: &Item| f.size().map(|s| s <= MathSize::Script).unwrap_or(false);
188 match (l.rclass(), r.lclass()) {
189 (_, C::Punctuation) => None,
190 (C::Punctuation, _) if !script(l) => { l.set_rspace(Some(THIN)); None }
191 (C::Opening, _) | (_, C::Closing) => None,
192 (C::Relation, C::Relation) => None,
193 (C::Relation, _) if !script(l) => { l.set_rspace(Some(THICK)); None }
194 (_, C::Relation) if !script(r) => { r.set_lspace(Some(THICK)); None }
195 (C::Binary, _) if !script(l) => { l.set_rspace(Some(MEDIUM)); None }
196 (_, C::Binary) if !script(r) => { r.set_lspace(Some(MEDIUM)); None }
197 (C::Large, C::Opening | C::Fence) => None,
198 (C::Large, _) => { l.set_rspace(Some(THIN)); None }
199 (_, C::Large) => { r.set_lspace(Some(THIN)); None }
200 _ => spaced(l, r, space),
201 }
202}
203
204fn spaced(l: &Item, r: &Item, space: Option<Item>) -> Option<Item> {
205 if l.is_spaced() || r.is_spaced() { space } else { None }
206}
207
208/// Splits items at alignment points into columns, marking an infix operator that opens a left-aligned
209/// column so its left space moves to the right-aligned column before it.
210pub fn split_at_align(items: Vec<Raw>, styles: &StyleChain) -> Row {
211 let mut cols: Vec<Vec<Item>> = vec![Vec::new()];
212 let mut at_boundary = false;
213 for raw in items {
214 match raw {
215 Raw::Align => {
216 cols.push(Vec::new());
217 at_boundary = true;
218 }
219 Raw::Linebreak => (),
220 Raw::Item(mut item) => {
221 if at_boundary && !item.is_ignorant() {
222 if cols.len() % 2 == 0 && matches!(item.class(), MathClass::Relation | MathClass::Binary) {
223 if let Item::Comp(c) = &mut item {
224 c.props.align_form_infix = true;
225 }
226 }
227 at_boundary = false;
228 }
229 if let Some(col) = cols.last_mut() {
230 col.push(item);
231 }
232 }
233 }
234 }
235 Row(cols.into_iter().map(|c| Item::wrap(c, styles)).collect())
236}
237
238/// A fence whose body breaks over rows: each row's columns become fenced segments sharing one size,
239/// the opening delimiter on the first and the closing on the last.
240pub fn expand_multiline_fence(
241 rows: Vec<Row>,
242 open: Option<Item>,
243 close: Option<Item>,
244 styles: &StyleChain,
245 span: Span,
246)
247 -> Vec<Raw>
248{
249 let nrows = rows.len();
250 let mut bodies = Vec::new();
251 let mut lengths = Vec::with_capacity(nrows);
252 for r in rows {
253 lengths.push(r.len());
254 bodies.extend(r.0);
255 }
256 let sizing = shared_sizing(bodies, styles);
257 let mut open = open;
258 let mut close = close;
259 let mut out = Vec::new();
260 let mut index = 0;
261 for (ri, &ncols) in lengths.iter().enumerate() {
262 if ri > 0 {
263 out.push(Raw::Linebreak);
264 }
265 for ci in 0..ncols {
266 if ci > 0 {
267 out.push(Raw::Align);
268 }
269 let first = ri == 0 && ci == 0;
270 let last = ri + 1 == nrows && ci + 1 == ncols;
271 let o = if first { open.take() } else { None };
272 let c = if last { close.take() } else { None };
273 out.push(Raw::Item(fenced(o, c, FencedBody::Shared { index, sizing: sizing.clone() }, true, styles, span)));
274 index += 1;
275 }
276 }
277 out
278}