use std::{ cell::RefCell, collections::{HashMap, VecDeque}, env, ffi::OsString, fmt::Write as _, fs, path::{Path, PathBuf}, rc::Rc, }; use genpdf::fonts; use texrra_core::math_list::{math_choice_variant, math_style_command}; use texrra_core::{MathClass, MathListContext, MathStyle, MathStyleCommand, math_expr::is_cjk}; mod box_font; mod document; mod engine; mod frontend; mod math_font; mod math_layout; mod page_builder; mod parser; mod pdf; mod texlang_adapter; mod tex_expansion { pub(super) use super::texlang_adapter::*; } mod text_layout; use document::{ Block, ColumnAlignment, DocumentModel, EquationNumber, ListBlock, MathAccent, MathAlignment, MathAlignmentBaseline, MathCellStyle, MathDelimiterCharacter, MathDelimiterGlyph, MathDelimiterSettings, MathExpr, MathFontFamilies, MathFontSelection, MathFontStyle, MathFractionDelimiters, MathFractionStyle, MathInfixFractionKind, MathLimitMode, MathLineBreakPenalties, MathMuGlue, MathPhantomKind, MathRowSpacing, MathSpacingSettings, PAGE_NUMBER_MARKER, PageDecoration, PageDecorationPosition, PageStyleKind, RuleBox, Run, }; use parser::parse_dimension; const PDF_POINTS_PER_INCH: f64 = 72.0; pub(super) fn log_timing(label: &str, start: std::time::Instant) { if env::var_os("TEXRRA_TIMING").is_some() { eprintln!( "[timing] {label}: {:.2} ms", start.elapsed().as_secs_f64() * 1000.0 ); } } struct CachedCompilation { input: FrontendInputKey, lowered: frontend::LoweredDocumentSource, document: DocumentModel, } #[derive(Clone, PartialEq, Eq)] struct FrontendInputKey { source: String, file_name: String, style_search_path: Option, style_lookup_fingerprint: u64, date: String, } #[derive(Default)] pub struct CompilerSession { paragraph_layout_cache: pdf::ParagraphLayoutCache, compilation_cache: VecDeque, expansion_cache: tex_expansion::ExpansionCache, math_parse_cache: frontend::MathParseCache, paragraph_parse_cache: parser::ParagraphParseCache, math_layout_cache: Rc>, math_font_metrics_cache: Option<(u64, math_font::MathFontMetrics)>, preview_resources_cache: Option, } impl CompilerSession { pub fn compile(&mut self, source: &str, file_name: &str) -> Result, String> { let timing_start = std::time::Instant::now(); let source_dir = source_directory(file_name); let model = self.interpret_document(source, file_name)?; log_timing("interpret", timing_start); let (_, math_metrics) = self.cached_math_font_metrics(&model)?; let pdf = pdf::render_pdf( model, source_dir, &mut self.paragraph_layout_cache, math_metrics, Rc::clone(&self.math_layout_cache), )?; log_timing("compile-total", timing_start); Ok(pdf) } pub fn preview_json(&mut self, source: &str, file_name: &str) -> Result { let timing_start = std::time::Instant::now(); let model = self.interpret_document(source, file_name)?; let (math_metrics_fingerprint, math_metrics) = self.cached_math_font_metrics(&model)?; let key = pdf::PreviewResourceKey::new(&model, math_metrics_fingerprint)?; if self .preview_resources_cache .as_ref() .is_none_or(|cached| cached.key() != &key) { self.preview_resources_cache = Some(pdf::PreviewResources::new( &model, math_metrics, math_metrics_fingerprint, Rc::clone(&self.math_layout_cache), )?); } let resources = self .preview_resources_cache .as_ref() .expect("preview resources were just cached"); let content_width = model.page.width_mm - model.margins.left - model.margins.right; let content_height = model.page.height_mm - model.margins.top - model.margins.bottom; let pages = pdf::preview::render_pages( &model, source_directory(file_name), resources, content_width, content_height, &mut self.paragraph_layout_cache, )?; let duration_ms = timing_start.elapsed().as_secs_f64() * 1000.0; log_timing("preview", timing_start); let mut json = String::new(); match pages { Some(pages) => { let _ = write!( json, "{{\"status\":\"ok\",\"durationMs\":{duration_ms:.2},\"pageWidthMm\":{:.2},\"pageHeightMm\":{:.2},\"pages\":[", model.page.width_mm, model.page.height_mm ); for (index, page) in pages.iter().enumerate() { if index > 0 { json.push(','); } let _ = write!( json, "{{\"hash\":\"{:016x}\",\"svg\":{}}}", page_hash(&page.svg), json_string(&page.svg) ); } json.push_str("]}"); } None => { let _ = write!( json, "{{\"status\":\"fallback\",\"durationMs\":{duration_ms:.2},\"message\":{}}}", json_string( "This document uses layout features that the live preview cannot render yet." ) ); } } Ok(json) } pub fn render_html_preview(&mut self, source: &str, file_name: &str) -> Result { let model = self.interpret_document(source, file_name)?; let math_metrics = if model.blocks.iter().any(block_contains_math) { Some(self.cached_math_font_metrics(&model)?.1) } else { None }; render_html_document( model, source_directory(file_name), Rc::clone(&self.math_layout_cache), math_metrics, ) } fn cached_math_font_metrics( &mut self, model: &DocumentModel, ) -> Result<(u64, math_font::MathFontMetrics), String> { let latin_dir = pdf::latin_font_directory()?; let custom_math_fonts = model.math_font_files(); let fingerprint = pdf::math_font_metrics_fingerprint(&latin_dir, &custom_math_fonts)?; if let Some((cached_fingerprint, metrics)) = &self.math_font_metrics_cache && *cached_fingerprint == fingerprint { return Ok((fingerprint, metrics.clone())); } let metrics = pdf::load_math_font_metrics(&latin_dir)? .with_additional_glyph_fonts(&custom_math_fonts)?; self.math_font_metrics_cache = Some((fingerprint, metrics.clone())); Ok((fingerprint, metrics)) } fn interpret_document( &mut self, source: &str, file_name: &str, ) -> Result { let input_key = FrontendInputKey { source: source.to_string(), file_name: file_name.to_string(), style_search_path: env::var_os("TEXRRA_STY_DIR"), style_lookup_fingerprint: frontend::style_lookup_fingerprint(file_name), date: frontend::date_stamp(), }; if let Some(index) = self .compilation_cache .iter() .position(|cached| cached.input == input_key) { let valid = { let cached = &self.compilation_cache[index]; cached.lowered.cacheable && frontend::dependencies_unchanged(&cached.lowered.dependencies) }; if valid { let cached = self .compilation_cache .remove(index) .expect("cached compilation index was found"); let document = cached.document.clone(); self.compilation_cache.push_back(cached); return Ok(document); } self.compilation_cache.remove(index); } let preprocessed = frontend::preprocess(source, file_name)?; let expanded = frontend::expand_tex(preprocessed, &mut self.expansion_cache)?; let lowered = frontend::lower_math(expanded, &mut self.math_parse_cache)?; let parsed = parser::parse_document(&lowered.source, &mut self.paragraph_parse_cache); let document = texrra_core::references::resolve(parsed); if lowered.cacheable && frontend::dependencies_unchanged(&lowered.dependencies) { const CACHE_CAPACITY: usize = 3; if self.compilation_cache.len() == CACHE_CAPACITY { self.compilation_cache.pop_front(); } self.compilation_cache.push_back(CachedCompilation { input: input_key, lowered, document: document.clone(), }); } Ok(document) } } #[derive(Clone)] struct MathLayoutEnvironment { cache: Rc>, font_fingerprint: u64, line_font_fingerprint: u64, } struct MathPreviewResources { font_cache: fonts::FontCache, metrics: math_font::MathFontMetrics, layout: MathLayoutEnvironment, monospace_family: Option>, font_css: String, } fn load_math_preview_resources( cache: Rc>, metrics: math_font::MathFontMetrics, include_monospace: bool, ) -> Result { let latin_dir = pdf::latin_font_directory()?; let monospace_dir = include_monospace .then(pdf::monospace_font_directory) .transpose()?; let latin_fonts = fonts::from_files(&latin_dir, "LiberationSerif", None) .map_err(|error| format!("could not load Latin fonts: {error}"))?; let font_fingerprint = pdf::math_font_family_fingerprint(&latin_dir, monospace_dir.as_deref())?; let mut font_cache = fonts::FontCache::new(latin_fonts); let monospace_family = if let Some(monospace_dir) = &monospace_dir { let family = fonts::from_files( monospace_dir, "LiberationMono", Some(fonts::Builtin::Courier), ) .map_err(|error| format!("could not load monospaced preview fonts: {error}"))?; Some(font_cache.add_font_family(family)) } else { None }; cache.borrow_mut().set_monospace_family(monospace_family); let layout = MathLayoutEnvironment { cache, font_fingerprint, line_font_fingerprint: font_fingerprint, }; let mut font_css = String::from( ".texrra-math { position: relative; text-align: center; overflow: visible; }\ .texrra-math-svg { display: block; width: 100%; overflow: visible; }\ .texrra-inline-math-svg { display: inline; overflow: visible; }", ); for (weight, style, file_name) in [ ("400", "normal", "LiberationSerif-Regular.ttf"), ("700", "normal", "LiberationSerif-Bold.ttf"), ("400", "italic", "LiberationSerif-Italic.ttf"), ("700", "italic", "LiberationSerif-BoldItalic.ttf"), ] { let path = latin_dir.join(file_name); let bytes = fs::read(&path).map_err(|error| { format!( "could not read preview math font {}: {error}", path.display() ) })?; font_css.push_str(&format!( "@font-face{{font-family:'TexrraMath';font-style:{style};font-weight:{weight};src:url(data:font/ttf;base64,{}) format('truetype');}}", encode_base64(&bytes), )); } if let Some(monospace_dir) = &monospace_dir { font_css.push_str(".texrra-page code{font-family:'TexrraMono',monospace;}"); for (weight, style, file_name) in [ ("400", "normal", "LiberationMono-Regular.ttf"), ("700", "normal", "LiberationMono-Bold.ttf"), ("400", "italic", "LiberationMono-Italic.ttf"), ("700", "italic", "LiberationMono-BoldItalic.ttf"), ] { let path = monospace_dir.join(file_name); let bytes = fs::read(&path).map_err(|error| { format!( "could not read preview monospaced font {}: {error}", path.display() ) })?; font_css.push_str(&format!( "@font-face{{font-family:'TexrraMono';font-style:{style};font-weight:{weight};src:url(data:font/ttf;base64,{}) format('truetype');}}", encode_base64(&bytes), )); } } Ok(MathPreviewResources { font_cache, metrics, layout, monospace_family, font_css, }) } fn render_html_document( model: DocumentModel, source_dir: &Path, math_layout_cache: Rc>, math_metrics: Option, ) -> Result { let math_preview = math_metrics .map(|metrics| { load_math_preview_resources( Rc::clone(&math_layout_cache), metrics, pdf::document_contains_monospace(&model), ) }) .transpose()?; let mut html = format!( "
", model.margins.top, model.margins.right, model.margins.bottom, model.margins.left ); if let Some(math_preview) = &math_preview { html.push_str(""); } if model.show_title { html.push_str("
"); if !model.title.is_empty() { html.push_str(&format!("

