oxedyne/fe2o3/fe2o3_austenite/src/math/resolve.rs
42.8 KiB, 1 run
created by r1870400018:63556, 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/resolve.rs`, version 0.15.1). |
| 3 | // Modified for Austenite: ported to Hematite's types, IR and error handling. |
| 4 | //! Realised maths content into IR items: a port of Typst 0.15's `math/ir/resolve.rs`. Each element's |
| 5 | //! body is realised in maths mode and resolved in turn, so show rules reach every level; the styles an |
| 6 | //! element sets for its parts (script size, cramped style, the alphabet) are chained as it descends. |
| 7 | |
| 8 | use crate::diag::DiagnosticKind; |
| 9 | use crate::eval::content::{ |
| 10 | Content, |
| 11 | ElemKind, |
| 12 | FieldId, |
| 13 | }; |
| 14 | use crate::eval::realise::{ |
| 15 | realise, |
| 16 | Pair, |
| 17 | RealiseMode, |
| 18 | }; |
| 19 | use crate::eval::content::display; |
| 20 | use crate::eval::styles::{ |
| 21 | to_stroke, |
| 22 | StyleChain, |
| 23 | }; |
| 24 | use crate::eval::value::{ |
| 25 | Length, |
| 26 | Ratio, |
| 27 | Relative, |
| 28 | Value, |
| 29 | }; |
| 30 | use crate::eval::Engine; |
| 31 | use crate::math::class::{ |
| 32 | default_math_class, |
| 33 | MathClass, |
| 34 | }; |
| 35 | use crate::math::item::{ |
| 36 | Alternator, |
| 37 | Augment, |
| 38 | Cancel, |
| 39 | Fixed, |
| 40 | FencedBody, |
| 41 | Glyph, |
| 42 | Item, |
| 43 | Kind, |
| 44 | Limits, |
| 45 | Position, |
| 46 | Props, |
| 47 | Raw, |
| 48 | Rel, |
| 49 | Row, |
| 50 | Scripts, |
| 51 | SharedSizing, |
| 52 | Stretch, |
| 53 | StretchInfo, |
| 54 | Table, |
| 55 | }; |
| 56 | use crate::math::process::{ |
| 57 | expand_multiline_fence, |
| 58 | process_group, |
| 59 | process_table_cell, |
| 60 | Group, |
| 61 | }; |
| 62 | use crate::math::props; |
| 63 | use crate::math::style::{ |
| 64 | styled, |
| 65 | MathSize, |
| 66 | }; |
| 67 | |
| 68 | use crate::syntax::Span; |
| 69 | |
| 70 | use oxedyne_fe2o3_core::prelude::*; |
| 71 | use oxedyne_fe2o3_text::unicode::property::Binary; |
| 72 | use oxedyne_fe2o3_text::unicode::segment::graphemes; |
| 73 | |
| 74 | use std::cell::Cell; |
| 75 | |
| 76 | pub const THIN: f64 = 1.0 / 6.0; |
| 77 | pub const MEDIUM: f64 = 2.0 / 9.0; |
| 78 | pub const THICK: f64 = 5.0 / 18.0; |
| 79 | pub const DELIM_SHORT_FALL: f64 = 0.1; |
| 80 | pub const ACCENT_SHORT_FALL: f64 = 0.5; |
| 81 | pub const FRAC_PADDING: f64 = 0.1; |
| 82 | const ROW_GAP: f64 = 0.2; // ems, vec, mat and cases |
| 83 | const COL_GAP: f64 = 0.5; // ems, mat |
| 84 | |
| 85 | /// Builds IR from realised maths content. |
| 86 | pub struct Resolver<'e> { |
| 87 | pub engine: &'e mut Engine, |
| 88 | items: Vec<Raw>, |
| 89 | } |
| 90 | |
| 91 | impl<'e> Resolver<'e> { |
| 92 | pub fn new(engine: &'e mut Engine) -> Self { Self { engine, items: Vec::new() } } |
| 93 | |
| 94 | fn push(&mut self, item: Item) { self.items.push(Raw::Item(item)); } |
| 95 | |
| 96 | /// Resolves content, returning where its items start in the buffer. |
| 97 | fn resolve_into_items(&mut self, content: &Content, styles: &StyleChain) -> Outcome<usize> { |
| 98 | let start = self.items.len(); |
| 99 | let pairs = res!(realise(self.engine, content, styles, RealiseMode::Math)); |
| 100 | for pair in pairs { |
| 101 | res!(self.realised(pair)); |
| 102 | } |
| 103 | Ok(start) |
| 104 | } |
| 105 | |
| 106 | /// Resolves content into one item: the item itself, a group, or a multiline item. |
| 107 | pub fn resolve_into_item(&mut self, content: &Content, styles: &StyleChain) -> Outcome<Item> { |
| 108 | let start = res!(self.resolve_into_items(content, styles)); |
| 109 | let len = self.items.len() - start; |
| 110 | if len == 1 && matches!(self.items.last(), Some(Raw::Item(_))) { |
| 111 | if let Some(Raw::Item(i)) = self.items.pop() { |
| 112 | return Ok(i); |
| 113 | } |
| 114 | } |
| 115 | let drained: Vec<Raw> = self.items.drain(start..).collect(); |
| 116 | Ok(match process_group(drained, styles, false, true, false) { |
| 117 | Group::Multiline(rows) => multiline(rows, styles), |
| 118 | Group::Flat(items) => Item::wrap(items, styles), |
| 119 | }) |
| 120 | } |
| 121 | |
| 122 | fn realised(&mut self, pair: Pair) -> Outcome<()> { |
| 123 | if let Some(tag) = pair.tag { |
| 124 | self.push(Item::Tag(tag)); |
| 125 | return Ok(()); |
| 126 | } |
| 127 | let elem = &pair.content; |
| 128 | let styles = &pair.styles; |
| 129 | let kind = match elem.kind() { |
| 130 | Some(k) => k, |
| 131 | None => return Ok(()), |
| 132 | }; |
| 133 | match kind { |
| 134 | ElemKind::Text => self.text(elem, styles, false), |
| 135 | ElemKind::Symbol => self.text(elem, styles, true), |
| 136 | ElemKind::Space => { self.push(Item::Space); Ok(()) } |
| 137 | ElemKind::MathAttach => self.attach(elem, styles), |
| 138 | ElemKind::MathLr => self.lr(elem, styles), |
| 139 | ElemKind::MathOp => self.op(elem, styles), |
| 140 | ElemKind::H => self.h(elem, styles), |
| 141 | ElemKind::MathOverline => self.overline(elem, styles), |
| 142 | ElemKind::MathAlignPoint => { self.items.push(Raw::Align); Ok(()) } |
| 143 | ElemKind::MathPrimes => self.primes(elem, styles), |
| 144 | ElemKind::MathClass => self.class(elem, styles), |
| 145 | ElemKind::Linebreak => { self.items.push(Raw::Linebreak); Ok(()) } |
| 146 | ElemKind::MathFrac => self.frac(elem, styles), |
| 147 | ElemKind::MathAccent => self.accent(elem, styles), |
| 148 | ElemKind::MathLimits => self.limits(elem, styles), |
| 149 | ElemKind::MathStretch => self.stretch(elem, styles), |
| 150 | ElemKind::MathRoot => self.root(elem, styles), |
| 151 | ElemKind::MathMat => self.mat(elem, styles), |
| 152 | ElemKind::MathMid => self.mid(elem, styles), |
| 153 | ElemKind::MathUnderline => self.underline(elem, styles), |
| 154 | ElemKind::MathCases => self.cases(elem, styles), |
| 155 | ElemKind::MathScripts => self.scripts(elem, styles), |
| 156 | ElemKind::MathCancel => self.cancel(elem, styles), |
| 157 | ElemKind::MathVec => self.vec(elem, styles), |
| 158 | ElemKind::MathBinom => self.binom(elem, styles), |
| 159 | ElemKind::MathUnderbrace => self.spreader(elem, styles, '\u{23df}', Position::Below), |
| 160 | ElemKind::MathOverbrace => self.spreader(elem, styles, '\u{23de}', Position::Above), |
| 161 | ElemKind::MathUnderbracket => self.spreader(elem, styles, '\u{23b5}', Position::Below), |
| 162 | ElemKind::MathOverbracket => self.spreader(elem, styles, '\u{23b4}', Position::Above), |
| 163 | ElemKind::MathUnderparen => self.spreader(elem, styles, '\u{23dd}', Position::Below), |
| 164 | ElemKind::MathOverparen => self.spreader(elem, styles, '\u{23dc}', Position::Above), |
| 165 | ElemKind::MathUndershell => self.spreader(elem, styles, '\u{23e1}', Position::Below), |
| 166 | ElemKind::MathOvershell => self.spreader(elem, styles, '\u{23e0}', Position::Above), |
| 167 | ElemKind::Box => { |
| 168 | let props = Props { spaced: true, ..Props::new(styles, None, elem.span()) }; |
| 169 | self.push(Item::comp(Kind::External(elem.clone()), props, styles.clone())); |
| 170 | Ok(()) |
| 171 | } |
| 172 | _ => { |
| 173 | let props = Props { |
| 174 | spaced: true, |
| 175 | ignorant: kind == ElemKind::Place, |
| 176 | ..Props::new(styles, None, elem.span()) |
| 177 | }; |
| 178 | self.push(Item::comp(Kind::External(elem.clone()), props, styles.clone())); |
| 179 | Ok(()) |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | // Text and symbols |
| 185 | |
| 186 | fn text(&mut self, elem: &Content, styles: &StyleChain, symbol: bool) -> Outcome<()> { |
| 187 | let text = match elem.get(FieldId(0)) { |
| 188 | Some(Value::Str(s)) => s.to_string(), |
| 189 | _ => return Ok(()), |
| 190 | }; |
| 191 | if symbol { |
| 192 | self.symbol(&text, elem.span(), styles) |
| 193 | } else { |
| 194 | self.text_elem(&text, elem.span(), styles) |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | fn text_elem(&mut self, text: &str, span: Span, styles: &StyleChain) -> Outcome<()> { |
| 199 | let variant = props::variant(styles); |
| 200 | let bold = props::bold(styles); |
| 201 | let italic = props::italic(styles).or(Some(false)); |
| 202 | let item_of = |t: &str| -> Item { |
| 203 | let s = styled(t, variant, bold, italic); |
| 204 | if is_number(t) { |
| 205 | Item::comp(Kind::Number(s), Props::new(styles, None, span), styles.clone()) |
| 206 | } else { |
| 207 | let props = Props { spaced: true, ..Props::new(styles, Some(MathClass::Alphabetic), span) }; |
| 208 | Item::comp(Kind::Text(s), props, styles.clone()) |
| 209 | } |
| 210 | }; |
| 211 | let mut lines: Vec<&str> = split_newlines(text); |
| 212 | if lines.last().map(|l| l.is_empty()).unwrap_or(false) { |
| 213 | lines.pop(); |
| 214 | } |
| 215 | let item = if lines.len() == 1 { |
| 216 | item_of(lines[0]) |
| 217 | } else { |
| 218 | let rows = lines.into_iter().map(|l| Row(vec![item_of(l)])).collect(); |
| 219 | multiline(rows, styles).with_multiline_centering() |
| 220 | }; |
| 221 | self.push(item); |
| 222 | Ok(()) |
| 223 | } |
| 224 | |
| 225 | fn symbol(&mut self, text: &str, span: Span, styles: &StyleChain) -> Outcome<()> { |
| 226 | let variant = props::variant(styles); |
| 227 | let bold = props::bold(styles); |
| 228 | let italic = props::italic(styles); |
| 229 | let ignorable = Binary::find("Default_Ignorable_Code_Point"); |
| 230 | for cluster in graphemes(text) { |
| 231 | if let Some(ig) = ignorable { |
| 232 | if cluster.chars().all(|c| ig.contains(c)) { |
| 233 | continue; |
| 234 | } |
| 235 | } |
| 236 | let item = glyph(styled(cluster, variant, bold, italic), styles, span); |
| 237 | if item.class() == MathClass::Large && item.size() == Some(MathSize::Display) { |
| 238 | item.replace_stretch(Stretch::new().with_y(StretchInfo::default())); |
| 239 | } |
| 240 | self.push(item); |
| 241 | } |
| 242 | Ok(()) |
| 243 | } |
| 244 | |
| 245 | /// A single character resolved as a symbol under `styles`. |
| 246 | fn symbol_item(&mut self, c: char, span: Span, styles: &StyleChain) -> Outcome<Item> { |
| 247 | let content = Content::symbol(&c.to_string()).with_span(span); |
| 248 | self.resolve_into_item(&content, styles) |
| 249 | } |
| 250 | |
| 251 | // Spacing |
| 252 | |
| 253 | fn h(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 254 | let amount = res!(self.f(elem, styles, "amount")); |
| 255 | let weak = matches!(res!(self.f(elem, styles, "weak")), Some(Value::Bool(true))); |
| 256 | let len = match amount { |
| 257 | Some(Value::Length(l)) => Some(l), |
| 258 | Some(Value::Relative(r)) if r.rel.0 == 0.0 => Some(r.abs), |
| 259 | Some(Value::Ratio(r)) if r.0 == 0.0 => Some(Length::zero()), |
| 260 | _ => None, |
| 261 | }; |
| 262 | if let Some(l) = len { |
| 263 | self.push(Item::Spacing(props::resolve(styles, l), weak)); |
| 264 | } |
| 265 | Ok(()) |
| 266 | } |
| 267 | |
| 268 | // Attachments |
| 269 | |
| 270 | fn attach(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 271 | let mut outer: [Vec<Option<Content>>; 6] = Default::default(); |
| 272 | let item = res!(self.inner_attach(elem, &mut outer, false, styles)); |
| 273 | self.push(item); |
| 274 | Ok(()) |
| 275 | } |
| 276 | |
| 277 | // Typst merges nested attachments inward (`attach(attach(a, t: 1), b: 2)` is `attach(a, t: 1, b: 2)`) |
| 278 | // through a linked list of each position's outer attachments; here each position keeps a stack, |
| 279 | // outermost first, and an inner level takes the nearest free one. |
| 280 | fn inner_attach( |
| 281 | &mut self, |
| 282 | elem: &Content, |
| 283 | outer: &mut [Vec<Option<Content>>; 6], |
| 284 | outer_t_inside_tr: bool, |
| 285 | styles: &StyleChain, |
| 286 | ) |
| 287 | -> Outcome<Item> |
| 288 | { |
| 289 | let sup = props::chain_with(styles, vec![props::for_superscript(styles)]); |
| 290 | let sub = props::chain_with(styles, props::for_subscript(styles)); |
| 291 | let own_t = res!(self.script(elem, "t", &sup)); |
| 292 | let own_tr = res!(self.script(elem, "tr", &sup)); |
| 293 | let no_inner_tr = own_tr.is_none(); |
| 294 | let t_inside_tr = no_inner_tr && (own_t.is_some() || outer_t_inside_tr); |
| 295 | // Positions: t, b, tl, tr, bl, br. |
| 296 | let own = [ |
| 297 | own_t, |
| 298 | res!(self.script(elem, "b", &sub)), |
| 299 | res!(self.script(elem, "tl", &sup)), |
| 300 | own_tr, |
| 301 | res!(self.script(elem, "bl", &sub)), |
| 302 | res!(self.script(elem, "br", &sub)), |
| 303 | ]; |
| 304 | for (i, o) in own.into_iter().enumerate() { |
| 305 | let merged = match o { |
| 306 | Some(c) => Some(c), |
| 307 | None => take_outer(&mut outer[i]), |
| 308 | }; |
| 309 | outer[i].push(merged); |
| 310 | } |
| 311 | let mut base = res!(self.c(elem, styles, "base")); |
| 312 | while base.is(ElemKind::Equation) { |
| 313 | match base.field("body") { |
| 314 | Some(Value::Content(b)) => base = b.clone(), |
| 315 | _ => break, |
| 316 | } |
| 317 | } |
| 318 | let base_item = if base.is(ElemKind::MathAttach) { |
| 319 | res!(self.inner_attach(&base, outer, t_inside_tr, styles)) |
| 320 | } else { |
| 321 | res!(self.resolve_into_item(&base, styles)) |
| 322 | }; |
| 323 | let mut mine: Vec<Option<Content>> = Vec::with_capacity(6); |
| 324 | for o in outer.iter_mut() { |
| 325 | mine.push(o.pop().flatten()); |
| 326 | } |
| 327 | let (t, b, tl, tr, bl, br) = (mine[0].take(), mine[1].take(), mine[2].take(), mine[3].take(), |
| 328 | mine[4].take(), mine[5].take()); |
| 329 | if t.is_none() && b.is_none() && tl.is_none() && tr.is_none() && bl.is_none() && br.is_none() { |
| 330 | return Ok(base_item); |
| 331 | } |
| 332 | let limits = base_item.limits().active(styles); |
| 333 | let (t, tr) = match (t, tr) { |
| 334 | (Some(t), Some(tr)) if !limits => { |
| 335 | let primed = tr.is(ElemKind::MathPrimes); |
| 336 | if primed && no_inner_tr && t_inside_tr { |
| 337 | // A primed tr brought inward goes back out, so `tr + t` does not invert the order. |
| 338 | unmerge(&mut outer[3], tr); |
| 339 | (None, Some(t)) |
| 340 | } else if primed { |
| 341 | (None, Some(Content::sequence(vec![tr, t]))) |
| 342 | } else { |
| 343 | (Some(t), Some(tr)) |
| 344 | } |
| 345 | } |
| 346 | (Some(t), None) if !limits => (None, Some(t)), |
| 347 | (t, tr) => (t, tr), |
| 348 | }; |
| 349 | let (b, br) = if limits || br.is_some() { (b, br) } else { (None, b) }; |
| 350 | let lay = |c: Option<Content>, chain: &StyleChain, me: &mut Self| -> Outcome<Option<Item>> { |
| 351 | match c { |
| 352 | Some(c) => Ok(Some(res!(me.resolve_into_item(&c, chain)))), |
| 353 | None => Ok(None), |
| 354 | } |
| 355 | }; |
| 356 | let top = res!(lay(t, &sup, self)); |
| 357 | let bottom = res!(lay(b, &sub, self)); |
| 358 | let tl = res!(lay(tl, &sup, self)); |
| 359 | let bl = res!(lay(bl, &sub, self)); |
| 360 | let tr = res!(lay(tr, &sup, self)); |
| 361 | let br = res!(lay(br, &sub, self)); |
| 362 | Ok(scripts(base_item, top, bottom, tl, bl, tr, br, styles)) |
| 363 | } |
| 364 | |
| 365 | fn primes(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 366 | let count = match res!(self.f(elem, styles, "count")) { |
| 367 | Some(Value::Int(n)) => n.max(0) as usize, |
| 368 | _ => 1, |
| 369 | }; |
| 370 | let c = match count { |
| 371 | 1 => Some('\u{2032}'), |
| 372 | 2 => Some('\u{2033}'), |
| 373 | 3 => Some('\u{2034}'), |
| 374 | 4 => Some('\u{2057}'), |
| 375 | _ => None, |
| 376 | }; |
| 377 | match c { |
| 378 | Some(c) => { |
| 379 | let item = res!(self.symbol_item(c, elem.span(), styles)); |
| 380 | self.push(item); |
| 381 | } |
| 382 | None => self.push(Item::comp(Kind::Primes(count), Props::new(styles, None, Span::detached()), styles.clone())), |
| 383 | } |
| 384 | Ok(()) |
| 385 | } |
| 386 | |
| 387 | fn scripts(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 388 | let mut item = { let tmp = res!(self.body(elem, styles)); res!(self.resolve_into_item(&tmp, styles)) }; |
| 389 | item.set_limits(Limits::Never); |
| 390 | self.push(item); |
| 391 | Ok(()) |
| 392 | } |
| 393 | |
| 394 | fn limits(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 395 | let mut item = { let tmp = res!(self.body(elem, styles)); res!(self.resolve_into_item(&tmp, styles)) }; |
| 396 | let inline = !matches!(res!(self.f(elem, styles, "inline")), Some(Value::Bool(false))); |
| 397 | item.set_limits(if inline { Limits::Always } else { Limits::Display }); |
| 398 | self.push(item); |
| 399 | Ok(()) |
| 400 | } |
| 401 | |
| 402 | fn stretch(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 403 | let item = { let tmp = res!(self.body(elem, styles)); res!(self.resolve_into_item(&tmp, styles)) }; |
| 404 | let size = relative(res!(self.f(elem, styles, "size"))).unwrap_or(ONE); |
| 405 | item.update_stretch(StretchInfo::from_size(&size, 0.0, props::font_size(styles))); |
| 406 | self.push(item); |
| 407 | Ok(()) |
| 408 | } |
| 409 | |
| 410 | fn cancel(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 411 | let base = { let tmp = res!(self.body(elem, styles)); res!(self.resolve_into_item(&tmp, styles)) }; |
| 412 | let fs = props::font_size(styles); |
| 413 | let length = match relative(res!(self.f(elem, styles, "length"))) { |
| 414 | Some(r) => Rel::of(&r, fs), |
| 415 | None => Rel::new(1.0, 0.3 * fs), |
| 416 | }; |
| 417 | let mut stroke = match res!(self.f(elem, styles, "stroke")) { |
| 418 | Some(v) => to_stroke(&v).unwrap_or_default(), |
| 419 | None => crate::eval::value::Stroke::default(), |
| 420 | }; |
| 421 | if stroke.thickness.is_none() { |
| 422 | stroke.thickness = Some(Length::em(0.05)); |
| 423 | } |
| 424 | let pen = crate::math::frame::pen(&stroke, fs, res!(props::fill(styles))); |
| 425 | let invert = matches!(res!(self.f(elem, styles, "inverted")), Some(Value::Bool(true))); |
| 426 | let cross = matches!(res!(self.f(elem, styles, "cross")), Some(Value::Bool(true))); |
| 427 | let angle = res!(self.f(elem, styles, "angle")).unwrap_or(Value::Auto); |
| 428 | let class = base.raw_class(); |
| 429 | let cancel = Cancel { base, length, stroke: pen, cross, invert_first_line: !cross && invert, angle }; |
| 430 | self.push(Item::comp(Kind::Cancel(Box::new(cancel)), Props::new(styles, class, elem.span()), styles.clone())); |
| 431 | Ok(()) |
| 432 | } |
| 433 | |
| 434 | // Fractions |
| 435 | |
| 436 | fn frac(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 437 | let num = res!(self.c(elem, styles, "num")); |
| 438 | let denom = res!(self.c(elem, styles, "denom")); |
| 439 | let style = match res!(self.f(elem, styles, "style")) { |
| 440 | Some(Value::Str(s)) => s.to_string(), |
| 441 | _ => "vertical".to_string(), |
| 442 | }; |
| 443 | match style.as_str() { |
| 444 | "skewed" => self.skewed_frac(&num, &denom, elem.span(), styles), |
| 445 | "horizontal" => { |
| 446 | let np = matches!(res!(self.f(elem, styles, "num-deparenthesized")), Some(Value::Bool(true))); |
| 447 | let dp = matches!(res!(self.f(elem, styles, "denom-deparenthesized")), Some(Value::Bool(true))); |
| 448 | self.horizontal_frac(num, denom, np, dp, elem.span(), styles) |
| 449 | } |
| 450 | _ => self.vertical_frac(&num, &[denom], false, elem.span(), styles), |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | fn binom(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 455 | let upper = res!(self.c(elem, styles, "upper")); |
| 456 | let lower = res!(self.children(elem, styles, "lower")); |
| 457 | self.vertical_frac(&upper, &lower, true, elem.span(), styles) |
| 458 | } |
| 459 | |
| 460 | fn vertical_frac( |
| 461 | &mut self, |
| 462 | num: &Content, |
| 463 | denom: &[Content], |
| 464 | binom: bool, |
| 465 | span: Span, |
| 466 | styles: &StyleChain, |
| 467 | ) |
| 468 | -> Outcome<()> |
| 469 | { |
| 470 | let num_styles = props::chain_with(styles, vec![props::for_numerator(styles)]); |
| 471 | let den_styles = props::chain_with(styles, props::for_denominator(styles)); |
| 472 | let numerator = res!(self.resolve_into_item(num, &num_styles)); |
| 473 | let mut parts = Vec::new(); |
| 474 | for (i, d) in denom.iter().enumerate() { |
| 475 | if i > 0 { |
| 476 | parts.push(Content::symbol(",").with_span(span)); |
| 477 | } |
| 478 | parts.push(d.clone()); |
| 479 | } |
| 480 | let denominator = res!(self.resolve_into_item(&Content::sequence(parts), &den_styles)); |
| 481 | let frac = Item::comp(Kind::Fraction { num: numerator, denom: denominator, line: !binom, padding: FRAC_PADDING }, |
| 482 | Props::new(styles, None, span), styles.clone()); |
| 483 | if binom { |
| 484 | let stretch = Stretch::new().with_y(StretchInfo::new(Rel::one(), DELIM_SHORT_FALL)); |
| 485 | let open = res!(self.symbol_item('(', span, styles)); |
| 486 | open.set_stretch(stretch); |
| 487 | let close = res!(self.symbol_item(')', span, styles)); |
| 488 | close.set_stretch(stretch); |
| 489 | self.push(fenced(Some(open), Some(close), FencedBody::Owned(frac), false, styles, span)); |
| 490 | } else { |
| 491 | self.push(frac); |
| 492 | } |
| 493 | Ok(()) |
| 494 | } |
| 495 | |
| 496 | fn horizontal_frac( |
| 497 | &mut self, |
| 498 | num: Content, |
| 499 | denom: Content, |
| 500 | num_deparen: bool, |
| 501 | denom_deparen: bool, |
| 502 | span: Span, |
| 503 | styles: &StyleChain, |
| 504 | ) |
| 505 | -> Outcome<()> |
| 506 | { |
| 507 | let paren = |c: Content| -> Content { |
| 508 | let body = Content::sequence(vec![Content::symbol("("), c, Content::symbol(")")]); |
| 509 | match ElemKind::MathLr.field_id("body") { |
| 510 | Some(id) => Content::new(ElemKind::MathLr, vec![(id, Value::Content(body))], span), |
| 511 | None => body, |
| 512 | } |
| 513 | }; |
| 514 | let num = if num_deparen { paren(num) } else { num }; |
| 515 | let n = res!(self.resolve_into_item(&num, styles)); |
| 516 | self.push(n); |
| 517 | let mut slash = res!(self.symbol_item('/', span, styles)); |
| 518 | slash.set_class(MathClass::Binary); |
| 519 | slash.set_lspace(Some(0.0)); |
| 520 | slash.set_rspace(Some(0.0)); |
| 521 | self.push(slash); |
| 522 | let denom = if denom_deparen { paren(denom) } else { denom }; |
| 523 | let d = res!(self.resolve_into_item(&denom, styles)); |
| 524 | self.push(d); |
| 525 | Ok(()) |
| 526 | } |
| 527 | |
| 528 | fn skewed_frac(&mut self, num: &Content, denom: &Content, span: Span, styles: &StyleChain) -> Outcome<()> { |
| 529 | let num_styles = props::chain_with(styles, vec![props::for_numerator(styles)]); |
| 530 | let den_styles = props::chain_with(styles, props::for_denominator(styles)); |
| 531 | let numerator = res!(self.resolve_into_item(num, &num_styles)); |
| 532 | let denominator = res!(self.resolve_into_item(denom, &den_styles)); |
| 533 | let slash = res!(self.symbol_item('\u{2044}', span, styles)); |
| 534 | slash.set_stretch(Stretch::new().with_y(StretchInfo::new(Rel::one(), DELIM_SHORT_FALL))); |
| 535 | self.push(Item::comp(Kind::Skewed { num: numerator, denom: denominator, slash }, |
| 536 | Props::new(styles, None, span), styles.clone())); |
| 537 | Ok(()) |
| 538 | } |
| 539 | |
| 540 | // Delimiters |
| 541 | |
| 542 | fn lr(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 543 | let mut body = res!(self.c(elem, styles, "body")); |
| 544 | if body.is(ElemKind::Equation) { |
| 545 | if let Some(Value::Content(b)) = body.field("body") { |
| 546 | body = b.clone(); |
| 547 | } |
| 548 | } |
| 549 | if body.is(ElemKind::MathLr) { |
| 550 | let inner_one = relative(res!(self.f(&body, styles, "size"))).map(|r| crate::math::item::is_one(&r)).unwrap_or(true); |
| 551 | if inner_one { |
| 552 | body = res!(self.c(&body, styles, "body")); |
| 553 | } |
| 554 | } |
| 555 | let start = res!(self.resolve_into_items(&body, styles)); |
| 556 | // Leading and trailing ignorant items stay outside the fence. |
| 557 | let slice = &self.items[start..]; |
| 558 | let lead = slice.iter().take_while(|r| r.is_ignorant()).count(); |
| 559 | let trail = slice.iter().rev().take_while(|r| r.is_ignorant()).count(); |
| 560 | let (s_idx, e_idx) = if lead == slice.len() { (lead, lead) } else { (lead, slice.len() - trail) }; |
| 561 | let lo = start + s_idx; |
| 562 | let hi = start + e_idx; |
| 563 | let size = relative(res!(self.f(elem, styles, "size"))).unwrap_or(ONE); |
| 564 | let fs = props::font_size(styles); |
| 565 | let stretch = Stretch::new().with_y(StretchInfo::from_size(&size, DELIM_SHORT_FALL, fs)); |
| 566 | let n = hi - lo; |
| 567 | if n == 1 { |
| 568 | if let Some(Raw::Item(one)) = self.items.get(lo) { |
| 569 | let mut done = false; |
| 570 | if let Item::Comp(c) = one { |
| 571 | if let Kind::Fenced { open, close, body: fbody, .. } = &c.kind { |
| 572 | if let Some(o) = open { o.set_stretch(stretch); } |
| 573 | if let Some(cl) = close { cl.set_stretch(stretch); } |
| 574 | for it in fbody.item().as_slice() { |
| 575 | if it.mid_stretched() == Some(true) { |
| 576 | it.set_stretch(stretch); |
| 577 | } |
| 578 | } |
| 579 | done = true; |
| 580 | } |
| 581 | } |
| 582 | if !done { |
| 583 | let mut info = StretchInfo::new(Rel::new(size.rel.0, size.abs.resolve(fs)), DELIM_SHORT_FALL); |
| 584 | if !crate::math::item::is_one(&size) { |
| 585 | info.requested_target = Some(size); |
| 586 | } |
| 587 | one.set_y_stretch(info); |
| 588 | } |
| 589 | } |
| 590 | return Ok(()); |
| 591 | } |
| 592 | if n >= 2 { |
| 593 | let is_delim = |i: &Item| matches!(i.class(), MathClass::Opening | MathClass::Closing | MathClass::Fence); |
| 594 | if let Some(Raw::Item(first)) = self.items.get_mut(lo) { |
| 595 | if is_delim(first) { |
| 596 | first.set_stretch(stretch); |
| 597 | first.set_class(MathClass::Opening); |
| 598 | } |
| 599 | } |
| 600 | if let Some(Raw::Item(last)) = self.items.get_mut(hi - 1) { |
| 601 | if is_delim(last) { |
| 602 | last.set_stretch(stretch); |
| 603 | last.set_class(MathClass::Closing); |
| 604 | } |
| 605 | } |
| 606 | } |
| 607 | for r in self.items[lo..hi].iter() { |
| 608 | if let Raw::Item(i) = r { |
| 609 | if i.mid_stretched() == Some(false) { |
| 610 | i.set_mid_stretched(Some(true)); |
| 611 | i.set_stretch(stretch); |
| 612 | } |
| 613 | } |
| 614 | } |
| 615 | let mut inner: Vec<Raw> = self.items.drain(lo..hi).collect(); |
| 616 | let len = inner.len(); |
| 617 | let opening = matches!(inner.first(), Some(Raw::Item(i)) if i.class() == MathClass::Opening); |
| 618 | let closing = matches!(inner.last(), Some(Raw::Item(i)) if i.class() == MathClass::Closing); |
| 619 | let mut index = 0; |
| 620 | inner.retain(|r| { |
| 621 | let discard = ((index == 1 && opening) || (index + 2 == len && closing)) |
| 622 | && matches!(r, Raw::Item(Item::Spacing(_, true))); |
| 623 | index += 1; |
| 624 | !discard |
| 625 | }); |
| 626 | let open = if opening && !inner.is_empty() { inner.remove(0).into_item() } else { None }; |
| 627 | let close = if closing { inner.pop().and_then(Raw::into_item) } else { None }; |
| 628 | match process_group(inner, styles, close.is_some(), false, true) { |
| 629 | Group::Multiline(rows) => { |
| 630 | let items = expand_multiline_fence(rows, open, close, styles, elem.span()); |
| 631 | let tail = self.items.split_off(lo); |
| 632 | self.items.extend(items); |
| 633 | self.items.extend(tail); |
| 634 | } |
| 635 | Group::Flat(items) => { |
| 636 | let body = Item::comp(Kind::Group(items), Props::new(styles, None, Span::detached()), styles.clone()); |
| 637 | let item = fenced(open, close, FencedBody::Owned(body), true, styles, elem.span()); |
| 638 | self.items.insert(lo, Raw::Item(item)); |
| 639 | } |
| 640 | } |
| 641 | Ok(()) |
| 642 | } |
| 643 | |
| 644 | fn mid(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 645 | let body = res!(self.body(elem, styles)); |
| 646 | let start = res!(self.resolve_into_items(&body, styles)); |
| 647 | for r in self.items[start..].iter_mut() { |
| 648 | if let Raw::Item(i) = r { |
| 649 | i.set_mid_stretched(Some(false)); |
| 650 | i.set_class(MathClass::Relation); |
| 651 | } |
| 652 | } |
| 653 | Ok(()) |
| 654 | } |
| 655 | |
| 656 | // Tables |
| 657 | |
| 658 | fn vec(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 659 | let rows: Vec<Vec<Content>> = res!(self.children(elem, styles, "children")).into_iter().map(|c| vec![c]).collect(); |
| 660 | let fs = props::font_size(styles); |
| 661 | let gap = relative(res!(self.f(elem, styles, "gap"))).map(|r| Rel::of(&r, fs)).unwrap_or(Rel::new(0.0, ROW_GAP * fs)); |
| 662 | let align = align_of(res!(self.f(elem, styles, "align"))); |
| 663 | let cells = res!(self.cells(rows, elem.span(), align, Alternator::Right, None, (Rel::default(), gap), |
| 664 | "elements", styles)); |
| 665 | let (open, close) = delims(res!(self.f(elem, styles, "delim")), ('(', ')')); |
| 666 | self.delimiters(cells, open, close, elem.span(), styles) |
| 667 | } |
| 668 | |
| 669 | fn mat(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 670 | let raw_rows: Vec<Value> = match res!(self.f(elem, styles, "rows")) { |
| 671 | Some(Value::Array(rows)) => rows.iter().cloned().collect(), |
| 672 | _ => Vec::new(), |
| 673 | }; |
| 674 | let mut rows: Vec<Vec<Content>> = Vec::with_capacity(raw_rows.len()); |
| 675 | for r in raw_rows { |
| 676 | let cells: Vec<Value> = match r { |
| 677 | Value::Array(cells) => cells.iter().cloned().collect(), |
| 678 | other => vec![other], |
| 679 | }; |
| 680 | let mut row = Vec::with_capacity(cells.len()); |
| 681 | for c in cells { |
| 682 | row.push(res!(self.disp(c, elem.span()))); |
| 683 | } |
| 684 | rows.push(row); |
| 685 | } |
| 686 | let nrows = rows.len(); |
| 687 | let ncols = rows.first().map(|r| r.len()).unwrap_or(0); |
| 688 | let fs = props::font_size(styles); |
| 689 | let aug = res!(self.f(elem, styles, "augment")); |
| 690 | let augment = res!(self.augment(aug, elem.span(), nrows, ncols)); |
| 691 | let rgap = relative(res!(self.f(elem, styles, "row-gap"))).map(|r| Rel::of(&r, fs)).unwrap_or(Rel::new(0.0, ROW_GAP * fs)); |
| 692 | let cgap = relative(res!(self.f(elem, styles, "column-gap"))).map(|r| Rel::of(&r, fs)).unwrap_or(Rel::new(0.0, COL_GAP * fs)); |
| 693 | let align = align_of(res!(self.f(elem, styles, "align"))); |
| 694 | let cells = res!(self.cells(rows, elem.span(), align, Alternator::Right, augment, (cgap, rgap), "cells", styles)); |
| 695 | let (open, close) = delims(res!(self.f(elem, styles, "delim")), ('(', ')')); |
| 696 | self.delimiters(cells, open, close, elem.span(), styles) |
| 697 | } |
| 698 | |
| 699 | fn augment(&mut self, v: Option<Value>, span: Span, nrows: usize, ncols: usize) -> Outcome<Option<Augment>> { |
| 700 | let offsets = |v: Option<&Value>| -> Vec<i64> { |
| 701 | match v { |
| 702 | Some(Value::Int(i)) => vec![*i], |
| 703 | Some(Value::Array(a)) => a.iter().filter_map(|x| match x { |
| 704 | Value::Int(i) => Some(*i), |
| 705 | _ => None, |
| 706 | }).collect(), |
| 707 | _ => Vec::new(), |
| 708 | } |
| 709 | }; |
| 710 | let aug = match v { |
| 711 | None | Some(Value::None) => return Ok(None), |
| 712 | Some(Value::Int(i)) => Augment { hline: Vec::new(), vline: vec![i], stroke: None }, |
| 713 | Some(Value::Dict(d)) => Augment { |
| 714 | hline: offsets(d.get("hline")), |
| 715 | vline: offsets(d.get("vline")), |
| 716 | stroke: d.get("stroke").and_then(to_stroke), |
| 717 | }, |
| 718 | Some(_) => return Ok(None), |
| 719 | }; |
| 720 | for &o in &aug.hline { |
| 721 | if o > nrows as i64 || o.unsigned_abs() as usize > nrows { |
| 722 | return Err(self.engine.error(DiagnosticKind::Type, span, fmt!( |
| 723 | "cannot draw a horizontal line at offset {} in a matrix with {} rows", o, nrows))); |
| 724 | } |
| 725 | } |
| 726 | for &o in &aug.vline { |
| 727 | if o > ncols as i64 || o.unsigned_abs() as usize > ncols { |
| 728 | return Err(self.engine.error(DiagnosticKind::Type, span, fmt!( |
| 729 | "cannot draw a vertical line at offset {} in a matrix with {} columns", o, ncols))); |
| 730 | } |
| 731 | } |
| 732 | Ok(Some(aug)) |
| 733 | } |
| 734 | |
| 735 | fn cases(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 736 | let rows: Vec<Vec<Content>> = res!(self.children(elem, styles, "children")).into_iter().map(|c| vec![c]).collect(); |
| 737 | let fs = props::font_size(styles); |
| 738 | let gap = relative(res!(self.f(elem, styles, "gap"))).map(|r| Rel::of(&r, fs)).unwrap_or(Rel::new(0.0, ROW_GAP * fs)); |
| 739 | let cells = res!(self.cells(rows, elem.span(), Fixed::Start, Alternator::None, None, |
| 740 | (Rel::default(), gap), "branches", styles)); |
| 741 | let (open, close) = delims(res!(self.f(elem, styles, "delim")), ('{', '}')); |
| 742 | let reverse = matches!(res!(self.f(elem, styles, "reverse")), Some(Value::Bool(true))); |
| 743 | let (open, close) = if reverse { (None, close) } else { (open, None) }; |
| 744 | self.delimiters(cells, open, close, elem.span(), styles) |
| 745 | } |
| 746 | |
| 747 | #[allow(clippy::too_many_arguments)] |
| 748 | fn cells( |
| 749 | &mut self, |
| 750 | rows: Vec<Vec<Content>>, |
| 751 | span: Span, |
| 752 | align: Fixed, |
| 753 | alternator: Alternator, |
| 754 | augment: Option<Augment>, |
| 755 | gap: (Rel, Rel), |
| 756 | what: &str, |
| 757 | styles: &StyleChain, |
| 758 | ) |
| 759 | -> Outcome<Item> |
| 760 | { |
| 761 | let cell_styles = props::chain_with(styles, props::for_denominator(styles)); |
| 762 | let mut cells: Vec<Vec<Row>> = Vec::with_capacity(rows.len()); |
| 763 | for row in rows { |
| 764 | let mut out = Vec::with_capacity(row.len()); |
| 765 | for cell in row { |
| 766 | let start = res!(self.resolve_into_items(&cell, &cell_styles)); |
| 767 | let drained: Vec<Raw> = self.items.drain(start..).collect(); |
| 768 | let (sub, had_breaks) = process_table_cell(drained, &cell_styles); |
| 769 | if had_breaks { |
| 770 | let d = crate::diag::Diagnostic::warning(DiagnosticKind::Lint, cell.span(), fmt!("linebreaks are ignored in {}", what)) |
| 771 | .with_hint("use commas instead to separate each line"); |
| 772 | self.engine.diags.push(d); |
| 773 | } |
| 774 | out.push(sub); |
| 775 | } |
| 776 | cells.push(out); |
| 777 | } |
| 778 | let ncols = cells.first().map(|r| r.len()).unwrap_or(0); |
| 779 | for c in 0..ncols { |
| 780 | let max = cells.iter().map(|r| r.get(c).map(|x| x.len()).unwrap_or(0)).max().unwrap_or(0); |
| 781 | for row in cells.iter_mut() { |
| 782 | if let Some(x) = row.get_mut(c) { |
| 783 | x.pad_to(max, &cell_styles); |
| 784 | } |
| 785 | } |
| 786 | } |
| 787 | let table = Table { cells, gap, augment, align, alternator }; |
| 788 | Ok(Item::comp(Kind::Table(Box::new(table)), Props::new(styles, None, span), styles.clone())) |
| 789 | } |
| 790 | |
| 791 | fn delimiters(&mut self, cells: Item, open: Option<char>, close: Option<char>, span: Span, styles: &StyleChain) -> Outcome<()> { |
| 792 | let stretch = Stretch::new().with_y(StretchInfo::new(Rel::new(1.1, 0.0), DELIM_SHORT_FALL)); |
| 793 | let open = match open { |
| 794 | Some(c) => { |
| 795 | let i = res!(self.symbol_item(c, span, styles)); |
| 796 | i.set_stretch(stretch); |
| 797 | Some(i) |
| 798 | } |
| 799 | None => None, |
| 800 | }; |
| 801 | let close = match close { |
| 802 | Some(c) => { |
| 803 | let i = res!(self.symbol_item(c, span, styles)); |
| 804 | i.set_stretch(stretch); |
| 805 | Some(i) |
| 806 | } |
| 807 | None => None, |
| 808 | }; |
| 809 | self.push(fenced(open, close, FencedBody::Owned(cells), false, styles, span)); |
| 810 | Ok(()) |
| 811 | } |
| 812 | |
| 813 | // Classes and operators |
| 814 | |
| 815 | fn class(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 816 | let class = match res!(self.f(elem, styles, "class")) { |
| 817 | Some(Value::Str(s)) => match MathClass::from_name(&s) { |
| 818 | Some(c) => c, |
| 819 | None => return Err(self.engine.error(DiagnosticKind::Type, elem.span(), fmt!("unknown math class: {}", s))), |
| 820 | }, |
| 821 | _ => MathClass::Normal, |
| 822 | }; |
| 823 | let mut item = { let tmp = res!(self.body(elem, styles)); res!(self.resolve_into_item(&tmp, styles)) }; |
| 824 | item.set_explicit_class(class); |
| 825 | item.set_limits(Limits::for_class(class)); |
| 826 | self.push(item); |
| 827 | Ok(()) |
| 828 | } |
| 829 | |
| 830 | fn op(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 831 | let text = res!(self.c(elem, styles, "text")); |
| 832 | let mut item = res!(self.resolve_into_item(&text, styles)); |
| 833 | item.set_class(MathClass::Large); |
| 834 | let limits = matches!(res!(self.f(elem, styles, "limits")), Some(Value::Bool(true))); |
| 835 | item.set_limits(if limits { Limits::Display } else { Limits::Never }); |
| 836 | self.push(item); |
| 837 | Ok(()) |
| 838 | } |
| 839 | |
| 840 | // Radicals, accents and lines |
| 841 | |
| 842 | fn root(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 843 | let cramped = props::chain_with(styles, vec![props::set_cramped(true)]); |
| 844 | let radicand = { let tmp = res!(self.c(elem, styles, "radicand")); res!(self.resolve_into_item(&tmp, &cramped)) } |
| 845 | .with_multiline_centering(); |
| 846 | let index = match res!(self.f(elem, styles, "index")) { |
| 847 | None | Some(Value::None) => None, |
| 848 | Some(v) => { |
| 849 | let ss = props::chain_with(&cramped, vec![props::set_size(MathSize::ScriptScript)]); |
| 850 | let c = res!(self.disp(v, elem.span())); |
| 851 | Some(res!(self.resolve_into_item(&c, &ss))) |
| 852 | } |
| 853 | }; |
| 854 | let sqrt = res!(self.symbol_item('\u{221a}', elem.span(), styles)); |
| 855 | sqrt.set_stretch(Stretch::new().with_y(StretchInfo::new(Rel::one(), 0.0))); |
| 856 | self.push(Item::comp(Kind::Radical { radicand, index, sqrt }, Props::new(styles, None, elem.span()), styles.clone())); |
| 857 | Ok(()) |
| 858 | } |
| 859 | |
| 860 | fn accent(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 861 | let accent = match res!(self.f(elem, styles, "accent")).and_then(|v| accent_char(&v)) { |
| 862 | Some(c) => c, |
| 863 | None => return Err(self.engine.error(DiagnosticKind::Type, elem.span(), "expected a single-codepoint symbol")), |
| 864 | }; |
| 865 | let position = if accent_is_bottom(accent) { Position::Below } else { Position::Above }; |
| 866 | let dotless = !matches!(res!(self.f(elem, styles, "dotless")), Some(Value::Bool(false))); |
| 867 | let base_styles = if position == Position::Above { |
| 868 | props::chain_with(styles, vec![props::set_cramped(true)]) |
| 869 | } else { |
| 870 | styles.clone() |
| 871 | }; |
| 872 | // The base asks for dotless forms (the `dtls` feature) so an accent over `i` loses the dot. |
| 873 | let base_styles = if position == Position::Above && dotless { |
| 874 | props::chain_with(&base_styles, vec![props::property(ElemKind::Equation, "dtls", Value::Bool(true))]) |
| 875 | } else { |
| 876 | base_styles |
| 877 | }; |
| 878 | let base = { let tmp = res!(self.c(elem, styles, "base")); res!(self.resolve_into_item(&tmp, &base_styles)) }; |
| 879 | let mut acc = res!(self.symbol_item(accent, elem.span(), styles)); |
| 880 | acc.set_class(MathClass::Diacritic); |
| 881 | let fs = props::font_size(styles); |
| 882 | let size = relative(res!(self.f(elem, styles, "size"))).map(|r| Rel::of(&r, fs)).unwrap_or(Rel::one()); |
| 883 | acc.set_stretch(Stretch::new().with_x(StretchInfo::new(size, ACCENT_SHORT_FALL))); |
| 884 | let class = base.raw_class(); |
| 885 | self.push(Item::comp(Kind::Accent { base, accent: acc, position, dotless, exact: false }, |
| 886 | Props::new(styles, class, Span::detached()), styles.clone())); |
| 887 | Ok(()) |
| 888 | } |
| 889 | |
| 890 | fn underline(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 891 | let base = { let tmp = res!(self.body(elem, styles)); res!(self.resolve_into_item(&tmp, styles)) }; |
| 892 | let class = base.raw_class(); |
| 893 | self.push(Item::comp(Kind::Line { base, position: Position::Below }, Props::new(styles, class, elem.span()), styles.clone())); |
| 894 | Ok(()) |
| 895 | } |
| 896 | |
| 897 | fn overline(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<()> { |
| 898 | let cramped = props::chain_with(styles, vec![props::set_cramped(true)]); |
| 899 | let base = { let tmp = res!(self.body(elem, styles)); res!(self.resolve_into_item(&tmp, &cramped)) }; |
| 900 | let class = base.raw_class(); |
| 901 | self.push(Item::comp(Kind::Line { base, position: Position::Above }, Props::new(styles, class, elem.span()), styles.clone())); |
| 902 | Ok(()) |
| 903 | } |
| 904 | |
| 905 | fn spreader(&mut self, elem: &Content, styles: &StyleChain, c: char, position: Position) -> Outcome<()> { |
| 906 | let base = { let tmp = res!(self.body(elem, styles)); res!(self.resolve_into_item(&tmp, styles)) }; |
| 907 | let mut acc = res!(self.symbol_item(c, elem.span(), styles)); |
| 908 | acc.set_class(MathClass::Diacritic); |
| 909 | acc.set_stretch(Stretch::new().with_x(StretchInfo::new(Rel::one(), 0.0))); |
| 910 | let class = base.raw_class(); |
| 911 | let base = Item::comp(Kind::Accent { base, accent: acc, position, dotless: false, exact: true }, |
| 912 | Props::new(styles, class, Span::detached()), styles.clone()); |
| 913 | let annotation = match res!(self.f(elem, styles, "annotation")) { |
| 914 | None | Some(Value::None) => None, |
| 915 | Some(v) => Some(res!(self.disp(v, elem.span()))), |
| 916 | }; |
| 917 | let annotation = match annotation { |
| 918 | Some(a) => a, |
| 919 | None => { |
| 920 | self.push(base); |
| 921 | return Ok(()); |
| 922 | } |
| 923 | }; |
| 924 | let item = match position { |
| 925 | Position::Below => { |
| 926 | let under = props::chain_with(styles, props::for_subscript(styles)); |
| 927 | let a = res!(self.resolve_into_item(&annotation, &under)); |
| 928 | scripts(base, None, Some(a), None, None, None, None, styles) |
| 929 | } |
| 930 | Position::Above => { |
| 931 | let over = props::chain_with(styles, vec![props::for_superscript(styles)]); |
| 932 | let a = res!(self.resolve_into_item(&annotation, &over)); |
| 933 | scripts(base, Some(a), None, None, None, None, None, styles) |
| 934 | } |
| 935 | }; |
| 936 | self.push(item); |
| 937 | Ok(()) |
| 938 | } |
| 939 | // Field access |
| 940 | |
| 941 | /// A field's value: the element's own, else the style chain's. |
| 942 | pub fn f(&mut self, elem: &Content, styles: &StyleChain, name: &str) -> Outcome<Option<Value>> { |
| 943 | let kind = match elem.kind() { |
| 944 | Some(k) => k, |
| 945 | None => return Ok(None), |
| 946 | }; |
| 947 | match kind.field_id(name) { |
| 948 | Some(id) => styles.resolve(elem, id), |
| 949 | None => Ok(None), |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | fn disp(&mut self, v: Value, span: Span) -> Outcome<Content> { display(self.engine, v, span) } |
| 954 | |
| 955 | fn c(&mut self, elem: &Content, styles: &StyleChain, name: &str) -> Outcome<Content> { |
| 956 | match res!(self.f(elem, styles, name)) { |
| 957 | Some(v) => self.disp(v, elem.span()), |
| 958 | None => Ok(Content::empty()), |
| 959 | } |
| 960 | } |
| 961 | |
| 962 | fn body(&mut self, elem: &Content, styles: &StyleChain) -> Outcome<Content> { self.c(elem, styles, "body") } |
| 963 | |
| 964 | // An attachment under the chain its position sets, `None` when unset. |
| 965 | fn script(&mut self, elem: &Content, name: &str, chain: &StyleChain) -> Outcome<Option<Content>> { |
| 966 | match res!(self.f(elem, chain, name)) { |
| 967 | None | Some(Value::None) => Ok(None), |
| 968 | Some(v) => Ok(Some(res!(self.disp(v, elem.span())))), |
| 969 | } |
| 970 | } |
| 971 | |
| 972 | fn children(&mut self, elem: &Content, styles: &StyleChain, name: &str) -> Outcome<Vec<Content>> { |
| 973 | let items = match res!(self.f(elem, styles, name)) { |
| 974 | Some(Value::Array(a)) => a.iter().cloned().collect(), |
| 975 | Some(v) => vec![v], |
| 976 | None => Vec::new(), |
| 977 | }; |
| 978 | let mut out = Vec::with_capacity(items.len()); |
| 979 | for v in items { |
| 980 | out.push(res!(self.disp(v, elem.span()))); |
| 981 | } |
| 982 | Ok(out) |
| 983 | } |
| 984 | } |
| 985 | |
| 986 | // Construction helpers |
| 987 | |
| 988 | const ONE: Relative = Relative { rel: Ratio(1.0), abs: Length { abs: 0.0, em: 0.0 } }; |
| 989 | |
| 990 | /// A symbol's glyph item: its class and default limits from its first character. |
| 991 | pub fn glyph(text: String, styles: &StyleChain, span: Span) -> Item { |
| 992 | let c = text.chars().next().unwrap_or(' '); |
| 993 | let class = default_math_class(c); |
| 994 | let limits = Limits::for_char_with_class(c, class); |
| 995 | let g = Glyph { |
| 996 | text, |
| 997 | class: class.unwrap_or(MathClass::Normal), |
| 998 | stretch: Cell::new(Stretch::new()), |
| 999 | mid_stretched: Cell::new(None), |
| 1000 | flac: Cell::new(false), |
| 1001 | }; |
| 1002 | let mut props = Props::new(styles, class, span); |
| 1003 | props.limits = limits; |
| 1004 | Item::comp(Kind::Glyph(g), props, styles.clone()) |
| 1005 | } |
| 1006 | |
| 1007 | pub fn multiline(rows: Vec<Row>, styles: &StyleChain) -> Item { |
| 1008 | Item::comp(Kind::Multiline { rows, centered: false }, Props::new(styles, None, Span::detached()), styles.clone()) |
| 1009 | } |
| 1010 | |
| 1011 | pub fn fenced(open: Option<Item>, close: Option<Item>, body: FencedBody, balanced: bool, styles: &StyleChain, span: Span) -> Item { |
| 1012 | Item::comp(Kind::Fenced { open, close, body, balanced }, Props::new(styles, None, span), styles.clone()) |
| 1013 | } |
| 1014 | |
| 1015 | #[allow(clippy::too_many_arguments)] |
| 1016 | fn scripts( |
| 1017 | base: Item, |
| 1018 | t: Option<Item>, |
| 1019 | b: Option<Item>, |
| 1020 | tl: Option<Item>, |
| 1021 | bl: Option<Item>, |
| 1022 | tr: Option<Item>, |
| 1023 | br: Option<Item>, |
| 1024 | styles: &StyleChain, |
| 1025 | ) |
| 1026 | -> Item |
| 1027 | { |
| 1028 | let class = base.raw_class(); |
| 1029 | let s = Scripts { base, t, b, tl, bl, tr, br }; |
| 1030 | Item::comp(Kind::Scripts(Box::new(s)), Props::new(styles, class, Span::detached()), styles.clone()) |
| 1031 | } |
| 1032 | |
| 1033 | pub fn shared_sizing(items: Vec<Item>, styles: &StyleChain) -> std::rc::Rc<SharedSizing> { |
| 1034 | SharedSizing::new(items, styles.clone()) |
| 1035 | } |
| 1036 | |
| 1037 | // Typst's `merge_inward` over one position's outer attachments (outermost first): the innermost outer |
| 1038 | // value comes in, and every value further out moves one level inward. |
| 1039 | fn take_outer(stack: &mut [Option<Content>]) -> Option<Content> { |
| 1040 | let n = stack.len(); |
| 1041 | if n == 0 { |
| 1042 | return None; |
| 1043 | } |
| 1044 | let out = stack[n - 1].take(); |
| 1045 | for j in (1..n).rev() { |
| 1046 | stack[j] = stack[j - 1].take(); |
| 1047 | } |
| 1048 | out |
| 1049 | } |
| 1050 | |
| 1051 | // Typst's `unmerge`: gives a value back to the innermost outer level, pushing what is there outward |
| 1052 | // until an empty level takes it. |
| 1053 | fn unmerge(stack: &mut [Option<Content>], content: Content) { |
| 1054 | let mut cur = Some(content); |
| 1055 | for j in (0..stack.len()).rev() { |
| 1056 | if cur.is_none() { |
| 1057 | break; |
| 1058 | } |
| 1059 | cur = std::mem::replace(&mut stack[j], cur); |
| 1060 | } |
| 1061 | } |
| 1062 | |
| 1063 | fn relative(v: Option<Value>) -> Option<Relative> { |
| 1064 | match v { |
| 1065 | Some(Value::Relative(r)) => Some(r), |
| 1066 | Some(Value::Length(l)) => Some(Relative { rel: Ratio(0.0), abs: l }), |
| 1067 | Some(Value::Ratio(r)) => Some(Relative { rel: r, abs: Length::zero() }), |
| 1068 | _ => None, |
| 1069 | } |
| 1070 | } |
| 1071 | |
| 1072 | fn align_of(v: Option<Value>) -> Fixed { |
| 1073 | use crate::eval::value::HAlign; |
| 1074 | match v { |
| 1075 | Some(Value::Alignment(a)) => match a.x { |
| 1076 | Some(HAlign::Start) | Some(HAlign::Left) => Fixed::Start, |
| 1077 | Some(HAlign::End) | Some(HAlign::Right) => Fixed::End, |
| 1078 | _ => Fixed::Center, |
| 1079 | }, |
| 1080 | _ => Fixed::Center, |
| 1081 | } |
| 1082 | } |
| 1083 | |
| 1084 | /// The single character of a delimiter value, `None` for `none`. |
| 1085 | pub fn delim_char(v: &Value) -> Option<Option<char>> { |
| 1086 | let one = |s: &str| -> Option<Option<char>> { |
| 1087 | let mut it = s.chars(); |
| 1088 | match (it.next(), it.next()) { |
| 1089 | (Some(c), None) => Some(Some(c)), |
| 1090 | _ => None, |
| 1091 | } |
| 1092 | }; |
| 1093 | match v { |
| 1094 | Value::None => Some(None), |
| 1095 | Value::Str(s) => one(s), |
| 1096 | Value::Symbol(s) => one(&crate::eval::ops::symbol_text(s)), |
| 1097 | Value::Content(c) => one(&c.plain_text()), |
| 1098 | _ => None, |
| 1099 | } |
| 1100 | } |
| 1101 | |
| 1102 | /// The delimiter matching an opening one: brackets and braces by name, other openers and closers by |
| 1103 | /// their neighbouring code point, fences by themselves. |
| 1104 | pub fn matching(c: char) -> Option<char> { |
| 1105 | match c { |
| 1106 | '[' => Some(']'), |
| 1107 | ']' => Some('['), |
| 1108 | '{' => Some('}'), |
| 1109 | '}' => Some('{'), |
| 1110 | c => match default_math_class(c) { |
| 1111 | Some(MathClass::Opening) => char::from_u32(c as u32 + 1), |
| 1112 | Some(MathClass::Closing) => char::from_u32(c as u32 - 1), |
| 1113 | _ => Some(c), |
| 1114 | }, |
| 1115 | } |
| 1116 | } |
| 1117 | |
| 1118 | // A `delim` value as an opening and closing pair: one delimiter and its match, or an array of two. |
| 1119 | fn delims(v: Option<Value>, default: (char, char)) -> (Option<char>, Option<char>) { |
| 1120 | match v { |
| 1121 | None => (Some(default.0), Some(default.1)), |
| 1122 | Some(Value::Array(a)) if a.len() == 2 => { |
| 1123 | let o = a.first().and_then(delim_char).flatten(); |
| 1124 | let c = a.get(1).and_then(delim_char).flatten(); |
| 1125 | (o, c) |
| 1126 | } |
| 1127 | Some(other) => match delim_char(&other) { |
| 1128 | Some(Some(c)) => (Some(c), matching(c)), |
| 1129 | _ => (None, None), |
| 1130 | }, |
| 1131 | } |
| 1132 | } |
| 1133 | |
| 1134 | /// The combining accents Typst knows, each with the spellings that name it. |
| 1135 | pub const ACCENTS: &[(char, &[&str])] = &[ |
| 1136 | ('\u{0300}', &["`"]), |
| 1137 | ('\u{0301}', &["\u{b4}"]), |
| 1138 | ('\u{0302}', &["^", "\u{2c6}"]), |
| 1139 | ('\u{0303}', &["~", "\u{223c}", "\u{2dc}"]), |
| 1140 | ('\u{0304}', &["\u{af}"]), |
| 1141 | ('\u{0305}', &["-", "\u{2013}", "\u{203e}", "\u{2212}"]), |
| 1142 | ('\u{0306}', &["\u{2d8}"]), |
| 1143 | ('\u{0307}', &[".", "\u{2d9}", "\u{22c5}"]), |
| 1144 | ('\u{0308}', &["\u{a8}"]), |
| 1145 | ('\u{20db}', &[]), |
| 1146 | ('\u{20dc}', &[]), |
| 1147 | ('\u{030a}', &["\u{2218}", "\u{25cb}"]), |
| 1148 | ('\u{030b}', &["\u{2dd}"]), |
| 1149 | ('\u{030c}', &["\u{2c7}"]), |
| 1150 | ('\u{20d6}', &["\u{2190}"]), |
| 1151 | ('\u{20d7}', &["\u{2192}", "\u{27f6}"]), |
| 1152 | ('\u{20e1}', &["\u{2194}", "\u{2194}\u{fe0e}", "\u{27f7}"]), |
| 1153 | ('\u{20d0}', &["\u{21bc}"]), |
| 1154 | ('\u{20d1}', &["\u{21c0}"]), |
| 1155 | ]; |
| 1156 | |
| 1157 | /// The combining accent a spelling names, if it names one. |
| 1158 | pub fn accent_combining(s: &str) -> Option<char> { |
| 1159 | let mut it = s.chars(); |
| 1160 | let single = match (it.next(), it.next()) { |
| 1161 | (Some(c), None) => Some(c), |
| 1162 | _ => None, |
| 1163 | }; |
| 1164 | ACCENTS.iter().find(|(a, names)| Some(*a) == single || names.contains(&s)).map(|(a, _)| *a) |
| 1165 | } |
| 1166 | |
| 1167 | /// Typst's accent cast: a known spelling to its combining form, else any single character as it is. |
| 1168 | pub fn accent_char(v: &Value) -> Option<char> { |
| 1169 | let s = match v { |
| 1170 | Value::Str(s) => s.to_string(), |
| 1171 | Value::Symbol(s) => crate::eval::ops::symbol_text(s), |
| 1172 | Value::Content(c) => c.plain_text(), |
| 1173 | _ => return None, |
| 1174 | }; |
| 1175 | if let Some(c) = accent_combining(&s) { |
| 1176 | return Some(c); |
| 1177 | } |
| 1178 | let mut it = s.chars(); |
| 1179 | match (it.next(), it.next()) { |
| 1180 | (Some(c), None) => Some(c), |
| 1181 | _ => None, |
| 1182 | } |
| 1183 | } |
| 1184 | |
| 1185 | // Bottom accents: the under-spreaders and every combining mark of canonical class 220 (below). |
| 1186 | fn accent_is_bottom(c: char) -> bool { |
| 1187 | if matches!(c, '\u{23df}' | '\u{23b5}' | '\u{23dd}' | '\u{23e1}') { |
| 1188 | return true; |
| 1189 | } |
| 1190 | oxedyne_fe2o3_text::unicode::norm::combining_class(c) == 220 |
| 1191 | } |
| 1192 | |
| 1193 | /// Is the text a number as maths sets it: digits with at most one decimal point? |
| 1194 | pub fn is_number(text: &str) -> bool { |
| 1195 | let mut dots = 0; |
| 1196 | let digits = text.chars().all(|c| { |
| 1197 | if c == '.' { |
| 1198 | dots += 1; |
| 1199 | } |
| 1200 | c.is_ascii_digit() || c == '.' |
| 1201 | }); |
| 1202 | digits && dots != text.chars().count() && dots <= 1 |
| 1203 | } |
| 1204 | |
| 1205 | // Typst's `split_newlines`: `\n`, `\r\n`, `\r` and the other Unicode line terminators. |
| 1206 | fn split_newlines(text: &str) -> Vec<&str> { |
| 1207 | let mut out = Vec::new(); |
| 1208 | let mut start = 0; |
| 1209 | let bytes: Vec<(usize, char)> = text.char_indices().collect(); |
| 1210 | let mut i = 0; |
| 1211 | while i < bytes.len() { |
| 1212 | let (at, c) = bytes[i]; |
| 1213 | let nl = matches!(c, '\n' | '\x0b' | '\x0c' | '\r' | '\u{85}' | '\u{2028}' | '\u{2029}'); |
| 1214 | if nl { |
| 1215 | out.push(&text[start..at]); |
| 1216 | let mut next = at + c.len_utf8(); |
| 1217 | if c == '\r' { |
| 1218 | if let Some(&(_, '\n')) = bytes.get(i + 1) { |
| 1219 | next += 1; |
| 1220 | i += 1; |
| 1221 | } |
| 1222 | } |
| 1223 | start = next; |
| 1224 | } |
| 1225 | i += 1; |
| 1226 | } |
| 1227 | out.push(&text[start..]); |
| 1228 | out |
| 1229 | } |