Files
texrra-engine/crates/texrra-core/src/math_parser.rs
T

2073 lines
76 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::{ops::Range, sync::Arc};
use crate::{
MathClass, MathStyleCommand, expanded as tex_expansion,
math_expr::{
MathAccent, MathDelimiterGlyph, MathDelimiterSettings, MathExpr, MathFontFamilies,
MathFontStyle, MathFractionStyle, MathInfixFractionKind, MathLimitMode,
MathLineBreakPenalties, MathPhantomKind,
},
source::{SourceLocation, SourceOrigin},
};
pub fn parse_math_expression_with_events(
expanded: &tex_expansion::ExpandedTokenStream,
range: Range<usize>,
events: &[tex_expansion::FrontendEvent],
) -> Result<MathExpr, String> {
let range_len = range.end - range.start;
if let Some((event_index, event)) = find_math_infix_fraction_event(&range, events) {
let numerator = parse_math_expression_with_events(
expanded,
range.start..event.position,
&events[..event_index],
)?;
let denominator = parse_math_expression_with_events(
expanded,
event.position..range.end,
&events[event_index + 1..],
)?;
let (has_rule, parentheses, rule_thickness, delimiters, delimiter_settings, math_fonts) =
match &event.kind {
tex_expansion::FrontendEventKind::MathInfixFraction(kind, math_fonts) => match kind
{
MathInfixFractionKind::Over => (true, false, None, None, None, math_fonts),
MathInfixFractionKind::Atop => (false, false, None, None, None, math_fonts),
MathInfixFractionKind::Choose(settings) => {
(false, true, None, None, Some(*settings), math_fonts)
}
MathInfixFractionKind::Above(thickness) => {
(true, false, Some(*thickness), None, None, math_fonts)
}
MathInfixFractionKind::OverWithDelims(delimiters) => (
true,
false,
None,
Some(delimiters),
Some(delimiters.settings),
math_fonts,
),
MathInfixFractionKind::AtopWithDelims(delimiters) => (
false,
false,
None,
Some(delimiters),
Some(delimiters.settings),
math_fonts,
),
MathInfixFractionKind::AboveWithDelims {
thickness,
delimiters,
} => (
true,
false,
Some(*thickness),
Some(delimiters),
Some(delimiters.settings),
math_fonts,
),
},
_ => unreachable!("only infix fraction events are selected"),
};
let math_fonts = Arc::clone(math_fonts);
let fraction = MathExpr::Fraction {
numerator: Box::new(numerator),
denominator: Box::new(denominator),
style: MathFractionStyle::Automatic,
has_rule,
rule_thickness,
math_fonts: Arc::clone(&math_fonts),
};
let expression = if parentheses {
MathExpr::Delimited {
left: MathDelimiterGlyph::plain_with_math_fonts("(", Arc::clone(&math_fonts)),
body: Box::new(fraction),
right: MathDelimiterGlyph::plain_with_math_fonts(")", math_fonts),
left_settings: delimiter_settings.unwrap_or_default(),
right_settings: delimiter_settings.unwrap_or_default(),
}
} else if let Some(delimiters) = delimiters {
MathExpr::Delimited {
left: delimiters.left.clone(),
body: Box::new(fraction),
right: delimiters.right.clone(),
left_settings: delimiters.settings,
right_settings: delimiters.settings,
}
} else {
fraction
};
return Ok(with_source(
expanded,
range,
with_location(Some(event.location.clone()), expression),
));
}
let mut items = Vec::new();
let mut active_math_line_break_penalties = MathLineBreakPenalties::default();
let mut cursor = 0usize;
let mut fraction_search_after = 0usize;
let mut root_search_after = 0usize;
let mut delimiter_search_after = 0usize;
let mut group_search_after = 0usize;
let mut math_space_search_after = 0usize;
let mut math_character_search_after = 0usize;
let mut math_style_search_after = 0usize;
let mut math_choice_search_after = 0usize;
let mut literal_character_search_after = 0usize;
let mut event_index = events.partition_point(|event| event.position < range.start);
let mut pending_limit_mode = None;
let mut active_spacing = None;
while cursor < range_len
|| events.iter().skip(math_space_search_after).any(|event| {
event.position == range.start + cursor
&& matches!(
&event.kind,
tex_expansion::FrontendEventKind::MathSpace(_)
| tex_expansion::FrontendEventKind::HorizontalGlue(_)
| tex_expansion::FrontendEventKind::Kern(_)
| tex_expansion::FrontendEventKind::Penalty(_)
)
})
|| events.iter().skip(math_style_search_after).any(|event| {
event.position == range.start + cursor
&& matches!(
&event.kind,
tex_expansion::FrontendEventKind::MathStyleChange(_)
)
})
|| events.iter().skip(math_choice_search_after).any(|event| {
event.position == range.start + cursor
&& matches!(
&event.kind,
tex_expansion::FrontendEventKind::MathChoiceStart
)
})
|| events
.iter()
.skip(math_character_search_after)
.any(|event| {
event.position == range.start + cursor
&& matches!(
&event.kind,
tex_expansion::FrontendEventKind::MathCharacter { .. }
| tex_expansion::FrontendEventKind::MathUnicodeCharacter { .. }
| tex_expansion::FrontendEventKind::MathUnicodeDelimiter { .. }
)
})
|| events
.iter()
.skip(literal_character_search_after)
.any(|event| {
event.position == range.start + cursor
&& matches!(
&event.kind,
tex_expansion::FrontendEventKind::LiteralAmpersand
| tex_expansion::FrontendEventKind::LiteralCharacter(_)
| tex_expansion::FrontendEventKind::LineBreak
| tex_expansion::FrontendEventKind::MathManualDelimiter { .. }
)
})
{
let absolute_cursor = range.start + cursor;
if let Some(item) = expanded.next_token_item_at_or_after(absolute_cursor, range.end) {
if active_spacing != Some(item.math_spacing) {
items.push(MathExpr::MathSpacingChange(item.math_spacing));
active_spacing = Some(item.math_spacing);
}
}
while events
.get(event_index)
.is_some_and(|event| event.position < absolute_cursor)
{
event_index += 1;
}
while let Some(event) = events
.get(event_index)
.filter(|event| event.position == absolute_cursor)
{
match &event.kind {
tex_expansion::FrontendEventKind::MathLimitMode(mode) => {
pending_limit_mode = Some(*mode);
}
tex_expansion::FrontendEventKind::MathSpace(_)
| tex_expansion::FrontendEventKind::HorizontalGlue(_)
| tex_expansion::FrontendEventKind::Kern(_)
| tex_expansion::FrontendEventKind::Penalty(_) => pending_limit_mode = None,
_ => {}
}
event_index += 1;
}
if pending_limit_mode.is_some()
&& expanded
.token_value_at(absolute_cursor)
.and_then(tex_expansion::ExpandedTokenValue::character)
.is_some_and(|character| {
!character.is_whitespace() && !matches!(character, '^' | '_')
})
{
pending_limit_mode = None;
}
let fraction_span =
find_math_fraction_span(events, absolute_cursor, range.end, fraction_search_after);
let root_span = find_math_root_span(events, absolute_cursor, range.end, root_search_after);
let delimiter_span =
find_math_delimiter_span(events, absolute_cursor, range.end, delimiter_search_after);
let group_span =
find_math_group_span(events, absolute_cursor, range.end, group_search_after);
let choice_span =
find_math_choice_span(events, absolute_cursor, range.end, math_choice_search_after);
let math_space_event = events
.iter()
.enumerate()
.skip(math_space_search_after)
.find(|(_, event)| {
event.position == absolute_cursor
&& matches!(
&event.kind,
tex_expansion::FrontendEventKind::MathSpace(_)
| tex_expansion::FrontendEventKind::HorizontalGlue(_)
| tex_expansion::FrontendEventKind::Kern(_)
| tex_expansion::FrontendEventKind::Penalty(_)
)
});
let literal_character_event = events
.iter()
.enumerate()
.skip(literal_character_search_after)
.find(|(_, event)| {
event.position == absolute_cursor
&& matches!(
&event.kind,
tex_expansion::FrontendEventKind::LiteralAmpersand
| tex_expansion::FrontendEventKind::LiteralCharacter(_)
| tex_expansion::FrontendEventKind::LineBreak
| tex_expansion::FrontendEventKind::MathManualDelimiter { .. }
)
});
let math_style_event = events
.iter()
.enumerate()
.skip(math_style_search_after)
.find(|(_, event)| {
event.position == absolute_cursor
&& matches!(
&event.kind,
tex_expansion::FrontendEventKind::MathStyleChange(_)
)
});
let math_character_event = events
.iter()
.enumerate()
.skip(math_character_search_after)
.find(|(_, event)| {
event.position == absolute_cursor
&& matches!(
&event.kind,
tex_expansion::FrontendEventKind::MathCharacter { .. }
| tex_expansion::FrontendEventKind::MathUnicodeCharacter { .. }
)
});
let first_container_event = fraction_span
.as_ref()
.map(|span| span.start_event)
.into_iter()
.chain(root_span.as_ref().map(|span| span.start_event))
.chain(delimiter_span.as_ref().map(|span| span.start_event))
.chain(group_span.as_ref().map(|span| span.start_event))
.chain(choice_span.as_ref().map(|span| span.start_event))
.min();
let next_inline_event = [
math_space_event,
literal_character_event,
math_style_event,
math_character_event,
]
.into_iter()
.flatten()
.min_by_key(|(event_index, _)| *event_index);
let next_inline_event = next_inline_event.filter(|(inline_event_index, _)| {
first_container_event.is_none_or(|container| *inline_event_index < container)
});
if let Some((inline_event_index, event)) = next_inline_event {
let expression = match &event.kind {
tex_expansion::FrontendEventKind::MathSpace(units) => {
math_space_search_after = inline_event_index + 1;
MathExpr::Space(*units)
}
tex_expansion::FrontendEventKind::Kern(width) => {
math_space_search_after = inline_event_index + 1;
MathExpr::Kern(*width)
}
tex_expansion::FrontendEventKind::HorizontalGlue(glue) => {
math_space_search_after = inline_event_index + 1;
MathExpr::Glue(*glue)
}
tex_expansion::FrontendEventKind::Penalty(penalty) => {
math_space_search_after = inline_event_index + 1;
MathExpr::BreakPenalty(*penalty)
}
tex_expansion::FrontendEventKind::MathStyleChange(style) => {
math_style_search_after = inline_event_index + 1;
MathExpr::MathStyleChange(*style)
}
tex_expansion::FrontendEventKind::MathCharacter {
code,
active_family,
math_fonts,
} => {
math_character_search_after = inline_event_index + 1;
let character = char::from_u32(u32::from(code & 0xff))
.expect("an eight-bit math slot is a valid character");
let (class, math_family, math_slot) =
math_code_properties(character, Some(*code), Some(*active_family));
MathExpr::Atom {
class,
text: character.to_string(),
math_family,
math_slots: math_slot.into_iter().collect(),
math_fonts: Arc::clone(math_fonts),
}
}
tex_expansion::FrontendEventKind::MathUnicodeCharacter {
class,
family,
character,
math_fonts,
} => {
math_character_search_after = inline_event_index + 1;
MathExpr::Atom {
class: *class,
text: character.to_string(),
math_family: Some(*family),
math_slots: Vec::new(),
math_fonts: Arc::clone(math_fonts),
}
}
tex_expansion::FrontendEventKind::MathUnicodeDelimiter {
class,
family,
character,
settings,
math_fonts,
} => {
math_character_search_after = inline_event_index + 1;
MathExpr::UnicodeDelimiter {
character: *character,
class: *class,
family: *family,
settings: *settings,
math_fonts: Arc::clone(math_fonts),
}
}
tex_expansion::FrontendEventKind::LiteralAmpersand => {
literal_character_search_after = inline_event_index + 1;
MathExpr::Atom {
class: MathClass::Ordinary,
text: "&".to_string(),
math_family: None,
math_slots: Vec::new(),
math_fonts: Arc::default(),
}
}
tex_expansion::FrontendEventKind::LiteralCharacter(character) => {
literal_character_search_after = inline_event_index + 1;
MathExpr::Atom {
class: match character {
'{' => MathClass::Opening,
'}' => MathClass::Closing,
_ => math_class_for_character(*character),
},
text: character.to_string(),
math_family: None,
math_slots: Vec::new(),
math_fonts: Arc::default(),
}
}
tex_expansion::FrontendEventKind::LineBreak => {
literal_character_search_after = inline_event_index + 1;
MathExpr::Space(1)
}
tex_expansion::FrontendEventKind::MathManualDelimiter {
delimiter,
half_points,
class,
settings,
math_fonts,
} => {
literal_character_search_after = inline_event_index + 1;
MathExpr::SizedDelimiter {
delimiter: delimiter.clone(),
half_points: *half_points,
class: *class,
settings: *settings,
math_fonts: Arc::clone(math_fonts),
}
}
_ => unreachable!("only inline math events are selected here"),
};
if active_math_line_break_penalties != event.math_line_break_penalties {
items.push(MathExpr::MathLineBreakPenaltiesChange(
event.math_line_break_penalties,
));
active_math_line_break_penalties = event.math_line_break_penalties;
}
items.push(with_location(Some(event.location.clone()), expression));
continue;
}
if group_span.as_ref().is_some_and(|group| {
fraction_span
.as_ref()
.is_none_or(|fraction| group.start_event < fraction.start_event)
&& root_span
.as_ref()
.is_none_or(|root| group.start_event < root.start_event)
&& delimiter_span
.as_ref()
.is_none_or(|delimiter| group.start_event < delimiter.start_event)
&& choice_span
.as_ref()
.is_none_or(|choice| group.start_event < choice.start_event)
}) {
let span = group_span.expect("math group span was selected");
let body_range = absolute_cursor..span.end_position;
let is_scope = matches!(&span.value, MathGroupValue::Scope);
let body = match span.value {
MathGroupValue::Scope => parse_math_expression_with_events(
expanded,
body_range.clone(),
&events[span.start_event + 1..span.end_event],
)?,
MathGroupValue::Accent {
position,
family,
math_fonts,
} => MathExpr::Accent {
position,
body: Box::new(parse_math_expression_with_events(
expanded,
body_range.clone(),
&events[span.start_event + 1..span.end_event],
)?),
family,
math_fonts,
},
MathGroupValue::Font(MathFontStyle::Text) => {
parse_math_text_group(expanded, body_range.clone())
}
MathGroupValue::Font(font) => {
let mut expression = parse_math_expression_with_events(
expanded,
body_range.clone(),
&events[span.start_event + 1..span.end_event],
)?;
match font {
MathFontStyle::Roman
| MathFontStyle::BoldRoman
| MathFontStyle::SansSerif
| MathFontStyle::Calligraphic
| MathFontStyle::Blackboard
| MathFontStyle::Fraktur => {
force_math_family(&mut expression, 1, 0);
}
MathFontStyle::Monospace => {
force_monospace_math_font(&mut expression);
}
_ => {}
}
if font == MathFontStyle::Monospace {
expression
} else {
MathExpr::Styled {
font,
expression: Box::new(expression),
}
}
}
MathGroupValue::Operator => MathExpr::Atom {
class: MathClass::Operator,
text: expanded.character_tokens_in(body_range),
math_family: None,
math_slots: Vec::new(),
math_fonts: Arc::default(),
},
MathGroupValue::Classified(class) => MathExpr::Classified {
class,
body: Box::new(parse_math_expression_with_events(
expanded,
body_range.clone(),
&events[span.start_event + 1..span.end_event],
)?),
},
MathGroupValue::Phantom(kind) => MathExpr::Phantom {
kind,
body: Box::new(parse_math_expression_with_events(
expanded,
body_range.clone(),
&events[span.start_event + 1..span.end_event],
)?),
},
};
if is_scope {
append_math_scope(&mut items, body, Some(span.location));
} else {
items.push(with_location(Some(span.location), body));
}
cursor = span.end_position - range.start;
fraction_search_after = span.end_event + 1;
root_search_after = span.end_event + 1;
delimiter_search_after = span.end_event + 1;
group_search_after = span.end_event + 1;
math_space_search_after = span.end_event + 1;
math_character_search_after = span.end_event + 1;
math_style_search_after = span.end_event + 1;
math_choice_search_after = span.end_event + 1;
continue;
}
if choice_span.as_ref().is_some_and(|choice| {
fraction_span
.as_ref()
.is_none_or(|fraction| choice.start_event < fraction.start_event)
&& root_span
.as_ref()
.is_none_or(|root| choice.start_event < root.start_event)
&& delimiter_span
.as_ref()
.is_none_or(|delimiter| choice.start_event < delimiter.start_event)
&& group_span
.as_ref()
.is_none_or(|group| choice.start_event < group.start_event)
}) {
let span = choice_span.expect("math choice span was selected");
let mut display = None;
let mut text = None;
let mut script = None;
let mut scriptscript = None;
for branch in &span.branches {
let expression = Box::new(parse_math_expression_with_events(
expanded,
branch.start_position..branch.end_position,
&events[branch.start_event + 1..branch.end_event],
)?);
match branch.style {
MathStyleCommand::Display => display = Some(expression),
MathStyleCommand::Text => text = Some(expression),
MathStyleCommand::Script => script = Some(expression),
MathStyleCommand::ScriptScript => scriptscript = Some(expression),
}
}
let expression = MathExpr::MathChoice {
display: display.expect("mathchoice has a display branch"),
text: text.expect("mathchoice has a text branch"),
script: script.expect("mathchoice has a script branch"),
scriptscript: scriptscript.expect("mathchoice has a scriptscript branch"),
};
items.push(with_location(
Some(span.location),
with_source(expanded, absolute_cursor..span.end_position, expression),
));
cursor = span.end_position - range.start;
fraction_search_after = span.end_event + 1;
root_search_after = span.end_event + 1;
delimiter_search_after = span.end_event + 1;
group_search_after = span.end_event + 1;
math_space_search_after = span.end_event + 1;
math_character_search_after = span.end_event + 1;
math_style_search_after = span.end_event + 1;
math_choice_search_after = span.end_event + 1;
event_index = span.end_event + 1;
continue;
}
if delimiter_span.as_ref().is_some_and(|delimiter| {
fraction_span
.as_ref()
.is_none_or(|fraction| delimiter.start_event < fraction.start_event)
&& root_span
.as_ref()
.is_none_or(|root| delimiter.start_event < root.start_event)
}) {
let span = delimiter_span.expect("delimiter span was selected");
let expression = if span.middles.is_empty() {
let body = parse_math_expression_with_events(
expanded,
absolute_cursor..span.end_position,
&events[span.start_event + 1..span.end_event],
)?;
MathExpr::Delimited {
left: span.left.clone(),
body: Box::new(body),
right: span.right.clone(),
left_settings: span.left_settings,
right_settings: span.right_settings,
}
} else {
let mut delimiters = vec![span.left.clone()];
let mut delimiter_settings = vec![span.left_settings];
let mut segments = Vec::with_capacity(span.middles.len() + 1);
let mut segment_start = absolute_cursor;
let mut segment_event_start = span.start_event + 1;
for (delimiter, settings, position, event_index) in &span.middles {
segments.push(parse_math_expression_with_events(
expanded,
segment_start..*position,
&events[segment_event_start..*event_index],
)?);
delimiters.push(delimiter.clone());
delimiter_settings.push(*settings);
segment_start = *position;
segment_event_start = *event_index + 1;
}
segments.push(parse_math_expression_with_events(
expanded,
segment_start..span.end_position,
&events[segment_event_start..span.end_event],
)?);
delimiters.push(span.right.clone());
delimiter_settings.push(span.right_settings);
MathExpr::Fenced {
delimiters,
delimiter_settings,
segments,
}
};
items.push(with_location(
Some(span.location),
with_source(expanded, absolute_cursor..span.end_position, expression),
));
cursor = span.end_position - range.start;
fraction_search_after = span.end_event + 1;
root_search_after = span.end_event + 1;
delimiter_search_after = span.end_event + 1;
group_search_after = span.end_event + 1;
math_space_search_after = span.end_event + 1;
math_character_search_after = span.end_event + 1;
math_style_search_after = span.end_event + 1;
math_choice_search_after = span.end_event + 1;
continue;
}
if root_span.as_ref().is_some_and(|root| {
fraction_span
.as_ref()
.is_none_or(|fraction| root.start_event < fraction.start_event)
&& delimiter_span
.as_ref()
.is_none_or(|delimiter| root.start_event < delimiter.start_event)
}) {
let span = root_span.expect("root span was selected");
let index = if span.has_index {
Some(parse_math_expression_with_events(
expanded,
absolute_cursor..span.separator_position,
&events[span.start_event + 1..span.separator_event],
)?)
} else {
None
};
let body = parse_math_expression_with_events(
expanded,
span.separator_position..span.end_position,
&events[span.separator_event + 1..span.end_event],
)?;
items.push(with_location(
Some(span.location),
with_source(
expanded,
absolute_cursor..span.end_position,
MathExpr::Root {
index: index.map(Box::new),
body: Box::new(body),
radical: span.radical,
math_fonts: span.math_fonts,
},
),
));
cursor = span.end_position - range.start;
fraction_search_after = span.end_event + 1;
root_search_after = span.end_event + 1;
delimiter_search_after = span.end_event + 1;
group_search_after = span.end_event + 1;
math_space_search_after = span.end_event + 1;
math_character_search_after = span.end_event + 1;
math_style_search_after = span.end_event + 1;
math_choice_search_after = span.end_event + 1;
continue;
}
if let Some(span) = fraction_span {
let numerator_range = absolute_cursor..span.separator_position;
let denominator_range = span.separator_position..span.end_position;
let numerator = parse_math_expression_with_events(
expanded,
numerator_range,
&events[span.start_event + 1..span.separator_event],
)?;
let denominator = parse_math_expression_with_events(
expanded,
denominator_range,
&events[span.separator_event + 1..span.end_event],
)?;
let fraction = MathExpr::Fraction {
numerator: Box::new(numerator),
denominator: Box::new(denominator),
style: span.style,
has_rule: span.has_rule,
rule_thickness: span.rule_thickness,
math_fonts: Arc::clone(&span.math_fonts),
};
let expression = if span.parentheses {
MathExpr::Delimited {
left: MathDelimiterGlyph::plain_with_math_fonts(
"(",
Arc::clone(&span.math_fonts),
),
body: Box::new(fraction),
right: MathDelimiterGlyph::plain_with_math_fonts(")", span.math_fonts),
left_settings: span.delimiter_settings,
right_settings: span.delimiter_settings,
}
} else {
fraction
};
items.push(with_location(Some(span.location), expression));
cursor = span.end_position - range.start;
fraction_search_after = span.end_event + 1;
root_search_after = span.end_event + 1;
delimiter_search_after = span.end_event + 1;
group_search_after = span.end_event + 1;
math_space_search_after = span.end_event + 1;
math_character_search_after = span.end_event + 1;
math_style_search_after = span.end_event + 1;
math_choice_search_after = span.end_event + 1;
continue;
}
let expanded_token = expanded.token_item_at(absolute_cursor);
let math_code = expanded_token.and_then(|item| item.math_code);
let active_math_family = expanded_token.and_then(|item| item.math_family);
let unicode_math_code = expanded_token.and_then(|item| item.unicode_math_code);
let math_fonts = expanded_token
.map(|item| Arc::clone(&item.math_fonts))
.unwrap_or_default();
let token_character = expanded_token.and_then(|item| match &item.kind {
tex_expansion::ExpandedItemKind::Token(value) => value.character(),
tex_expansion::ExpandedItemKind::Event(_) => None,
});
let cursor_advance = expanded_token
.map(|item| item.end_position - absolute_cursor)
.or_else(|| {
expanded
.next_token_item_at_or_after(absolute_cursor + 1, range.end)
.map(|item| item.position - absolute_cursor)
})
.unwrap_or(range.end - absolute_cursor);
let script_direction = match expanded.token_value_at(absolute_cursor) {
Some(tex_expansion::ExpandedTokenValue::Superscript(_)) => Some(true),
Some(tex_expansion::ExpandedTokenValue::Subscript(_)) => Some(false),
_ => None,
};
if let Some(superscript) = script_direction.filter(|_| token_character.is_some()) {
if let Some((script_range, after)) = read_math_argument_with_events(
expanded,
&range,
events,
cursor + cursor_advance,
event_index,
) {
let script = parse_child_expression(expanded, events, script_range)?;
attach_math_script(
&mut items,
superscript,
script,
expanded.source_at(absolute_cursor),
pending_limit_mode.take(),
)?;
cursor = after;
continue;
}
let location = expanded.source_at(absolute_cursor);
return Err(math_parse_error(location.as_ref(), "Missing { inserted"));
}
if let Some(character) = token_character {
if !character.is_whitespace() {
if let Some(item) = expanded_token {
if active_math_line_break_penalties != item.math_line_break_penalties {
items.push(MathExpr::MathLineBreakPenaltiesChange(
item.math_line_break_penalties,
));
active_math_line_break_penalties = item.math_line_break_penalties;
}
}
let (class, character, math_family, math_slot) =
if let Some(unicode_math_code) = unicode_math_code {
(
unicode_math_code.math_class(),
unicode_math_code.character(),
Some(unicode_math_code.math_family(active_math_family)),
None,
)
} else {
let (class, math_family, math_slot) =
math_code_properties(character, math_code, active_math_family);
(class, character, math_family, math_slot)
};
append_math_text(
&mut items,
character,
class,
math_family,
math_slot,
math_fonts,
expanded.source_at(absolute_cursor),
);
}
}
if cursor_advance == 0 {
break;
}
cursor += cursor_advance;
}
let expression = match items.len() {
0 => MathExpr::Text(String::new()),
1 => items.pop().unwrap(),
_ => MathExpr::Sequence(items),
};
Ok(with_source(expanded, range, expression))
}
fn parse_math_text_group(
expanded: &tex_expansion::ExpandedTokenStream,
range: Range<usize>,
) -> MathExpr {
use tex_expansion::{ExpandedItemKind as Item, FrontendEventKind as Event, TextStyle};
let mut runs = Vec::new();
let mut text = String::new();
let mut bold = false;
let mut italic = false;
let mut monospace = false;
let mut style_stack = Vec::new();
let item_start = expanded
.items
.partition_point(|item| item.position < range.start);
for item in expanded.items[item_start..]
.iter()
.take_while(|item| item.position < range.end)
{
match &item.kind {
Item::Token(token) => {
if let Some(character) = token.character() {
text.push(character);
}
}
Item::Event(Event::TextStyleStart(style)) => {
push_math_text_run(&mut runs, &mut text, bold, italic, monospace);
style_stack.push((*style, bold, italic, monospace));
match style {
TextStyle::Bold => bold = true,
TextStyle::Italic => italic = true,
TextStyle::Monospace => monospace = true,
TextStyle::SmallCaps | TextStyle::Sans => {}
TextStyle::Normal => {
bold = false;
italic = false;
monospace = false;
}
}
}
Item::Event(Event::TextStyleEnd(style)) => {
push_math_text_run(&mut runs, &mut text, bold, italic, monospace);
if style_stack
.last()
.is_some_and(|(active, _, _, _)| active == style)
{
if let Some((_, previous_bold, previous_italic, previous_monospace)) =
style_stack.pop()
{
bold = previous_bold;
italic = previous_italic;
monospace = previous_monospace;
}
}
}
Item::Event(Event::LiteralAmpersand) => text.push('&'),
Item::Event(Event::LiteralCharacter(character)) => text.push(*character),
Item::Event(Event::LineBreak | Event::RowBreak) => text.push(' '),
_ => {}
}
}
push_math_text_run(&mut runs, &mut text, bold, italic, monospace);
match runs.len() {
0 => MathExpr::Text(String::new()),
1 => runs.pop().expect("one text run was collected"),
_ => MathExpr::Sequence(runs),
}
}
fn push_math_text_run(
runs: &mut Vec<MathExpr>,
text: &mut String,
bold: bool,
italic: bool,
monospace: bool,
) {
if text.is_empty() {
return;
}
let text = std::mem::take(text);
if bold || italic || monospace {
runs.push(MathExpr::TextStyled {
text,
bold,
italic,
monospace,
});
} else {
runs.push(MathExpr::Text(text));
}
}
fn force_monospace_math_font(expression: &mut MathExpr) {
match expression {
MathExpr::Spanned { expression, .. } => force_monospace_math_font(expression),
MathExpr::Classified { body, .. }
| MathExpr::Phantom { body, .. }
| MathExpr::Accent { body, .. } => {
force_monospace_math_font(body);
}
MathExpr::Sequence(items) => {
for item in items {
force_monospace_math_font(item);
}
}
MathExpr::Alignment { rows, .. } => {
for item in rows.iter_mut().flatten() {
force_monospace_math_font(item);
}
}
MathExpr::Fraction {
numerator,
denominator,
..
} => {
force_monospace_math_font(numerator);
force_monospace_math_font(denominator);
}
MathExpr::MathChoice {
display,
text,
script,
scriptscript,
} => {
force_monospace_math_font(display);
force_monospace_math_font(text);
force_monospace_math_font(script);
force_monospace_math_font(scriptscript);
}
MathExpr::Root { index, body, .. } => {
if let Some(index) = index {
force_monospace_math_font(index);
}
force_monospace_math_font(body);
}
MathExpr::Delimited { body, .. } => force_monospace_math_font(body),
MathExpr::Fenced { segments, .. } => {
for segment in segments {
force_monospace_math_font(segment);
}
}
MathExpr::Script {
base,
sub,
superscript,
..
} => {
force_monospace_math_font(base);
if let Some(sub) = sub {
force_monospace_math_font(sub);
}
if let Some(superscript) = superscript {
force_monospace_math_font(superscript);
}
}
MathExpr::Atom {
class: MathClass::Ordinary,
text,
..
} => {
*expression = MathExpr::TextStyled {
text: std::mem::take(text),
bold: false,
italic: false,
monospace: true,
};
}
MathExpr::TextStyled { monospace, .. } => *monospace = true,
MathExpr::Text(_)
| MathExpr::Styled { .. }
| MathExpr::Atom { .. }
| MathExpr::MathSpacingChange(_)
| MathExpr::MathLineBreakPenaltiesChange(_)
| MathExpr::BreakPenalty(_)
| MathExpr::MathStyleChange(_)
| MathExpr::Space(_)
| MathExpr::Glue(_)
| MathExpr::Kern(_)
| MathExpr::SizedDelimiter { .. }
| MathExpr::UnicodeDelimiter { .. } => {}
}
}
fn find_math_infix_fraction_event<'a>(
range: &Range<usize>,
events: &'a [tex_expansion::FrontendEvent],
) -> Option<(usize, &'a tex_expansion::FrontendEvent)> {
use tex_expansion::FrontendEventKind as Event;
let mut group_depth = 0usize;
let mut fraction_depth = 0usize;
let mut root_depth = 0usize;
let mut delimiter_depth = 0usize;
let mut choice_depth = 0usize;
let mut wrapped_group_depth = 0usize;
for (index, event) in events.iter().enumerate() {
if event.position < range.start {
continue;
}
if event.position >= range.end {
break;
}
match &event.kind {
Event::MathInfixFraction(..)
if group_depth
+ fraction_depth
+ root_depth
+ delimiter_depth
+ choice_depth
+ wrapped_group_depth
== 0 =>
{
return Some((index, event));
}
Event::GroupStart => group_depth += 1,
Event::GroupEnd => group_depth = group_depth.saturating_sub(1),
Event::MathFractionStart { .. } => fraction_depth += 1,
Event::MathFractionEnd => fraction_depth = fraction_depth.saturating_sub(1),
Event::MathRootStart { .. } => root_depth += 1,
Event::MathRootEnd => root_depth = root_depth.saturating_sub(1),
Event::MathDelimiterStart { .. } => delimiter_depth += 1,
Event::MathDelimiterEnd { .. } => delimiter_depth = delimiter_depth.saturating_sub(1),
Event::MathChoiceStart => choice_depth += 1,
Event::MathChoiceEnd => choice_depth = choice_depth.saturating_sub(1),
Event::MathAccentStart { .. }
| Event::MathFontStart(_)
| Event::MathOperatorStart
| Event::MathClassStart(_) => wrapped_group_depth += 1,
Event::MathAccentEnd
| Event::MathFontEnd
| Event::MathOperatorEnd
| Event::MathClassEnd => wrapped_group_depth = wrapped_group_depth.saturating_sub(1),
_ => {}
}
}
None
}
struct MathFractionSpan {
style: MathFractionStyle,
has_rule: bool,
rule_thickness: Option<common::Scaled>,
parentheses: bool,
delimiter_settings: MathDelimiterSettings,
math_fonts: MathFontFamilies,
start_event: usize,
separator_event: usize,
end_event: usize,
separator_position: usize,
end_position: usize,
location: SourceLocation,
}
struct MathRootSpan {
has_index: bool,
radical: Option<(u8, char)>,
math_fonts: MathFontFamilies,
start_event: usize,
separator_event: usize,
end_event: usize,
separator_position: usize,
end_position: usize,
location: SourceLocation,
}
struct MathDelimiterSpan {
left: MathDelimiterGlyph,
left_settings: MathDelimiterSettings,
right: MathDelimiterGlyph,
right_settings: MathDelimiterSettings,
middles: Vec<(MathDelimiterGlyph, MathDelimiterSettings, usize, usize)>,
start_event: usize,
end_event: usize,
end_position: usize,
location: SourceLocation,
}
struct MathChoiceSpan {
branches: Vec<MathChoiceBranchSpan>,
start_event: usize,
end_event: usize,
end_position: usize,
location: SourceLocation,
}
struct MathChoiceBranchSpan {
style: MathStyleCommand,
start_event: usize,
end_event: usize,
start_position: usize,
end_position: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MathGroupType {
Accent,
Classified,
Font,
Operator,
Phantom,
Scope,
}
#[derive(Clone)]
enum MathGroupValue {
Accent {
position: MathAccent,
family: u8,
math_fonts: MathFontFamilies,
},
Classified(MathClass),
Font(MathFontStyle),
Operator,
Phantom(MathPhantomKind),
Scope,
}
struct MathGroupSpan {
value: MathGroupValue,
start_event: usize,
end_event: usize,
end_position: usize,
location: SourceLocation,
}
fn math_group_marker(
kind: &tex_expansion::FrontendEventKind,
) -> Option<(MathGroupType, bool, Option<MathGroupValue>)> {
use tex_expansion::FrontendEventKind as Event;
match kind {
Event::MathAccentStart {
accent,
family,
math_fonts,
} => Some((
MathGroupType::Accent,
true,
Some(MathGroupValue::Accent {
position: *accent,
family: *family,
math_fonts: Arc::clone(math_fonts),
}),
)),
Event::MathAccentEnd => Some((MathGroupType::Accent, false, None)),
Event::MathFontStart(font) => {
Some((MathGroupType::Font, true, Some(MathGroupValue::Font(*font))))
}
Event::MathFontEnd => Some((MathGroupType::Font, false, None)),
Event::MathPhantomStart(kind) => Some((
MathGroupType::Phantom,
true,
Some(MathGroupValue::Phantom(*kind)),
)),
Event::MathPhantomEnd => Some((MathGroupType::Phantom, false, None)),
Event::MathOperatorStart => Some((
MathGroupType::Operator,
true,
Some(MathGroupValue::Operator),
)),
Event::MathOperatorEnd => Some((MathGroupType::Operator, false, None)),
Event::MathClassStart(class) => Some((
MathGroupType::Classified,
true,
Some(MathGroupValue::Classified(*class)),
)),
Event::MathClassEnd => Some((MathGroupType::Classified, false, None)),
Event::GroupStart => Some((MathGroupType::Scope, true, Some(MathGroupValue::Scope))),
Event::GroupEnd => Some((MathGroupType::Scope, false, None)),
_ => None,
}
}
fn find_math_group_span(
events: &[tex_expansion::FrontendEvent],
start_position: usize,
limit: usize,
search_after: usize,
) -> Option<MathGroupSpan> {
let (start_event, group_type, value, location) = events
.iter()
.enumerate()
.skip(search_after)
.find_map(|(index, event)| {
if event.position != start_position {
return None;
}
let (group_type, is_start, value) = math_group_marker(&event.kind)?;
if is_start {
Some((index, group_type, value?, event.location.clone()))
} else {
None
}
})?;
let mut stack = vec![group_type];
for (index, event) in events.iter().enumerate().skip(start_event + 1) {
if event.position > limit {
break;
}
let Some((marker_type, is_start, _)) = math_group_marker(&event.kind) else {
continue;
};
if is_start {
stack.push(marker_type);
} else if stack.last() == Some(&marker_type) {
stack.pop();
if stack.is_empty() {
return Some(MathGroupSpan {
value,
start_event,
end_event: index,
end_position: event.position,
location,
});
}
} else {
return None;
}
}
None
}
fn find_math_fraction_span(
events: &[tex_expansion::FrontendEvent],
start_position: usize,
limit: usize,
search_after: usize,
) -> Option<MathFractionSpan> {
use tex_expansion::FrontendEventKind as Event;
let (start_event, start) =
events
.iter()
.enumerate()
.skip(search_after)
.find_map(|(index, event)| {
if event.position != start_position {
return None;
}
match &event.kind {
Event::MathFractionStart {
style,
has_rule,
parentheses,
delimiter_settings,
math_fonts,
} => Some((
index,
(
*style,
*has_rule,
*parentheses,
*delimiter_settings,
Arc::clone(math_fonts),
event.location.clone(),
),
)),
_ => None,
}
})?;
let (style, has_rule, parentheses, delimiter_settings, math_fonts, location) = start;
let mut depth = 1usize;
let mut separator_event = None;
for (index, event) in events.iter().enumerate().skip(start_event + 1) {
if event.position > limit {
break;
}
match &event.kind {
Event::MathFractionStart { .. } => depth += 1,
Event::MathFractionSeparator if depth == 1 && separator_event.is_none() => {
separator_event = Some(index);
}
Event::MathFractionEnd if depth == 1 => {
let separator_event = separator_event?;
return Some(MathFractionSpan {
style,
has_rule,
rule_thickness: None,
parentheses,
delimiter_settings,
math_fonts,
start_event,
separator_event,
end_event: index,
separator_position: events[separator_event].position,
end_position: event.position,
location,
});
}
Event::MathFractionEnd => depth -= 1,
_ => {}
}
}
None
}
fn find_math_root_span(
events: &[tex_expansion::FrontendEvent],
start_position: usize,
limit: usize,
search_after: usize,
) -> Option<MathRootSpan> {
use tex_expansion::FrontendEventKind as Event;
let (start_event, has_index, radical, math_fonts, location) = events
.iter()
.enumerate()
.skip(search_after)
.find_map(|(index, event)| {
if event.position != start_position {
return None;
}
match &event.kind {
Event::MathRootStart {
has_index,
radical,
math_fonts,
} => Some((
index,
*has_index,
*radical,
Arc::clone(math_fonts),
event.location.clone(),
)),
_ => None,
}
})?;
let mut depth = 1usize;
let mut separator_event = None;
for (index, event) in events.iter().enumerate().skip(start_event + 1) {
if event.position > limit {
break;
}
match &event.kind {
Event::MathRootStart { .. } => depth += 1,
Event::MathRootSeparator if depth == 1 && separator_event.is_none() => {
separator_event = Some(index);
}
Event::MathRootEnd if depth == 1 => {
let separator_event = separator_event?;
return Some(MathRootSpan {
has_index,
radical,
math_fonts,
start_event,
separator_event,
end_event: index,
separator_position: events[separator_event].position,
end_position: event.position,
location,
});
}
Event::MathRootEnd => depth -= 1,
_ => {}
}
}
None
}
fn find_math_delimiter_span(
events: &[tex_expansion::FrontendEvent],
start_position: usize,
limit: usize,
search_after: usize,
) -> Option<MathDelimiterSpan> {
use tex_expansion::FrontendEventKind as Event;
let (start_event, left, left_settings, location) = events
.iter()
.enumerate()
.skip(search_after)
.find_map(|(index, event)| {
if event.position != start_position {
return None;
}
match &event.kind {
Event::MathDelimiterStart {
delimiter,
settings,
} => Some((index, delimiter.clone(), *settings, event.location.clone())),
_ => None,
}
})?;
let mut depth = 1usize;
let mut middles = Vec::new();
for (index, event) in events.iter().enumerate().skip(start_event + 1) {
if event.position > limit {
break;
}
match &event.kind {
Event::MathDelimiterStart { .. } => depth += 1,
Event::MathDelimiterMiddle {
delimiter,
settings,
} if depth == 1 => {
middles.push((delimiter.clone(), *settings, event.position, index));
}
Event::MathDelimiterEnd {
delimiter,
settings,
} if depth == 1 => {
return Some(MathDelimiterSpan {
left,
left_settings,
right: delimiter.clone(),
right_settings: *settings,
middles,
start_event,
end_event: index,
end_position: event.position,
location,
});
}
Event::MathDelimiterEnd { .. } => depth -= 1,
_ => {}
}
}
None
}
fn find_math_choice_span(
events: &[tex_expansion::FrontendEvent],
start_position: usize,
limit: usize,
search_after: usize,
) -> Option<MathChoiceSpan> {
use tex_expansion::FrontendEventKind as Event;
let (start_event, location) =
events
.iter()
.enumerate()
.skip(search_after)
.find_map(|(index, event)| {
(event.position == start_position && matches!(&event.kind, Event::MathChoiceStart))
.then(|| (index, event.location.clone()))
})?;
let mut nested_depth = 0usize;
let mut current_branch: Option<(MathStyleCommand, usize, usize)> = None;
let mut branches = Vec::with_capacity(4);
for (index, event) in events.iter().enumerate().skip(start_event + 1) {
if event.position > limit {
break;
}
match &event.kind {
Event::MathChoiceStart => nested_depth += 1,
Event::MathChoiceEnd if nested_depth > 0 => nested_depth -= 1,
Event::MathChoiceEnd => {
let (style, branch_event, branch_position) = current_branch?;
branches.push(MathChoiceBranchSpan {
style,
start_event: branch_event,
end_event: index,
start_position: branch_position,
end_position: event.position,
});
if branches.len() != 4 {
return None;
}
return Some(MathChoiceSpan {
branches,
start_event,
end_event: index,
end_position: event.position,
location,
});
}
Event::MathChoiceBranch(style) if nested_depth == 0 => {
if let Some((previous_style, branch_event, branch_position)) = current_branch {
branches.push(MathChoiceBranchSpan {
style: previous_style,
start_event: branch_event,
end_event: index,
start_position: branch_position,
end_position: event.position,
});
}
current_branch = Some((*style, index, event.position));
}
_ => {}
}
}
None
}
fn find_math_container_end(
events: &[tex_expansion::FrontendEvent],
start_position: usize,
limit: usize,
fraction_search_after: usize,
root_search_after: usize,
delimiter_search_after: usize,
group_search_after: usize,
choice_search_after: usize,
) -> Option<(usize, usize)> {
let fraction = find_math_fraction_span(events, start_position, limit, fraction_search_after);
let root = find_math_root_span(events, start_position, limit, root_search_after);
let delimiter = find_math_delimiter_span(events, start_position, limit, delimiter_search_after);
let group = find_math_group_span(events, start_position, limit, group_search_after);
let choice = find_math_choice_span(events, start_position, limit, choice_search_after);
[
fraction.map(|span| (span.start_event, span.end_position, span.end_event)),
root.map(|span| (span.start_event, span.end_position, span.end_event)),
delimiter.map(|span| (span.start_event, span.end_position, span.end_event)),
group.map(|span| (span.start_event, span.end_position, span.end_event)),
choice.map(|span| (span.start_event, span.end_position, span.end_event)),
]
.into_iter()
.flatten()
.min_by_key(|(start_event, _, _)| *start_event)
.map(|(_, end_position, end_event)| (end_position, end_event))
}
fn read_math_argument_with_events(
expanded: &tex_expansion::ExpandedTokenStream,
range: &Range<usize>,
events: &[tex_expansion::FrontendEvent],
start: usize,
search_after: usize,
) -> Option<(Range<usize>, usize)> {
let mut argument_start = start;
while let Some(tex_expansion::ExpandedTokenValue::Space(character)) =
expanded.token_value_at(range.start + argument_start)
{
if !character.is_whitespace() {
break;
}
argument_start += character.len_utf8();
}
let absolute_start = range.start + argument_start;
if let Some((end_position, _)) = find_math_container_end(
events,
absolute_start,
range.end,
search_after,
search_after,
search_after,
search_after,
search_after,
) {
return Some((absolute_start..end_position, end_position - range.start));
}
let end_position = expanded.token_item_at(absolute_start)?.end_position;
(end_position <= range.end)
.then_some((absolute_start..end_position, end_position - range.start))
}
fn parse_child_expression(
expanded: &tex_expansion::ExpandedTokenStream,
parent_events: &[tex_expansion::FrontendEvent],
range: Range<usize>,
) -> Result<MathExpr, String> {
let events = events_for_range(parent_events, &range);
parse_math_expression_with_events(expanded, range, &events)
}
fn events_for_range(
events: &[tex_expansion::FrontendEvent],
range: &Range<usize>,
) -> Vec<tex_expansion::FrontendEvent> {
events
.iter()
.filter(|event| range.start <= event.position && event.position <= range.end)
.cloned()
.collect()
}
fn with_source(
expanded: &tex_expansion::ExpandedTokenStream,
range: Range<usize>,
expression: MathExpr,
) -> MathExpr {
MathExpr::Spanned {
location: expanded.source_at(range.start),
expression: Box::new(expression),
}
}
pub fn split_math_cells(
expanded: &tex_expansion::ExpandedTokenStream,
range: Range<usize>,
separators: &[usize],
) -> Option<Vec<Range<usize>>> {
if separators.is_empty() {
return None;
}
let range_len = range.end - range.start;
let events = events_for_range(&expanded.events, &range);
let mut cells = Vec::with_capacity(separators.len() + 1);
let mut cell_start = 0usize;
let mut cursor = 0usize;
let mut separator_index = 0usize;
let mut fraction_search_after = 0usize;
let mut root_search_after = 0usize;
let mut delimiter_search_after = 0usize;
let mut group_search_after = 0usize;
let mut choice_search_after = 0usize;
while cursor < range_len {
if let Some((end_position, end_event)) = find_math_container_end(
&events,
range.start + cursor,
range.end,
fraction_search_after,
root_search_after,
delimiter_search_after,
group_search_after,
choice_search_after,
) {
cursor = end_position - range.start;
fraction_search_after = end_event + 1;
root_search_after = end_event + 1;
delimiter_search_after = end_event + 1;
group_search_after = end_event + 1;
choice_search_after = end_event + 1;
continue;
}
while separators
.get(separator_index)
.is_some_and(|separator| *separator < cursor)
{
separator_index += 1;
}
if separators.get(separator_index) == Some(&cursor) {
cells.push(cell_start..cursor);
cell_start = cursor;
separator_index += 1;
continue;
}
let absolute_cursor = range.start + cursor;
if let Some(token) = expanded.token_item_at(absolute_cursor) {
cursor = token.end_position - range.start;
} else {
cursor = expanded
.next_token_item_at_or_after(absolute_cursor + 1, range.end)
.map(|token| token.position - range.start)
.unwrap_or(range_len);
}
}
while separators.get(separator_index) == Some(&range_len) {
cells.push(cell_start..range_len);
cell_start = range_len;
separator_index += 1;
}
cells.push(cell_start..range_len);
Some(cells)
}
fn attach_math_script(
items: &mut Vec<MathExpr>,
is_superscript: bool,
script: MathExpr,
location: Option<SourceLocation>,
limit_mode: Option<MathLimitMode>,
) -> Result<(), String> {
let base = items.pop().unwrap_or_else(|| MathExpr::Text(String::new()));
let (base_location, base_expression) = unwrap_source(base);
let base = match base_expression {
MathExpr::Atom {
class: MathClass::Ordinary,
text,
math_family,
math_slots,
math_fonts,
} if text.chars().count() > 1 => {
let split_at = text.char_indices().last().map(|(index, _)| index).unwrap();
let split_slot = text[..split_at].chars().count();
let (base_math_slots, script_base_math_slots) = if math_family.is_some() {
(
math_slots[..split_slot].to_vec(),
math_slots[split_slot..].to_vec(),
)
} else {
(Vec::new(), Vec::new())
};
let split_location = base_location
.as_ref()
.map(|location| advance_location(location, text[..split_at].chars().count()));
items.push(with_location(
base_location.clone(),
MathExpr::Atom {
class: MathClass::Ordinary,
text: text[..split_at].to_string(),
math_family,
math_slots: base_math_slots,
math_fonts: Arc::clone(&math_fonts),
},
));
with_location(
split_location,
MathExpr::Atom {
class: MathClass::Ordinary,
text: text[split_at..].to_string(),
math_family,
math_slots: script_base_math_slots,
math_fonts,
},
)
}
base => with_location(base_location, base),
};
let (base_location, base_expression) = unwrap_source(base);
let (base, mut sub, mut superscript, current_limit_mode) = match base_expression {
MathExpr::Script {
base,
sub,
superscript,
limits,
} => (base, sub, superscript, limits),
base => {
let limits = if matches!(
base,
MathExpr::Accent {
position: MathAccent::OverBrace | MathAccent::UnderBrace,
..
}
) {
MathLimitMode::Limits
} else {
MathLimitMode::Automatic
};
(
Box::new(with_location(base_location, base)),
None,
None,
limits,
)
}
};
if is_superscript {
if superscript.is_some() {
return Err(math_script_error(location.as_ref(), true));
}
superscript = Some(Box::new(script));
} else {
if sub.is_some() {
return Err(math_script_error(location.as_ref(), false));
}
sub = Some(Box::new(script));
}
let limit_mode = limit_mode.filter(|_| base.class() == MathClass::Operator);
let limits = limit_mode.unwrap_or(current_limit_mode);
items.push(with_location(
location,
MathExpr::Script {
base,
sub,
superscript,
limits,
},
));
Ok(())
}
fn math_script_error(location: Option<&SourceLocation>, is_superscript: bool) -> String {
let message = if is_superscript {
"Double superscript"
} else {
"Double subscript"
};
math_parse_error(location, message)
}
fn math_parse_error(location: Option<&SourceLocation>, message: &str) -> String {
let Some(location) = location else {
return message.to_string();
};
let origin = match &location.origin {
SourceOrigin::File(path) => path.display().to_string(),
SourceOrigin::Terminal => "<input>".to_string(),
};
format!("{origin}:{}:{}: {message}", location.line, location.column)
}
fn append_math_text(
items: &mut Vec<MathExpr>,
character: char,
class: MathClass,
math_family: Option<u8>,
math_slot: Option<u8>,
math_fonts: MathFontFamilies,
location: Option<SourceLocation>,
) {
if let Some(MathExpr::Spanned {
location: previous_location,
expression,
}) = items.last_mut()
{
if let MathExpr::Atom {
class: previous_class,
text,
math_family: previous_family,
math_slots,
math_fonts: previous_math_fonts,
} = expression.as_mut()
{
if *previous_class == class
&& *previous_family == math_family
&& **previous_math_fonts == *math_fonts
&& math_slot_follows(math_family, math_slots.last().copied(), math_slot)
&& locations_are_contiguous(previous_location.as_ref(), text, location.as_ref())
{
text.push(character);
if let Some(slot) = math_slot {
math_slots.push(slot);
}
return;
}
}
}
items.push(with_location(
location,
MathExpr::Atom {
class,
text: character.to_string(),
math_family,
math_slots: math_slot.into_iter().collect(),
math_fonts,
},
));
}
fn math_slot_follows(family: Option<u8>, previous_slot: Option<u8>, next_slot: Option<u8>) -> bool {
match (family, previous_slot, next_slot) {
(None, None, None) => true,
(Some(_), Some(previous), Some(next)) => previous.checked_add(1) == Some(next),
_ => false,
}
}
fn force_math_family(expression: &mut MathExpr, from: u8, to: u8) {
match expression {
MathExpr::Spanned { expression, .. } => force_math_family(expression, from, to),
MathExpr::Styled { .. } => {}
MathExpr::Classified { body, .. }
| MathExpr::Phantom { body, .. }
| MathExpr::Accent { body, .. } => {
force_math_family(body, from, to);
}
MathExpr::Atom { math_family, .. } if *math_family == Some(from) => {
*math_family = Some(to);
}
MathExpr::Sequence(items) => {
for item in items {
force_math_family(item, from, to);
}
}
MathExpr::Alignment { rows, .. } => {
for item in rows.iter_mut().flatten() {
force_math_family(item, from, to);
}
}
MathExpr::Fraction {
numerator,
denominator,
..
} => {
force_math_family(numerator, from, to);
force_math_family(denominator, from, to);
}
MathExpr::MathChoice {
display,
text,
script,
scriptscript,
} => {
force_math_family(display, from, to);
force_math_family(text, from, to);
force_math_family(script, from, to);
force_math_family(scriptscript, from, to);
}
MathExpr::Root { index, body, .. } => {
if let Some(index) = index {
force_math_family(index, from, to);
}
force_math_family(body, from, to);
}
MathExpr::Delimited { body, .. } => force_math_family(body, from, to),
MathExpr::Fenced { segments, .. } => {
for segment in segments {
force_math_family(segment, from, to);
}
}
MathExpr::Script {
base,
sub,
superscript,
..
} => {
force_math_family(base, from, to);
if let Some(sub) = sub {
force_math_family(sub, from, to);
}
if let Some(superscript) = superscript {
force_math_family(superscript, from, to);
}
}
MathExpr::Text(_)
| MathExpr::TextStyled { .. }
| MathExpr::Atom { .. }
| MathExpr::SizedDelimiter { .. }
| MathExpr::UnicodeDelimiter { .. }
| MathExpr::MathStyleChange(_)
| MathExpr::MathSpacingChange(_)
| MathExpr::MathLineBreakPenaltiesChange(_)
| MathExpr::BreakPenalty(_)
| MathExpr::Space(_)
| MathExpr::Glue(_)
| MathExpr::Kern(_) => {}
}
}
fn with_location(location: Option<SourceLocation>, expression: MathExpr) -> MathExpr {
MathExpr::Spanned {
location,
expression: Box::new(expression),
}
}
fn append_math_scope(
items: &mut Vec<MathExpr>,
expression: MathExpr,
location: Option<SourceLocation>,
) {
// Ordinary math braces scope TeX state but do not create an atom boundary.
let expression = match expression {
MathExpr::Spanned { expression, .. } => *expression,
expression => expression,
};
if contains_math_style_change(&expression) {
let expression = match expression {
MathExpr::Sequence(_) => expression,
expression => MathExpr::Sequence(vec![expression]),
};
items.push(with_location(location, expression));
return;
}
match expression {
MathExpr::Sequence(mut group_items) => items.append(&mut group_items),
MathExpr::Text(text) if text.is_empty() => {}
MathExpr::TextStyled { text, .. } if text.is_empty() => {}
expression => items.push(expression),
}
}
fn contains_math_style_change(expression: &MathExpr) -> bool {
match expression {
MathExpr::Spanned { expression, .. } => contains_math_style_change(expression),
MathExpr::MathStyleChange(_) => true,
MathExpr::Sequence(items) => items.iter().any(contains_math_style_change),
_ => false,
}
}
fn unwrap_source(expression: MathExpr) -> (Option<SourceLocation>, MathExpr) {
match expression {
MathExpr::Spanned {
location,
expression,
} => (location, *expression),
expression => (None, expression),
}
}
fn advance_location(location: &SourceLocation, characters: usize) -> SourceLocation {
let mut location = location.clone();
location.column += characters;
location
}
fn locations_are_contiguous(
previous: Option<&SourceLocation>,
previous_text: &str,
next: Option<&SourceLocation>,
) -> bool {
match (previous, next) {
(None, None) => true,
(Some(previous), Some(next)) => {
previous.origin == next.origin
&& previous.line == next.line
&& previous.column + previous_text.chars().count() == next.column
}
_ => false,
}
}
fn math_class_for_character(character: char) -> MathClass {
match character {
'+' | '−' | '-' | '±' | '∓' | '×' | '÷' | '⋅' | '·' | '∪' | '∩' => {
MathClass::Binary
}
'=' | '<' | '>' | '≤' | '≥' | '≠' | '≈' | '≃' | '∼' | ':' | '∈' | '∉' | '⊂' | '⊆' | '⊃'
| '⊇' | '→' | '←' | '⇒' | '⇔' | '↦' => MathClass::Relation,
'(' | '[' | '{' | '⟨' => MathClass::Opening,
')' | ']' | '}' | '⟩' => MathClass::Closing,
',' | ';' => MathClass::Punctuation,
'∑' | '∏' | '∫' | '∮' | '⋃' | '⋂' | '⋁' | '⋀' => MathClass::Operator,
_ => MathClass::Ordinary,
}
}
fn math_code_properties(
character: char,
math_code: Option<u16>,
active_math_family: Option<i32>,
) -> (MathClass, Option<u8>, Option<u8>) {
let Some(code) = math_code.filter(|code| character.is_ascii() || *code != 0) else {
return (math_class_for_character(character), None, None);
};
let math_class = (code >> 12) & 0x7;
let class = match math_class {
1 => MathClass::Operator,
2 => MathClass::Binary,
3 => MathClass::Relation,
4 => MathClass::Opening,
5 => MathClass::Closing,
6 => MathClass::Punctuation,
0 | 7 => MathClass::Ordinary,
_ => unreachable!("math code classes use three bits"),
};
let math_family = if math_class == 7 {
active_math_family
.filter(|family| (0..=15).contains(family))
.map(|family| family as u8)
.unwrap_or(((code >> 8) & 0xf) as u8)
} else {
((code >> 8) & 0xf) as u8
};
(class, Some(math_family), Some((code & 0xff) as u8))
}