pub mod align;
pub mod font;
pub mod mlist;
pub mod noad;
pub mod parse;
pub mod set;
use crate::expand::{Engine, TexError};
use crate::ir::Cmd;
use crate::lexer::Lexer;
use crate::token::Token;
use noad::{Noad, Scaled, Style, DISPLAY_STYLE, TEXT_STYLE};
use set::Setting;
pub const SETTING: char = 'M';
pub const RUN: char = '\u{17}';
pub fn pt(sp: Scaled) -> f64 {
sp as f64 / 65536.0
}
pub fn is_setting(spec: &str) -> bool {
spec.starts_with(SETTING)
}
pub fn run(spec: &str) -> String {
format!("{RUN}{spec}")
}
pub fn run_setting(text: &str) -> Option<Setting> {
let rest = text.strip_prefix(RUN)?;
set::decode(rest.strip_prefix(SETTING)?)
}
pub fn run_width(text: &str) -> Option<f64> {
run_setting(text).map(|s| pt(s.width))
}
pub fn glyphs(s: &Setting) -> Vec<(String, f64, f64, f64)> {
s.glyphs
.iter()
.map(|g| (g.ch.to_string(), pt(g.x), pt(g.y), pt(g.size)))
.collect()
}
pub fn rules(s: &Setting) -> Vec<(f64, f64, f64, f64)> {
s.rules
.iter()
.map(|r| (pt(r.x), pt(r.y), pt(r.width), pt(r.height)))
.collect()
}
pub fn set_mlist(list: &[Noad], style: Style, size: f64) -> Option<Setting> {
let fonts = fonts_at(size)?;
let b = mlist::set(fonts, list, style);
Some(set::flatten(&b, &|i| set::font_size(fonts, i)))
}
fn set_formula(list: &[Noad], style: Style, size: f64, display: bool) -> Option<Setting> {
let fonts = fonts_at(size)?;
let b = match display {
true => mlist::set(fonts, list, style),
false => mlist::set_with_penalties(fonts, list, style),
};
Some(set::flatten(&b, &|i| set::font_size(fonts, i)))
}
pub fn set_display(
f: &parse::Formula,
style: Style,
size: f64,
environment: &str,
measure: f64,
) -> Option<Vec<Setting>> {
let fonts = fonts_at(size)?;
let widest = f.rows.iter().map(|r| r.len()).max().unwrap_or(1);
let columns = align::columns(environment, widest);
let mut boxes = align::rows(fonts, &f.rows, style, &columns);
if let Some(number) = &f.number {
let a = mlist::set(fonts, number, TEXT_STYLE);
let z = (measure * 65536.0).round() as noad::Scaled;
if let Some(last) = boxes.pop() {
boxes.push(align::numbered(fonts, last, a, z, f.number_left));
}
}
Some(
boxes
.iter()
.map(|b| set::flatten(b, &|i| set::font_size(fonts, i)))
.collect(),
)
}
pub fn parse_formula(source: &str) -> Result<Vec<Noad>, TexError> {
Ok(read_formula(source)?.flat())
}
pub fn read_formula(source: &str) -> Result<parse::Formula, TexError> {
let mut eng = Engine::new();
eng.cats.set('{', crate::catcode::Cat::BeginGroup);
eng.cats.set('}', crate::catcode::Cat::EndGroup);
eng.cats.set('&', crate::catcode::Cat::AlignTab);
let mut lx = Lexer::new(source);
parse::formula(&mut eng, &mut lx, parse::Stop::MathShift)
}
fn fonts_at(size: f64) -> Option<&'static font::MathFonts> {
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
static CACHE: OnceLock<Mutex<HashMap<u64, Option<&'static font::MathFonts>>>> = OnceLock::new();
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
let key = size.to_bits();
let mut held = cache.lock().ok()?;
if let Some(hit) = held.get(&key) {
return *hit;
}
let loaded = font::MathFonts::load(size);
let answer = match loaded.usable() {
true => Some(&*Box::leak(Box::new(loaded))),
false => None,
};
held.insert(key, answer);
answer
}
const ENVIRONMENTS: &[&str] = &[
"equation",
"equation*",
"displaymath",
"align",
"align*",
"aligned",
"alignat",
"alignat*",
"gather",
"gather*",
"gathered",
"multline",
"multline*",
"eqnarray",
"eqnarray*",
"math",
BODY,
];
const BODY: &str = "document";
pub fn lower_math(
eng: &mut Engine,
size: f64,
measure: f64,
lx: &mut Lexer,
tok: &Token,
out: &mut Vec<Cmd>,
) -> Result<bool, TexError> {
let (style, stop) = match tok {
Token::Char(_, crate::catcode::Cat::MathShift) => match second_shift(eng, lx) {
true => (DISPLAY_STYLE, parse::Stop::MathShift),
false => (TEXT_STYLE, parse::Stop::MathShift),
},
Token::Cs(name) => match name.name() {
"(" => (TEXT_STYLE, parse::Stop::Cs(")")),
"[" => (DISPLAY_STYLE, parse::Stop::Cs("]")),
"begin" => match environment(lx) {
Some(BODY) => {
eng.cats.set('$', crate::catcode::Cat::MathShift);
return Ok(false);
}
Some(name) => {
consume_environment_name(eng, lx);
let f = parse::formula(eng, lx, parse::Stop::Cs("end"))?;
consume_end(eng, lx);
emit(out, &f, DISPLAY_STYLE, size, true, name, measure);
return Ok(true);
}
None => return Ok(false),
},
_ => return Ok(false),
},
_ => return Ok(false),
};
let f = parse::formula(eng, lx, stop)?;
if style == DISPLAY_STYLE && stop == parse::Stop::MathShift {
let _ = second_shift(eng, lx);
}
emit(out, &f, style, size, style == DISPLAY_STYLE, "", measure);
Ok(true)
}
fn second_shift(eng: &mut Engine, lx: &mut Lexer) -> bool {
match lx.next_token(&eng.cats) {
Some(Token::Char(_, crate::catcode::Cat::MathShift)) => true,
Some(t) => {
lx.push_back(&[t]);
false
}
None => false,
}
}
fn environment(lx: &Lexer) -> Option<&'static str> {
if !lx.pending.is_empty() {
return None;
}
let chars = lx.chars();
let mut at = lx.pos();
while chars.get(at) == Some(&' ') {
at += 1;
}
if chars.get(at) != Some(&'{') {
return None;
}
at += 1;
let mut name = String::new();
while let Some(c) = chars.get(at) {
if *c == '}' {
return ENVIRONMENTS.iter().find(|e| **e == name).copied();
}
name.push(*c);
at += 1;
if name.len() > 32 {
return None;
}
}
None
}
fn consume_environment_name(eng: &mut Engine, lx: &mut Lexer) {
while let Some(t) = lx.next_token(&eng.cats) {
if matches!(t, Token::Char(_, crate::catcode::Cat::EndGroup)) {
break;
}
}
}
fn consume_end(eng: &mut Engine, lx: &mut Lexer) {
match lx.next_token(&eng.cats) {
Some(Token::Cs(c)) if c.name() == "end" => consume_environment_name(eng, lx),
Some(t) => lx.push_back(&[t]),
None => {}
}
}
#[allow(clippy::too_many_arguments)]
fn emit(
out: &mut Vec<Cmd>,
f: &parse::Formula,
style: Style,
size: f64,
display: bool,
environment: &str,
measure: f64,
) {
let flat = f.flat();
if f.is_single() && f.number.is_none() {
let Some(setting) = set_formula(&flat, style, size, display) else {
push(out, &set::plain(&flat));
return;
};
push_setting(out, &setting, &set::plain(&flat), display);
return;
}
let Some(settings) = set_display(f, style, size, environment, measure) else {
push(out, &set::plain(&flat));
return;
};
let last = f.rows.len().saturating_sub(1);
for (at, (row, setting)) in f.rows.iter().zip(settings.iter()).enumerate() {
let mut spelled: String = row.iter().map(|cell| set::plain(cell)).collect();
if at == last {
if let Some(number) = &f.number {
spelled.push_str(&set::plain(number));
}
}
push_setting(out, setting, &spelled, display);
}
}
fn push_setting(out: &mut Vec<Cmd>, setting: &Setting, spelled: &str, display: bool) {
let marked = format!("\u{1}{SETTING}{}\u{2}{spelled}\u{3}", set::encode(setting));
match display {
true => push(
out,
&format!(
"\n\n{}{marked}{}\n\n",
crate::typeset::CENTRE,
crate::typeset::CENTRE_END
),
),
false => push(out, &marked),
}
}
fn push(out: &mut Vec<Cmd>, text: &str) {
let mut at = out.len();
while at > 0 && matches!(out[at - 1], Cmd::Line(_)) {
at -= 1;
}
match at.checked_sub(1).and_then(|i| out.get_mut(i)) {
Some(Cmd::Text(t)) => t.push_str(text),
_ => out.push(Cmd::Text(text.to_string())),
}
}