use std::{ops::Range, sync::Arc}; use crate::{ MathClass, MathStyleCommand, TeXGlue, document::ColumnAlignment, math_code::UnicodeMathCode, math_expr::{ MathAccent, MathDelimiterGlyph, MathDelimiterSettings, MathExpr, MathFontFamilies, MathFontStyle, MathFractionStyle, MathInfixFractionKind, MathLimitMode, MathLineBreakPenalties, MathPhantomKind, MathSpacingSettings, }, source::SourceLocation, }; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum TextStyle { Sans, Bold, Italic, Monospace, SmallCaps, Normal, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum MetadataField { Title, Author, Date, } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct SourceSegment { pub output: Range, pub location: SourceLocation, pub column_advances: bool, pub column_character_starts: Vec, } fn rebased_column_character_starts( segment: &SourceSegment, start: usize, end: usize, ) -> Vec { let start_offset = start - segment.output.start; let end_offset = end - segment.output.start; segment .column_character_starts .iter() .filter_map(|offset| { (*offset >= start_offset && *offset < end_offset).then_some(*offset - start_offset) }) .collect() } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct DisplayMathTag { pub text: String, pub starred: bool, } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct DisplayMathRow { pub equation_tag: Option, pub suppress_number: bool, pub labels: Vec, } impl Default for DisplayMathRow { fn default() -> Self { Self { equation_tag: None, suppress_number: false, labels: Vec::new(), } } } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum FrontendEventKind { ParagraphBreak, PageBreak, Kern(common::Scaled), Rule { width: common::Scaled, raise: common::Scaled, height: common::Scaled, }, HorizontalGlue(TeXGlue), VerticalGlue(TeXGlue), Penalty(i32), MakeTitle, FramedBoxStart, ParboxStart { width: common::Scaled, }, VBoxStart, VBoxEnd, HorizontalRule { height: common::Scaled, width: Option, }, FramedBoxEnd, InlineBoxStart { width: Option, align: crate::document::InlineBoxAlign, raise: common::Scaled, frame: bool, }, InlineBoxEnd, FootnoteStart, FootnoteEnd, MetadataStart(MetadataField), MetadataValue(MetadataField), MetadataEnd(MetadataField), DisplayMathStart, DisplayMathEnd(MathDelimiterSettings), InlineMathStart, InlineMathEnd(MathDelimiterSettings), DisplayMath { expression: MathExpr, environment: Option, rows: Vec, }, SuppressEquationNumber, EquationTag(DisplayMathTag), InlineMath(MathExpr), MathFractionStart { style: MathFractionStyle, has_rule: bool, parentheses: bool, delimiter_settings: MathDelimiterSettings, math_fonts: MathFontFamilies, }, MathInfixFraction(MathInfixFractionKind, MathFontFamilies), MathCharacter { code: u16, active_family: i32, math_fonts: MathFontFamilies, }, MathUnicodeCharacter { class: MathClass, family: u8, character: char, math_fonts: MathFontFamilies, }, MathUnicodeDelimiter { class: MathClass, family: u8, character: char, settings: MathDelimiterSettings, math_fonts: MathFontFamilies, }, MathStyleChange(MathStyleCommand), MathChoiceStart, MathChoiceBranch(MathStyleCommand), MathChoiceEnd, MathFractionSeparator, MathFractionEnd, MathLimitMode(MathLimitMode), MathSpace(i8), MathAccentStart { accent: MathAccent, family: u8, math_fonts: MathFontFamilies, }, MathAccentEnd, MathFontStart(MathFontStyle), MathFontEnd, MathPhantomStart(MathPhantomKind), MathPhantomEnd, MathOperatorStart, MathOperatorEnd, MathClassStart(MathClass), MathClassEnd, MathRootStart { has_index: bool, radical: Option<(u8, char)>, math_fonts: MathFontFamilies, }, MathRootSeparator, MathRootEnd, MathDelimiterStart { delimiter: MathDelimiterGlyph, settings: MathDelimiterSettings, }, MathDelimiterMiddle { delimiter: MathDelimiterGlyph, settings: MathDelimiterSettings, }, MathDelimiterEnd { delimiter: MathDelimiterGlyph, settings: MathDelimiterSettings, }, MathManualDelimiter { delimiter: String, half_points: u8, class: MathClass, settings: MathDelimiterSettings, math_fonts: MathFontFamilies, }, BeginEnvironment { name: String, math_fonts: MathFontFamilies, jot: common::Scaled, }, EnvironmentArgument(String), EndEnvironment { name: String, delimiter_settings: MathDelimiterSettings, }, Geometry(String), TextStyleStart(TextStyle), TextStyleEnd(TextStyle), TextStyleDeclare(TextStyle), LiteralAmpersand, LiteralCharacter(char), LineBreak, MathCell, RowBreak, ListItem, TableCell, TableCellSpan { colspan: usize, alignment: Option, }, TableRule, TableRuleRange { start_column: usize, end_column: usize, trim_left: bool, trim_right: bool, }, HeadingStart { level: u8, numbered: bool, }, Parindent(common::Scaled), NoIndent, HeadingEnd, CaptionStart, CaptionEnd, IncludeGraphics { options: String, path: String, }, Label(String), Reference(String), Citation(String), BibliographyItem(String), BibliographyMetadata { key: String, author: String, year: String, }, PageStyle(crate::document::PageStyleKind), ThisPageStyle(crate::document::PageStyleKind), PageDecorationStart { header: bool, position: crate::document::PageDecorationPosition, }, PageDecorationEnd, PageDecorationClear { header: bool, }, PageNumber, /// Start of hyperlink material. LinkStart, /// `\href` target: display text and URL, used for PDF annotations. LinkTarget { text: String, url: String, }, /// End of hyperlink material. LinkEnd, /// A package or class was loaded from a local file. PackageLoaded(String), /// A separator between author blocks (LaTeX's \And). MetadataSeparator, /// Short title from the optional argument of `\title[short]{long}`. MetadataShortTitle(String), /// Affiliation indices from the optional argument of `\author[1,2]{...}`. AuthorAffiliations(Vec), /// Start of an `\affil[n]{...}` body. AffiliationStart(usize), AffiliationEnd, /// Start/end of an `\abstract{...}` body captured for the title block. AbstractStart, AbstractEnd, /// Start/end of a `\keywords{...}` body. KeywordsStart, KeywordsEnd, /// Start/end of the e-mail address inside an author block. MetadataEmailStart, MetadataAuthorCorresponding, MetadataEmailEnd, ParagraphAlignment(crate::document::ParagraphAlignment), TableOfContents, ListOfFigures, ListOfTables, GroupStart, GroupEnd, } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct FrontendEvent { pub position: usize, pub kind: FrontendEventKind, pub location: SourceLocation, pub math_line_break_penalties: MathLineBreakPenalties, } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum ExpandedTokenValue { BeginGroup(char), EndGroup(char), MathShift(char), AlignmentTab(char), Parameter(char), Superscript(char), Subscript(char), Space(char), Letter(char), Other(char), ActiveCharacter(char), ControlSequence(String), } impl ExpandedTokenValue { pub fn character(&self) -> Option { match self { Self::BeginGroup(character) | Self::EndGroup(character) | Self::MathShift(character) | Self::AlignmentTab(character) | Self::Parameter(character) | Self::Superscript(character) | Self::Subscript(character) | Self::Space(character) | Self::Letter(character) | Self::Other(character) | Self::ActiveCharacter(character) => Some(*character), Self::ControlSequence(_) => None, } } } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum ExpandedItemKind { Token(ExpandedTokenValue), Event(FrontendEventKind), } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ExpandedItem { pub position: usize, pub end_position: usize, pub kind: ExpandedItemKind, pub location: SourceLocation, pub math_code: Option, pub math_family: Option, pub unicode_math_code: Option, pub delimiter_settings: Option, pub math_fonts: MathFontFamilies, pub math_spacing: MathSpacingSettings, pub math_line_break_penalties: MathLineBreakPenalties, } #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct ExpandedSource { pub text: String, pub segments: Vec, pub events: Vec, pub items: Vec, } /// Semantic consumers receive typed items without the VM's serialized text view. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct ExpandedTokenStream { pub items: Vec, pub segments: Vec, pub events: Vec, } impl ExpandedSource { pub fn into_token_stream(self) -> ExpandedTokenStream { ExpandedTokenStream { items: self.items, segments: self.segments, events: self.events, } } pub fn source_at(&self, output_offset: usize) -> Option { let index = self .segments .partition_point(|segment| segment.output.end <= output_offset); let segment = self .segments .get(index) .filter(|segment| segment.output.contains(&output_offset))?; Some(self.location_at(segment, output_offset)) } fn location_at(&self, segment: &SourceSegment, output_offset: usize) -> SourceLocation { let mut location = segment.location.clone(); if segment.column_advances { let byte_offset = output_offset - segment.output.start; location.column += segment .column_character_starts .partition_point(|start| *start < byte_offset); } location } } impl ExpandedTokenStream { pub fn output_len(&self) -> usize { self.items .last() .map(|item| item.end_position) .unwrap_or_default() .max( self.segments .last() .map(|segment| segment.output.end) .unwrap_or_default(), ) .max( self.events .last() .map(|event| event.position) .unwrap_or_default(), ) } pub fn token_item_at(&self, output_offset: usize) -> Option<&ExpandedItem> { let item_start = self .items .partition_point(|item| item.position < output_offset); self.items[item_start..] .iter() .take_while(|item| item.position == output_offset) .find(|item| { item.end_position > item.position && matches!(&item.kind, ExpandedItemKind::Token(_)) }) } pub fn next_token_item_at_or_after( &self, output_offset: usize, limit: usize, ) -> Option<&ExpandedItem> { let item_start = self .items .partition_point(|item| item.position < output_offset); self.items[item_start..] .iter() .take_while(|item| item.position < limit) .find(|item| { item.end_position > item.position && matches!(&item.kind, ExpandedItemKind::Token(_)) }) } pub fn token_value_at(&self, output_offset: usize) -> Option<&ExpandedTokenValue> { let item = self.token_item_at(output_offset)?; match &item.kind { ExpandedItemKind::Token(value) => Some(value), ExpandedItemKind::Event(_) => unreachable!(), } } pub fn character_tokens_in(&self, range: Range) -> String { let item_start = self .items .partition_point(|item| item.position < range.start); let mut text = String::new(); for item in self.items[item_start..] .iter() .take_while(|item| item.position < range.end) { let ExpandedItemKind::Token(value) = &item.kind else { continue; }; if let Some(character) = value.character() { text.push(character); } } text } pub fn source_at(&self, output_offset: usize) -> Option { let index = self .segments .partition_point(|segment| segment.output.end <= output_offset); let segment = self .segments .get(index) .filter(|segment| segment.output.contains(&output_offset))?; Some(self.location_at(segment, output_offset)) } fn location_at(&self, segment: &SourceSegment, output_offset: usize) -> SourceLocation { let mut location = segment.location.clone(); if segment.column_advances { let byte_offset = output_offset - segment.output.start; location.column += segment .column_character_starts .partition_point(|start| *start < byte_offset); } location } pub fn segment_signature(&self, range: Range) -> Vec { self.segments .iter() .filter_map(|segment| { let start = segment.output.start.max(range.start); let end = segment.output.end.min(range.end); (start < end).then(|| SourceSegment { output: start - range.start..end - range.start, location: self.location_at(segment, start), column_advances: segment.column_advances, column_character_starts: rebased_column_character_starts(segment, start, end), }) }) .collect() } pub fn copy_token_range(&mut self, source: &Self, range: Range) { if range.is_empty() { return; } let destination_start = self.output_len(); self.copy_segments(source, &range, destination_start); self.items.extend(source.items.iter().filter_map(|item| { (range.start <= item.position && item.position < range.end && matches!(&item.kind, ExpandedItemKind::Token(_))) .then(|| rebase_expanded_item(item, destination_start, range.start)) })); } /// Copies a slice of source items onto the current output in item order. /// /// Items with zero output width (space tokens and events) share their byte /// position with the next written token; copying by item index keeps those /// items in expansion order instead of splitting them by position. pub fn copy_items(&mut self, source: &Self, items: &[ExpandedItem]) { if items.is_empty() { return; } let destination_start = self.output_len(); let position_start = items[0].position; let position_end = items .iter() .map(|item| item.end_position.max(item.position)) .max() .unwrap_or(position_start); if position_end > position_start { self.copy_segments(source, &(position_start..position_end), destination_start); } for item in items { let item = rebase_expanded_item(item, destination_start, position_start); if let ExpandedItemKind::Event(kind) = &item.kind { self.events.push(FrontendEvent { position: item.position, kind: kind.clone(), location: item.location.clone(), math_line_break_penalties: item.math_line_break_penalties, }); } self.items.push(item); } } pub fn copy_range(&mut self, source: &Self, range: Range) { if range.is_empty() { return; } let destination_start = self.output_len(); self.copy_segments(source, &range, destination_start); for item in source .items .iter() .filter(|item| range.start <= item.position && item.position < range.end) { let item = rebase_expanded_item(item, destination_start, range.start); if let ExpandedItemKind::Event(kind) = &item.kind { self.events.push(FrontendEvent { position: item.position, kind: kind.clone(), location: item.location.clone(), math_line_break_penalties: item.math_line_break_penalties, }); } self.items.push(item); } } fn copy_segments(&mut self, source: &Self, range: &Range, destination_start: usize) { for segment in &source.segments { let start = segment.output.start.max(range.start); let end = segment.output.end.min(range.end); if start < end { self.segments.push(SourceSegment { output: destination_start + start - range.start ..destination_start + end - range.start, location: source.location_at(segment, start), column_advances: segment.column_advances, column_character_starts: rebased_column_character_starts(segment, start, end), }); } } } pub fn copy_events_at(&mut self, source: &Self, source_position: usize) { let destination_position = self.output_len(); for item in source.items.iter().filter(|item| { item.position == source_position && matches!(&item.kind, ExpandedItemKind::Event(_)) }) { let ExpandedItemKind::Event(kind) = &item.kind else { unreachable!(); }; self.events.push(FrontendEvent { position: destination_position, kind: kind.clone(), location: item.location.clone(), math_line_break_penalties: item.math_line_break_penalties, }); self.items.push(ExpandedItem { position: destination_position, end_position: destination_position, kind: item.kind.clone(), location: item.location.clone(), math_code: None, math_family: None, unicode_math_code: None, delimiter_settings: None, math_fonts: Arc::default(), math_spacing: MathSpacingSettings::default(), math_line_break_penalties: item.math_line_break_penalties, }); } } pub fn insert_event(&mut self, kind: FrontendEventKind, location: SourceLocation) { let position = self.output_len(); self.events.push(FrontendEvent { position, kind: kind.clone(), location: location.clone(), math_line_break_penalties: MathLineBreakPenalties::default(), }); self.items.push(ExpandedItem { position, end_position: position, kind: ExpandedItemKind::Event(kind), location, math_code: None, math_family: None, unicode_math_code: None, delimiter_settings: None, math_fonts: Arc::default(), math_spacing: MathSpacingSettings::default(), math_line_break_penalties: MathLineBreakPenalties::default(), }); } } fn rebase_expanded_item( item: &ExpandedItem, destination_start: usize, source_start: usize, ) -> ExpandedItem { ExpandedItem { position: destination_start + item.position - source_start, end_position: destination_start + item.end_position - source_start, kind: item.kind.clone(), location: item.location.clone(), math_code: item.math_code, math_family: item.math_family, unicode_math_code: item.unicode_math_code, delimiter_settings: item.delimiter_settings, math_fonts: Arc::clone(&item.math_fonts), math_spacing: item.math_spacing, math_line_break_penalties: item.math_line_break_penalties, } }