{}

", escape_html(&model.title))); } if !model.author.is_empty() { html.push_str(&format!( "

{}

", escape_html(&model.author) )); } if !model.date.is_empty() { html.push_str(&format!( "

{}

", escape_html(&model.date) )); } html.push_str("
"); } for (index, block) in model.blocks.into_iter().enumerate() { let source_attributes = source_attributes(model.block_sources.get(index).and_then(Option::as_ref)); match block { Block::Paragraph(runs) => { html.push_str(&format!("")); html.push_str(&render_html_runs(&runs, math_preview.as_ref(), 11)); html.push_str("

"); } Block::FramedBox { runs, .. } => { html.push_str(&format!("
")); html.push_str(&render_html_runs(&runs, math_preview.as_ref(), 11)); html.push_str("
"); } Block::HorizontalRule { .. } => { html.push_str(&format!("")); } Block::Centered { runs } => { html.push_str(&format!( "
" )); html.push_str(&render_html_runs(&runs, math_preview.as_ref(), 11)); html.push_str("
"); } Block::Heading { level, runs } => { let level = level.clamp(1, 3); html.push_str(&format!( "{}", render_html_runs( &runs, math_preview.as_ref(), match level { 1 => 18, 2 => 15, _ => 13, }, ) )); } Block::List(list) => html.push_str(&render_html_list( &list, &source_attributes, math_preview.as_ref(), )), Block::Table { rows, caption, alignments, rules, cell_styles, .. } => { html.push_str(&format!( "" )); if let Some(caption) = caption { html.push_str(""); } html.push_str(""); for (row_index, row) in rows.iter().enumerate() { let rule_class = if rules.iter().any(|rule| { rule.row == row_index && rule.start_column == 0 && rule.end_column == usize::MAX }) { " class=\"rule-before\"" } else { "" }; html.push_str(&format!("")); let mut column_index = 0; for (cell_index, cell) in row.iter().enumerate() { let style = cell_styles .get(row_index) .and_then(|styles| styles.get(cell_index)); let colspan = style.map(|style| style.colspan.max(1)).unwrap_or(1); let alignment = match style .and_then(|style| style.alignment) .or_else(|| alignments.get(column_index).copied()) { Some(ColumnAlignment::Center) => "center", Some(ColumnAlignment::Right) => "right", _ => "left", }; html.push_str(&format!( ""); column_index += colspan; } html.push_str(""); } if rules.iter().any(|rule| { rule.row == rows.len() && rule.start_column == 0 && rule.end_column == usize::MAX }) { html.push_str(""); } html.push_str("
"); html.push_str(&render_html_runs(&caption, math_preview.as_ref(), 10)); html.push_str("
" )); html.push_str(&render_html_runs(cell, math_preview.as_ref(), 10)); html.push_str("
"); } Block::Image { path, options, caption, .. } => { let image_path = PathBuf::from(&path); let image_path = if image_path.is_absolute() { image_path } else { source_dir.join(image_path) }; html.push_str(&format!( "
" )); if let (Some(bytes), Some(mime)) = (fs::read(&image_path).ok(), image_mime_type(&image_path)) { let dimensions = image::image_dimensions(&image_path).ok(); let style = dimensions .map(|(width, height)| { let available_width = model.page.width_mm - model.margins.left - model.margins.right; let available_height = model.page.height_mm - model.margins.top - model.margins.bottom; let (scale_x, scale_y) = pdf::image_scale( &options, width, height, available_width, available_height, ); let width_mm = f64::from(width) * 25.4 / 300.0 * scale_x; let height_mm = f64::from(height) * 25.4 / 300.0 * scale_y; format!(" style=\"width:{width_mm:.2}mm;height:{height_mm:.2}mm\"") }) .unwrap_or_default(); html.push_str(&format!( "\"{}\"{style}", encode_base64(&bytes), escape_html(&path) )); } else { html.push_str(&format!( "
Image unavailable: {}
", escape_html(&path) )); } if let Some(caption) = caption { html.push_str("
"); html.push_str(&render_html_runs(&caption, math_preview.as_ref(), 10)); html.push_str("
"); } html.push_str("
"); } Block::Bibliography(items) => { html.push_str(&format!( "

References

    " )); for (_key, runs) in items { html.push_str("
  1. "); html.push_str(&render_html_runs(&runs, math_preview.as_ref(), 10)); html.push_str("
  2. "); } html.push_str("
"); } Block::Math { expression: value, equation_numbers, } => { html.push_str(&format!("
")); let math_preview = math_preview .as_ref() .expect("math preview resources are loaded for display math"); html.push_str(&math_layout::display_math_svg( &value, &math_preview.font_cache, &math_preview.metrics, &math_preview.layout.cache, math_preview.layout.font_fingerprint, math_preview.monospace_family, &equation_numbers, model.page.width_mm - model.margins.left - model.margins.right, )); html.push_str("
"); } Block::VerticalKern(width) => { let points = f64::from(width.0) / 65_536.0; let height = points.max(0.0); let margin_top = points.min(0.0); html.push_str(&format!( "
" )); } Block::VerticalGlue(glue) => { let points = f64::from(glue.width.0) / 65_536.0; let height = points.max(0.0); let margin_top = points.min(0.0); html.push_str(&format!( "
" )); } Block::Penalty(_) => {} Block::PageBreak => html.push_str(&format!( "
Page break
" )), } } html.push_str("
"); Ok(html) } fn render_html_list( list: &ListBlock, source_attributes: &str, math_preview: Option<&MathPreviewResources>, ) -> String { let tag = if list.ordered { "ol" } else { "ul" }; let mut html = format!("<{tag} class=\"texrra-list\"{source_attributes}>"); for item in &list.items { html.push_str("
  • "); html.push_str(&render_html_runs(&item.runs, math_preview, 11)); for nested in &item.nested { html.push_str(&render_html_list(nested, "", math_preview)); } html.push_str("
  • "); } html.push_str(&format!("")); html } fn source_attributes(source: Option<&tex_expansion::SourceLocation>) -> String { let Some(source) = source else { return String::new(); }; let origin = match &source.origin { tex_expansion::SourceOrigin::File(path) if path == Path::new("texrra-engine-rust-preamble.tex") => { return String::new(); } tex_expansion::SourceOrigin::File(path) => path.display().to_string(), tex_expansion::SourceOrigin::Terminal => "terminal".to_string(), }; format!( " data-tex-source-file=\"{}\" data-tex-source-line=\"{}\" data-tex-source-column=\"{}\"", escape_html(&origin), source.line, source.column.saturating_add(1), ) } fn block_contains_math(block: &Block) -> bool { let runs_have_math = |runs: &[Run]| runs.iter().any(|run| run.math.is_some()); fn list_has_math(list: &ListBlock) -> bool { list.items.iter().any(|item| { item.runs.iter().any(|run| run.math.is_some()) || item.nested.iter().any(list_has_math) }) } match block { Block::Paragraph(runs) | Block::Heading { runs, .. } => runs_have_math(runs), Block::List(list) => list_has_math(list), Block::Table { rows, caption, .. } => { caption.as_deref().is_some_and(runs_have_math) || rows.iter().flatten().any(|cell| runs_have_math(cell)) } Block::Image { caption, .. } => caption.as_deref().is_some_and(runs_have_math), Block::FramedBox { runs, .. } | Block::Centered { runs } => runs_have_math(runs), Block::HorizontalRule { .. } => false, Block::Bibliography(items) => items.iter().any(|(_, runs)| runs_have_math(runs)), Block::Math { .. } => true, Block::VerticalKern(_) | Block::VerticalGlue(_) | Block::Penalty(_) | Block::PageBreak => { false } } } fn render_html_runs( runs: &[Run], math_preview: Option<&MathPreviewResources>, font_size: u8, ) -> String { let mut html = String::new(); for run in runs { if let Some(width) = run.kern { let points = f64::from(width.0) / 65_536.0; let width = points.max(0.0); let margin_left = points.min(0.0); html.push_str(&format!( "" )); } if let Some(glue) = run.glue { let points = f64::from(glue.width.0) / 65_536.0; let width = points.max(0.0); let margin_left = points.min(0.0); html.push_str(&format!( "" )); } if let Some(expression) = &run.math { if let Some(math_preview) = math_preview { html.push_str(&math_layout::inline_math_svg( expression, &math_preview.font_cache, &math_preview.metrics, &math_preview.layout.cache, math_preview.layout.font_fingerprint, font_size, run.bold, math_preview.monospace_family, )); } else { html.push_str(&escape_html(&run.text)); } continue; } let mut text = escape_html(&run.text); if run.monospace { text = format!("{text}"); } if run.italic { text = format!("{text}"); } if run.bold { text = format!("{text}"); } html.push_str(&text); } html } fn escape_html(source: &str) -> String { let mut escaped = String::with_capacity(source.len()); for character in source.chars() { match character { '&' => escaped.push_str("&"), '<' => escaped.push_str("<"), '>' => escaped.push_str(">"), '"' => escaped.push_str("""), '\'' => escaped.push_str("'"), _ => escaped.push(character), } } escaped } fn image_mime_type(path: &Path) -> Option<&'static str> { match path.extension()?.to_str()?.to_ascii_lowercase().as_str() { "png" => Some("image/png"), "jpg" | "jpeg" => Some("image/jpeg"), "bmp" => Some("image/bmp"), _ => None, } } fn encode_base64(bytes: &[u8]) -> String { const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; let mut encoded = String::with_capacity(bytes.len().div_ceil(3) * 4); for chunk in bytes.chunks(3) { let first = chunk[0]; let second = *chunk.get(1).unwrap_or(&0); let third = *chunk.get(2).unwrap_or(&0); encoded.push(ALPHABET[(first >> 2) as usize] as char); encoded.push(ALPHABET[(((first & 0x03) << 4) | (second >> 4)) as usize] as char); encoded.push(if chunk.len() > 1 { ALPHABET[(((second & 0x0f) << 2) | (third >> 6)) as usize] as char } else { '=' }); encoded.push(if chunk.len() > 2 { ALPHABET[(third & 0x3f) as usize] as char } else { '=' }); } encoded } fn page_hash(svg: &str) -> u64 { let mut hash = 0xcbf2_9ce4_8422_2325_u64; for byte in svg.as_bytes() { hash ^= u64::from(*byte); hash = hash.wrapping_mul(0x0000_0100_0000_01b3); } hash } pub fn json_string(value: &str) -> String { let mut output = String::with_capacity(value.len() + 2); output.push('"'); for character in value.chars() { match character { '"' => output.push_str("\\\""), '\\' => output.push_str("\\\\"), '\n' => output.push_str("\\n"), '\r' => output.push_str("\\r"), '\t' => output.push_str("\\t"), character if (character as u32) < 0x20 => { let _ = write!(output, "\\u{:04x}", character as u32); } character => output.push(character), } } output.push('"'); output } pub fn preview_error_json(message: &str) -> String { format!( "{{\"status\":\"error\",\"message\":{}}}", json_string(message) ) } fn preview_font_path(name: &str) -> Option { let (directory, file_name) = match name { "serif-regular.ttf" => ( pdf::latin_font_directory().ok()?, "LiberationSerif-Regular.ttf", ), "serif-bold.ttf" => ( pdf::latin_font_directory().ok()?, "LiberationSerif-Bold.ttf", ), "serif-italic.ttf" => ( pdf::latin_font_directory().ok()?, "LiberationSerif-Italic.ttf", ), "serif-bolditalic.ttf" => ( pdf::latin_font_directory().ok()?, "LiberationSerif-BoldItalic.ttf", ), "sans-regular.ttf" => ( pdf::sans_font_directory().ok()?, "LiberationSans-Regular.ttf", ), "sans-bold.ttf" => (pdf::sans_font_directory().ok()?, "LiberationSans-Bold.ttf"), "sans-italic.ttf" => ( pdf::sans_font_directory().ok()?, "LiberationSans-Italic.ttf", ), "sans-bolditalic.ttf" => ( pdf::sans_font_directory().ok()?, "LiberationSans-BoldItalic.ttf", ), "mono-regular.ttf" => ( pdf::monospace_font_directory().ok()?, "LiberationMono-Regular.ttf", ), "mono-bold.ttf" => ( pdf::monospace_font_directory().ok()?, "LiberationMono-Bold.ttf", ), "mono-italic.ttf" => ( pdf::monospace_font_directory().ok()?, "LiberationMono-Italic.ttf", ), "mono-bolditalic.ttf" => ( pdf::monospace_font_directory().ok()?, "LiberationMono-BoldItalic.ttf", ), _ => return None, }; let path = directory.join(file_name); path.is_file().then_some(path) } pub fn preview_font_file(name: &str) -> Option> { fs::read(preview_font_path(name)?).ok() } pub fn preview_font_css() -> Result { let mut css = String::new(); for (family, weight, style, url) in [ ("TexrraSerif", "400", "normal", "serif-regular.ttf"), ("TexrraSerif", "700", "normal", "serif-bold.ttf"), ("TexrraSerif", "400", "italic", "serif-italic.ttf"), ("TexrraSerif", "700", "italic", "serif-bolditalic.ttf"), ("TexrraMath", "400", "normal", "serif-regular.ttf"), ("TexrraMath", "700", "normal", "serif-bold.ttf"), ("TexrraMath", "400", "italic", "serif-italic.ttf"), ("TexrraMath", "700", "italic", "serif-bolditalic.ttf"), ("TexrraSans", "400", "normal", "sans-regular.ttf"), ("TexrraSans", "700", "normal", "sans-bold.ttf"), ("TexrraSans", "400", "italic", "sans-italic.ttf"), ("TexrraSans", "700", "italic", "sans-bolditalic.ttf"), ("TexrraMono", "400", "normal", "mono-regular.ttf"), ("TexrraMono", "700", "normal", "mono-bold.ttf"), ("TexrraMono", "400", "italic", "mono-italic.ttf"), ("TexrraMono", "700", "italic", "mono-bolditalic.ttf"), ] { if preview_font_path(url).is_some() { let _ = write!( css, "@font-face{{font-family:'{family}';font-style:{style};font-weight:{weight};font-display:swap;src:url('/fonts/{url}') format('truetype');}}" ); } } css.push_str( "@font-face{font-family:'TexrraCjk';src:local('Noto Serif CJK SC'),local('Source Han Serif SC'),local('Songti SC'),local('SimSun'),local('Microsoft YaHei'),local('Noto Sans CJK SC');}", ); Ok(css) } fn source_directory(file_name: &str) -> &Path { Path::new(file_name) .parent() .filter(|parent| !parent.as_os_str().is_empty()) .unwrap_or_else(|| Path::new(".")) } fn natbib_author_list(author: &str) -> String { let names = author .split(" and ") .map(|name| { let name = name.trim(); match name.split_once(',') { Some((last, first)) => format!("{} {}", first.trim(), last.trim()), None => name.to_string(), } }) .collect::>(); match names.as_slice() { [] => String::new(), [only] => only.clone(), [first, second] => format!("{first} and {second}"), [rest @ .., last] => format!("{}, and {last}", rest.join(", ")), } } struct BibEntry { kind: String, key: String, fields: HashMap, } impl BibEntry { fn to_latex(&self, author_year: bool) -> String { if author_year { return self.natbib_latex(); } let field = |name: &str| self.fields.get(name).map(String::as_str).unwrap_or(""); let mut parts = Vec::new(); let author = field("author"); if !author.is_empty() { parts.push(format!("{author}.")); } else if !field("editor").is_empty() { parts.push(format!("{} (ed.).", field("editor"))); } let title = field("title"); if !title.is_empty() { if self.kind == "book" || self.kind == "inbook" { parts.push(format!("\\emph{{{title}}}.")); } else { parts.push(format!("{title}.")); } } let publication = if field("journal").is_empty() { field("booktitle") } else { field("journal") }; if !publication.is_empty() { parts.push(format!("\\emph{{{publication}}}")); } let volume = field("volume"); let number = field("number"); let pages = field("pages"); let mut details = Vec::new(); if !volume.is_empty() { details.push(volume.to_string()); } if !number.is_empty() { details.push(format!("({number})")); } if !pages.is_empty() { details.push(format!("pp. {pages}")); } if !details.is_empty() { parts.push(details.join(", ")); } let publisher = field("publisher"); if !publisher.is_empty() { parts.push(format!("{publisher}.")); } for name in ["institution", "school", "organization", "howpublished"] { if !field(name).is_empty() { parts.push(format!("{}.", field(name))); } } if !field("edition").is_empty() { parts.push(format!("{} ed.", field("edition"))); } if !field("address").is_empty() { parts.push(format!("{}:", field("address"))); } if !field("month").is_empty() { parts.push(field("month").to_string()); } let year = field("year"); if !year.is_empty() { parts.push(format!("({year}).")); } if !field("note").is_empty() { parts.push(format!("{}.", field("note"))); } escape_bib_text(&parts.join(" ")) } /// plainnat/author-year layout used by `natbib` and the arXiv class. fn natbib_latex(&self) -> String { let field = |name: &str| self.fields.get(name).map(String::as_str).unwrap_or(""); let authors = if !field("author").is_empty() { natbib_author_list(field("author")) } else if !field("editor").is_empty() { format!("{} (ed.)", field("editor")) } else { String::new() }; let mut output = String::new(); if !authors.is_empty() { output.push_str(&authors); output.push_str(". "); } let title = field("title"); if !title.is_empty() { output.push_str(title); output.push_str(". "); } let mut tail = Vec::new(); let booktitle = field("booktitle"); if !booktitle.is_empty() { tail.push(format!("In \\emph{{{booktitle}}}")); } else if !field("journal").is_empty() { tail.push(format!("\\emph{{{}}}", field("journal"))); } if !field("volume").is_empty() { let mut volume = field("volume").to_string(); if !field("number").is_empty() { volume.push_str(&format!("({})", field("number"))); } tail.push(volume); } if !field("pages").is_empty() { tail.push(format!( "pages {}", field("pages").replace("--", "\u{2013}") )); } if !tail.is_empty() { output.push_str(&tail.join(", ")); output.push_str(", "); } let publisher = if field("publisher").is_empty() { field("organization") } else { field("publisher") }; let year = field("year"); match (publisher.is_empty(), year.is_empty()) { (false, false) => output.push_str(&format!("{publisher}, {year}.")), (false, true) => output.push_str(&format!("{publisher}.")), (true, false) => output.push_str(&format!("{year}.")), (true, true) => { if output.ends_with(", ") { output.truncate(output.len() - 2); output.push('.'); } } } escape_bib_text(output.trim()) } } fn escape_bib_text(source: &str) -> String { let mut output = String::with_capacity(source.len()); for character in source.chars() { match character { '&' if !output.ends_with('\\') => output.push_str("\\&"), '%' => output.push('%'), _ => output.push(character), } } output } fn load_bibliography( file_names: &str, source_dir: &Path, dependencies: &mut Vec, ) -> Result, String> { let mut sources = String::new(); let mut seen_keys = std::collections::HashSet::new(); for file_name in file_names .split(',') .map(str::trim) .filter(|name| !name.is_empty()) { let mut path = PathBuf::from(file_name); if path.extension().is_none() { path.set_extension("bib"); } if !path.is_absolute() { path = source_dir.join(path); } let source = fs::read_to_string(&path) .map_err(|error| format!("could not read bibliography {}: {error}", path.display()))?; tex_expansion::SourceDependency::record(dependencies, &path, &source); sources.push_str(&source); sources.push('\n'); } let mut entries = parse_bib_entries(&sources)?; for entry in &entries { if !seen_keys.insert(entry.key.clone()) { return Err(format!("duplicate BibTeX key `{}`", entry.key)); } } let parent_fields = entries .iter() .map(|entry| (entry.key.clone(), entry.fields.clone())) .collect::>(); for entry in &mut entries { if let Some(crossref) = entry.fields.remove("crossref") && let Some(parent) = parent_fields.get(&crossref) { for (name, value) in parent { entry .fields .entry(name.clone()) .or_insert_with(|| value.clone()); } } } Ok(entries) } fn parse_bib_entries(source: &str) -> Result, String> { let mut raw_entries = Vec::new(); let mut string_macros = HashMap::new(); let mut cursor = 0; while let Some(offset) = source[cursor..].find('@') { cursor += offset + 1; let type_start = cursor; while source .as_bytes() .get(cursor) .is_some_and(u8::is_ascii_alphabetic) { cursor += 1; } if type_start == cursor { continue; } let kind = source[type_start..cursor].to_ascii_lowercase(); while source .as_bytes() .get(cursor) .is_some_and(|byte| byte.is_ascii_whitespace()) { cursor += 1; } let Some(open) = source.as_bytes().get(cursor).copied() else { break; }; if !matches!(open, b'{' | b'(') { continue; } let (body, after_entry) = read_bib_entry_body(source, cursor, open) .ok_or_else(|| format!("unclosed BibTeX entry of type `{kind}`"))?; cursor = after_entry; if matches!(kind.as_str(), "comment" | "preamble") { continue; } let mut fields = split_bib_top_level(body, ',').into_iter(); if kind == "string" { if let Some((name, value)) = body.split_once('=') { string_macros.insert(name.trim().to_ascii_lowercase(), value.trim().to_string()); } continue; } let Some(key) = fields.next().map(|value| value.trim().to_string()) else { continue; }; if key.is_empty() { continue; } let mut parsed_fields = HashMap::new(); for field in fields { let Some((name, value)) = field.split_once('=') else { continue; }; let name = name.trim().to_ascii_lowercase(); if !name.is_empty() { parsed_fields.insert(name, value.trim().to_string()); } } raw_entries.push((kind, key, parsed_fields)); } Ok(raw_entries .into_iter() .map(|(kind, key, raw_fields)| BibEntry { kind, key, fields: raw_fields .into_iter() .map(|(name, value)| (name, expand_bib_value(&value, &string_macros, 0))) .collect(), }) .collect()) } fn read_bib_entry_body(source: &str, open_index: usize, open: u8) -> Option<(&str, usize)> { let outer_close = if open == b'{' { b'}' } else { b')' }; let mut outer_depth = 1usize; let mut brace_depth = 0usize; let mut quoted = false; let mut escaped = false; let mut cursor = open_index + 1; while cursor < source.len() { let character = source[cursor..].chars().next()?; let width = character.len_utf8(); if escaped { escaped = false; cursor += width; continue; } if character == '\\' { escaped = true; cursor += width; continue; } if character == '"' && brace_depth == 0 { quoted = !quoted; cursor += width; continue; } if !quoted { if character == '{' { brace_depth += 1; } else if character == '}' && brace_depth > 0 { brace_depth -= 1; } else if brace_depth == 0 && open == b'{' && character as u32 == u32::from(outer_close) { outer_depth -= 1; if outer_depth == 0 { return Some((&source[open_index + 1..cursor], cursor + width)); } } else if brace_depth == 0 && open == b'(' && character == '(' { outer_depth += 1; } else if brace_depth == 0 && open == b'(' && character == ')' { outer_depth -= 1; if outer_depth == 0 { return Some((&source[open_index + 1..cursor], cursor + width)); } } } cursor += width; } None } fn split_bib_top_level(source: &str, delimiter: char) -> Vec<&str> { let mut parts = Vec::new(); let mut start = 0; let mut brace_depth = 0usize; let mut quoted = false; let mut escaped = false; for (index, character) in source.char_indices() { if escaped { escaped = false; continue; } if character == '\\' { escaped = true; continue; } if character == '"' && brace_depth == 0 { quoted = !quoted; continue; } if quoted { continue; } match character { '{' => brace_depth += 1, '}' => brace_depth = brace_depth.saturating_sub(1), c if c == delimiter && brace_depth == 0 => { parts.push(&source[start..index]); start = index + c.len_utf8(); } _ => {} } } parts.push(&source[start..]); parts } fn expand_bib_value(value: &str, macros: &HashMap, depth: usize) -> String { if depth > 16 { return value.to_string(); } split_bib_top_level(value, '#') .into_iter() .map(str::trim) .map(|part| { if let Some((inner, after)) = read_braced_group(part, 0) && after == part.len() { return inner.trim().to_string(); } if part.starts_with('"') && part.ends_with('"') && part.len() >= 2 { return part[1..part.len() - 1].trim().to_string(); } if let Some(value) = macros.get(&part.to_ascii_lowercase()) { return expand_bib_value(value, macros, depth + 1); } part.to_string() }) .collect::>() .join("") } fn read_control_sequence(source: &str, start: usize) -> (String, usize) { let bytes = source.as_bytes(); if bytes.get(start) != Some(&b'\\') { return (String::new(), start); } let mut end = start + 1; if end < bytes.len() && (bytes[end].is_ascii_alphabetic() || bytes[end] == b'@') { while end < bytes.len() && (bytes[end].is_ascii_alphabetic() || bytes[end] == b'@') { end += 1; } } else if end < bytes.len() { end += source[end..] .chars() .next() .expect("valid UTF-8 boundary") .len_utf8() - 1; } (source[start..end].to_string(), end) } 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 } fn prohibits_cjk_line_break(previous: char, current: char) -> bool { if previous == ' ' || current == ' ' { return true; } let previous_is_opening = matches!( previous, '(' | '[' | '{' | '〈' | '《' | '「' | '『' | '【' | '〔' | '〖' | '〘' | '〚' | '(' | '[' | '{' | '‘' | '“' | '«' | '‹' ); let current_is_nonstarter = matches!( current, ')' | ']' | '}' | ',' | '.' | '!' | '?' | ':' | ';' | '%' | '、' | '。' | ',' | '.' | '・' | ':' | ';' | '!' | '?' | '‼' | '⁇' | '⁈' | '⁉' | '〕' | '〉' | '》' | '」' | '』' | '】' | '〗' | '〙' | '〛' | '〟' | '’' | '”' | '»' | '›' | 'ぁ' | 'ぃ' | 'ぅ' | 'ぇ' | 'ぉ' | 'っ' | 'ゃ' | 'ゅ' | 'ょ' | 'ゎ' | 'ァ' | 'ィ' | 'ゥ' | 'ェ' | 'ォ' | 'ッ' | 'ャ' | 'ュ' | 'ョ' | 'ヮ' | 'ヵ' | 'ヶ' | 'ー' ); previous_is_opening || current_is_nonstarter }