use std::collections::BTreeSet;
use std::sync::Arc;
use techy::core::node::{NodeKind, NodeRef, NodeTree};
use techy::error::{Diagnostic, DiagnosticInfo};
use crate::lang::guard;
use crate::lang::structural;
use crate::lang::{nowhere, Flm, FlmDiagnostics, FlmGroupType, FlmOrigin};
use crate::model::addr::TreeId;
use crate::model::element::element_of;
use crate::model::names::Name;
use crate::stdlib::backends::latex::construct::{self, BEGIN_SLOT, END_SLOT, arg_slots, slot_named};
use crate::stdlib::backends::latex::{
Declared, EscapeConfig, LatexArgShape, LatexDefinitionKind, LatexDefinitionPayload,
LatexEnvironmentPayload, LatexMacroPayload, LatexRaw, LatexRawPayload, LatexSink,
RecomposedDefinition, packages, preamble,
};
use crate::stdlib::backends::pres::{
self, BODY_SLOT, MathDisplay, MathPassthroughPayload, UnknownKind, UnknownPayload,
DroppedPayload, SubtreePayload, UnsupportedPayload, VerbatimDisplay, VerbatimKind, VerbatimPayload, is_presentation,
payload_of, recompose_source,
};
use super::feature::LatexRecomposedRenderOptions;
use super::stages::StageFailed;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LatexFragment {
pub text: String,
pub declared: Declared,
pub requires: BTreeSet<Name>,
pub definitions: Vec<RecomposedDefinition>,
pub placed: Vec<(usize, TreeId)>,
}
#[derive(Debug)]
pub struct Emitted {
pub fragment: Option<LatexFragment>,
pub diags: FlmDiagnostics,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.latex-recomposed.unknown-character",
message = "the character `{ch}` (U+{code}) has no known LaTeX spelling: neither the \
built-in table of LaTeX spellings nor the render option `unicode_overrides` gives \
one; give it a spelling in `unicode_overrides`, or leave the character out of \
the document"
)]
pub struct UnknownCharacter {
pub ch: char,
pub code: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.latex-recomposed.worker-thread-unavailable",
message = "writing the document as LaTeX needs a thread with a large stack, and the \
operating system refused to create one: {detail}"
)]
pub struct NoWorkerThread {
pub detail: String,
}
const LEVEL_STACK_ESTIMATE: usize = 12 * 1024;
pub const DEPTH_LIMIT: usize = guard::STACK_BUDGET / LEVEL_STACK_ESTIMATE;
const _: () = assert!(DEPTH_LIMIT >= 1024 && DEPTH_LIMIT <= 65536);
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.latex-recomposed.nesting-too-deep",
message = "the content nests too deeply to be written as LaTeX: {detail}"
)]
pub struct NestingTooDeep {
pub detail: String,
}
pub(crate) const NOWHERE_LABEL: &str = "latex-recomposed backend";
pub fn emit_tree(
tree: &Arc<NodeTree<Flm>>,
options: &LatexRecomposedRenderOptions,
comment_prefix: Option<&str>,
) -> Emitted {
match guard::on_worker_thread(|| emit_on_worker_thread(tree, options, comment_prefix)) {
Ok(emitted) => emitted,
Err(error) => {
let mut diags = FlmDiagnostics::new();
diags.push(Diagnostic::error(
NoWorkerThread { detail: error.to_string() },
nowhere(FlmOrigin::synthetic(NOWHERE_LABEL)),
));
Emitted { fragment: None, diags }
}
}
}
pub fn escape_config(options: &LatexRecomposedRenderOptions) -> EscapeConfig {
let overrides =
options.unicode_overrides.iter().map(|(ch, spelling)| (*ch, spelling.clone())).collect();
EscapeConfig::new(options.unicode).with_overrides(overrides)
}
fn emit_on_worker_thread(
tree: &Arc<NodeTree<Flm>>,
options: &LatexRecomposedRenderOptions,
comment_prefix: Option<&str>,
) -> Emitted {
let mut emitter = Emitter {
sink: LatexSink::new(escape_config(options)),
options,
comment_prefix: comment_prefix.unwrap_or("%"),
depth: 0,
in_token_group: false,
refused: false,
requires: BTreeSet::new(),
definitions: Vec::new(),
placed: Vec::new(),
extra_declared: Declared::new(),
extra_unknown: Vec::new(),
diags: FlmDiagnostics::new(),
};
let root = tree.root();
let children: Vec<NodeRef<'_, Flm>> = root.children().iter().collect();
if root.is_list() {
emitter.run(&children);
} else {
emitter.run(&[root]);
}
let Emitter { sink, refused, requires, definitions, placed, extra_declared, extra_unknown, mut diags, .. } =
emitter;
if refused {
diags.push(Diagnostic::error(
NestingTooDeep {
detail: format!(
"more than {DEPTH_LIMIT} levels"
),
},
root.span().clone(),
));
return Emitted { fragment: None, diags };
}
let mut output = sink.finish();
output.declared.merge(&extra_declared);
for ch in extra_unknown {
if !output.unknown.contains(&ch) {
output.unknown.push(ch);
}
}
for ch in output.unknown {
diags.push(Diagnostic::warning(
UnknownCharacter { ch, code: format!("{:04X}", u32::from(ch)) },
root.span().clone(),
));
}
let fragment =
LatexFragment { text: output.text, declared: output.declared, requires, definitions, placed };
Emitted { fragment: Some(fragment), diags }
}
struct Emitter<'a> {
sink: LatexSink,
options: &'a LatexRecomposedRenderOptions,
comment_prefix: &'a str,
depth: usize,
in_token_group: bool,
refused: bool,
requires: BTreeSet<Name>,
definitions: Vec<RecomposedDefinition>,
placed: Vec<(usize, TreeId)>,
extra_declared: Declared,
extra_unknown: Vec<char>,
diags: FlmDiagnostics,
}
fn latex_parameters(payload: &LatexDefinitionPayload) -> usize {
if payload.packed { 1 } else { payload.args }
}
fn macro_definition_head(payload: &LatexDefinitionPayload) -> String {
let name = &payload.name;
let parameters = latex_parameters(payload);
if payload.robust {
let definer =
if payload.is_bare() { "DeclareDocumentCommand" } else { "ProvideDocumentCommand" };
let specifiers: Vec<&str> = std::iter::repeat_n("+m", parameters).collect();
return format!("\\{definer}\\{name}{{{}}}", specifiers.join(" "));
}
if payload.is_bare() {
let text: String = (1..=parameters).map(|at| format!("#{at}")).collect();
return format!("\\long\\def\\{name}{text}");
}
match parameters {
0 => format!("\\providecommand\\{name}"),
count => format!("\\providecommand\\{name}[{count}]"),
}
}
fn environment_argument_specification(payload: &LatexDefinitionPayload) -> String {
let mut specifiers: Vec<&str> = std::iter::repeat_n("+m", latex_parameters(payload)).collect();
if payload.body_argument {
specifiers.push("+b");
}
format!("{{{}}}", specifiers.join(" "))
}
fn is_comment_line(node: &NodeRef<'_, Flm>) -> bool {
is_presentation(node) && matches!(element_of(node).name.as_str(), pres::UNSUPPORTED | pres::DROPPED)
}
fn ends_with_newline(node: &NodeRef<'_, Flm>) -> bool {
node.chars().is_some_and(|text| text.ends_with('\n'))
}
fn begins_with_letter(node: &NodeRef<'_, Flm>) -> bool {
let starts = |text: &str| text.starts_with(|c: char| c.is_ascii_alphabetic());
if let Some(text) = node.chars() {
return starts(text);
}
if let Some(raw) = payload_of::<LatexRawPayload>(node) {
return starts(&raw.text);
}
let transparent = node.is_list()
|| (!is_presentation(node) && element_of(node).name.as_str() == structural::CONTAINER)
|| (is_presentation(node) && element_of(node).name.as_str() == pres::SPAN);
transparent && node.children().first().is_some_and(|first| begins_with_letter(&first))
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum VerbatimPiece {
Text(String),
Latex(String),
}
fn verbatim_pieces(nodes: &[NodeRef<'_, Flm>]) -> Vec<VerbatimPiece> {
let mut out = Vec::new();
collect_verbatim_pieces(nodes, &mut out);
out
}
fn collect_verbatim_pieces(nodes: &[NodeRef<'_, Flm>], out: &mut Vec<VerbatimPiece>) {
for node in nodes {
if let Some(raw) = payload_of::<LatexRawPayload>(node) {
out.push(VerbatimPiece::Latex(raw.text.clone()));
} else if let Some(text) = node.chars() {
out.push(VerbatimPiece::Text(String::from(text)));
} else if node.group_type() == Some(FlmGroupType::Content) {
let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
collect_verbatim_pieces(&children, out);
} else {
out.push(VerbatimPiece::Text(recompose_source(&[*node])));
}
}
}
fn verbatim_text(nodes: &[NodeRef<'_, Flm>]) -> String {
let mut out = String::new();
for piece in verbatim_pieces(nodes) {
match piece {
VerbatimPiece::Text(text) | VerbatimPiece::Latex(text) => out.push_str(&text),
}
}
out
}
fn verbatim_block_groups(pieces: Vec<VerbatimPiece>) -> Vec<Vec<Vec<VerbatimPiece>>> {
let mut lines: Vec<Vec<Vec<VerbatimPiece>>> = vec![vec![Vec::new()]];
let push = |lines: &mut Vec<Vec<Vec<VerbatimPiece>>>, piece: VerbatimPiece| {
lines
.last_mut()
.expect("a line is open")
.last_mut()
.expect("a segment is open")
.push(piece);
};
for piece in pieces {
match piece {
VerbatimPiece::Latex(text) => push(&mut lines, VerbatimPiece::Latex(text)),
VerbatimPiece::Text(text) => {
for (at_line, line) in text.split('\n').enumerate() {
if at_line > 0 {
lines.push(vec![Vec::new()]);
}
for (at_segment, segment) in line.split('\t').enumerate() {
if at_segment > 0 {
lines.last_mut().expect("a line is open").push(Vec::new());
}
if !segment.is_empty() {
push(&mut lines, VerbatimPiece::Text(String::from(segment)));
}
}
}
}
}
}
let empty_last = lines.last().is_some_and(|line| line.len() == 1 && line[0].is_empty());
if lines.len() > 1 && empty_last {
lines.pop();
}
lines
}
impl Emitter<'_> {
fn descend(&mut self) -> bool {
if self.depth >= DEPTH_LIMIT {
self.refused = true;
return false;
}
self.depth += 1;
true
}
fn ascend(&mut self) {
self.depth -= 1;
}
fn unexpected(&mut self, node: &NodeRef<'_, Flm>, what: &str) {
self.diags.push(Diagnostic::error(
StageFailed {
stage: String::from(super::stages::EMIT_STAGE),
detail: format!("{what} `{}` reached the LaTeX emitter, which cannot write it", element_of(node).name),
},
node.span().clone(),
));
}
fn run(&mut self, nodes: &[NodeRef<'_, Flm>]) {
for (index, node) in nodes.iter().enumerate() {
if !self.descend() {
return;
}
self.node(node, nodes, index);
self.ascend();
}
}
fn node(&mut self, node: &NodeRef<'_, Flm>, siblings: &[NodeRef<'_, Flm>], index: usize) {
let ended = self.line_already_ended(siblings, index);
if let Some(text) = node.chars() {
self.text(if ended { text.strip_prefix('\n').unwrap_or(text) } else { text });
return;
}
if node.is_comment() {
self.comment(node);
return;
}
if !is_presentation(node) {
match node.kind() {
NodeKind::Group(data) if data.group_type == Some(FlmGroupType::OpaqueWrapper) => {
self.children(node);
}
NodeKind::Group(data) => {
let source = node.span().source();
let brackets =
data.open.resolve(source) == "[" && data.close.resolve(source) == "]";
if brackets {
self.sink.open_bracket();
} else {
self.sink.open_brace();
}
self.children(node);
if brackets {
self.sink.close_bracket();
} else {
self.sink.close_brace();
}
}
NodeKind::List => {
self.children(node);
}
_ => {
let name = element_of(node).name.clone();
if name.as_str() == structural::CONTAINER {
self.children(node);
} else {
self.unexpected(node, "a node of the element");
}
}
}
return;
}
let next = siblings.get(index + 1);
let name = element_of(node).name.clone();
match name.as_str() {
construct::MACRO => self.macro_call(node, next),
construct::ENVIRONMENT => self.environment(node),
construct::RAW => {
if let Some(payload) = payload_of::<LatexRawPayload>(node) {
if ended && payload.text.starts_with('\n') {
let text = LatexRawPayload::new(&payload.text[1..]);
self.write_raw(node, &LatexRaw::from_raw_payload(&text));
} else {
self.write_raw(node, &LatexRaw::from_raw_payload(payload));
}
}
}
construct::DEFINITION => self.definition(node),
pres::MATH_PASSTHROUGH => self.math(node),
pres::VERBATIM => self.verbatim(node),
pres::UNKNOWN => self.unknown(node, next),
pres::UNSUPPORTED => self.unsupported(node, siblings, index),
pres::DROPPED => self.dropped(node, siblings, index),
pres::SUBTREE => self.subtree(node),
pres::SPAN => self.children(node),
_ => self.unexpected(node, "a presentation node of the element"),
}
}
fn line_already_ended(&self, siblings: &[NodeRef<'_, Flm>], index: usize) -> bool {
let Some(previous) = index.checked_sub(1).and_then(|i| siblings.get(i)) else {
return false;
};
if is_comment_line(previous) {
return true;
}
if self.options.drop_comments {
return false;
}
let Some(data) = previous.comment() else { return false };
!data.post_space.resolve(previous.span().source()).starts_with('\n')
}
fn children(&mut self, node: &NodeRef<'_, Flm>) {
let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
self.run(&children);
}
fn slot(&mut self, slot: Option<techy::core::node::NodeSlice<'_, Flm>>) {
if let Some(slot) = slot {
let nodes: Vec<NodeRef<'_, Flm>> = slot.iter().collect();
self.run(&nodes);
}
}
fn text(&mut self, text: &str) {
self.sink.text(text);
}
fn comment(&mut self, node: &NodeRef<'_, Flm>) {
if self.options.drop_comments {
return;
}
let Some(data) = node.comment() else { return };
let source = node.span().source();
self.sink.comment(self.comment_prefix, data.content.resolve(source));
let after = data.post_space.resolve(source);
self.sink.text(after.strip_prefix('\n').unwrap_or(after));
}
fn arguments(&mut self, node: &NodeRef<'_, Flm>, args: &[LatexArgShape], packed: bool) {
let outer = std::mem::replace(&mut self.in_token_group, true);
if packed {
self.packed_arguments(node, args);
} else {
self.argument_slots(node, args);
}
self.in_token_group = outer;
}
fn argument_slots(&mut self, node: &NodeRef<'_, Flm>, args: &[LatexArgShape]) {
for (shape, slot) in arg_slots(node, args) {
match shape {
LatexArgShape::Star => self.sink.star(),
LatexArgShape::Optional => {
let nodes: Vec<NodeRef<'_, Flm>> =
slot.map(|slot| slot.iter().collect()).unwrap_or_default();
self.optional(&nodes);
}
LatexArgShape::Mandatory => {
self.sink.open_brace();
self.slot(slot);
self.sink.close_brace();
}
LatexArgShape::EscVerb => {
let nodes: Vec<NodeRef<'_, Flm>> =
slot.map(|slot| slot.iter().collect()).unwrap_or_default();
let pieces = verbatim_pieces(&nodes);
self.sink.open_brace();
self.escverb_pieces(node, pieces);
self.sink.close_brace();
}
}
}
}
fn packed_arguments(&mut self, node: &NodeRef<'_, Flm>, args: &[LatexArgShape]) {
if args.iter().any(|shape| *shape != LatexArgShape::Mandatory) {
return self.unexpected(node, "a packed call with an argument that is not a group,");
}
self.sink.open_brace();
for (_, slot) in arg_slots(node, args) {
self.sink.open_brace();
self.slot(slot);
self.sink.close_brace();
}
self.sink.close_brace();
}
fn optional(&mut self, nodes: &[NodeRef<'_, Flm>]) {
let plain = nodes.iter().all(|node| {
if let Some(text) = node.chars() {
!text.contains(']')
} else if let Some(raw) = payload_of::<LatexRawPayload>(node) {
!raw.text.contains(']')
} else {
node.group_type() == Some(FlmGroupType::Content)
}
});
self.sink.open_bracket();
if !plain {
self.sink.open_brace();
}
self.run(nodes);
if !plain {
self.sink.close_brace();
}
self.sink.close_bracket();
}
fn control_word(&mut self, name: &str, has_arguments: bool, next: Option<&NodeRef<'_, Flm>>) {
self.sink.control_word(name);
if !has_arguments
&& name.ends_with(|c: char| c.is_ascii_alphabetic())
&& next.is_some_and(begins_with_letter)
{
self.sink.text(" ");
}
}
fn macro_call(&mut self, node: &NodeRef<'_, Flm>, next: Option<&NodeRef<'_, Flm>>) {
let Some(payload) = payload_of::<LatexMacroPayload>(node) else {
return self.unexpected(node, "a macro node without its payload,");
};
self.control_word(&payload.name, !payload.args.is_empty(), next);
self.arguments(node, &payload.args, payload.packed);
}
fn environment(&mut self, node: &NodeRef<'_, Flm>) {
let Some(payload) = payload_of::<LatexEnvironmentPayload>(node) else {
return self.unexpected(node, "an environment node without its payload,");
};
if payload.verbatim && self.in_token_group {
return self.escaped_verbatim_environment(node, payload);
}
self.sink.begin(&payload.name);
self.arguments(node, &payload.args, payload.packed);
let body: Vec<NodeRef<'_, Flm>> =
node.body().map(|body| body.iter().collect()).unwrap_or_default();
let outer = self.in_token_group;
self.in_token_group |= payload.body_argument;
if payload.verbatim {
self.verbatim_body(&body);
} else {
self.run(&body);
}
self.in_token_group = outer;
self.sink.end(&payload.name);
}
fn verbatim_block_call(
&mut self,
node: &NodeRef<'_, Flm>,
env: &str,
options: impl FnOnce(&mut Self),
pieces: Vec<VerbatimPiece>,
) {
self.sink.control_word(preamble::VERBATIM_BLOCK_COMMAND);
options(self);
self.sink.open_brace();
self.raw_text(node, env);
self.sink.close_brace();
self.sink.open_brace();
for line in verbatim_block_groups(pieces) {
self.sink.open_brace();
for segment in line {
self.sink.open_brace();
self.escverb_pieces(node, segment);
self.sink.close_brace();
}
self.sink.close_brace();
}
self.sink.close_brace();
}
fn escverb_pieces(&mut self, node: &NodeRef<'_, Flm>, pieces: Vec<VerbatimPiece>) {
for piece in pieces {
match piece {
VerbatimPiece::Text(text) => self.sink.escverb(&text),
VerbatimPiece::Latex(text) => self.raw_text(node, &text),
}
}
}
fn escaped_verbatim_environment(
&mut self,
node: &NodeRef<'_, Flm>,
payload: &LatexEnvironmentPayload,
) {
let body: Vec<NodeRef<'_, Flm>> =
node.body().map(|body| body.iter().collect()).unwrap_or_default();
let pieces = verbatim_pieces(&body);
let args = payload.args.clone();
let name = payload.name.clone();
self.verbatim_block_call(node, &name, |me| me.arguments(node, &args, false), pieces);
}
fn verbatim_body(&mut self, body: &[NodeRef<'_, Flm>]) {
let text = verbatim_text(body);
self.sink.newline();
self.sink.verbatim_block(&text);
if !text.ends_with('\n') {
self.sink.newline();
}
}
fn definition(&mut self, node: &NodeRef<'_, Flm>) {
let Some(payload) = payload_of::<LatexDefinitionPayload>(node) else {
return self.unexpected(node, "a definition node without its payload,");
};
let display_name = match payload.kind {
LatexDefinitionKind::Macro => format!("\\{}", payload.name),
LatexDefinitionKind::Environment | LatexDefinitionKind::Declaration => {
payload.name.clone()
}
};
let source_display_name = match payload.kind {
LatexDefinitionKind::Macro => format!("\\{}", payload.source_name),
LatexDefinitionKind::Environment | LatexDefinitionKind::Declaration => {
payload.source_name.clone()
}
};
if self.definitions.iter().any(|definition| definition.name == display_name) {
return;
}
let mut sub = Emitter {
sink: LatexSink::new(self.sink.config().clone()),
options: self.options,
comment_prefix: self.comment_prefix,
depth: self.depth,
in_token_group: true,
refused: false,
requires: BTreeSet::new(),
definitions: Vec::new(),
placed: Vec::new(),
extra_declared: Declared::new(),
extra_unknown: Vec::new(),
diags: FlmDiagnostics::new(),
};
match payload.kind {
LatexDefinitionKind::Macro => {
sub.raw_text(node, ¯o_definition_head(payload));
sub.sink.open_brace();
sub.slot(slot_named(node, BODY_SLOT));
sub.sink.close_brace();
sub.sink.newline();
}
LatexDefinitionKind::Environment => {
let definer = if payload.is_bare() {
"DeclareDocumentEnvironment"
} else {
"ProvideDocumentEnvironment"
};
sub.raw_text(node, &format!("\\{definer}{{{}}}", payload.name));
sub.raw_text(node, &environment_argument_specification(payload));
sub.sink.open_brace();
sub.slot(slot_named(node, BEGIN_SLOT));
sub.sink.close_brace();
sub.sink.open_brace();
sub.slot(slot_named(node, END_SLOT));
sub.sink.close_brace();
sub.sink.newline();
}
LatexDefinitionKind::Declaration => {
sub.raw_text(node, &format!("\\ifcsname {}\\endcsname\\else", payload.name));
sub.slot(slot_named(node, BODY_SLOT));
sub.raw_text(node, "\\fi");
sub.sink.newline();
}
}
let Emitter { sink, refused, requires, definitions, extra_declared, extra_unknown, diags, .. } =
sub;
self.refused |= refused;
self.requires.extend(requires);
for definition in definitions {
if !self.definitions.iter().any(|seen| seen.name == definition.name) {
self.definitions.push(definition);
}
}
for diagnostic in diags.iter() {
self.diags.push(diagnostic.clone());
}
let output = sink.finish();
self.extra_declared.merge(&output.declared);
self.extra_declared.merge(&extra_declared);
for ch in output.unknown.into_iter().chain(extra_unknown) {
if !self.extra_unknown.contains(&ch) {
self.extra_unknown.push(ch);
}
}
let mut recorded =
RecomposedDefinition::new(display_name, source_display_name, output.text);
if payload.robust {
recorded = recorded.robust();
}
if payload.kind == LatexDefinitionKind::Declaration {
recorded = recorded.declaration();
}
if let Some(feature) = &payload.feature {
recorded = recorded.of_feature(feature.as_str());
}
self.definitions.push(recorded);
}
fn raw_text(&mut self, node: &NodeRef<'_, Flm>, text: &str) {
self.write_raw(node, &LatexRaw::from_raw_payload(&LatexRawPayload::new(text)));
}
fn write_raw(&mut self, node: &NodeRef<'_, Flm>, raw: &LatexRaw) {
let Err(refused) = self.sink.raw(raw) else { return };
self.diags.push(Diagnostic::error(
StageFailed {
stage: String::from(super::stages::EMIT_STAGE),
detail: refused.to_string(),
},
node.span().clone(),
));
}
fn math(&mut self, node: &NodeRef<'_, Flm>) {
let body: Vec<NodeRef<'_, Flm>> =
node.body().map(|body| body.iter().collect()).unwrap_or_default();
let payload = payload_of::<MathPassthroughPayload>(node);
let display = payload.map_or(MathDisplay::Inline, |payload| payload.display);
let env = payload.and_then(|payload| payload.env.clone());
match (display, env) {
(_, Some(env)) => {
self.sink.begin(&env);
self.write_raw(node, &LatexRaw::from_source(&body));
self.sink.end(&env);
}
(MathDisplay::Inline, None) => {
self.sink.control_word("(");
self.write_raw(node, &LatexRaw::from_source(&body));
self.sink.control_word(")");
}
(MathDisplay::Display, None) => {
self.sink.control_word("[");
self.write_raw(node, &LatexRaw::from_source(&body));
self.sink.control_word("]");
}
}
}
fn verbatim(&mut self, node: &NodeRef<'_, Flm>) {
let body: Vec<NodeRef<'_, Flm>> =
node.body().map(|body| body.iter().collect()).unwrap_or_default();
let (kind, display, lang) = payload_of::<VerbatimPayload>(node)
.map_or((VerbatimKind::Text, VerbatimDisplay::Inline, None), |payload| {
(payload.kind, payload.display, payload.lang.clone())
});
self.requires.insert(Name::from(packages::FVEXTRA));
self.requires.insert(Name::from(preamble::VERBATIM));
match display {
VerbatimDisplay::Inline => {
self.sink.control_word(preamble::ESCVERB);
self.sink.open_bracket();
self.write_raw(
node,
&LatexRaw::from_raw_payload(&LatexRawPayload::new(preamble::escverb_options(
kind,
))),
);
self.sink.close_bracket();
self.sink.open_brace();
let pieces = verbatim_pieces(&body);
self.escverb_pieces(node, pieces);
self.sink.close_brace();
}
VerbatimDisplay::Block => {
let env = match kind {
VerbatimKind::Text => preamble::VERBATIM_TEXT_ENVIRONMENT,
VerbatimKind::Code | VerbatimKind::Identifier => {
preamble::VERBATIM_CODE_ENVIRONMENT
}
};
let lang = lang.filter(|_| env == preamble::VERBATIM_CODE_ENVIRONMENT);
if self.in_token_group {
let pieces = verbatim_pieces(&body);
return self.verbatim_block_call(
node,
env,
|me| {
me.sink.open_bracket();
if let Some(lang) = lang {
me.sink.text(&lang);
}
me.sink.close_bracket();
},
pieces,
);
}
self.sink.begin(env);
if let Some(lang) = lang {
self.sink.open_bracket();
self.sink.text(&lang);
self.sink.close_bracket();
}
self.verbatim_body(&body);
self.sink.end(env);
}
}
}
fn unknown(&mut self, node: &NodeRef<'_, Flm>, next: Option<&NodeRef<'_, Flm>>) {
let Some(payload) = payload_of::<UnknownPayload>(node) else {
return self.unexpected(node, "an unattributed-callable node without its payload,");
};
match payload.kind {
UnknownKind::Macro => self.control_word(&payload.name, false, next),
UnknownKind::Environment => {
self.sink.begin(&payload.name);
let body: Vec<NodeRef<'_, Flm>> =
node.body().map(|body| body.iter().collect()).unwrap_or_default();
self.run(&body);
self.sink.end(&payload.name);
}
}
}
fn unsupported(&mut self, node: &NodeRef<'_, Flm>, siblings: &[NodeRef<'_, Flm>], index: usize) {
let element = payload_of::<UnsupportedPayload>(node)
.map_or_else(|| String::from("?"), |payload| payload.element.to_string());
self.comment_line(siblings, index, &format!(" flm: unsupported element {element}"));
}
fn dropped(&mut self, node: &NodeRef<'_, Flm>, siblings: &[NodeRef<'_, Flm>], index: usize) {
let detail = payload_of::<DroppedPayload>(node)
.map_or_else(|| String::from("?"), |payload| payload.detail.clone());
self.comment_line(siblings, index, &format!(" flm: dropped {detail}"));
}
fn subtree(&mut self, node: &NodeRef<'_, Flm>) {
if let Some(payload) = payload_of::<SubtreePayload>(node) {
self.placed.push((self.sink.position(), payload.tree));
}
}
fn comment_line(&mut self, siblings: &[NodeRef<'_, Flm>], index: usize, text: &str) {
let previous = index.checked_sub(1).and_then(|i| siblings.get(i));
if previous.is_some_and(|node| !ends_with_newline(node) && !is_comment_line(node)) {
self.sink.newline();
}
self.sink.comment("%", text);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_escape_config_carries_the_mode_and_the_override_spellings() {
use crate::stdlib::backends::latex::UnicodeMode;
let options = LatexRecomposedRenderOptions {
unicode: UnicodeMode::Replace,
unicode_overrides: [('𝟙', String::from("\\ensuremath{\\mathds{1}}"))]
.into_iter()
.collect(),
..LatexRecomposedRenderOptions::default()
};
let config = escape_config(&options);
assert_eq!(config.mode, UnicodeMode::Replace);
assert_eq!(config.overrides.get(&'𝟙').map(String::as_str), Some("\\ensuremath{\\mathds{1}}"));
}
#[test]
fn a_block_is_split_into_one_group_per_line_and_one_per_tab_separated_segment() {
fn groups(text: &str) -> Vec<Vec<String>> {
verbatim_block_groups(vec![VerbatimPiece::Text(String::from(text))])
.into_iter()
.map(|line| {
line.into_iter()
.map(|segment| {
segment
.into_iter()
.map(|piece| match piece {
VerbatimPiece::Text(t) | VerbatimPiece::Latex(t) => t,
})
.collect()
})
.collect()
})
.collect()
}
assert_eq!(groups(""), vec![vec![String::new()]]);
assert_eq!(groups("one"), vec![vec![String::from("one")]]);
assert_eq!(
groups("one\ntwo"),
vec![vec![String::from("one")], vec![String::from("two")]]
);
assert_eq!(
groups("a\tb\t\tc"),
vec![vec![
String::from("a"),
String::from("b"),
String::new(),
String::from("c"),
]]
);
assert_eq!(
groups("\ta\t"),
vec![vec![String::new(), String::from("a"), String::new()]]
);
assert_eq!(
groups("a\n\nb"),
vec![
vec![String::from("a")],
vec![String::new()],
vec![String::from("b")],
]
);
assert_eq!(groups("a\n"), vec![vec![String::from("a")]]);
assert_eq!(
groups("a\n\n"),
vec![vec![String::from("a")], vec![String::new()]]
);
assert_eq!(groups("\n"), vec![vec![String::new()]]);
let mixed = verbatim_block_groups(vec![
VerbatimPiece::Text(String::from("v = ")),
VerbatimPiece::Latex(String::from("#2")),
VerbatimPiece::Text(String::from(";\nend")),
]);
assert_eq!(mixed.len(), 2);
assert_eq!(mixed[0].len(), 1);
assert_eq!(mixed[0][0].len(), 3);
assert_eq!(mixed[1].len(), 1);
}
#[test]
fn an_environment_declares_one_specifier_per_argument_and_a_body_argument_last() {
let plain = LatexDefinitionPayload::new(LatexDefinitionKind::Environment, "flmUEnote", 2);
assert_eq!(environment_argument_specification(&plain), "{+m +m}");
assert_eq!(
environment_argument_specification(&LatexDefinitionPayload::new(
LatexDefinitionKind::Environment,
"flmUEbare",
0
)),
"{}"
);
assert_eq!(environment_argument_specification(&plain.clone().body_argument()), "{+m +m +b}");
let packed = LatexDefinitionPayload::new(LatexDefinitionKind::Environment, "flmUEbig", 12)
.packed();
assert_eq!(environment_argument_specification(&packed), "{+m}");
assert_eq!(environment_argument_specification(&packed.clone().body_argument()), "{+m +b}");
}
}