#[derive(Clone, Debug, Default, PartialEq)]
pub struct Math {
pub body: Node,
pub style: MathStyle,
pub inline: bool,
}
impl Math {
pub fn new(body: impl Into<Node>) -> Self {
Self {
body: body.into(),
style: MathStyle::Full,
inline: false,
}
}
pub fn node_at(&self, path: &Path) -> Option<&Node> {
self.body.node_at(path)
}
pub fn node_at_mut(&mut self, path: &Path) -> Option<&mut Node> {
self.body.node_at_mut(path)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MathStyle {
Text,
Script,
ScriptScript,
#[default]
Full,
Symbol,
SubSymbol,
User1,
User2,
}
impl MathStyle {
pub fn smaller(self) -> Self {
match self {
MathStyle::Full
| MathStyle::Text
| MathStyle::Symbol
| MathStyle::User1
| MathStyle::User2 => MathStyle::Script,
MathStyle::Script | MathStyle::SubSymbol | MathStyle::ScriptScript => {
MathStyle::ScriptScript
}
}
}
}
pub type Row = Vec<Node>;
#[derive(Clone, Debug, PartialEq)]
pub enum Node {
Row(Row),
Char(Char),
Text(Box<TextRun>),
Space(Space),
Frac(Box<Frac>),
Sqrt(Box<Sqrt>),
Scripts(Box<Scripts>),
Limits(Box<Limits>),
Fence(Box<Fence>),
Matrix(Box<Matrix>),
Accent(Box<Accent>),
LabeledArrow(Box<LabeledArrow>),
Big(Box<BigOp>),
Styled(Box<Styled>),
Align,
Error(String),
}
impl Node {
pub fn empty() -> Self {
Node::Row(Row::new())
}
pub fn row(items: impl IntoIterator<Item = Node>) -> Self {
Node::Row(items.into_iter().collect())
}
pub fn char_with(ch: char, class: Class, font: Font) -> Self {
Node::Char(Char {
ch,
class,
font,
style_ref: None,
})
}
pub fn variable(ch: char) -> Self {
Node::Char(Char {
style_ref: None,
ch,
class: Class::Ord,
font: Font::Italic,
})
}
pub fn symbol(ch: char, class: Class) -> Self {
Node::Char(Char {
style_ref: None,
ch,
class,
font: Font::Upright,
})
}
pub fn text(text: impl Into<String>) -> Self {
Node::Text(Box::new(TextRun {
text: text.into(),
font: Font::Upright,
}))
}
pub fn is_empty_slot(&self) -> bool {
matches!(self, Node::Row(row) if row.is_empty())
}
pub fn is_row(&self) -> bool {
matches!(self, Node::Row(_))
}
pub fn slot_count(&self) -> usize {
match self {
Node::Row(row) => row.len(),
Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => 0,
Node::Frac(_) => 2,
Node::Sqrt(sqrt) => 1 + usize::from(sqrt.index.is_some()),
Node::Scripts(_) => 3,
Node::Limits(_) => 3,
Node::Fence(_) => 1,
Node::Matrix(matrix) => matrix.rows.iter().map(Row::len).sum(),
Node::Accent(_) => 1,
Node::LabeledArrow(arrow) => arrow.slot_count(),
Node::Big(_) => 3,
Node::Styled(_) => 1,
}
}
pub fn slot(&self, index: usize) -> Option<&Node> {
match self {
Node::Row(row) => row.get(index),
Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => None,
Node::Frac(frac) => match index {
0 => Some(&frac.num),
1 => Some(&frac.den),
_ => None,
},
Node::Sqrt(sqrt) => match (index, &sqrt.index) {
(0, Some(radicand)) => Some(radicand),
(0, None) => Some(&sqrt.radicand),
(1, Some(_)) => Some(&sqrt.radicand),
_ => None,
},
Node::Scripts(scripts) => match index {
0 => Some(&scripts.base),
1 => scripts.sub.as_ref(),
2 => scripts.sup.as_ref(),
_ => None,
},
Node::Limits(limits) => match index {
0 => Some(&limits.base),
1 => limits.under.as_ref(),
2 => limits.over.as_ref(),
_ => None,
},
Node::Fence(fence) => (index == 0).then_some(&fence.body),
Node::Matrix(matrix) => matrix.cell_at(index),
Node::Accent(accent) => (index == 0).then_some(&accent.base),
Node::LabeledArrow(arrow) => arrow.slot(index),
Node::Big(big) => match index {
0 => Some(&big.base),
1 => big.sub.as_ref(),
2 => big.sup.as_ref(),
_ => None,
},
Node::Styled(styled) => (index == 0).then_some(&styled.body),
}
}
pub fn slot_mut(&mut self, index: usize) -> Option<&mut Node> {
match self {
Node::Row(row) => row.get_mut(index),
Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => None,
Node::Frac(frac) => match index {
0 => Some(&mut frac.num),
1 => Some(&mut frac.den),
_ => None,
},
Node::Sqrt(sqrt) => match (index, &mut sqrt.index) {
(0, Some(radicand)) => Some(radicand),
(0, None) => Some(&mut sqrt.radicand),
(1, Some(_)) => Some(&mut sqrt.radicand),
_ => None,
},
Node::Scripts(scripts) => match index {
0 => Some(&mut scripts.base),
1 => scripts.sub.as_mut(),
2 => scripts.sup.as_mut(),
_ => None,
},
Node::Limits(limits) => match index {
0 => Some(&mut limits.base),
1 => limits.under.as_mut(),
2 => limits.over.as_mut(),
_ => None,
},
Node::Fence(fence) => (index == 0).then_some(&mut fence.body),
Node::Matrix(matrix) => matrix.cell_at_mut(index),
Node::Accent(accent) => (index == 0).then_some(&mut accent.base),
Node::LabeledArrow(arrow) => arrow.slot_mut(index),
Node::Big(big) => match index {
0 => Some(&mut big.base),
1 => big.sub.as_mut(),
2 => big.sup.as_mut(),
_ => None,
},
Node::Styled(styled) => (index == 0).then_some(&mut styled.body),
}
}
pub fn slots(&self) -> Vec<&Node> {
(0..self.slot_count())
.filter_map(|i| self.slot(i))
.collect()
}
pub fn walk<'a>(&'a self, visit: &mut impl FnMut(&'a Node)) {
visit(self);
for index in 0..self.slot_count() {
if let Some(slot) = self.slot(index) {
slot.walk(visit);
}
}
}
pub fn node_at(&self, path: &Path) -> Option<&Node> {
let mut current = self;
for &index in path.as_slice() {
current = current.slot(index)?;
}
Some(current)
}
pub fn node_at_mut(&mut self, path: &Path) -> Option<&mut Node> {
let mut current = self;
for &index in path.as_slice() {
current = current.slot_mut(index)?;
}
Some(current)
}
pub fn replace_at(&mut self, path: &Path, node: Node) -> Option<Node> {
let (parent_path, index) = path.split_last()?;
let parent = self.node_at_mut(&parent_path)?;
match parent {
Node::Row(row) => {
let target = row.get_mut(index)?;
Some(std::mem::replace(target, node))
}
other => {
let target = other.slot_mut(index)?;
Some(std::mem::replace(target, node))
}
}
}
pub fn insert_at(&mut self, path: &Path, node: Node) -> bool {
match self.node_at_mut(path) {
Some(Node::Row(row)) => {
row.push(node);
true
}
Some(_) => match path.split_last() {
Some((parent_path, index)) => match self.node_at_mut(&parent_path) {
Some(parent) => parent.insert_sibling(index, node),
None => false,
},
None => false,
},
None => false,
}
}
fn insert_sibling(&mut self, index: usize, node: Node) -> bool {
match self {
Node::Row(row) => {
let index = index.min(row.len());
row.insert(index, node);
true
}
_ => false,
}
}
pub fn remove_at(&mut self, path: &Path) -> Option<Node> {
let (parent_path, index) = path.split_last()?;
match self.node_at_mut(&parent_path)? {
Node::Row(row) => (index < row.len()).then(|| row.remove(index)),
_ => None,
}
}
pub fn normalize(&mut self) {
for index in 0..self.slot_count() {
if let Some(slot) = self.slot_mut(index) {
slot.normalize();
}
}
if let Node::Row(row) = self {
let mut flat = Row::with_capacity(row.len());
for node in row.drain(..) {
match node {
Node::Row(inner) => flat.extend(inner),
other => flat.push(other),
}
}
*row = flat;
}
}
}
impl From<char> for Node {
fn from(ch: char) -> Self {
Node::variable(ch)
}
}
impl From<&str> for Node {
fn from(text: &str) -> Self {
Node::Text(Box::new(TextRun {
text: text.to_owned(),
font: Font::Upright,
}))
}
}
impl From<String> for Node {
fn from(text: String) -> Self {
Node::Text(Box::new(TextRun {
text,
font: Font::Upright,
}))
}
}
impl From<Vec<Node>> for Node {
fn from(items: Vec<Node>) -> Self {
Node::Row(items)
}
}
impl Default for Node {
fn default() -> Self {
Node::empty()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Char {
pub ch: char,
pub class: Class,
pub font: Font,
pub style_ref: Option<StyleRef>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum StyleRef {
User1,
User2,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Class {
#[default]
Ord,
Op,
Bin,
Rel,
Open,
Close,
Punct,
Inner,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Font {
#[default]
Italic,
Upright,
Bold,
BoldItalic,
SansSerif,
SansSerifBold,
SansSerifItalic,
SansSerifBoldItalic,
Monospace,
Script,
BoldScript,
Fraktur,
BoldFraktur,
DoubleStruck,
Symbol,
Extra,
Fences,
Euclid,
EuclidItalic,
EuclidBold,
EuclidBoldItalic,
EuclidSymbol,
EuclidSymbolItalic,
EuclidSymbolBold,
EuclidSymbolBoldItalic,
EuclidExtra,
EuclidExtraBold,
}
impl Font {
pub fn is_italic(self) -> bool {
matches!(
self,
Font::Italic
| Font::BoldItalic
| Font::SansSerifItalic
| Font::SansSerifBoldItalic
| Font::EuclidItalic
| Font::EuclidBoldItalic
| Font::EuclidSymbolItalic
| Font::EuclidSymbolBoldItalic
)
}
pub fn is_bold(self) -> bool {
matches!(
self,
Font::Bold
| Font::BoldItalic
| Font::SansSerifBold
| Font::SansSerifBoldItalic
| Font::BoldScript
| Font::BoldFraktur
| Font::EuclidBold
| Font::EuclidBoldItalic
| Font::EuclidSymbolBold
| Font::EuclidSymbolBoldItalic
| Font::EuclidExtraBold
)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextRun {
pub text: String,
pub font: Font,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Space {
Thin,
Medium,
Thick,
Sixteenth,
Quad,
DoubleQuad,
ZeroWidth,
OnePoint,
NegativeThin,
NegativeMedium,
NegativeThick,
}
impl Space {
pub fn em(self, size: f64) -> f64 {
match self {
Space::Thin => 3.0 / 18.0,
Space::Medium => 4.0 / 18.0,
Space::Thick => 5.0 / 18.0,
Space::Sixteenth => 6.0 / 18.0,
Space::Quad => 1.0,
Space::DoubleQuad => 2.0,
Space::ZeroWidth => 0.0,
Space::OnePoint => 1.0 / size,
Space::NegativeThin => -3.0 / 18.0,
Space::NegativeMedium => -4.0 / 18.0,
Space::NegativeThick => -5.0 / 18.0,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Frac {
pub num: Node,
pub den: Node,
pub kind: FracKind,
pub small: bool,
}
impl Frac {
pub fn new(num: Node, den: Node) -> Self {
Self {
num,
den,
kind: FracKind::Bar,
small: false,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FracKind {
#[default]
Bar,
Slash,
NoBar,
Linear,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Sqrt {
pub index: Option<Node>,
pub radicand: Node,
}
impl Sqrt {
pub fn square(radicand: Node) -> Self {
Self {
index: None,
radicand,
}
}
pub fn nth(index: Node, radicand: Node) -> Self {
Self {
index: Some(index),
radicand,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Scripts {
pub base: Node,
pub sub: Option<Node>,
pub sup: Option<Node>,
pub precedes: bool,
}
impl Scripts {
pub fn attach(base: Node, sub: Option<Node>, sup: Option<Node>) -> Self {
Self {
base,
sub,
sup,
precedes: false,
}
}
pub fn attach_preceding(base: Node, sub: Option<Node>, sup: Option<Node>) -> Self {
Self {
base,
sub,
sup,
precedes: true,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Limits {
pub base: Node,
pub under: Option<Node>,
pub over: Option<Node>,
pub align: Side,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Side {
#[default]
Center,
Left,
Right,
AtRelation,
AtDecimal,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum VerticalAlign {
Top,
#[default]
Center,
Bottom,
Centered,
Axis,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum LineStyle {
#[default]
None,
Solid,
Dashed,
Dotted,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Delim {
Paren,
Bracket,
Brace,
Abs,
Norm,
Angle,
Floor,
Ceil,
None,
Custom(char),
Arrow,
DoubleBar,
}
impl Delim {
pub fn open(self) -> Option<char> {
Some(match self {
Delim::Paren => '(',
Delim::Bracket => '[',
Delim::Brace => '{',
Delim::Abs => '|',
Delim::Norm => '\u{2016}',
Delim::Angle => '\u{27E8}',
Delim::Floor => '\u{230A}',
Delim::Ceil => '\u{2308}',
Delim::None => return None,
Delim::Custom(ch) => ch,
Delim::Arrow => '\u{27E8}',
Delim::DoubleBar => '\u{2016}',
})
}
pub fn close(self) -> Option<char> {
Some(match self {
Delim::Paren => ')',
Delim::Bracket => ']',
Delim::Brace => '}',
Delim::Abs => '|',
Delim::Norm => '\u{2016}',
Delim::Angle => '\u{27E9}',
Delim::Floor => '\u{230B}',
Delim::Ceil => '\u{2309}',
Delim::None => return None,
Delim::Custom(ch) => ch,
Delim::Arrow => '\u{27E9}',
Delim::DoubleBar => '\u{2016}',
})
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FenceAlign {
#[default]
Axis,
Contents,
Centered,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Fence {
pub open: Delim,
pub close: Delim,
pub body: Node,
pub align: FenceAlign,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Matrix {
pub rows: Vec<Row>,
pub delims: Option<(Delim, Delim)>,
pub kind: MatrixKind,
pub line_spacings: Vec<Option<f64>>,
pub align: Side,
pub columns: Vec<Side>,
pub stack_align: VerticalAlign,
pub cell_align: VerticalAlign,
pub row_lines: Vec<LineStyle>,
pub col_lines: Vec<LineStyle>,
}
impl Matrix {
pub fn empty(rows: usize, cols: usize) -> Self {
Self {
rows: vec![vec![Node::empty(); cols]; rows],
delims: None,
kind: MatrixKind::Matrix,
line_spacings: vec![None; rows],
align: Side::Center,
columns: Vec::new(),
stack_align: VerticalAlign::Center,
cell_align: VerticalAlign::Center,
row_lines: vec![LineStyle::None; rows + 1],
col_lines: vec![LineStyle::None; cols + 1],
}
}
pub fn has_lines(&self) -> bool {
self.row_lines
.iter()
.chain(&self.col_lines)
.any(|style| *style != LineStyle::None)
}
pub fn row_count(&self) -> usize {
self.rows.len()
}
pub fn col_count(&self) -> usize {
self.rows.iter().map(Row::len).max().unwrap_or(0)
}
pub fn cell_position(&self, index: usize) -> Option<(usize, usize)> {
let mut remaining = index;
for (row, cells) in self.rows.iter().enumerate() {
if remaining < cells.len() {
return Some((row, remaining));
}
remaining -= cells.len();
}
None
}
pub fn cell_at(&self, index: usize) -> Option<&Node> {
let (row, col) = self.cell_position(index)?;
self.rows[row].get(col)
}
pub fn cell_at_mut(&mut self, index: usize) -> Option<&mut Node> {
let (row, col) = self.cell_position(index)?;
self.rows[row].get_mut(col)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MatrixKind {
#[default]
Matrix,
Cases,
Aligned,
Array,
Pile,
LongDivision,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Accent {
pub kind: AccentKind,
pub base: Node,
pub under: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AccentKind {
Hat,
WideHat,
Tilde,
WideTilde,
Bar,
Vector,
Dot,
DoubleDot,
TripleDot,
QuadDot,
Breve,
Check,
Acute,
Grave,
Circle,
OverBrace,
UnderBrace,
OverBracket,
UnderBracket,
OverParen,
UnderParen,
ArrowRight,
ArrowLeft,
HarpoonRight,
HarpoonLeft,
DoubleArrow,
Line,
Strike,
StrikeUp,
StrikeDown,
CrossStrike,
Arc,
JointStatus,
}
impl AccentKind {
pub fn glyph(self) -> Option<char> {
Some(match self {
AccentKind::Hat => '\u{02C6}',
AccentKind::WideHat => '\u{0302}',
AccentKind::Tilde => '~',
AccentKind::WideTilde => '\u{0303}',
AccentKind::Dot => '\u{02D9}',
AccentKind::DoubleDot => '\u{00A8}',
AccentKind::TripleDot => '\u{20DB}',
AccentKind::QuadDot => '\u{20DC}',
AccentKind::Breve => '\u{02D8}',
AccentKind::Check => '\u{02C7}',
AccentKind::Acute => '\u{00B4}',
AccentKind::Grave => '`',
AccentKind::Circle => '\u{02DA}',
AccentKind::ArrowRight => '\u{2192}',
AccentKind::ArrowLeft => '\u{2190}',
AccentKind::HarpoonRight => '\u{21C0}',
AccentKind::HarpoonLeft => '\u{21BC}',
AccentKind::DoubleArrow => '\u{2194}',
AccentKind::Arc => '\u{0311}',
AccentKind::Bar
| AccentKind::Vector
| AccentKind::Line
| AccentKind::Strike
| AccentKind::StrikeUp
| AccentKind::StrikeDown
| AccentKind::CrossStrike
| AccentKind::JointStatus => return None,
AccentKind::OverBrace => '\u{23DE}',
AccentKind::UnderBrace => '\u{23DF}',
AccentKind::OverBracket => '\u{23B4}',
AccentKind::UnderBracket => '\u{23B5}',
AccentKind::OverParen => '\u{23DC}',
AccentKind::UnderParen => '\u{23DD}',
})
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct LabeledArrow {
pub arrow: ArrowKind,
pub over: Option<Node>,
pub under: Option<Node>,
}
impl LabeledArrow {
pub fn slot_count(&self) -> usize {
usize::from(self.over.is_some()) + usize::from(self.under.is_some())
}
pub fn slot(&self, index: usize) -> Option<&Node> {
match (index, &self.over) {
(0, Some(over)) => Some(over),
(0, None) => self.under.as_ref(),
(1, Some(_)) => self.under.as_ref(),
_ => None,
}
}
pub fn slot_mut(&mut self, index: usize) -> Option<&mut Node> {
match (index, &mut self.over) {
(0, Some(over)) => Some(over),
(0, None) => self.under.as_mut(),
(1, Some(_)) => self.under.as_mut(),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ArrowKind {
Right,
Left,
DoubleHeaded,
Double,
LargeOverSmall,
SmallOverLarge,
Harpoons,
LargeOverSmallHarpoons,
SmallOverLargeHarpoons,
}
impl ArrowKind {
pub fn glyph(self) -> Option<char> {
Some(match self {
ArrowKind::Right => '\u{2192}',
ArrowKind::Left => '\u{2190}',
ArrowKind::DoubleHeaded => '\u{2194}',
ArrowKind::Double => '\u{21C4}',
ArrowKind::LargeOverSmall | ArrowKind::SmallOverLarge => '\u{21C4}',
ArrowKind::Harpoons => '\u{21CC}',
ArrowKind::LargeOverSmallHarpoons | ArrowKind::SmallOverLargeHarpoons => '\u{21CC}',
})
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct BigOp {
pub base: Node,
pub sub: Option<Node>,
pub sup: Option<Node>,
pub limits: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Nudge {
pub dx: i32,
pub dy: i32,
}
impl Nudge {
pub fn is_zero(&self) -> bool {
self.dx == 0 && self.dy == 0
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Styled {
pub body: Node,
pub style: Option<MathStyle>,
pub font: Option<Font>,
pub class: Option<Class>,
pub size: Option<Size>,
pub nudge: Option<Nudge>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Size {
Delta(i32),
Points(i32),
}
impl Size {
pub fn delta(points: f64) -> Self {
Size::Delta(thirty_seconds(points))
}
pub fn points(points: f64) -> Self {
Size::Points(thirty_seconds(points))
}
}
fn thirty_seconds(points: f64) -> i32 {
(points * 32.0).round() as i32
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Path(Vec<usize>);
impl Path {
pub fn root() -> Self {
Self(Vec::new())
}
pub fn child(&self, index: usize) -> Self {
let mut path = self.clone();
path.0.push(index);
path
}
pub fn parent(&self) -> Option<Self> {
let mut path = self.clone();
path.0.pop().map(|_| path)
}
pub fn last(&self) -> Option<usize> {
self.0.last().copied()
}
pub fn split_last(&self) -> Option<(Self, usize)> {
let (index, rest) = self.0.split_last()?;
Some((Self(rest.to_vec()), *index))
}
pub fn push(&mut self, index: usize) {
self.0.push(index);
}
pub fn pop(&mut self) -> Option<usize> {
self.0.pop()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn as_slice(&self) -> &[usize] {
&self.0
}
}
impl FromIterator<usize> for Path {
fn from_iter<T: IntoIterator<Item = usize>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
impl std::fmt::Display for Path {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.0.is_empty() {
return f.write_str(".");
}
for (position, index) in self.0.iter().enumerate() {
if position > 0 {
f.write_str(".")?;
}
write!(f, "{index}")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn scripts(base: Node, sub: Node, sup: Node) -> Node {
Node::Scripts(Box::new(Scripts {
base,
sub: Some(sub),
sup: Some(sup),
precedes: false,
}))
}
#[test]
fn a_new_equation_is_a_display_equation() {
assert!(!Math::new(Node::variable('x')).inline);
}
#[test]
fn fraction_slots_are_numerator_then_denominator() {
let frac = Node::Frac(Box::new(Frac::new(
Node::variable('a'),
Node::variable('b'),
)));
assert_eq!(frac.slot_count(), 2);
assert_eq!(frac.slot(0), Some(&Node::variable('a')));
assert_eq!(frac.slot(1), Some(&Node::variable('b')));
assert_eq!(frac.slot(2), None);
}
#[test]
fn square_root_has_a_single_slot() {
let root = Node::Sqrt(Box::new(Sqrt::square(Node::variable('x'))));
assert_eq!(root.slot_count(), 1);
assert_eq!(root.slot(0), Some(&Node::variable('x')));
let nth = Node::Sqrt(Box::new(Sqrt::nth(
Node::variable('n'),
Node::variable('x'),
)));
assert_eq!(nth.slot_count(), 2);
assert_eq!(nth.slot(0), Some(&Node::variable('n')));
assert_eq!(nth.slot(1), Some(&Node::variable('x')));
}
#[test]
fn path_navigation_reaches_nested_slots() {
let math = Math::new(Node::row([
Node::variable('x'),
scripts(
Node::variable('a'),
Node::variable('i'),
Node::variable('2'),
),
]));
let sup = Path::root().child(1).child(2);
assert_eq!(math.node_at(&sup), Some(&Node::variable('2')));
assert_eq!(sup.to_string(), "1.2");
assert_eq!(
sup.parent().map(|path| path.to_string()),
Some("1".to_owned())
);
assert_eq!(math.node_at(&Path::root()), Some(&math.body));
}
#[test]
fn replace_and_insert_operate_on_nested_slots() {
let mut math = Math::new(Node::row([
Node::variable('a'),
Node::Sqrt(Box::new(Sqrt::square(Node::variable('x')))),
]));
let radicand = Path::root().child(1).child(0);
let replaced = math
.node_at_mut(&radicand)
.map(|node| std::mem::replace(node, Node::variable('y')));
assert_eq!(replaced, Some(Node::variable('x')));
assert_eq!(math.node_at(&radicand), Some(&Node::variable('y')));
let row = Path::root();
assert!(math.body.insert_at(&row, Node::variable('z')));
assert_eq!(math.body.slot_count(), 3);
assert_eq!(
math.node_at(&Path::root().child(2)),
Some(&Node::variable('z'))
);
assert_eq!(
math.body.remove_at(&Path::root().child(2)),
Some(Node::variable('z'))
);
assert_eq!(math.body.slot_count(), 2);
}
#[test]
fn matrix_cells_are_addressed_row_major() {
let mut matrix = Matrix::empty(2, 3);
if let Some(cell) = matrix.cell_at_mut(4) {
*cell = Node::variable('q');
}
let node = Node::Matrix(Box::new(matrix));
assert_eq!(node.slot_count(), 6);
assert_eq!(node.slot(4), Some(&Node::variable('q')));
assert_eq!(node.slot(1), Some(&Node::empty()));
}
#[test]
fn walk_visits_every_reachable_node() {
let math = Math::new(Node::row([
scripts(Node::variable('a'), Node::variable('i'), Node::empty()),
Node::Sqrt(Box::new(Sqrt::square(Node::variable('x')))),
]));
let mut names = Vec::new();
math.body.walk(&mut |node| {
if let Node::Char(Char { ch, .. }) = node {
names.push(*ch);
}
});
assert_eq!(names, vec!['a', 'i', 'x']);
}
#[test]
fn normalisation_flattens_nested_rows_only() {
let mut node = Node::row([
Node::variable('a'),
Node::row([Node::variable('b'), Node::variable('c')]),
]);
node.normalize();
assert_eq!(
node,
Node::row([
Node::variable('a'),
Node::variable('b'),
Node::variable('c')
])
);
let mut node = Node::row([Node::row([Node::variable('a')])]);
node.normalize();
assert_eq!(node, Node::row([Node::variable('a')]));
let mut fraction = Node::Frac(Box::new(Frac::new(
Node::row([Node::row([Node::variable('1')])]),
Node::variable('2'),
)));
fraction.normalize();
assert_eq!(fraction.slot(0), Some(&Node::row([Node::variable('1')])));
}
#[test]
fn space_widths_follow_the_em_grid() {
assert_eq!(Space::Thin.em(12.0), 3.0 / 18.0);
assert_eq!(Space::Quad.em(12.0), 1.0);
assert_eq!(Space::NegativeThick.em(12.0), -5.0 / 18.0);
}
#[test]
fn the_zero_width_space_takes_no_room_at_any_size() {
assert_eq!(Space::ZeroWidth.em(12.0), 0.0);
assert_eq!(Space::ZeroWidth.em(24.0), 0.0);
}
#[test]
fn the_point_space_is_one_point_whatever_the_size() {
assert_eq!(Space::OnePoint.em(12.0), 1.0 / 12.0);
assert_eq!(Space::OnePoint.em(24.0), 1.0 / 24.0);
}
#[test]
fn delimiters_expose_matching_pairs() {
assert_eq!(Delim::Paren.open(), Some('('));
assert_eq!(Delim::Paren.close(), Some(')'));
assert_eq!(Delim::None.open(), None);
assert_eq!(Delim::Brace.close(), Some('}'));
}
#[test]
fn style_nesting_saturates() {
assert_eq!(MathStyle::Full.smaller(), MathStyle::Script);
assert_eq!(MathStyle::Script.smaller(), MathStyle::ScriptScript);
assert_eq!(MathStyle::ScriptScript.smaller(), MathStyle::ScriptScript);
}
#[test]
fn the_euclid_faces_answer_for_their_own_weight_and_slant() {
assert!(!Font::Euclid.is_bold() && !Font::Euclid.is_italic());
assert!(Font::EuclidItalic.is_italic() && !Font::EuclidItalic.is_bold());
assert!(Font::EuclidBold.is_bold() && !Font::EuclidBold.is_italic());
assert!(Font::EuclidBoldItalic.is_bold() && Font::EuclidBoldItalic.is_italic());
assert!(Font::EuclidSymbolItalic.is_italic() && !Font::EuclidSymbolItalic.is_bold());
assert!(Font::EuclidSymbolBoldItalic.is_bold() && Font::EuclidSymbolBoldItalic.is_italic());
assert!(Font::EuclidExtraBold.is_bold() && !Font::EuclidExtraBold.is_italic());
assert!(!Font::EuclidExtra.is_bold() && !Font::EuclidExtra.is_italic());
assert!(!Font::Fences.is_bold() && !Font::Fences.is_italic());
}
}