use std::collections::{HashMap, VecDeque}; use crate::{ expanded::{self, ExpandedTokenStream}, math_code::UnicodeMathCode, math_expr::*, math_mode::{ MathScope as Delimiter, is_display_math_environment, math_delimiter_error, validate_math_delimiters, }, source::{SourceLocation, SourceOrigin}, }; const DEFAULT_JOT: common::Scaled = common::Scaled(3 * 65_536); fn default_jot() -> common::Scaled { DEFAULT_JOT } #[derive(Clone, PartialEq, Eq, Hash)] struct MathParseCacheKey { source_segments: Vec, tokens: Vec, events: Vec, delimiter: Delimiter, } #[derive(Clone, PartialEq, Eq, Hash)] struct MathParseSourceSegmentKey { output: std::ops::Range, origin: SourceOrigin, column_advances: bool, column_character_starts: Vec, } #[derive(Clone, PartialEq, Eq, Hash)] struct MathParseTokenKey { position: usize, end_position: usize, value: expanded::ExpandedTokenValue, math_code: Option, math_family: Option, unicode_math_code: Option, math_fonts: MathFontFamilies, math_line_break_penalties: MathLineBreakPenalties, } #[derive(Clone, PartialEq, Eq, Hash)] struct MathParseEventKey { position: usize, kind: expanded::FrontendEventKind, math_line_break_penalties: MathLineBreakPenalties, } #[derive(Clone)] struct MathParseCacheEntry { expression: MathExpr, source_segments: Vec, events: Vec, } #[derive(Default)] pub struct MathParseCache { entries: std::collections::HashMap, insertion_order: VecDeque, } impl MathParseCache { fn get( &self, key: &MathParseCacheKey, source_segments: &[expanded::SourceSegment], events: &[expanded::FrontendEvent], ) -> Option { let entry = self.entries.get(key)?; let locations = rebase_source_locations( &entry.source_segments, source_segments, &entry.events, events, &key.tokens, )?; let mut expression = entry.expression.clone(); if !expression.rebase_source_locations(&locations) { return None; } Some(expression) } fn insert( &mut self, key: MathParseCacheKey, expression: MathExpr, source_segments: Vec, events: Vec, ) { const CAPACITY: usize = 2048; if !self.entries.contains_key(&key) { if self.entries.len() == CAPACITY && let Some(oldest) = self.insertion_order.pop_front() { self.entries.remove(&oldest); } self.insertion_order.push_back(key.clone()); } self.entries.insert( key, MathParseCacheEntry { expression, source_segments, events, }, ); } } pub fn lower_math( source: ExpandedTokenStream, math_parse_cache: &mut MathParseCache, ) -> Result { let delimited = convert_math_shift_delimiters(&source)?; validate_math_delimiters(&delimited)?; collect_math_expressions(&delimited, math_parse_cache) } fn collect_math_expressions( source: &expanded::ExpandedTokenStream, math_parse_cache: &mut MathParseCache, ) -> Result { use expanded::FrontendEventKind as Event; let mut output = expanded::ExpandedTokenStream::default(); let mut copied_item = 0; let mut event_item = 0; let mut active_math: Option<(usize, Delimiter, SourceLocation)> = None; let mut math_events: Vec = Vec::new(); for event in &source.events { // The event list and the event items are kept in the same order, so the // next event item belongs to this event. Items before it are the tokens // that were expanded before the event, including zero-width spaces that // share the event's byte position. while event_item < source.items.len() && !matches!( source.items[event_item].kind, expanded::ExpandedItemKind::Event(_) ) { event_item += 1; } let this_event_item = event_item; event_item += 1; let start_delimiter = match &event.kind { Event::DisplayMathStart => Some(Delimiter::Display), Event::InlineMathStart => Some(Delimiter::Inline), Event::BeginEnvironment { name: environment, .. } if is_display_math_environment(environment) => { Some(Delimiter::Environment(environment.clone())) } _ => None, }; let end_delimiter = match &event.kind { Event::DisplayMathEnd(_) => Some(Delimiter::Display), Event::InlineMathEnd(_) => Some(Delimiter::Inline), Event::EndEnvironment { name, .. } if is_display_math_environment(name) => { Some(Delimiter::Environment(name.clone())) } _ => None, }; if let Some((content_start, delimiter, location)) = active_math.as_ref() { if end_delimiter.as_ref() == Some(delimiter) { if let Some(settings) = math_delimiter_settings_at_scope_end(&event.kind) { apply_math_delimiter_settings(&mut math_events, settings); } let expression = parse_math_for_delimiter( source, *content_start..event.position, &math_events, delimiter, math_parse_cache, )?; let expression_text = expression.plain_text(); if !expression_text.is_empty() { let rows = equation_rows_for_math(&math_events, delimiter, &expression, location)?; output.insert_event( if *delimiter != Delimiter::Inline { Event::DisplayMath { expression, environment: match delimiter { Delimiter::Environment(name) => Some(name.clone()), Delimiter::Display | Delimiter::Inline => None, }, rows, } } else { Event::InlineMath(expression) }, location.clone(), ); } for nested_event in math_events.drain(..) { if !is_math_structure_event(&nested_event.kind) && (delimiter == &Delimiter::Inline || !matches!(&nested_event.kind, Event::Label(_))) { output.insert_event(nested_event.kind, nested_event.location); } } active_math = None; copied_item = this_event_item + 1; continue; } math_events.push(event.clone()); continue; } output.copy_items(source, &source.items[copied_item..this_event_item]); copied_item = this_event_item + 1; if let Some(delimiter) = start_delimiter { active_math = Some((event.position, delimiter, event.location.clone())); } else { output.insert_event(event.kind.clone(), event.location.clone()); } } if let Some((content_start, delimiter, location)) = active_math { let expression = parse_math_for_delimiter( source, content_start..source.output_len(), &math_events, &delimiter, math_parse_cache, )?; if !expression.plain_text().is_empty() { let rows = equation_rows_for_math(&math_events, &delimiter, &expression, &location)?; output.insert_event( if delimiter != Delimiter::Inline { Event::DisplayMath { expression, environment: match &delimiter { Delimiter::Environment(name) => Some(name.clone()), Delimiter::Display | Delimiter::Inline => None, }, rows, } } else { Event::InlineMath(expression) }, location, ); } for nested_event in math_events { if !is_math_structure_event(&nested_event.kind) && (delimiter == Delimiter::Inline || !matches!(&nested_event.kind, Event::Label(_))) { output.insert_event(nested_event.kind, nested_event.location); } } copied_item = source.items.len(); } output.copy_items(source, &source.items[copied_item..]); Ok(output) } fn math_delimiter_settings_at_scope_end( kind: &expanded::FrontendEventKind, ) -> Option { use expanded::FrontendEventKind as Event; match kind { Event::DisplayMathEnd(settings) | Event::InlineMathEnd(settings) => Some(*settings), Event::EndEnvironment { delimiter_settings, .. } => Some(*delimiter_settings), _ => None, } } fn apply_math_delimiter_settings( events: &mut [expanded::FrontendEvent], settings: MathDelimiterSettings, ) { use expanded::FrontendEventKind as Event; for event in events { match &mut event.kind { Event::MathDelimiterStart { settings: event_settings, .. } | Event::MathDelimiterMiddle { settings: event_settings, .. } | Event::MathDelimiterEnd { settings: event_settings, .. } => *event_settings = settings, Event::MathManualDelimiter { settings: event_settings, .. } | Event::MathUnicodeDelimiter { settings: event_settings, .. } => *event_settings = settings, Event::MathFractionStart { delimiter_settings, .. } => *delimiter_settings = settings, Event::MathInfixFraction(kind, _) => match kind { MathInfixFractionKind::Choose(event_settings) => *event_settings = settings, MathInfixFractionKind::OverWithDelims(delimiters) | MathInfixFractionKind::AtopWithDelims(delimiters) => { delimiters.settings = settings; } MathInfixFractionKind::AboveWithDelims { delimiters, .. } => { delimiters.settings = settings; } MathInfixFractionKind::Over | MathInfixFractionKind::Atop | MathInfixFractionKind::Above(_) => {} }, _ => {} } } } fn is_math_structure_event(kind: &expanded::FrontendEventKind) -> bool { use expanded::FrontendEventKind as Event; matches!( kind, Event::MathCell | Event::RowBreak | Event::MathFractionStart { .. } | Event::MathFractionSeparator | Event::MathFractionEnd | Event::MathInfixFraction(..) | Event::MathCharacter { .. } | Event::MathUnicodeCharacter { .. } | Event::MathUnicodeDelimiter { .. } | Event::MathStyleChange(_) | Event::MathChoiceStart | Event::MathChoiceBranch(_) | Event::MathChoiceEnd | Event::MathLimitMode(_) | Event::SuppressEquationNumber | Event::EquationTag(_) | Event::MathSpace(_) | Event::HorizontalGlue(_) | Event::VerticalGlue(_) | Event::Penalty(_) | Event::MathAccentStart { .. } | Event::MathAccentEnd | Event::MathFontStart(_) | Event::MathFontEnd | Event::MathOperatorStart | Event::MathOperatorEnd | Event::MathClassStart(_) | Event::MathClassEnd | Event::MathRootStart { .. } | Event::MathRootSeparator | Event::MathRootEnd | Event::MathDelimiterStart { .. } | Event::MathDelimiterMiddle { .. } | Event::MathDelimiterEnd { .. } | Event::MathManualDelimiter { .. } | Event::LiteralAmpersand | Event::LiteralCharacter(_) | Event::LineBreak | Event::GroupStart | Event::GroupEnd ) } fn equation_rows_for_math( events: &[expanded::FrontendEvent], delimiter: &Delimiter, expression: &MathExpr, location: &SourceLocation, ) -> Result, String> { use expanded::{DisplayMathRow, FrontendEventKind as Event}; if matches!(delimiter, Delimiter::Inline) && events .iter() .any(|event| matches!(event.kind, Event::EquationTag(_))) { return Err(math_delimiter_error( location, "`\\tag` can only be used in display math", )); } let has_alignment_rows = matches!( delimiter, Delimiter::Environment(name) if matches!( name.as_str(), "align" | "align*" | "alignat" | "alignat*" | "flalign" | "flalign*" | "eqnarray" | "eqnarray*" | "gather" | "gather*" ) ); let mut rows = vec![DisplayMathRow::default()]; let mut nested_environment_depth = 0usize; for event in events { match &event.kind { Event::BeginEnvironment { .. } => nested_environment_depth += 1, Event::EndEnvironment { .. } => { nested_environment_depth = nested_environment_depth.saturating_sub(1); } Event::RowBreak if has_alignment_rows && nested_environment_depth == 0 => { rows.push(DisplayMathRow::default()); } Event::EquationTag(tag) => { let row = rows.last_mut().expect("display math has at least one row"); if row.equation_tag.replace(tag.clone()).is_some() { return Err(math_delimiter_error( &event.location, "only one `\\tag` is allowed per displayed equation row", )); } } Event::SuppressEquationNumber => { rows.last_mut() .expect("display math has at least one row") .suppress_number = true; } Event::Label(key) => rows .last_mut() .expect("display math has at least one row") .labels .push(key.clone()), _ => {} } } if has_alignment_rows && let Some(row_count) = equation_alignment_row_count(expression) { rows.truncate(row_count); rows.resize_with(row_count, DisplayMathRow::default); } Ok(rows) } fn equation_alignment_row_count(expression: &MathExpr) -> Option { match expression { MathExpr::Spanned { expression, .. } | MathExpr::Styled { expression, .. } | MathExpr::Classified { body: expression, .. } => equation_alignment_row_count(expression), MathExpr::Sequence(items) if items.len() == 1 => equation_alignment_row_count(&items[0]), MathExpr::Alignment { rows, .. } => Some(rows.len()), _ => None, } } fn parse_math_for_delimiter( source: &expanded::ExpandedTokenStream, range: std::ops::Range, events: &[expanded::FrontendEvent], delimiter: &Delimiter, math_parse_cache: &mut MathParseCache, ) -> Result { let source_segments = source.segment_signature(range.clone()); let math_events = events .iter() .filter(|event| range.start <= event.position && event.position <= range.end) .cloned() .collect::>(); let math_tokens = source .items .iter() .filter(|item| range.start <= item.position && item.position < range.end) .filter_map(|item| match &item.kind { expanded::ExpandedItemKind::Token(value) => Some(MathParseTokenKey { position: item.position - range.start, end_position: item.end_position - range.start, value: value.clone(), math_code: item.math_code, math_family: item.math_family, unicode_math_code: item.unicode_math_code, math_fonts: std::sync::Arc::clone(&item.math_fonts), math_line_break_penalties: item.math_line_break_penalties, }), expanded::ExpandedItemKind::Event(_) => None, }) .collect(); let key = MathParseCacheKey { source_segments: source_segments .iter() .map(|segment| MathParseSourceSegmentKey { output: segment.output.clone(), origin: segment.location.origin.clone(), column_advances: segment.column_advances, column_character_starts: segment.column_character_starts.clone(), }) .collect(), tokens: math_tokens, events: math_events .iter() .map(|event| MathParseEventKey { position: event.position - range.start, kind: event.kind.clone(), math_line_break_penalties: event.math_line_break_penalties, }) .collect(), delimiter: delimiter.clone(), }; if let Some(expression) = math_parse_cache.get(&key, &source_segments, &math_events) { return Ok(expression); } let expression = if let Delimiter::Environment(environment) = delimiter { let (body_start, alignment) = math_environment_preamble(range.clone(), environment, events); let (math_fonts, jot) = events .iter() .find_map(|event| { if range.start <= event.position && event.position <= range.end { match &event.kind { expanded::FrontendEventKind::BeginEnvironment { name, math_fonts, jot, } if name == environment => Some((math_fonts.clone(), *jot)), _ => None, } } else { None } }) .unwrap_or_else(|| (MathFontFamilies::default(), default_jot())); let expression = parse_math_with_environments(source, body_start..range.end, events)?; apply_math_environment_with_alignment(expression, environment, alignment, math_fonts, jot) } else { parse_math_with_environments(source, range, events)? }; math_parse_cache.insert(key, expression.clone(), source_segments, math_events); Ok(expression) } fn rebase_source_locations( old_segments: &[expanded::SourceSegment], new_segments: &[expanded::SourceSegment], old_events: &[expanded::FrontendEvent], new_events: &[expanded::FrontendEvent], tokens: &[MathParseTokenKey], ) -> Option> { if old_segments.len() != new_segments.len() || old_events.len() != new_events.len() { return None; } let mut locations = HashMap::new(); for (old, new) in old_segments.iter().zip(new_segments) { if old.output != new.output || old.column_advances != new.column_advances || old.location.origin != new.location.origin { return None; } if old.column_advances { let character_count = token_character_count(tokens, &old.output)?; let mut old_location = old.location.clone(); let mut new_location = new.location.clone(); if !insert_location_mapping(&mut locations, old_location.clone(), new_location.clone()) { return None; } for _ in 0..character_count { old_location.column += 1; new_location.column += 1; if !insert_location_mapping( &mut locations, old_location.clone(), new_location.clone(), ) { return None; } } } else if !insert_location_mapping( &mut locations, old.location.clone(), new.location.clone(), ) { return None; } } for (old, new) in old_events.iter().zip(new_events) { if old.kind != new.kind || old.math_line_break_penalties != new.math_line_break_penalties || !insert_location_mapping(&mut locations, old.location.clone(), new.location.clone()) { return None; } } Some(locations) } fn token_character_count( tokens: &[MathParseTokenKey], range: &std::ops::Range, ) -> Option { let count = tokens .iter() .filter(|token| range.start <= token.position && token.position < range.end) .try_fold(0, |count, token| token.value.character().map(|_| count + 1))?; (count > 0).then_some(count) } fn insert_location_mapping( locations: &mut HashMap, old: SourceLocation, new: SourceLocation, ) -> bool { match locations.get(&old) { Some(previous) => previous == &new, None => { locations.insert(old, new); true } } } fn parse_math_with_environments( source: &expanded::ExpandedTokenStream, range: std::ops::Range, events: &[expanded::FrontendEvent], ) -> Result { use expanded::FrontendEventKind as Event; let Some((begin_index, end_index, environment, math_fonts, jot)) = events.iter().enumerate().find_map(|(begin_index, event)| { let Event::BeginEnvironment { name: environment, math_fonts, jot, } = &event.kind else { return None; }; if event.position < range.start || event.position >= range.end || !is_nested_math_environment(environment) { return None; } let mut depth = 0usize; let end_index = events .iter() .enumerate() .skip(begin_index) .find_map(|(index, candidate)| match &candidate.kind { Event::BeginEnvironment { name, .. } if name == environment => { depth += 1; None } Event::EndEnvironment { name, .. } if name == environment => { depth -= 1; (depth == 0).then_some(index) } _ => None, })?; Some(( begin_index, end_index, environment.clone(), math_fonts.clone(), *jot, )) }) else { return parse_math_rows(source, range, events); }; let begin_position = events[begin_index].position; let end_position = events[end_index].position; let (body_start, alignment) = math_environment_preamble(begin_position..end_position, &environment, events); let mut expressions = Vec::with_capacity(3); if range.start < begin_position { let prefix = parse_math_with_environments( source, range.start..begin_position, &events[..begin_index], )?; if !prefix.plain_text().is_empty() { expressions.push(prefix); } } let body = parse_math_with_environments( source, body_start..end_position, &events[begin_index + 1..end_index], )?; expressions.push(apply_math_environment_with_alignment( body, &environment, alignment, math_fonts, jot, )); if end_position < range.end { let suffix = parse_math_with_environments( source, end_position..range.end, &events[end_index + 1..], )?; if !suffix.plain_text().is_empty() { expressions.push(suffix); } } Ok(match expressions.len() { 1 => expressions.pop().unwrap(), _ => MathExpr::Sequence(expressions), }) } fn parse_math_rows( source: &expanded::ExpandedTokenStream, range: std::ops::Range, events: &[expanded::FrontendEvent], ) -> Result { use expanded::FrontendEventKind as Event; let row_breaks = events .iter() .enumerate() .filter(|(_, event)| { matches!(&event.kind, Event::RowBreak) && range.start <= event.position && event.position < range.end }) .collect::>(); let mut rows = Vec::with_capacity(row_breaks.len() + 1); let mut row_start = range.start; let mut event_start = 0; for (break_index, row_break) in row_breaks { rows.push(parse_math_row( source, row_start..row_break.position, &events[event_start..break_index], )?); row_start = row_break.position; event_start = break_index + 1; } if row_start < range.end || rows.is_empty() { rows.push(parse_math_row( source, row_start..range.end, &events[event_start..], )?); } if rows.len() == 1 && rows[0].len() == 1 { return Ok(rows.pop().unwrap().pop().unwrap()); } Ok(MathExpr::Spanned { location: source.source_at(range.start), expression: Box::new(MathExpr::Alignment { rows, alignment: MathAlignment::Alternating, baseline: MathAlignmentBaseline::FirstRow, math_fonts: MathFontFamilies::default(), cell_style: MathCellStyle::Inherit, row_spacing: MathRowSpacing::Array, }), }) } fn parse_math_row( source: &expanded::ExpandedTokenStream, range: std::ops::Range, events: &[expanded::FrontendEvent], ) -> Result, String> { let cell_positions = events .iter() .filter_map(|event| { (matches!(&event.kind, expanded::FrontendEventKind::MathCell) && range.start <= event.position && event.position <= range.end) .then_some(event.position - range.start) }) .collect::>(); if let Some(cells) = crate::math_parser::split_math_cells(source, range.clone(), &cell_positions) { return cells .into_iter() .map(|cell| { let child_range = range.start + cell.start..range.start + cell.end; let child_events = events .iter() .filter(|event| { child_range.start <= event.position && event.position <= child_range.end }) .cloned() .collect::>(); crate::math_parser::parse_math_expression_with_events( source, child_range, &child_events, ) }) .collect(); } Ok(vec![crate::math_parser::parse_math_expression_with_events( source, range, events, )?]) } fn is_nested_math_environment(environment: &str) -> bool { matches!( environment, "matrix" | "pmatrix" | "bmatrix" | "Bmatrix" | "vmatrix" | "Vmatrix" | "smallmatrix" | "aligned" | "alignedat" | "split" | "gathered" | "array" | "cases" ) } fn math_environment_preamble( range: std::ops::Range, environment: &str, events: &[expanded::FrontendEvent], ) -> (usize, MathAlignment) { let default_alignment = match environment { "matrix" | "pmatrix" | "bmatrix" | "Bmatrix" | "vmatrix" | "Vmatrix" | "smallmatrix" | "gather" | "gather*" | "gathered" => MathAlignment::Centered, "multline" | "multline*" => MathAlignment::Multline, "cases" => MathAlignment::Left, "alignedat" | "alignat" | "alignat*" => MathAlignment::AlternatingTight, "eqnarray" | "eqnarray*" => MathAlignment::Columns(vec![ MathColumnAlignment::Right, MathColumnAlignment::Center, MathColumnAlignment::Left, ]), _ => MathAlignment::Alternating, }; if !matches!(environment, "array" | "alignedat" | "alignat" | "alignat*") { return (range.start, default_alignment); } let argument = events.iter().find_map(|event| { (event.position == range.start) .then_some(&event.kind) .and_then(|kind| match kind { expanded::FrontendEventKind::EnvironmentArgument(argument) => { Some(argument.as_str()) } _ => None, }) }); let alignment = if environment == "array" { argument .and_then(parse_array_preamble) .map(|(columns, vertical_rules)| MathAlignment::ArrayColumns { columns, vertical_rules, }) .unwrap_or(default_alignment) } else { default_alignment }; (range.start, alignment) } fn parse_array_preamble(preamble: &str) -> Option<(Vec, Vec)> { let mut columns = Vec::new(); let mut vertical_rules = vec![0]; parse_array_preamble_part(preamble, &mut columns, &mut vertical_rules, 0)?; (!columns.is_empty()).then_some((columns, vertical_rules)) } fn parse_array_preamble_part( preamble: &str, columns: &mut Vec, vertical_rules: &mut Vec, depth: usize, ) -> Option<()> { const MAX_ARRAY_COLUMNS: usize = 256; const MAX_PREAMBLE_DEPTH: usize = 16; if depth > MAX_PREAMBLE_DEPTH { return None; } let mut cursor = 0; while cursor < preamble.len() { cursor = skip_space_and_comments(preamble, cursor); if cursor >= preamble.len() { break; } let character = preamble[cursor..].chars().next()?; let next = cursor + character.len_utf8(); match character { 'l' | 'c' | 'r' => { if columns.len() >= MAX_ARRAY_COLUMNS { return None; } columns.push(match character { 'l' => MathColumnAlignment::Left, 'c' => MathColumnAlignment::Center, 'r' => MathColumnAlignment::Right, _ => unreachable!(), }); vertical_rules.push(0); cursor = next; } '|' => { if let Some(rule_count) = vertical_rules.last_mut() { *rule_count += 1; } cursor = next; } '*' => { let count_start = skip_space_and_comments(preamble, next); let Some((count, after_count)) = read_braced_group(preamble, count_start) else { cursor = next; continue; }; let Ok(repetitions) = count.trim().parse::() else { return None; }; let pattern_start = skip_space_and_comments(preamble, after_count); let Some((pattern, after_pattern)) = read_braced_group(preamble, pattern_start) else { cursor = next; continue; }; if repetitions > MAX_ARRAY_COLUMNS { return None; } for _ in 0..repetitions { parse_array_preamble_part(pattern, columns, vertical_rules, depth + 1)?; } cursor = after_pattern; } '@' | 'p' | 'm' | 'b' | '>' | '<' | '!' => { let group_start = skip_space_and_comments(preamble, next); if preamble[group_start..].starts_with('{') && let Some((_, after_group)) = read_braced_group(preamble, group_start) { cursor = after_group; } else { cursor = next; } } _ => cursor = next, } } Some(()) } fn apply_math_environment_with_alignment( expression: MathExpr, environment: &str, alignment: MathAlignment, math_fonts: MathFontFamilies, jot: common::Scaled, ) -> MathExpr { let force_alignment = matches!( environment, "matrix" | "pmatrix" | "bmatrix" | "Bmatrix" | "vmatrix" | "Vmatrix" | "smallmatrix" | "aligned" | "alignedat" | "split" | "gathered" | "array" | "cases" ); let expression = if force_alignment || is_display_alignment_environment(environment) { set_math_alignment( expression, alignment, math_alignment_baseline_for_environment(environment), math_fonts, math_cell_style_for_environment(environment), math_row_spacing_for_environment(environment, jot), force_alignment, ) } else { expression }; let (left, right) = match environment { "pmatrix" => Some(("(", ")")), "bmatrix" => Some(("[", "]")), "Bmatrix" => Some(("{", "}")), "vmatrix" => Some(("|", "|")), "Vmatrix" => Some(("‖", "‖")), "cases" => Some(("{", "")), _ => None, } .unwrap_or(("", "")); if left.is_empty() && right.is_empty() { expression } else { MathExpr::Delimited { left: MathDelimiterGlyph::plain(left), body: Box::new(expression), right: MathDelimiterGlyph::plain(right), left_settings: MathDelimiterSettings::default(), right_settings: MathDelimiterSettings::default(), } } } fn set_math_alignment( expression: MathExpr, alignment: MathAlignment, baseline: MathAlignmentBaseline, math_fonts: MathFontFamilies, cell_style: MathCellStyle, row_spacing: MathRowSpacing, force_alignment: bool, ) -> MathExpr { match expression { MathExpr::Spanned { location, expression, } => MathExpr::Spanned { location, expression: Box::new(set_math_alignment( *expression, alignment, baseline, math_fonts.clone(), cell_style, row_spacing, force_alignment, )), }, MathExpr::Alignment { baseline: MathAlignmentBaseline::MathAxisCentered, .. } if !force_alignment => expression, MathExpr::Alignment { rows, .. } => MathExpr::Alignment { rows, alignment, baseline, math_fonts, cell_style, row_spacing, }, expression if force_alignment => MathExpr::Alignment { rows: vec![vec![expression]], alignment, baseline, math_fonts, cell_style, row_spacing, }, expression => expression, } } fn is_display_alignment_environment(environment: &str) -> bool { matches!( environment, "align" | "align*" | "alignat" | "alignat*" | "flalign" | "flalign*" | "eqnarray" | "eqnarray*" | "gather" | "gather*" | "multline" | "multline*" ) } fn math_alignment_baseline_for_environment(environment: &str) -> MathAlignmentBaseline { match environment { "matrix" | "pmatrix" | "bmatrix" | "Bmatrix" | "vmatrix" | "Vmatrix" | "smallmatrix" | "aligned" | "alignedat" | "alignedat*" | "split" | "gathered" | "array" | "cases" => { MathAlignmentBaseline::MathAxisCentered } _ => MathAlignmentBaseline::FirstRow, } } fn math_cell_style_for_environment(environment: &str) -> MathCellStyle { match environment { "matrix" | "pmatrix" | "bmatrix" | "Bmatrix" | "vmatrix" | "Vmatrix" | "array" | "cases" => MathCellStyle::Text, "smallmatrix" => MathCellStyle::Script, "aligned" | "alignedat" | "alignedat*" | "split" | "gathered" | "align" | "align*" | "alignat" | "alignat*" | "flalign" | "flalign*" | "eqnarray" | "eqnarray*" | "gather" | "gather*" | "multline" | "multline*" => MathCellStyle::Display, _ => MathCellStyle::Inherit, } } fn math_row_spacing_for_environment(environment: &str, jot: common::Scaled) -> MathRowSpacing { match environment { "cases" => MathRowSpacing::Cases, "aligned" | "alignedat" | "alignedat*" | "split" | "gathered" | "align" | "align*" | "alignat" | "alignat*" | "flalign" | "flalign*" | "eqnarray" | "eqnarray*" | "gather" | "gather*" | "multline" | "multline*" => MathRowSpacing::Equation(jot), _ => MathRowSpacing::Array, } } #[derive(Clone, Copy)] enum DollarMathMode { Inline, Display, } struct ActiveDollarMath { mode: DollarMathMode, opened_at: SourceLocation, } fn convert_math_shift_delimiters( source: &expanded::ExpandedTokenStream, ) -> Result { let mut output = expanded::ExpandedTokenStream::default(); let mut copied_item = 0; let mut search_item = 0; let mut active_math: Option = None; while let Some(shift_index) = source.items[search_item..] .iter() .position(is_math_shift_item) .map(|offset| search_item + offset) { let item = &source.items[shift_index]; output.copy_items(source, &source.items[copied_item..shift_index]); let location = math_shift_location(source, item.position); let pair_end = math_shift_pair_at(source, item.position); let mut cursor = item.end_position; match active_math.take() { None => { if let Some(pair_end) = pair_end { output.insert_event( expanded::FrontendEventKind::DisplayMathStart, location.clone(), ); cursor = pair_end; active_math = Some(ActiveDollarMath { mode: DollarMathMode::Display, opened_at: location, }); } else { output.insert_event( expanded::FrontendEventKind::InlineMathStart, location.clone(), ); active_math = Some(ActiveDollarMath { mode: DollarMathMode::Inline, opened_at: location, }); } } Some(active) => match active.mode { DollarMathMode::Inline => { output.insert_event( expanded::FrontendEventKind::InlineMathEnd(math_delimiter_settings( source, item.position, )), active.opened_at, ); } DollarMathMode::Display => { let Some(pair_end) = pair_end else { return Err(math_delimiter_error( &location, "display math should end with `$$`", )); }; output.insert_event( expanded::FrontendEventKind::DisplayMathEnd(math_delimiter_settings( source, item.position, )), active.opened_at, ); cursor = pair_end; } }, } copied_item = source.items.partition_point(|item| item.position < cursor); search_item = copied_item; } if let Some(active) = active_math { let expected = math_shift_delimiter_name(active.mode); return Err(math_delimiter_error( &active.opened_at, &format!("math mode opened with `{expected}` has no matching closer"), )); } output.copy_items(source, &source.items[copied_item..]); Ok(output) } fn math_delimiter_settings( source: &expanded::ExpandedTokenStream, position: usize, ) -> MathDelimiterSettings { let start = source .items .partition_point(|item| item.position < position); source.items[start..] .iter() .take_while(|item| item.position == position) .find(|item| is_math_shift_item(item)) .and_then(|item| item.delimiter_settings) .unwrap_or_default() } fn math_shift_location(source: &expanded::ExpandedTokenStream, position: usize) -> SourceLocation { source.source_at(position).unwrap_or(SourceLocation { origin: SourceOrigin::Terminal, line: 1, column: 1, }) } fn math_shift_delimiter_name(mode: DollarMathMode) -> &'static str { match mode { DollarMathMode::Inline => "$", DollarMathMode::Display => "$$", } } fn math_shift_pair_at(source: &expanded::ExpandedTokenStream, position: usize) -> Option { let first = math_shift_item_at(source, position)?; let second = math_shift_item_at(source, first.end_position)?; Some(second.end_position) } fn math_shift_item_at( source: &expanded::ExpandedTokenStream, position: usize, ) -> Option<&expanded::ExpandedItem> { let start = source .items .partition_point(|item| item.position < position); source.items[start..] .iter() .take_while(|item| item.position == position) .find(|item| is_math_shift_item(item)) } fn is_math_shift_item(item: &expanded::ExpandedItem) -> bool { matches!( &item.kind, expanded::ExpandedItemKind::Token(expanded::ExpandedTokenValue::MathShift(_)) ) } fn skip_space_and_comments(source: &str, mut index: usize) -> usize { loop { while source .as_bytes() .get(index) .is_some_and(|byte| byte.is_ascii_whitespace()) { index += 1; } if source.as_bytes().get(index) != Some(&b'%') { return index; } index = source[index..] .find('\n') .map(|offset| index + offset + 1) .unwrap_or(source.len()); } } fn read_braced_group(source: &str, index: usize) -> Option<(&str, usize)> { read_delimited_group(source, index, b'{', b'}') } fn read_delimited_group(source: &str, index: usize, open: u8, close: u8) -> Option<(&str, usize)> { let bytes = source.as_bytes(); if bytes.get(index) != Some(&open) { return None; } let mut depth = 1usize; let mut cursor = index + 1; while cursor < bytes.len() { match bytes[cursor] { b'\\' => { cursor += 1; if cursor < bytes.len() { let character = source[cursor..].chars().next()?; cursor += character.len_utf8(); } } b'%' => { cursor = source[cursor..] .find('\n') .map(|offset| cursor + offset + 1) .unwrap_or(source.len()); } byte if byte == open => { depth += 1; cursor += 1; } byte if byte == close => { depth -= 1; if depth == 0 { return Some((&source[index + 1..cursor], cursor + 1)); } cursor += 1; } _ => { let character = source[cursor..].chars().next()?; cursor += character.len_utf8(); } } } None }