Files
texrra-engine/crates/texrra-core/src/math_expr.rs
T
gloamxun bb1d9e0561 Initial texrra engine
Rename the crate, binary, core crate, font families, env vars, and internal commands from texcraft/tex-engine to texrra. Serve the separately versioned texrra-web frontend from TEXRRA_WEB_DIR, ../web, or ./web instead of embedding index.html. Add starred section heading support and an arXiv template conformance fixture.
2026-10-19 11:41:46 +08:00

1425 lines
46 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use std::{
collections::{BTreeMap, HashMap, HashSet},
hash::{Hash, Hasher},
path::PathBuf,
sync::Arc,
};
use crate::{MathClass, MathStyle, MathStyleCommand, TeXGlue, source::SourceLocation};
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum MathExpr {
Text(String),
TextStyled {
text: String,
bold: bool,
italic: bool,
monospace: bool,
},
Spanned {
location: Option<SourceLocation>,
expression: Box<MathExpr>,
},
Styled {
font: MathFontStyle,
expression: Box<MathExpr>,
},
Classified {
class: MathClass,
body: Box<MathExpr>,
},
Phantom {
kind: MathPhantomKind,
body: Box<MathExpr>,
},
Accent {
position: MathAccent,
body: Box<MathExpr>,
family: u8,
math_fonts: MathFontFamilies,
},
Atom {
class: MathClass,
text: String,
math_family: Option<u8>,
math_slots: Vec<u8>,
math_fonts: MathFontFamilies,
},
MathSpacingChange(MathSpacingSettings),
MathLineBreakPenaltiesChange(MathLineBreakPenalties),
BreakPenalty(i32),
MathStyleChange(MathStyleCommand),
Space(i8),
Glue(TeXGlue),
Kern(common::Scaled),
Sequence(Vec<MathExpr>),
Alignment {
rows: Vec<Vec<MathExpr>>,
alignment: MathAlignment,
baseline: MathAlignmentBaseline,
math_fonts: MathFontFamilies,
cell_style: MathCellStyle,
row_spacing: MathRowSpacing,
},
Fraction {
numerator: Box<MathExpr>,
denominator: Box<MathExpr>,
style: MathFractionStyle,
has_rule: bool,
rule_thickness: Option<common::Scaled>,
math_fonts: MathFontFamilies,
},
MathChoice {
display: Box<MathExpr>,
text: Box<MathExpr>,
script: Box<MathExpr>,
scriptscript: Box<MathExpr>,
},
Root {
index: Option<Box<MathExpr>>,
body: Box<MathExpr>,
radical: Option<(u8, char)>,
math_fonts: MathFontFamilies,
},
Delimited {
left: MathDelimiterGlyph,
body: Box<MathExpr>,
right: MathDelimiterGlyph,
left_settings: MathDelimiterSettings,
right_settings: MathDelimiterSettings,
},
SizedDelimiter {
delimiter: String,
half_points: u8,
class: MathClass,
settings: MathDelimiterSettings,
math_fonts: MathFontFamilies,
},
UnicodeDelimiter {
character: char,
class: MathClass,
family: u8,
settings: MathDelimiterSettings,
math_fonts: MathFontFamilies,
},
Fenced {
delimiters: Vec<MathDelimiterGlyph>,
delimiter_settings: Vec<MathDelimiterSettings>,
segments: Vec<MathExpr>,
},
Script {
base: Box<MathExpr>,
sub: Option<Box<MathExpr>>,
superscript: Option<Box<MathExpr>>,
limits: MathLimitMode,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MathMuGlue(pub common::Glue);
impl Hash for MathMuGlue {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.width.hash(state);
self.0.stretch.hash(state);
(self.0.stretch_order as u8).hash(state);
self.0.shrink.hash(state);
(self.0.shrink_order as u8).hash(state);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MathLineBreakPenalties {
pub binary: i32,
pub relation: i32,
}
impl Default for MathLineBreakPenalties {
fn default() -> Self {
Self {
binary: 700,
relation: 500,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MathSpacingSettings {
pub thin: MathMuGlue,
pub medium: MathMuGlue,
pub thick: MathMuGlue,
}
impl Default for MathSpacingSettings {
fn default() -> Self {
let glue = |width, stretch, shrink| {
MathMuGlue(common::Glue {
width: common::Scaled::ONE * width,
stretch: common::Scaled::ONE * stretch,
shrink: common::Scaled::ONE * shrink,
..common::Glue::default()
})
};
Self {
thin: glue(3, 0, 0),
medium: glue(4, 2, 4),
thick: glue(5, 5, 0),
}
}
}
/// Font files assigned to one math family at each TeX math style size.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct MathFontSelection {
pub text: Option<PathBuf>,
pub script: Option<PathBuf>,
pub scriptscript: Option<PathBuf>,
}
pub type MathFontFamilies = Arc<BTreeMap<u8, MathFontSelection>>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MathDelimiterCharacter {
pub family: u8,
pub character: char,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MathDelimiterGlyph {
pub text: String,
pub small: Option<MathDelimiterCharacter>,
pub large: Option<MathDelimiterCharacter>,
pub is_null: bool,
pub math_fonts: MathFontFamilies,
}
impl MathDelimiterGlyph {
pub fn plain(text: impl Into<String>) -> Self {
Self::plain_with_math_fonts(text, Arc::default())
}
pub fn plain_with_math_fonts(text: impl Into<String>, math_fonts: MathFontFamilies) -> Self {
Self {
text: text.into(),
small: None,
large: None,
is_null: false,
math_fonts,
}
}
pub fn collect_math_font_files(&self, files: &mut HashSet<PathBuf>) {
for family in [self.small, self.large].into_iter().flatten() {
if let Some(selection) = self.math_fonts.get(&family.family) {
selection.collect_files(files);
}
}
if let Some(selection) = self.math_fonts.get(&2) {
selection.collect_files(files);
}
}
}
impl MathFontSelection {
fn collect_files(&self, files: &mut HashSet<PathBuf>) {
files.extend(
[
self.text.as_ref(),
self.script.as_ref(),
self.scriptscript.as_ref(),
]
.into_iter()
.flatten()
.cloned(),
);
}
pub fn for_style(&self, style: MathStyle) -> Option<&PathBuf> {
match style {
MathStyle::Display
| MathStyle::DisplayCramped
| MathStyle::Text
| MathStyle::TextCramped => self.text.as_ref(),
MathStyle::Script | MathStyle::ScriptCramped => self.script.as_ref(),
MathStyle::ScriptScript | MathStyle::ScriptScriptCramped => self.scriptscript.as_ref(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum MathAlignment {
Alternating,
AlternatingTight,
Centered,
Left,
Multline,
Columns(Vec<MathColumnAlignment>),
ArrayColumns {
columns: Vec<MathColumnAlignment>,
vertical_rules: Vec<usize>,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MathAlignmentBaseline {
FirstRow,
MathAxisCentered,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MathCellStyle {
Inherit,
Display,
Text,
Script,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MathRowSpacing {
Array,
Cases,
Equation(common::Scaled),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MathDelimiterSettings {
pub factor: i32,
pub shortfall: common::Scaled,
}
impl Default for MathDelimiterSettings {
fn default() -> Self {
Self {
factor: 901,
shortfall: common::Scaled(5 * 65_536),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MathFractionStyle {
Automatic,
Display,
Text,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum MathInfixFractionKind {
Over,
Atop,
Choose(MathDelimiterSettings),
Above(common::Scaled),
OverWithDelims(MathFractionDelimiters),
AtopWithDelims(MathFractionDelimiters),
AboveWithDelims {
thickness: common::Scaled,
delimiters: MathFractionDelimiters,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MathFractionDelimiters {
pub left: MathDelimiterGlyph,
pub right: MathDelimiterGlyph,
pub settings: MathDelimiterSettings,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MathPhantomKind {
Both,
Horizontal,
Vertical,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MathColumnAlignment {
Left,
Center,
Right,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MathFontStyle {
Blackboard,
Bold,
BoldRoman,
Calligraphic,
Fraktur,
Italic,
Monospace,
Roman,
SansSerif,
Text,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MathLimitMode {
Automatic,
DisplayLimits,
Limits,
NoLimits,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MathAccent {
Overline,
Underline,
Hat,
Tilde,
WideHat,
WideTilde,
OverBrace,
UnderBrace,
Unicode {
class: MathClass,
family: u8,
character: char,
stretch: bool,
bottom: bool,
},
}
fn math_accent_class(accent: MathAccent) -> MathClass {
match accent {
MathAccent::Unicode { class, .. } => class,
_ => MathClass::Ordinary,
}
}
impl MathExpr {
pub fn collect_math_font_files(&self, files: &mut HashSet<PathBuf>) {
match self {
Self::Atom {
math_family,
math_fonts,
..
} => {
if let Some(selection) = math_family.and_then(|family| math_fonts.get(&family)) {
files.extend(
[
selection.text.as_ref(),
selection.script.as_ref(),
selection.scriptscript.as_ref(),
]
.into_iter()
.flatten()
.cloned(),
);
}
}
Self::Spanned { expression, .. } | Self::Styled { expression, .. } => {
expression.collect_math_font_files(files)
}
Self::Classified { body, .. } | Self::Phantom { body, .. } => {
body.collect_math_font_files(files)
}
Self::Accent {
position,
body,
family,
math_fonts,
} => {
if !matches!(position, MathAccent::Overline | MathAccent::Underline) {
if let Some(selection) = math_fonts.get(family) {
files.extend(
[
selection.text.as_ref(),
selection.script.as_ref(),
selection.scriptscript.as_ref(),
]
.into_iter()
.flatten()
.cloned(),
);
}
}
body.collect_math_font_files(files);
}
Self::Sequence(items) => {
for item in items {
item.collect_math_font_files(files);
}
}
Self::Alignment {
rows, math_fonts, ..
} => {
if let Some(selection) = math_fonts.get(&2) {
selection.collect_files(files);
}
for item in rows.iter().flatten() {
item.collect_math_font_files(files);
}
}
Self::Fraction {
numerator,
denominator,
math_fonts,
..
} => {
if let Some(selection) = math_fonts.get(&2) {
selection.collect_files(files);
}
numerator.collect_math_font_files(files);
denominator.collect_math_font_files(files);
}
Self::MathChoice {
display,
text,
script,
scriptscript,
} => {
display.collect_math_font_files(files);
text.collect_math_font_files(files);
script.collect_math_font_files(files);
scriptscript.collect_math_font_files(files);
}
Self::Root {
index,
body,
radical,
math_fonts,
} => {
if let Some((family, _)) = radical {
if let Some(selection) = math_fonts.get(family) {
files.extend(
[
selection.text.as_ref(),
selection.script.as_ref(),
selection.scriptscript.as_ref(),
]
.into_iter()
.flatten()
.cloned(),
);
}
}
if let Some(index) = index {
index.collect_math_font_files(files);
}
body.collect_math_font_files(files);
}
Self::UnicodeDelimiter {
family, math_fonts, ..
} => {
if let Some(selection) = math_fonts.get(family) {
selection.collect_files(files);
}
if let Some(selection) = math_fonts.get(&2) {
selection.collect_files(files);
}
}
Self::SizedDelimiter { math_fonts, .. } => {
if let Some(selection) = math_fonts.get(&2) {
selection.collect_files(files);
}
}
Self::Delimited {
left, body, right, ..
} => {
left.collect_math_font_files(files);
right.collect_math_font_files(files);
body.collect_math_font_files(files);
}
Self::Fenced {
delimiters,
segments,
..
} => {
for delimiter in delimiters {
delimiter.collect_math_font_files(files);
}
for segment in segments {
segment.collect_math_font_files(files);
}
}
Self::Script {
base,
sub,
superscript,
..
} => {
base.collect_math_font_files(files);
if let Some(sub) = sub {
sub.collect_math_font_files(files);
}
if let Some(superscript) = superscript {
superscript.collect_math_font_files(files);
}
}
Self::Text(_)
| Self::TextStyled { .. }
| Self::MathSpacingChange(_)
| Self::MathLineBreakPenaltiesChange(_)
| Self::BreakPenalty(_)
| Self::MathStyleChange(_)
| Self::Space(_)
| Self::Glue(_)
| Self::Kern(_) => {}
}
}
pub fn plain_text(&self) -> String {
match self {
Self::Text(text) => text.clone(),
Self::TextStyled { text, .. } => text.clone(),
Self::Spanned { expression, .. } => expression.plain_text(),
Self::Styled { expression, .. } => expression.plain_text(),
Self::Classified { body, .. } | Self::Phantom { body, .. } => body.plain_text(),
Self::Accent { position, body, .. } => {
let mark = match position {
MathAccent::Overline => '\u{0305}',
MathAccent::Underline => '\u{0332}',
MathAccent::Hat => '^',
MathAccent::Tilde => '~',
MathAccent::WideHat => '\u{0302}',
MathAccent::WideTilde => '\u{0303}',
MathAccent::OverBrace => '\u{23de}',
MathAccent::UnderBrace => '\u{23df}',
MathAccent::Unicode { character, .. } => *character,
};
format!("{}{mark}", body.plain_text())
}
Self::Atom { text, .. } => text.clone(),
Self::SizedDelimiter { delimiter, .. } => delimiter.clone(),
Self::UnicodeDelimiter { character, .. } => character.to_string(),
Self::MathSpacingChange(_)
| Self::MathLineBreakPenaltiesChange(_)
| Self::BreakPenalty(_)
| Self::MathStyleChange(_) => String::new(),
Self::Space(units) => {
if *units <= 0 {
String::new()
} else {
" ".to_string()
}
}
Self::Kern(_) => String::new(),
Self::Glue(_) => String::new(),
Self::Sequence(items) => items
.iter()
.map(Self::plain_text)
.collect::<Vec<_>>()
.join(""),
Self::Alignment { rows, .. } => rows
.iter()
.map(|row| {
row.iter()
.map(Self::plain_text)
.collect::<Vec<_>>()
.join(" & ")
})
.collect::<Vec<_>>()
.join("\n"),
Self::Fraction {
numerator,
denominator,
..
} => {
format!("{}⁄{}", numerator.plain_text(), denominator.plain_text())
}
Self::MathChoice { display, .. } => display.plain_text(),
Self::Root {
index,
body,
radical,
..
} => {
let index = index
.as_deref()
.map(|index| format!("[{}]", index.plain_text()))
.unwrap_or_default();
let radical = radical.map(|(_, character)| character).unwrap_or('√');
format!("{radical}{index}({})", body.plain_text())
}
Self::Delimited {
left, body, right, ..
} => {
format!("{}{}{}", left.text, body.plain_text(), right.text)
}
Self::Fenced {
delimiters,
segments,
..
} => {
let mut text = String::new();
for (index, segment) in segments.iter().enumerate() {
if let Some(delimiter) = delimiters.get(index) {
text.push_str(&delimiter.text);
}
text.push_str(&segment.plain_text());
}
if let Some(delimiter) = delimiters.last() {
text.push_str(&delimiter.text);
}
text
}
Self::Script {
base,
sub,
superscript,
..
} => {
let mut text = base.plain_text();
if let Some(superscript) = superscript {
text.push_str(&format_script(&superscript.plain_text(), true));
}
if let Some(sub) = sub {
text.push_str(&format_script(&sub.plain_text(), false));
}
text
}
}
}
pub fn contains_cjk(&self) -> bool {
match self {
Self::Text(text) | Self::TextStyled { text, .. } => text.chars().any(is_cjk),
Self::Spanned { expression, .. } => expression.contains_cjk(),
Self::Styled { expression, .. } => expression.contains_cjk(),
Self::Classified { body, .. } | Self::Phantom { body, .. } => body.contains_cjk(),
Self::Accent { body, .. } => body.contains_cjk(),
Self::Atom { text, .. } => text.chars().any(is_cjk),
Self::MathStyleChange(_)
| Self::MathSpacingChange(_)
| Self::MathLineBreakPenaltiesChange(_)
| Self::BreakPenalty(_)
| Self::Space(_)
| Self::Glue(_)
| Self::Kern(_)
| Self::SizedDelimiter { .. }
| Self::UnicodeDelimiter { .. } => false,
Self::Sequence(items) => items.iter().any(Self::contains_cjk),
Self::Alignment { rows, .. } => rows.iter().flatten().any(Self::contains_cjk),
Self::Fraction {
numerator,
denominator,
..
} => numerator.contains_cjk() || denominator.contains_cjk(),
Self::MathChoice {
display,
text,
script,
scriptscript,
} => {
display.contains_cjk()
|| text.contains_cjk()
|| script.contains_cjk()
|| scriptscript.contains_cjk()
}
Self::Root { index, body, .. } => {
body.contains_cjk() || index.as_deref().is_some_and(Self::contains_cjk)
}
Self::Delimited { body, .. } => body.contains_cjk(),
Self::Fenced { segments, .. } => segments.iter().any(Self::contains_cjk),
Self::Script {
base,
sub,
superscript,
..
} => {
base.contains_cjk()
|| sub.as_deref().is_some_and(Self::contains_cjk)
|| superscript.as_deref().is_some_and(Self::contains_cjk)
}
}
}
pub fn contains_monospace_text(&self) -> bool {
match self {
Self::TextStyled { monospace, .. } => *monospace,
Self::Spanned { expression, .. } | Self::Styled { expression, .. } => {
expression.contains_monospace_text()
}
Self::Classified { body, .. }
| Self::Phantom { body, .. }
| Self::Accent { body, .. } => body.contains_monospace_text(),
Self::Sequence(items) => items.iter().any(Self::contains_monospace_text),
Self::Alignment { rows, .. } => {
rows.iter().flatten().any(Self::contains_monospace_text)
}
Self::Fraction {
numerator,
denominator,
..
} => numerator.contains_monospace_text() || denominator.contains_monospace_text(),
Self::MathChoice {
display,
text,
script,
scriptscript,
} => {
display.contains_monospace_text()
|| text.contains_monospace_text()
|| script.contains_monospace_text()
|| scriptscript.contains_monospace_text()
}
Self::Root { index, body, .. } => {
body.contains_monospace_text()
|| index.as_deref().is_some_and(Self::contains_monospace_text)
}
Self::Delimited { body, .. } => body.contains_monospace_text(),
Self::Fenced { segments, .. } => segments.iter().any(Self::contains_monospace_text),
Self::Script {
base,
sub,
superscript,
..
} => {
base.contains_monospace_text()
|| sub.as_deref().is_some_and(Self::contains_monospace_text)
|| superscript
.as_deref()
.is_some_and(Self::contains_monospace_text)
}
Self::Text(_)
| Self::Atom { .. }
| Self::MathSpacingChange(_)
| Self::MathLineBreakPenaltiesChange(_)
| Self::BreakPenalty(_)
| Self::MathStyleChange(_)
| Self::Space(_)
| Self::Glue(_)
| Self::Kern(_)
| Self::SizedDelimiter { .. }
| Self::UnicodeDelimiter { .. } => false,
}
}
pub fn leading_class(&self) -> Option<MathClass> {
match self {
Self::Spanned { expression, .. } => expression.leading_class(),
Self::Styled { expression, .. } => expression.leading_class(),
Self::Classified { class, .. } => Some(*class),
Self::Phantom { .. } => Some(MathClass::Ordinary),
Self::SizedDelimiter { class, .. } => Some(*class),
Self::UnicodeDelimiter { class, .. } => Some(*class),
Self::Accent { position, .. } => Some(math_accent_class(*position)),
Self::Text(_) | Self::TextStyled { .. } | Self::Atom { .. } | Self::Root { .. } => {
Some(self.class())
}
Self::MathSpacingChange(_)
| Self::MathLineBreakPenaltiesChange(_)
| Self::BreakPenalty(_)
| Self::MathStyleChange(_)
| Self::Space(_)
| Self::Glue(_)
| Self::Kern(_) => None,
Self::Sequence(items) => items.iter().find_map(Self::leading_class).map(|class| {
if class == MathClass::Binary {
MathClass::Ordinary
} else {
class
}
}),
Self::MathChoice { display, .. } => display.leading_class(),
Self::Alignment { .. }
| Self::Fraction { .. }
| Self::Delimited { .. }
| Self::Fenced { .. } => Some(MathClass::Inner),
Self::Script { base, .. } => base.leading_class(),
}
}
pub fn trailing_class(&self) -> Option<MathClass> {
match self {
Self::Spanned { expression, .. } => expression.trailing_class(),
Self::Styled { expression, .. } => expression.trailing_class(),
Self::Classified { class, .. } => Some(*class),
Self::Phantom { .. } => Some(MathClass::Ordinary),
Self::SizedDelimiter { class, .. } => Some(*class),
Self::UnicodeDelimiter { class, .. } => Some(*class),
Self::Accent { position, .. } => Some(math_accent_class(*position)),
Self::Text(_) | Self::TextStyled { .. } | Self::Atom { .. } | Self::Root { .. } => {
Some(self.class())
}
Self::MathSpacingChange(_)
| Self::MathLineBreakPenaltiesChange(_)
| Self::BreakPenalty(_)
| Self::MathStyleChange(_)
| Self::Space(_)
| Self::Glue(_)
| Self::Kern(_) => None,
Self::Sequence(items) => {
items
.iter()
.rev()
.find_map(Self::trailing_class)
.map(|class| {
if class == MathClass::Binary {
MathClass::Ordinary
} else {
class
}
})
}
Self::MathChoice { display, .. } => display.trailing_class(),
Self::Alignment { .. }
| Self::Fraction { .. }
| Self::Delimited { .. }
| Self::Fenced { .. } => Some(MathClass::Inner),
Self::Script { base, .. } => base.trailing_class(),
}
}
pub fn class(&self) -> MathClass {
match self {
Self::Spanned { expression, .. } => expression.class(),
Self::Styled { expression, .. } => expression.class(),
Self::Classified { class, .. } => *class,
Self::Phantom { .. } => MathClass::Ordinary,
Self::Accent { position, .. } => math_accent_class(*position),
Self::Atom { class, .. } => *class,
Self::SizedDelimiter { class, .. } => *class,
Self::UnicodeDelimiter { class, .. } => *class,
Self::MathChoice { display, .. } => display.class(),
Self::Alignment { .. }
| Self::Fraction { .. }
| Self::Delimited { .. }
| Self::Fenced { .. } => MathClass::Inner,
Self::Script { base, .. } => base.class(),
Self::Sequence(items) => items
.iter()
.find_map(Self::leading_class)
.unwrap_or(MathClass::Ordinary),
Self::Text(_)
| Self::TextStyled { .. }
| Self::MathStyleChange(_)
| Self::Space(_)
| Self::Glue(_)
| Self::Kern(_)
| Self::MathSpacingChange(_)
| Self::MathLineBreakPenaltiesChange(_)
| Self::BreakPenalty(_)
| Self::Root { .. } => MathClass::Ordinary,
}
}
pub fn uses_display_limits(&self) -> bool {
match self {
Self::Spanned { expression, .. } => expression.uses_display_limits(),
Self::Styled { expression, .. } => expression.uses_display_limits(),
Self::Classified {
class: MathClass::Operator,
..
} => true,
Self::Accent { .. } => false,
Self::Atom {
class: MathClass::Operator,
text,
..
} => matches!(text.as_str(), "∑" | "∏" | "lim" | "max" | "min"),
Self::Script { base, limits, .. } => match limits {
MathLimitMode::Automatic => base.uses_display_limits(),
MathLimitMode::DisplayLimits | MathLimitMode::Limits => true,
MathLimitMode::NoLimits => false,
},
Self::MathChoice { display, .. } => display.uses_display_limits(),
_ => false,
}
}
pub fn without_source(&self) -> Self {
match self {
Self::Spanned { expression, .. } => expression.without_source(),
Self::Styled { font, expression } => Self::Styled {
font: *font,
expression: Box::new(expression.without_source()),
},
Self::Classified { class, body } => Self::Classified {
class: *class,
body: Box::new(body.without_source()),
},
Self::Phantom { kind, body } => Self::Phantom {
kind: *kind,
body: Box::new(body.without_source()),
},
Self::Accent {
position,
body,
family,
math_fonts,
} => Self::Accent {
position: *position,
body: Box::new(body.without_source()),
family: *family,
math_fonts: Arc::clone(math_fonts),
},
Self::Sequence(items) => {
Self::Sequence(items.iter().map(Self::without_source).collect())
}
Self::Alignment {
rows,
alignment,
baseline,
math_fonts,
cell_style,
row_spacing,
} => Self::Alignment {
rows: rows
.iter()
.map(|row| row.iter().map(Self::without_source).collect())
.collect(),
alignment: alignment.clone(),
baseline: *baseline,
math_fonts: Arc::clone(math_fonts),
cell_style: *cell_style,
row_spacing: *row_spacing,
},
Self::Fraction {
numerator,
denominator,
style,
has_rule,
rule_thickness,
math_fonts,
} => Self::Fraction {
numerator: Box::new(numerator.without_source()),
denominator: Box::new(denominator.without_source()),
style: *style,
has_rule: *has_rule,
rule_thickness: *rule_thickness,
math_fonts: Arc::clone(math_fonts),
},
Self::MathChoice {
display,
text,
script,
scriptscript,
} => Self::MathChoice {
display: Box::new(display.without_source()),
text: Box::new(text.without_source()),
script: Box::new(script.without_source()),
scriptscript: Box::new(scriptscript.without_source()),
},
Self::Root {
index,
body,
radical,
math_fonts,
} => Self::Root {
index: index
.as_deref()
.map(|index| Box::new(index.without_source())),
body: Box::new(body.without_source()),
radical: *radical,
math_fonts: Arc::clone(math_fonts),
},
Self::Delimited {
left,
body,
right,
left_settings,
right_settings,
} => Self::Delimited {
left: left.clone(),
body: Box::new(body.without_source()),
right: right.clone(),
left_settings: *left_settings,
right_settings: *right_settings,
},
Self::Fenced {
delimiters,
delimiter_settings,
segments,
} => Self::Fenced {
delimiters: delimiters.clone(),
delimiter_settings: delimiter_settings.clone(),
segments: segments.iter().map(Self::without_source).collect(),
},
Self::Script {
base,
sub,
superscript,
limits,
} => Self::Script {
base: Box::new(base.without_source()),
sub: sub.as_deref().map(|sub| Box::new(sub.without_source())),
superscript: superscript
.as_deref()
.map(|superscript| Box::new(superscript.without_source())),
limits: *limits,
},
_ => self.clone(),
}
}
pub fn rebase_source_locations(
&mut self,
locations: &HashMap<SourceLocation, SourceLocation>,
) -> bool {
match self {
Self::Spanned {
location,
expression,
} => {
if let Some(location) = location {
let Some(rebased) = locations.get(location) else {
return false;
};
*location = rebased.clone();
}
expression.rebase_source_locations(locations)
}
Self::Styled { expression, .. } => expression.rebase_source_locations(locations),
Self::Classified { body, .. } | Self::Phantom { body, .. } => {
body.rebase_source_locations(locations)
}
Self::Accent { body, .. } => body.rebase_source_locations(locations),
Self::Sequence(items) => items
.iter_mut()
.all(|item| item.rebase_source_locations(locations)),
Self::Alignment { rows, .. } => rows
.iter_mut()
.flatten()
.all(|item| item.rebase_source_locations(locations)),
Self::Fraction {
numerator,
denominator,
..
} => {
numerator.rebase_source_locations(locations)
&& denominator.rebase_source_locations(locations)
}
Self::MathChoice {
display,
text,
script,
scriptscript,
} => {
display.rebase_source_locations(locations)
&& text.rebase_source_locations(locations)
&& script.rebase_source_locations(locations)
&& scriptscript.rebase_source_locations(locations)
}
Self::Root { index, body, .. } => {
index
.as_deref_mut()
.is_none_or(|index| index.rebase_source_locations(locations))
&& body.rebase_source_locations(locations)
}
Self::Delimited { body, .. } => body.rebase_source_locations(locations),
Self::Fenced { segments, .. } => segments
.iter_mut()
.all(|segment| segment.rebase_source_locations(locations)),
Self::Script {
base,
sub,
superscript,
..
} => {
base.rebase_source_locations(locations)
&& sub
.as_deref_mut()
.is_none_or(|sub| sub.rebase_source_locations(locations))
&& superscript
.as_deref_mut()
.is_none_or(|superscript| superscript.rebase_source_locations(locations))
}
Self::Text(_)
| Self::TextStyled { .. }
| Self::Atom { .. }
| Self::MathSpacingChange(_)
| Self::MathLineBreakPenaltiesChange(_)
| Self::BreakPenalty(_)
| Self::MathStyleChange(_)
| Self::Space(_)
| Self::Glue(_)
| Self::Kern(_)
| Self::SizedDelimiter { .. }
| Self::UnicodeDelimiter { .. } => true,
}
}
}
/// Whether a math nucleus is a single character-like atom eligible for the
/// ordinary character script-placement rules.
pub fn is_character_like_math_nucleus(expression: &MathExpr) -> bool {
match expression {
MathExpr::Spanned { expression, .. } | MathExpr::Styled { expression, .. } => {
is_character_like_math_nucleus(expression)
}
MathExpr::Classified {
class: MathClass::Ordinary,
body,
} => is_character_like_math_nucleus(body),
MathExpr::Classified { .. } => false,
MathExpr::Atom { text, .. } => text.chars().count() == 1,
MathExpr::Accent { .. }
| MathExpr::Phantom { .. }
| MathExpr::Alignment { .. }
| MathExpr::SizedDelimiter { .. }
| MathExpr::UnicodeDelimiter { .. }
| MathExpr::Fraction { .. }
| MathExpr::Root { .. }
| MathExpr::Delimited { .. }
| MathExpr::Fenced { .. }
| MathExpr::Script { .. }
| MathExpr::Sequence(_)
| MathExpr::MathChoice { .. }
| MathExpr::MathSpacingChange(_)
| MathExpr::MathLineBreakPenaltiesChange(_)
| MathExpr::BreakPenalty(_)
| MathExpr::MathStyleChange(_)
| MathExpr::Space(_)
| MathExpr::Glue(_)
| MathExpr::Kern(_)
| MathExpr::TextStyled { .. }
| MathExpr::Text(_) => false,
}
}
/// Whether a math nucleus has operator class after style wrappers.
pub fn is_operator_math_nucleus(expression: &MathExpr) -> bool {
match expression {
MathExpr::Spanned { expression, .. } | MathExpr::Styled { expression, .. } => {
is_operator_math_nucleus(expression)
}
MathExpr::Classified { class, .. } | MathExpr::Atom { class, .. } => {
*class == MathClass::Operator
}
_ => false,
}
}
/// Whether the nucleus exposes exactly one glyph after transparent wrappers.
pub fn is_single_glyph_math_nucleus(expression: &MathExpr) -> bool {
match expression {
MathExpr::Spanned { expression, .. }
| MathExpr::Styled { expression, .. }
| MathExpr::Classified {
body: expression, ..
} => is_single_glyph_math_nucleus(expression),
MathExpr::Atom { text, .. } => text.chars().count() == 1,
_ => false,
}
}
/// A character nucleus selected for OpenType MATH script-kern placement.
pub struct MathScriptGlyphCandidate<'a, Style> {
pub expression: &'a MathExpr,
pub style: Style,
pub math_style: MathStyle,
}
/// Finds the first character nucleus used to kern an ordinary script.
///
/// The callbacks let the font backend translate math-style changes and math
/// font wrappers into its own style type while this function owns the TeX list
/// traversal and skip rules.
pub fn first_script_math_glyph_candidate<'a, Style: Clone>(
expression: &'a MathExpr,
style: Style,
math_style: MathStyle,
style_for_math_style: impl Fn(&Style, MathStyle, MathStyle) -> Style,
style_for_font: impl Fn(&Style, MathFontStyle) -> Style,
) -> Option<MathScriptGlyphCandidate<'a, Style>> {
fn find<'a, Style: Clone>(
expression: &'a MathExpr,
style: Style,
math_style: MathStyle,
style_for_math_style: &impl Fn(&Style, MathStyle, MathStyle) -> Style,
style_for_font: &impl Fn(&Style, MathFontStyle) -> Style,
) -> Option<MathScriptGlyphCandidate<'a, Style>> {
match expression {
MathExpr::Spanned { expression, .. } => find(
expression,
style,
math_style,
style_for_math_style,
style_for_font,
),
MathExpr::Styled { font, expression } => find(
expression,
style_for_font(&style, *font),
math_style,
style_for_math_style,
style_for_font,
),
MathExpr::Atom { class, .. } if *class != MathClass::Inner => {
Some(MathScriptGlyphCandidate {
expression,
style,
math_style,
})
}
MathExpr::Sequence(expressions) => {
let initial_style = style.clone();
let initial_math_style = math_style;
let mut current_style = style;
let mut current_math_style = math_style;
for expression in expressions {
if let Some(command) = crate::math_list::math_style_command(expression) {
let next_math_style = MathStyle::from_command(command);
current_style = style_for_math_style(
&initial_style,
initial_math_style,
next_math_style,
);
current_math_style = next_math_style;
continue;
}
if is_math_kern_ignorable(expression) {
continue;
}
return find(
expression,
current_style,
current_math_style,
style_for_math_style,
style_for_font,
);
}
None
}
MathExpr::MathChoice { .. } => find(
crate::math_list::math_choice_variant(expression, math_style),
style,
math_style,
style_for_math_style,
style_for_font,
),
_ => None,
}
}
find(
expression,
style,
math_style,
&style_for_math_style,
&style_for_font,
)
}
fn is_math_kern_ignorable(expression: &MathExpr) -> bool {
match expression {
MathExpr::Spanned { expression, .. } => is_math_kern_ignorable(expression),
MathExpr::MathStyleChange(_)
| MathExpr::Space(_)
| MathExpr::Glue(_)
| MathExpr::Kern(_) => true,
_ => false,
}
}
pub fn is_cjk(character: char) -> bool {
matches!(
character as u32,
0x2E80..=0x2EFF
| 0x2F00..=0x2FDF
| 0x3000..=0x30FF
| 0x3100..=0x31FF
| 0x3400..=0x4DBF
| 0x4E00..=0x9FFF
| 0xAC00..=0xD7AF
| 0xF900..=0xFAFF
| 0xFE30..=0xFE4F
| 0xFF00..=0xFFEF
| 0x20000..=0x2FA1F
)
}
pub fn format_script(source: &str, superscript: bool) -> String {
let mut converted = String::new();
for character in source.chars() {
let mapped = if superscript {
superscript_character(character)
} else {
subscript_character(character)
};
let Some(mapped) = mapped else {
return format!("{}({source})", if superscript { "^" } else { "_" });
};
converted.push(mapped);
}
converted
}
fn superscript_character(character: char) -> Option<char> {
Some(match character {
'0' => '⁰',
'1' => '¹',
'2' => '²',
'3' => '³',
'4' => '⁴',
'5' => '⁵',
'6' => '⁶',
'7' => '⁷',
'8' => '⁸',
'9' => '⁹',
'+' => '⁺',
'-' | '−' => '⁻',
'=' => '⁼',
'(' => '⁽',
')' => '⁾',
'n' => 'ⁿ',
'i' => 'ⁱ',
'a' => 'ᵃ',
'b' => 'ᵇ',
'c' => 'ᶜ',
'd' => 'ᵈ',
'e' => 'ᵉ',
'f' => 'ᶠ',
'g' => 'ᵍ',
'h' => 'ʰ',
'j' => 'ʲ',
'k' => 'ᵏ',
'l' => 'ˡ',
'm' => 'ᵐ',
'o' => 'ᵒ',
'p' => 'ᵖ',
'r' => 'ʳ',
's' => 'ˢ',
't' => 'ᵗ',
'u' => 'ᵘ',
'v' => 'ᵛ',
'w' => 'ʷ',
'x' => 'ˣ',
'y' => 'ʸ',
'z' => 'ᶻ',
_ => return None,
})
}
fn subscript_character(character: char) -> Option<char> {
Some(match character {
'0' => '₀',
'1' => '₁',
'2' => '₂',
'3' => '₃',
'4' => '₄',
'5' => '₅',
'6' => '₆',
'7' => '₇',
'8' => '₈',
'9' => '₉',
'+' => '₊',
'-' | '−' => '₋',
'=' => '₌',
'(' => '₍',
')' => '₎',
'a' => 'ₐ',
'e' => 'ₑ',
'h' => 'ₕ',
'i' => 'ᵢ',
'j' => 'ⱼ',
'k' => 'ₖ',
'l' => 'ₗ',
'm' => 'ₘ',
'n' => 'ₙ',
'o' => 'ₒ',
'p' => 'ₚ',
'r' => 'ᵣ',
's' => 'ₛ',
't' => 'ₜ',
'u' => 'ᵤ',
'v' => 'ᵥ',
'x' => 'ₓ',
_ => return None,
})
}