use techy::core::node::NodeRef;
use techy::latexlike::InvocationSyntaxData;
use crate::lang::Flm;
use crate::lang::mint::is_math_text_command;
use crate::model::element::element_of;
use crate::stdlib::backends::pres::read::ends_with_control_word;
use crate::stdlib::backends::pres::recompose_source;
use super::ensuremath::ENSUREMATH;
use super::latex::normalize_line_newlines;
use super::lines::EquationLine;
#[derive(Debug, Clone)]
pub enum TexPart<'t> {
Tex(String),
Hole(TextHole<'t>),
}
#[derive(Debug, Clone)]
pub struct TextHole<'t> {
pub command: String,
pub node: NodeRef<'t, Flm>,
}
#[derive(Debug, Clone)]
pub struct LineTex<'t> {
pub parts: Vec<TexPart<'t>>,
pub trailing: String,
}
impl LineTex<'_> {
pub fn ends_line(&self) -> bool {
!self.trailing.is_empty()
}
}
pub fn group_tex<'t>(node: &NodeRef<'t, Flm>) -> Vec<TexPart<'t>> {
let mut writer = Writer::default();
writer.nodes(&node.children().iter().collect::<Vec<_>>());
writer.parts
}
pub fn line_tex<'t>(line: &EquationLine<'t>, after_line_end: bool) -> LineTex<'t> {
let mut writer = Writer::default();
writer.nodes(&line.content);
let count = writer.parts.len();
let mut after_line_end = after_line_end;
let mut parts = Vec::with_capacity(count);
let mut trailing = String::new();
for (index, part) in writer.parts.into_iter().enumerate() {
match part {
TexPart::Tex(text) => {
let line = normalize_line_newlines(&text, after_line_end, index + 1 < count);
if !line.text.is_empty() {
parts.push(TexPart::Tex(line.text));
}
trailing = line.trailing;
}
TexPart::Hole(hole) => {
parts.push(TexPart::Hole(hole));
after_line_end = false;
}
}
}
LineTex { parts, trailing }
}
fn needs_walk(node: &NodeRef<'_, Flm>) -> bool {
let walked = |node: &NodeRef<'_, Flm>| {
node.is_comment() || is_math_text_command(node) || element_of(node).name == ENSUREMATH
};
walked(node) || node.descendants().any(|descendant| walked(&descendant))
}
fn macro_call(node: &NodeRef<'_, Flm>) -> String {
let name = node.name().unwrap_or_default();
match node.invocation_syntax() {
Some(InvocationSyntaxData::Macro { escape_char, post_space }) => {
format!("{escape_char}{name}{}", post_space.resolve(node.span().source()))
}
_ => format!("\\{name}"),
}
}
#[derive(Debug, Default)]
struct Writer<'t> {
parts: Vec<TexPart<'t>>,
}
impl<'t> Writer<'t> {
fn text(&mut self, text: &str) {
if text.is_empty() {
return;
}
if let Some(TexPart::Tex(previous)) = self.parts.last_mut() {
if text.starts_with(|c: char| c.is_ascii_alphabetic()) && ends_with_control_word(previous) {
previous.push(' ');
}
previous.push_str(text);
} else {
self.parts.push(TexPart::Tex(String::from(text)));
}
}
fn nodes(&mut self, nodes: &[NodeRef<'t, Flm>]) {
let mut run: Vec<NodeRef<'t, Flm>> = Vec::new();
for node in nodes {
if needs_walk(node) {
self.source(&mut run);
self.node(*node);
} else {
run.push(*node);
}
}
self.source(&mut run);
}
fn source(&mut self, run: &mut Vec<NodeRef<'t, Flm>>) {
if !run.is_empty() {
self.text(&recompose_source(run));
run.clear();
}
}
fn node(&mut self, node: NodeRef<'t, Flm>) {
if node.is_comment() {
self.text(" ");
return;
}
if is_math_text_command(&node) {
let command = String::from(node.name().unwrap_or_default());
self.parts.push(TexPart::Hole(TextHole { command, node }));
return;
}
if element_of(&node).name == ENSUREMATH {
let content: Vec<NodeRef<'t, Flm>> =
node.argument_content_nodes(0).map(|slice| slice.iter().collect()).unwrap_or_default();
self.nodes(&content);
return;
}
if let Some((open, close)) = node.group_delimiters() {
self.text(open);
self.nodes(&node.children().iter().collect::<Vec<_>>());
self.text(close);
return;
}
if node.is_list() {
self.nodes(&node.children().iter().collect::<Vec<_>>());
return;
}
if let Some(body) = node.body() {
let name = node.name().unwrap_or_default();
self.text(&format!("\\begin{{{name}}}"));
self.arguments(&node);
self.nodes(&body.iter().collect::<Vec<_>>());
self.text(&format!("\\end{{{name}}}"));
return;
}
if node.callable().is_some_and(|callable| !callable.arguments.is_empty()) {
self.text(¯o_call(&node));
self.arguments(&node);
return;
}
self.text(&recompose_source(&[node]));
}
fn arguments(&mut self, node: &NodeRef<'t, Flm>) {
let count = node.callable().map_or(0, |callable| callable.arguments.len());
for index in 0..count {
if let Some(region) = node.argument_nodes(index) {
self.nodes(®ion.iter().collect::<Vec<_>>());
}
}
}
}