use std::collections::BTreeSet;
use std::fmt;
use std::ops::Range;
use std::sync::Arc;
use techy::core::node::{NodeKind, NodeRef, NodeTree};
use techy::error::{Diagnostic, DiagnosticInfo};
use crate::lang::guard;
use crate::layout::is_breakable_space;
use crate::lang::structural;
use crate::lang::{Flm, FlmDiagnostics, FlmGroupType, FlmOrigin, FlmSpan, nowhere};
use crate::model::addr::TreeId;
use crate::model::element::element_of;
use crate::model::names::Name;
use crate::stdlib::backends::pres::{
self, BlockPayload, CellHeader, CellSpec, DroppedPayload, GridPosition, HeadingPayload,
ImageDisplay, ImagePayload, Length, LinePayload, LinkPayload, ListPayload, MathDisplay,
MathPassthroughPayload, MathTextPayload, ParPayload, SpanPayload, SpanStyle, SubtreePayload,
UnknownKind, UnknownPayload, UnsupportedPayload, VerbatimDisplay, VerbatimKind,
VerbatimPayload, cells_of,
decoration_at, ends_in_sentence_punctuation, heading_depth, holds_text, is_presentation,
list_entries, payload_of, recompose_source,
};
use super::address::{AddressUse, HtmlAllowedUrlSchemes, check_address};
use super::construct::{HtmlTagPayload, TagBody};
use super::conventions::{
Convention, LIST_LABEL_CLASS, PARAGRAPH_FLOW_TAG, PARAGRAPH_ROLE, SCRIPT_MATHJAX,
STYLE_ATTRIBUTE, UNKNOWN_MARKER_CLASS, Written, block_tag, css_length, css_ratio,
doc_role_value, row,
};
use super::escape::json_string_into;
use super::feature::HtmlRenderOptions;
use super::names::{class_of_element, class_of_role, data_attribute, is_valid_attribute_name,
is_valid_tag_name, is_valid_token, style_property};
use super::sink::HtmlSink;
use super::stages::{HtmlSegment, StageFailed};
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.html.invalid-name",
message = "the {what} name `{name}` cannot be written into the HTML page: a tag name must be \
an ASCII letter followed by ASCII letters, digits and `-`, an attribute name may \
also contain `_`, `:` and `.`, and a role or a kind must be one word, not empty \
and without whitespace"
)]
pub struct InvalidName {
pub what: String,
pub name: String,
pub recovery: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.html.refused-address",
message = "the address `{address}` in the `{attribute}` attribute uses the scheme `{scheme}`, which is \
not allowed; the allowed addresses are {allowed}"
)]
pub struct AddressRefused {
pub address: String,
pub scheme: String,
pub attribute: String,
pub allowed: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.html.refused-in-math",
message = "an attribute value inside a formula must not contain `{sequence}`, which the \
formula renderer would read as the end of the formula or as its own tag: the \
value of the `{attribute}` attribute contains it"
)]
pub struct RefusedInMath {
pub attribute: String,
pub sequence: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.html.worker-thread-unavailable",
message = "writing HTML 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;
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.html.nesting-too-deep",
message = "the content nests too deeply to be written as HTML: {detail}"
)]
pub struct NestingTooDeep {
pub detail: String,
}
pub(crate) const NOWHERE_LABEL: &str = "html backend";
#[derive(Debug, Default)]
pub struct EmittedTree {
pub segments: Vec<HtmlSegment>,
pub requires: BTreeSet<Name>,
pub placed_at: Vec<FlmSpan>,
pub diags: FlmDiagnostics,
}
pub fn emit_tree(
tree: &Arc<NodeTree<Flm>>,
options: &HtmlRenderOptions,
url_schemes: &HtmlAllowedUrlSchemes,
) -> EmittedTree {
match guard::on_worker_thread(|| emit_on_worker_thread(tree, options, url_schemes)) {
Ok(emitted) => emitted,
Err(error) => {
let mut diags = FlmDiagnostics::new();
diags.push(Diagnostic::error(
NoWorkerThread { detail: error.to_string() },
nowhere(FlmOrigin::synthetic(NOWHERE_LABEL)),
));
EmittedTree { diags, ..EmittedTree::default() }
}
}
}
fn emit_on_worker_thread(
tree: &Arc<NodeTree<Flm>>,
options: &HtmlRenderOptions,
url_schemes: &HtmlAllowedUrlSchemes,
) -> EmittedTree {
let mut emitter = Emitter {
sink: HtmlSink::new(),
options,
url_schemes,
placements: Vec::new(),
requires: BTreeSet::new(),
depth: 0,
depth_limit: guard::levels_within_budget(LEVEL_STACK_ESTIMATE),
refused: false,
math: None,
in_tex_html: false,
tex_html_constructs: 0,
construct_sequences: Arc::from(sequences_in_construct()),
piece: None,
links_open: 0,
diags: FlmDiagnostics::new(),
};
let root = tree.root();
let children: Vec<NodeRef<'_, Flm>> = root.children().iter().collect();
if root.is_list() {
emitter.run(None, &children);
} else {
emitter.run(None, &[root]);
}
let Emitter { sink, placements, requires, depth_limit, refused, mut diags, .. } = emitter;
let html = sink.finish();
if refused {
diags.push(Diagnostic::error(
NestingTooDeep {
detail: format!("more than {depth_limit} levels"),
},
root.span().clone(),
));
return EmittedTree { diags, ..EmittedTree::default() };
}
let placed_at = placements.iter().map(|(_, _, span)| span.clone()).collect();
EmittedTree { segments: segments_of(html, &placements), requires, placed_at, diags }
}
fn segments_of(html: String, placements: &[(usize, TreeId, FlmSpan)]) -> Vec<HtmlSegment> {
let mut segments = Vec::new();
let mut at = 0usize;
for (offset, tree, _) in placements {
if *offset > at {
segments.push(HtmlSegment::Html(String::from(&html[at..*offset])));
}
segments.push(HtmlSegment::Tree(*tree));
at = *offset;
}
if at < html.len() {
segments.push(HtmlSegment::Html(String::from(&html[at..])));
}
segments
}
const TEX_HTML: &str = "tex-html";
const EMPTY_GROUP: &str = "{}";
#[derive(Debug, Clone, PartialEq, Eq)]
struct Sequence {
text: String,
break_at: usize,
}
impl Sequence {
fn new(before: &str, after: &str) -> Sequence {
Sequence { text: format!("{before}{after}"), break_at: before.len() }
}
}
fn tex_html_sequences() -> Vec<Sequence> {
vec![Sequence::new("<", TEX_HTML), Sequence::new("<", &format!("/{TEX_HTML}"))]
}
fn opening_delimiter(display: MathDisplay, env: Option<&str>) -> String {
match (display, env) {
(_, Some(env)) => format!("\\begin{{{env}}}"),
(MathDisplay::Inline, None) => String::from("\\("),
(MathDisplay::Display, None) => String::from("\\["),
}
}
fn closing_delimiter(display: MathDisplay, env: Option<&str>) -> Sequence {
match (display, env) {
(_, Some(env)) => Sequence::new("\\end", &format!("{{{env}}}")),
(MathDisplay::Inline, None) => Sequence::new("\\", ")"),
(MathDisplay::Display, None) => Sequence::new("\\", "]"),
}
}
fn sequences_in_math(closing: &Sequence) -> Vec<Sequence> {
let mut sequences = vec![closing.clone()];
sequences.extend(tex_html_sequences());
sequences
}
fn sequences_in_construct() -> Vec<Sequence> {
let mut sequences = vec![Sequence::new("\\", ")"), Sequence::new("\\", "]"), Sequence::new("\\end", "{")];
sequences.extend(tex_html_sequences());
sequences
}
fn neutralized_source(source: &str) -> String {
let sequences = tex_html_sequences();
let mut out = String::with_capacity(source.len());
let mut at = 0;
while at < source.len() {
let rest = &source[at..];
match sequences.iter().find(|sequence| rest.starts_with(&sequence.text)) {
Some(sequence) => {
out.push_str(&sequence.text[..sequence.break_at]);
out.push_str(EMPTY_GROUP);
at += sequence.break_at;
}
None => {
let ch = rest.chars().next().expect("a character starts at a character boundary");
out.push(ch);
at += ch.len_utf8();
}
}
}
out
}
fn break_points(text: &str, sequences: &[Sequence]) -> Vec<usize> {
let mut points = Vec::new();
let mut at = 0;
while at < text.len() {
let rest = &text[at..];
match sequences.iter().find(|sequence| rest.starts_with(&sequence.text)) {
Some(sequence) => {
at += sequence.break_at;
points.push(at);
}
None => {
at += rest
.chars()
.next()
.map_or(1, |ch| ch.len_utf8());
}
}
}
points
}
fn refused_sequence(value: &str, sequences: &[Sequence]) -> Option<String> {
sequences
.iter()
.filter_map(|sequence| value.find(&sequence.text).map(|at| (at, sequence.text.clone())))
.min_by(|(left, _), (right, _)| left.cmp(right))
.map(|(_, text)| text)
}
#[derive(Debug, Clone)]
struct OpenInMath {
tag: String,
block: bool,
classes: Vec<String>,
attributes: Vec<(String, String)>,
preformatted: bool,
}
#[derive(Debug, Clone)]
struct Piece {
classes: Vec<String>,
open: Vec<OpenInMath>,
}
#[derive(Debug, Clone)]
struct MathContext {
sequences: Arc<[Sequence]>,
span: FlmSpan,
}
struct Emitter<'o> {
sink: HtmlSink,
options: &'o HtmlRenderOptions,
url_schemes: &'o HtmlAllowedUrlSchemes,
placements: Vec<(usize, TreeId, FlmSpan)>,
requires: BTreeSet<Name>,
depth: usize,
depth_limit: usize,
refused: bool,
math: Option<MathContext>,
in_tex_html: bool,
tex_html_constructs: usize,
construct_sequences: Arc<[Sequence]>,
piece: Option<Piece>,
links_open: usize,
diags: FlmDiagnostics,
}
impl fmt::Debug for Emitter<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Emitter")
.field("depth", &self.depth)
.field("placements", &self.placements.len())
.finish_non_exhaustive()
}
}
fn body<'t>(node: &NodeRef<'t, Flm>) -> Vec<NodeRef<'t, Flm>> {
node.body().map(|slice| slice.iter().collect()).unwrap_or_default()
}
fn is_element(node: &NodeRef<'_, Flm>, name: &str) -> bool {
element_of(node).name == name
}
fn shows_nothing(content: &[NodeRef<'_, Flm>]) -> bool {
let mut pending: Vec<NodeRef<'_, Flm>> = content.to_vec();
while let Some(node) = pending.pop() {
if let Some(text) = node.chars() {
if !text.chars().all(is_breakable_space) {
return false;
}
} else if node.is_comment() || is_element(&node, structural::PARBREAK) {
continue;
} else if is_presentation(&node) {
return false;
} else {
pending.extend(node.children().iter());
}
}
true
}
fn holds_flow_content(paragraph: &NodeRef<'_, Flm>) -> bool {
let mut pending: Vec<NodeRef<'_, Flm>> = paragraph.children().iter().collect();
while let Some(node) = pending.pop() {
if node.chars().is_some() || node.is_comment() {
continue;
}
if written_as_flow(&node) {
return true;
}
pending.extend(node.children().iter());
}
false
}
fn heading_values(payload: Option<&HeadingPayload>) -> Vec<(&'static str, String)> {
let mut values: Vec<(&'static str, String)> = Vec::new();
if let Some(anchor) = payload.and_then(|payload| payload.anchor.clone()) {
values.push(("anchor", anchor));
}
if let Some(payload) = payload {
values.push(("name", payload.name.to_string()));
}
values.push(("level", payload.map_or(1, |payload| payload.level).to_string()));
if let Some(payload) = payload {
values.push(("in_toc", payload.in_toc.to_string()));
}
values
}
fn heading_tag(depth: u8) -> &'static str {
match depth {
0 => "h1",
1 => "h2",
2 => "h3",
3 => "h4",
4 => "h5",
_ => "h6",
}
}
fn span_tag(style: Option<SpanStyle>) -> &'static str {
match style {
Some(SpanStyle::Emphasis) => "em",
Some(SpanStyle::Bold) => "strong",
Some(SpanStyle::Italic) => "i",
Some(SpanStyle::Monospace) => "code",
Some(SpanStyle::Underline) => "u",
Some(SpanStyle::Superscript) => "sup",
Some(SpanStyle::Subscript) => "sub",
Some(SpanStyle::SmallCaps) | Some(SpanStyle::UnresolvedReference) | None => "span",
}
}
fn list_tag(kinds: &[Name]) -> &'static str {
for kind in kinds {
match kind.as_str() {
pres::LIST_NUMBERED => return "ol",
pres::LIST_UNNUMBERED => return "ul",
pres::LIST_TERMS => return "dl",
_ => {}
}
}
"ul"
}
fn written_as_flow(node: &NodeRef<'_, Flm>) -> bool {
match element_of(node).name.as_str() {
pres::PAR
| pres::BLOCK
| pres::BLOCK_HEADING
| pres::LIST
| pres::CELLS
| pres::LINES
| pres::LINE
| pres::SUBTREE => true,
pres::VERBATIM => payload_of::<VerbatimPayload>(node)
.is_some_and(|payload| payload.display == VerbatimDisplay::Block),
pres::UNKNOWN => payload_of::<UnknownPayload>(node)
.is_some_and(|payload| payload.kind == UnknownKind::Environment),
super::construct::TAG => payload_of::<HtmlTagPayload>(node).is_some_and(|payload| {
CLOSES_A_PARAGRAPH.iter().any(|tag| tag.eq_ignore_ascii_case(&payload.tag))
}),
_ => false,
}
}
const CLOSES_A_PARAGRAPH: [&str; 41] = [
"address", "article", "aside", "blockquote", "center", "dd", "details", "dialog", "dir",
"div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3",
"h4", "h5", "h6", "header", "hgroup", "hr", "li", "listing", "main", "menu", "nav", "ol", "p",
"plaintext", "pre", "search", "section", "summary", "table", "ul", "xmp",
];
fn ordered_attributes(
convention: &Convention,
values: &[(&'static str, String)],
lengths: &[(&'static str, &Length)],
) -> Vec<(String, String)> {
let mut own: Vec<(String, String)> = Vec::new();
let mut properties: Vec<String> = Vec::new();
let mut data: Vec<(String, String)> = Vec::new();
for field in convention.fields {
let length_of =
|wanted: &str| lengths.iter().find(|(name, _)| *name == wanted).map(|(_, length)| *length);
match field.written {
Written::Style => {
if let Some(length) = length_of(field.field).filter(|length| !length.is_zero()) {
properties
.push(format!("{}: {}", style_property(field.field), css_length(length)));
}
continue;
}
Written::Ratio(first, second) => {
if let Some(ratio) = length_of(first)
.zip(length_of(second))
.and_then(|(first, second)| css_ratio(first, second))
{
properties.push(format!("{}: {ratio}", style_property(field.field)));
}
continue;
}
_ => {}
}
let Some(value) = values.iter().find(|(name, _)| *name == field.field) else { continue };
match field.written {
Written::Own(attribute) => own.push((String::from(attribute), value.1.clone())),
Written::Data(stem) => data.push((data_attribute(stem), value.1.clone())),
Written::Style
| Written::Ratio(..)
| Written::RoleClass
| Written::BlockClass
| Written::Entry(_)
| Written::EntryData(_)
| Written::Dropped(_) => {}
}
}
if !properties.is_empty() {
own.push((String::from(STYLE_ATTRIBUTE), properties.join("; ")));
}
own.extend(data);
own
}
fn entry_attribute(convention: &Convention, field: &str) -> Option<String> {
convention.field(field).and_then(|field| field.entry_attribute())
}
fn source_position(span: &FlmSpan) -> Option<(String, Range<usize>)> {
let mut span = span.clone();
loop {
if let Some(path) = span.source().origin().canonical_path() {
return Some((String::from(path), span.range()));
}
let triggered = span.source().provenance().triggered_at()?.clone();
span = triggered;
}
}
const SOURCE_SPAN_ATTRIBUTE: &str = "data-flm-source-span";
fn source_span_value(source: &str, range: &Range<usize>) -> String {
let mut value = String::from("[");
json_string_into(&mut value, source);
value.push(',');
value.push_str(&range.start.to_string());
value.push(',');
value.push_str(&range.end.to_string());
value.push(']');
value
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct CellRendering {
tag: &'static str,
scope: Option<&'static str>,
colspan: Option<u32>,
rowspan: Option<u32>,
attributes: Vec<(String, String)>,
}
impl CellRendering {
fn empty() -> CellRendering {
CellRendering { tag: "td", scope: None, colspan: None, rowspan: None, attributes: Vec::new() }
}
}
impl<'o> Emitter<'o> {
fn descend(&mut self) -> bool {
if self.depth >= self.depth_limit {
self.refused = true;
return false;
}
self.depth += 1;
true
}
fn ascend(&mut self) {
self.depth -= 1;
}
fn require(&mut self, identifier: &str) {
self.requires.insert(Name::from(identifier));
}
fn unexpected(&mut self, node: &NodeRef<'_, Flm>) {
self.diags.push(Diagnostic::error(
StageFailed {
stage: String::from(super::stages::EMIT_STAGE),
detail: format!(
"the element `{}` reached the HTML emitter, which cannot write it",
element_of(node).name
),
},
node.span().clone(),
));
}
fn open(
&mut self,
node: Option<&NodeRef<'_, Flm>>,
tag: &str,
block: bool,
classes: &[String],
attributes: Vec<(String, String)>,
preformatted: bool,
) {
let attributes = self.with_source_span(node, attributes);
let attributes = self.writable_in_math(node, attributes);
let with_class = !classes.is_empty() && self.class_writable_in_math(node, classes);
let classes: Vec<String> = if with_class { classes.to_vec() } else { Vec::new() };
self.write_open(OpenInMath {
tag: String::from(tag),
block,
classes,
attributes,
preformatted,
});
}
fn write_open(&mut self, element: OpenInMath) {
let mut builder = if element.block {
self.sink.open_block(&element.tag)
} else {
self.sink.open_inline(&element.tag)
};
if !element.classes.is_empty() {
builder = builder.class(&element.classes);
}
for (name, value) in &element.attributes {
builder = if name == SOURCE_SPAN_ATTRIBUTE {
builder.attr_json(name, value)
} else {
builder.attr(name, value)
};
}
if element.preformatted {
builder = builder.preformatted();
}
builder.finish();
if self.in_tex_html {
if let Some(piece) = self.piece.as_mut() {
let mut element = element;
element
.attributes
.retain(|(name, _)| name != "id" && name != SOURCE_SPAN_ATTRIBUTE);
piece.open.push(element);
}
}
}
fn close(&mut self) {
if self.in_tex_html {
if let Some(piece) = self.piece.as_mut() {
let popped = piece.open.pop();
debug_assert_eq!(
popped.as_ref().map(|element| element.tag.as_str()),
self.sink.open_tag(),
"an element inside a formula was opened or closed \
without going through the emitter's own pair"
);
}
}
self.sink.close();
}
fn with_source_span(
&self,
node: Option<&NodeRef<'_, Flm>>,
attributes: Vec<(String, String)>,
) -> Vec<(String, String)> {
let mut attributes = attributes;
if self.options.source_spans {
if let Some((source, range)) = node.and_then(|node| source_position(node.span())) {
attributes.push((
String::from(SOURCE_SPAN_ATTRIBUTE),
source_span_value(&source, &range),
));
}
}
attributes
}
fn void(
&mut self,
node: Option<&NodeRef<'_, Flm>>,
tag: &str,
classes: &[String],
attributes: Vec<(String, String)>,
) {
let attributes = self.with_source_span(node, attributes);
let attributes = self.writable_in_math(node, attributes);
let with_class = !classes.is_empty() && self.class_writable_in_math(node, classes);
let mut builder = self.sink.void_inline(tag);
if with_class {
builder = builder.class(classes);
}
for (name, value) in &attributes {
builder = if name == SOURCE_SPAN_ATTRIBUTE {
builder.attr_json(name, value)
} else {
builder.attr(name, value)
};
}
builder.finish();
}
fn writable_in_math(
&mut self,
node: Option<&NodeRef<'_, Flm>>,
attributes: Vec<(String, String)>,
) -> Vec<(String, String)> {
if !self.in_tex_html {
return attributes;
}
let Some(sequences) = self.math.as_ref().map(|math| Arc::clone(&math.sequences)) else {
return attributes;
};
let mut written = Vec::with_capacity(attributes.len());
for (name, value) in attributes {
match refused_sequence(&value, &sequences) {
Some(sequence) => self.refused_in_math(node, &name, &sequence),
None => written.push((name, value)),
}
}
written
}
fn class_writable_in_math(
&mut self,
node: Option<&NodeRef<'_, Flm>>,
classes: &[String],
) -> bool {
if !self.in_tex_html {
return true;
}
let attribute = vec![(String::from("class"), classes.join(" "))];
!self.writable_in_math(node, attribute).is_empty()
}
fn refused_in_math(
&mut self,
node: Option<&NodeRef<'_, Flm>>,
attribute: &str,
sequence: &str,
) {
let span = match node {
Some(node) => node.span().clone(),
None => match self.math.as_ref() {
Some(math) => math.span.clone(),
None => nowhere(FlmOrigin::synthetic(NOWHERE_LABEL)),
},
};
self.diags.push(Diagnostic::error(
RefusedInMath {
attribute: String::from(attribute),
sequence: String::from(sequence),
},
span,
));
}
fn write_text(&mut self, text: &str) {
let in_math = match (self.in_tex_html, self.math.as_ref()) {
(true, Some(math)) => Some(Arc::clone(&math.sequences)),
_ => None,
};
let in_construct = (self.tex_html_constructs > 0).then(|| Arc::clone(&self.construct_sequences));
let sequences: Arc<[Sequence]> = match (in_math, in_construct) {
(None, None) => {
self.sink.text(text);
return;
}
(Some(sequences), None) | (None, Some(sequences)) => sequences,
(Some(math), Some(construct)) => math.iter().chain(construct.iter()).cloned().collect(),
};
let mut at = 0;
for point in break_points(text, &sequences) {
self.sink.text(&text[at..point]);
self.sink.open_inline("span").finish();
self.sink.close();
at = point;
}
self.sink.text(&text[at..]);
}
fn write_math_source(&mut self, source: &str) {
let neutralized = neutralized_source(source);
self.sink.text(&neutralized);
}
fn classes(
&mut self,
node: &NodeRef<'_, Flm>,
convention: &Convention,
role: Option<&Name>,
) -> Vec<String> {
let mut classes = vec![class_of_element(convention.element)];
if convention.has_role() {
if let Some(role) = role {
if is_valid_token(role.as_str()) {
classes.push(class_of_role(role.as_str()));
} else {
self.refused_name(
node,
"role",
role.as_str(),
"the class the role would have added was left out",
);
}
}
}
classes
}
fn kind_tokens(&mut self, node: &NodeRef<'_, Flm>, kinds: &[Name]) -> Option<String> {
let mut tokens: Vec<&str> = Vec::new();
let mut refused: Vec<&str> = Vec::new();
for kind in kinds {
if is_valid_token(kind.as_str()) {
tokens.push(kind.as_str());
} else {
refused.push(kind.as_str());
}
}
let written = (!tokens.is_empty()).then(|| tokens.join(" "));
let recovery = if written.is_some() {
"the token was left out of the `data-flm-kind` attribute"
} else {
"the `data-flm-kind` attribute was not written"
};
for name in refused {
self.refused_name(node, "kind", name, recovery);
}
written
}
fn refused_name(
&mut self,
node: &NodeRef<'_, Flm>,
what: &str,
name: &str,
recovery: &str,
) {
self.diags.push(Diagnostic::error(
InvalidName {
what: String::from(what),
name: String::from(name),
recovery: String::from(recovery),
},
node.span().clone(),
));
}
fn run(&mut self, carrier: Option<&NodeRef<'_, Flm>>, nodes: &[NodeRef<'_, Flm>]) {
for node in nodes {
if !self.descend() {
return;
}
self.node(carrier, node);
self.ascend();
}
}
fn node(&mut self, carrier: Option<&NodeRef<'_, Flm>>, node: &NodeRef<'_, Flm>) {
if let Some(text) = node.chars() {
self.write_text(text);
return;
}
if node.is_comment() {
return;
}
if is_element(node, structural::PARBREAK) {
return;
}
if !is_presentation(node) {
let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
self.run(Some(node), &children);
return;
}
let name = element_of(node).name.clone();
if name == super::construct::TAG {
self.construct(node);
return;
}
let Some(convention) = row(name.as_str()) else {
self.unexpected(node);
return;
};
match name.as_str() {
pres::PAR => self.par(node, convention),
pres::BLOCK => self.block(node, convention),
pres::BLOCK_HEADING => self.heading(node, convention),
pres::RUNIN_HEADING => self.runin_heading(node, convention),
pres::SPAN => self.span(node, convention),
pres::LIST => self.list(node, convention),
pres::CELLS => self.cells(node, convention),
pres::LINES => self.lines(node, convention),
pres::LINE => self.line(node, convention),
pres::VERBATIM => self.verbatim(node, convention),
pres::MATH_PASSTHROUGH => self.math_passthrough(node, convention),
pres::MATH_TEXT => self.math_text(node, convention),
pres::LINK => self.link(node, convention),
pres::IMAGE => self.image(node, convention),
pres::UNSUPPORTED => self.unsupported(node),
pres::DROPPED => self.dropped(node, convention),
pres::UNKNOWN => self.unknown(node, convention),
pres::DECO_RUNIN | pres::DECO_FINAL | pres::DECO_MARGIN => {
self.decoration(node, convention)
}
pres::DECO_MARK => self.deco_mark(carrier, node),
pres::SUBTREE => self.subtree(node),
_ => self.unexpected(node),
}
}
fn par(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
let payload = payload_of::<ParPayload>(node);
let anchor = payload.and_then(|payload| payload.anchor.clone());
let content = body(node);
if anchor.is_none() && shows_nothing(&content) {
return;
}
self.require_style(convention);
let mut values: Vec<(&'static str, String)> = Vec::new();
if let Some(anchor) = anchor {
values.push(("anchor", anchor));
}
let classes = self.classes(node, convention, None);
let mut attributes = ordered_attributes(convention, &values, &[]);
let flow = holds_flow_content(node);
if flow {
attributes.push((String::from("role"), String::from(PARAGRAPH_ROLE)));
}
let tag = if flow { PARAGRAPH_FLOW_TAG } else { "p" };
self.open(Some(node), tag, true, &classes, attributes, false);
self.run(Some(node), &content);
self.close();
}
fn block(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
self.require_style(convention);
let payload = payload_of::<BlockPayload>(node);
let mut values: Vec<(&'static str, String)> = Vec::new();
if let Some(anchor) = payload.and_then(|payload| payload.anchor.clone()) {
values.push(("anchor", anchor));
}
if let Some(role) = payload.and_then(|payload| payload.doc_role) {
values.push(("doc_role", doc_role_value(role)));
}
let kinds = payload.map(|payload| payload.kinds.clone()).unwrap_or_default();
if let Some(kinds) = self.kind_tokens(node, &kinds) {
values.push(("kinds", kinds));
}
let role = payload.and_then(|payload| payload.role.as_ref());
let tag = block_tag(role.map(Name::as_str));
let classes = self.classes(node, convention, role);
self.open(
Some(node),
tag,
true,
&classes,
ordered_attributes(convention, &values, &[]),
false,
);
let content = body(node);
self.run(Some(node), &content);
self.close();
}
fn heading(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
self.require_style(convention);
let payload = payload_of::<HeadingPayload>(node);
let level = payload.map_or(self.options.root_heading_level, |payload| payload.level);
let values = heading_values(payload);
let depth = match heading_depth(level, self.options.root_heading_level) {
Ok(depth) => depth,
Err(above) => {
self.diags.push(Diagnostic::error(above, node.span().clone()));
0
}
};
let mapped = payload.and_then(|payload| self.options.heading_tags.get(&payload.name));
let tag = match mapped {
Some(tag) if is_valid_tag_name(tag) => tag.clone(),
Some(tag) => {
self.diags.push(Diagnostic::error(
InvalidName {
what: String::from("tag"),
name: tag.clone(),
recovery: String::from("the heading was written with the tag of its level"),
},
node.span().clone(),
));
heading_tag(depth).to_string()
}
None => heading_tag(depth).to_string(),
};
let classes = self.classes(node, convention, None);
self.open(
Some(node),
&tag,
true,
&classes,
ordered_attributes(convention, &values, &[]),
false,
);
let content = body(node);
self.run(Some(node), &content);
self.close();
}
fn runin_heading(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
self.require_style(convention);
let values = heading_values(payload_of::<HeadingPayload>(node));
let classes = self.classes(node, convention, None);
self.open(
Some(node),
"span",
false,
&classes,
ordered_attributes(convention, &values, &[]),
false,
);
let content = body(node);
self.run(Some(node), &content);
self.close();
}
fn span(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
self.require_style(convention);
let payload = payload_of::<SpanPayload>(node);
let style = payload.and_then(|payload| payload.style);
let mut values: Vec<(&'static str, String)> = Vec::new();
if let Some(anchor) = payload.and_then(|payload| payload.anchor.clone()) {
values.push(("anchor", anchor));
}
if let Some(role) = payload.and_then(|payload| payload.doc_role) {
values.push(("doc_role", doc_role_value(role)));
}
if let Some(style) = style {
values.push(("style", String::from(style.as_str())));
}
let kinds = payload.map(|payload| payload.kinds.clone()).unwrap_or_default();
if let Some(kinds) = self.kind_tokens(node, &kinds) {
values.push(("kinds", kinds));
}
let classes = self.classes(node, convention, payload.and_then(|payload| payload.role.as_ref()));
self.open(
Some(node),
span_tag(style),
false,
&classes,
ordered_attributes(convention, &values, &[]),
false,
);
let content = body(node);
self.run(Some(node), &content);
self.close();
}
fn list(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
self.require_style(convention);
let payload = payload_of::<ListPayload>(node);
let kinds: Vec<Name> = payload.map(|payload| payload.kinds.clone()).unwrap_or_default();
let entry_anchors: Vec<Option<String>> =
payload.map(|payload| payload.entry_anchors.clone()).unwrap_or_default();
let entry_levels: Vec<Option<u32>> =
payload.map(|payload| payload.entry_levels.clone()).unwrap_or_default();
let tag = list_tag(&kinds);
let mut values: Vec<(&'static str, String)> = Vec::new();
if let Some(anchor) = payload.and_then(|payload| payload.anchor.clone()) {
values.push(("anchor", anchor));
}
if let Some(tokens) = self.kind_tokens(node, &kinds) {
values.push(("kinds", tokens));
}
let classes = self.classes(node, convention, None);
self.open(Some(node), tag, true, &classes, ordered_attributes(convention, &values, &[]), false);
let description = tag == "dl";
for (index, (label, item)) in list_entries(node).into_iter().enumerate() {
let label: Vec<NodeRef<'_, Flm>> = label.iter().collect();
let item: Vec<NodeRef<'_, Flm>> = item.iter().collect();
let label_class = [String::from(LIST_LABEL_CLASS)];
let mut attributes: Vec<(String, String)> = Vec::new();
if let (Some(attribute), Some(Some(anchor))) =
(entry_attribute(convention, "entry_anchors"), entry_anchors.get(index))
{
attributes.push((attribute, anchor.clone()));
}
if let (Some(attribute), Some(Some(level))) =
(entry_attribute(convention, "entry_levels"), entry_levels.get(index))
{
attributes.push((attribute, level.to_string()));
}
if description {
self.open(None, "dt", true, &label_class, attributes, false);
self.run(Some(node), &label);
self.close();
self.open(None, "dd", true, &[], Vec::new(), false);
self.run(Some(node), &item);
self.close();
} else {
self.open(None, "li", true, &[], attributes, false);
if !label.is_empty() {
self.open(None, "span", false, &label_class, Vec::new(), false);
self.run(Some(node), &label);
self.close();
}
self.run(Some(node), &item);
self.close();
}
}
self.close();
}
fn cells(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
self.require_style(convention);
let classes = self.classes(node, convention, None);
self.open(Some(node), "table", true, &classes, Vec::new(), false);
if let Some((payload, contents)) = cells_of(node) {
for row in payload.grid() {
self.open(None, "tr", true, &[], Vec::new(), false);
for position in row {
match position {
GridPosition::Empty => {
self.cell(node, convention, &CellRendering::empty(), &[]);
}
GridPosition::TopLeft(index) => {
let rendering = self.cell_rendering(node, convention, &payload.cells[index]);
let content: Vec<NodeRef<'_, Flm>> = contents
.get(index)
.and_then(|slice| slice.as_ref())
.map(|slice| slice.iter().collect())
.unwrap_or_default();
self.cell(node, convention, &rendering, &content);
}
GridPosition::Covered(_) => {}
}
}
self.close();
}
}
self.close();
}
fn cell_rendering(
&mut self,
node: &NodeRef<'_, Flm>,
convention: &Convention,
spec: &CellSpec,
) -> CellRendering {
let mut attributes: Vec<(String, String)> = Vec::new();
if let (Some(attribute), Some(align)) = (entry_attribute(convention, "align"), spec.align) {
attributes.push((attribute, String::from(align.as_str())));
}
if let Some(attribute) = entry_attribute(convention, "rules").filter(|_| !spec.rules.is_empty()) {
let edges: Vec<&str> = spec.rules.iter().map(|edge| edge.as_str()).collect();
attributes.push((attribute, edges.join(" ")));
}
if let Some(family) = entry_attribute(convention, "styles") {
for style in &spec.styles {
let attribute = format!("{family}{style}");
if is_valid_attribute_name(&attribute) {
attributes.push((attribute, String::new()));
} else {
self.refused_name(
node,
"attribute",
&attribute,
"the attribute of the custom style was left out",
);
}
}
}
CellRendering {
tag: if spec.header.is_some() { "th" } else { "td" },
scope: spec.header.map(|header| match header {
CellHeader::Column => "col",
CellHeader::Row => "row",
}),
colspan: (spec.col_span != 1).then_some(spec.col_span),
rowspan: (spec.row_span != 1).then_some(spec.row_span),
attributes,
}
}
fn cell(
&mut self,
node: &NodeRef<'_, Flm>,
convention: &Convention,
rendering: &CellRendering,
content: &[NodeRef<'_, Flm>],
) {
let mut attributes: Vec<(String, String)> = Vec::new();
for field in convention.fields {
let value = match field.field {
"row_span" => rendering.rowspan.map(|span| span.to_string()),
"col_span" => rendering.colspan.map(|span| span.to_string()),
"header" => rendering.scope.map(String::from),
_ => None,
};
if let (Some(attribute), Some(value)) = (field.entry_attribute(), value) {
attributes.push((attribute, value));
}
}
attributes.extend(rendering.attributes.iter().cloned());
self.open(None, rendering.tag, true, &[], attributes, false);
self.run(Some(node), content);
self.close();
}
fn lines(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
self.require_style(convention);
let classes = self.classes(node, convention, None);
self.open(Some(node), "div", true, &classes, Vec::new(), false);
let content = body(node);
self.run(Some(node), &content);
self.close();
}
fn line(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
self.require_style(convention);
let payload = payload_of::<LinePayload>(node);
let mut values: Vec<(&'static str, String)> = Vec::new();
let mut lengths: Vec<(&'static str, &Length)> = Vec::new();
if let Some(payload) = payload {
lengths.push(("indent_left", &payload.indent_left));
lengths.push(("indent_right", &payload.indent_right));
values.push(("align", String::from(payload.align.as_str())));
}
let classes = self.classes(node, convention, None);
self.open(
Some(node),
"div",
true,
&classes,
ordered_attributes(convention, &values, &lengths),
false,
);
let content = body(node);
self.run(Some(node), &content);
self.close();
}
fn verbatim_text(&mut self, nodes: &[NodeRef<'_, Flm>]) -> String {
let mut out = String::new();
for node in nodes {
match node.kind() {
NodeKind::Chars { .. } => out.push_str(node.chars().unwrap_or("")),
NodeKind::Group(_) if node.group_type() == Some(FlmGroupType::Content) => {
if self.descend() {
let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
let text = self.verbatim_text(&children);
out.push_str(&text);
self.ascend();
}
}
_ => out.push_str(&recompose_source(&[*node])),
}
}
out
}
fn verbatim(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
let payload = payload_of::<VerbatimPayload>(node);
let block =
payload.is_some_and(|payload| payload.display == VerbatimDisplay::Block);
let code = payload.is_some_and(|payload| payload.kind == VerbatimKind::Code);
self.require_style(convention);
let mut values: Vec<(&'static str, String)> = Vec::new();
if let Some(payload) = payload {
values.push(("kind", String::from(payload.kind.as_str())));
values.push(("display", String::from(payload.display.as_str())));
if let Some(lang) = payload.lang.as_deref() {
values.push(("lang", String::from(lang)));
}
}
let classes = self.classes(node, convention, None);
let attributes = ordered_attributes(convention, &values, &[]);
let content = self.verbatim_text(&body(node));
let tag = match (code, block) {
(true, true) => "pre",
(true, false) => "code",
(false, true) => "div",
(false, false) => "span",
};
self.open(Some(node), tag, block, &classes, attributes, block);
if code && block {
self.open(None, "code", false, &[], Vec::new(), false);
}
self.write_text(&content);
if code && block {
self.close();
}
self.close();
}
fn math_passthrough(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
if self.math.is_some() {
self.formula_deeper_in_a_piece(node);
return;
}
let payload = payload_of::<MathPassthroughPayload>(node);
let display = payload.map_or(MathDisplay::Inline, |payload| payload.display);
let env: Option<String> = payload.and_then(|payload| payload.env.clone());
let block = display == MathDisplay::Display;
self.require_style(convention);
self.require(SCRIPT_MATHJAX);
let mut values: Vec<(&'static str, String)> =
vec![("display", String::from(display.as_str()))];
if let Some(env) = &env {
values.push(("env", env.clone()));
}
let classes = self.classes(node, convention, payload.and_then(|payload| payload.role.as_ref()));
self.open(
Some(node),
"span",
block,
&classes,
ordered_attributes(convention, &values, &[]),
false,
);
let closing = closing_delimiter(display, env.as_deref());
self.math = Some(MathContext {
sequences: Arc::from(sequences_in_math(&closing)),
span: node.span().clone(),
});
let opening = opening_delimiter(display, env.as_deref());
self.write_math_source(&opening);
self.math_stream(node);
let closing = closing.text.clone();
self.write_math_source(&closing);
self.math = None;
self.close();
}
fn math_stream(&mut self, node: &NodeRef<'_, Flm>) {
let body = body(node);
let mut source: Vec<NodeRef<'_, Flm>> = Vec::new();
for child in &body {
if !is_element(child, pres::MATH_TEXT) {
source.push(*child);
continue;
}
let text = recompose_source(&source);
self.write_math_source(&text);
source.clear();
if !self.descend() {
return;
}
if let Some(convention) = row(pres::MATH_TEXT) {
self.math_text(child, convention);
}
self.ascend();
}
let text = recompose_source(&source);
self.write_math_source(&text);
}
fn math_text(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
self.require_style(convention);
let payload = payload_of::<MathTextPayload>(node);
let content = body(node);
if self.math.is_none() {
let values = self.math_text_values(payload);
let classes = self.classes(node, convention, None);
self.open(
Some(node),
"span",
false,
&classes,
ordered_attributes(convention, &values, &[]),
false,
);
self.run(Some(node), &content);
self.close();
return;
}
let at_tag = payload.is_some_and(|payload| payload.at_tag);
if at_tag {
self.write_math_source("$");
}
let mut written = false;
let mut piece: Vec<NodeRef<'_, Flm>> = Vec::new();
for child in &content {
if !is_element(child, pres::MATH_PASSTHROUGH) {
piece.push(*child);
continue;
}
if !written || !piece.is_empty() {
self.tex_html(node, convention, payload, !written, &piece);
written = true;
}
piece.clear();
if self.descend() {
self.math_stream(child);
self.ascend();
}
}
if !written || !piece.is_empty() {
self.tex_html(node, convention, payload, !written, &piece);
}
if at_tag {
self.write_math_source("$");
}
}
fn math_text_values(
&self,
payload: Option<&MathTextPayload>,
) -> Vec<(&'static str, String)> {
let mut values: Vec<(&'static str, String)> = Vec::new();
if let Some(anchor) = payload.and_then(|payload| payload.anchor.clone()) {
values.push(("anchor", anchor));
}
if let Some(command) = payload.and_then(|payload| payload.command.clone()) {
values.push(("command", command));
}
values
}
fn tex_html(
&mut self,
node: &NodeRef<'_, Flm>,
convention: &Convention,
payload: Option<&MathTextPayload>,
first: bool,
content: &[NodeRef<'_, Flm>],
) {
let values = if first { self.math_text_values(payload) } else { Vec::new() };
let classes = self.classes(node, convention, None);
let outer = self.piece.take();
let was_in_tex_html = self.in_tex_html;
self.sink.open_inline(TEX_HTML).finish();
self.in_tex_html = true;
self.open(
first.then_some(node),
"span",
false,
&classes,
ordered_attributes(convention, &values, &[]),
false,
);
self.piece = Some(Piece { classes, open: Vec::new() });
self.run(Some(node), content);
self.piece = None;
self.sink.close();
self.in_tex_html = was_in_tex_html;
self.sink.close();
self.piece = outer;
}
fn formula_deeper_in_a_piece(&mut self, node: &NodeRef<'_, Flm>) {
let Some(piece) = self.piece.take() else {
self.unexpected(node);
return;
};
for _ in &piece.open {
self.sink.close();
}
self.sink.close();
self.in_tex_html = false;
self.sink.close();
self.math_stream(node);
self.sink.open_inline(TEX_HTML).finish();
self.in_tex_html = true;
self.write_open(OpenInMath {
tag: String::from("span"),
block: false,
classes: piece.classes.clone(),
attributes: Vec::new(),
preformatted: false,
});
self.piece = Some(Piece { classes: piece.classes, open: Vec::new() });
for element in piece.open {
self.write_open(element);
}
}
fn link(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
self.require_style(convention);
let nested = self.links_open > 0;
let payload = payload_of::<LinkPayload>(node);
let mut values: Vec<(&'static str, String)> = Vec::new();
if let Some(payload) = payload {
if !nested {
match check_address(&payload.href, AddressUse::Link, self.url_schemes) {
Ok(()) => values.push(("href", payload.href.clone())),
Err(refused) => self.diags.push(Diagnostic::error(
AddressRefused {
address: payload.href.clone(),
scheme: refused.scheme,
attribute: String::from("href"),
allowed: self.url_schemes.allowed_addresses(),
},
node.span().clone(),
)),
}
if let Some(role) = payload.doc_role {
values.push(("doc_role", doc_role_value(role)));
}
if let Some(label) = &payload.label {
values.push(("label", label.clone()));
}
}
if let Some(kind) = self.kind_tokens(node, std::slice::from_ref(&payload.kind)) {
values.push(("kind", kind));
}
}
let classes = self.classes(node, convention, None);
self.open(
Some(node),
if nested { "span" } else { "a" },
false,
&classes,
ordered_attributes(convention, &values, &[]),
false,
);
let content = body(node);
self.links_open += 1;
self.run(Some(node), &content);
self.links_open -= 1;
self.close();
}
fn image(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
self.require_style(convention);
let payload = payload_of::<ImagePayload>(node);
let mut values: Vec<(&'static str, String)> = Vec::new();
if let Some(payload) = payload {
if let Some(anchor) = payload.anchor.clone() {
values.push(("anchor", anchor));
}
match check_address(&payload.src, AddressUse::Image, self.url_schemes) {
Ok(()) => values.push(("src", payload.src.clone())),
Err(refused) => self.diags.push(Diagnostic::error(
AddressRefused {
address: payload.src.clone(),
scheme: refused.scheme,
attribute: String::from("src"),
allowed: self.url_schemes.allowed_addresses(),
},
node.span().clone(),
)),
}
if let Some(alt) = payload.alt.clone() {
values.push(("alt", alt));
}
let mut candidates: Vec<String> = Vec::new();
for candidate in &payload.srcset {
match check_address(&candidate.src, AddressUse::Image, self.url_schemes) {
Ok(()) => candidates.push(
if candidate.descriptor.is_empty() {
candidate.src.clone()
} else {
format!("{} {}", candidate.src, candidate.descriptor)
},
),
Err(refused) => self.diags.push(Diagnostic::error(
AddressRefused {
address: candidate.src.clone(),
scheme: refused.scheme,
attribute: String::from("srcset"),
allowed: self.url_schemes.allowed_addresses(),
},
node.span().clone(),
)),
}
}
if !candidates.is_empty() {
values.push(("srcset", candidates.join(", ")));
}
}
let mut lengths: Vec<(&'static str, &Length)> = Vec::new();
if let Some(payload) = payload {
lengths.extend(payload.width.as_ref().map(|width| ("width", width)));
lengths.extend(payload.height.as_ref().map(|height| ("height", height)));
}
let mut classes = self.classes(node, convention, None);
if payload.is_some_and(|payload| payload.display == ImageDisplay::Block) {
classes.insert(0, class_of_element(pres::BLOCK));
}
self.void(Some(node), "img", &classes, ordered_attributes(convention, &values, &lengths));
}
fn unsupported(&mut self, node: &NodeRef<'_, Flm>) {
let element = payload_of::<UnsupportedPayload>(node)
.map_or_else(String::new, |payload| payload.element.to_string());
self.stand_in(node, &element);
}
fn dropped(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
self.require_style(convention);
let payload = payload_of::<DroppedPayload>(node);
let mut values: Vec<(&'static str, String)> = Vec::new();
if let Some(payload) = payload {
values.push(("condition", payload.condition.to_string()));
}
let classes = self.classes(node, convention, None);
self.open(Some(node), "span", false, &classes, ordered_attributes(convention, &values, &[]), false);
let detail = payload.map_or("", |payload| payload.detail.as_str());
self.write_text(&format!("dropped: {detail}"));
self.close();
}
fn stand_in(&mut self, node: &NodeRef<'_, Flm>, element: &str) {
let convention = row(pres::UNSUPPORTED).expect("the vocabulary has a row for every element");
self.require_style(convention);
let values = vec![("element", String::from(element))];
let classes = vec![class_of_element(convention.element)];
self.open(
Some(node),
"span",
false,
&classes,
ordered_attributes(convention, &values, &[]),
false,
);
self.close();
}
fn unknown(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
let payload = payload_of::<UnknownPayload>(node);
let kind = payload.map_or(UnknownKind::Macro, |payload| payload.kind);
self.require_style(convention);
let mut values: Vec<(&'static str, String)> = Vec::new();
if let Some(payload) = payload {
values.push(("kind", String::from(payload.kind.as_str())));
values.push(("name", payload.name.clone()));
}
let classes = self.classes(node, convention, None);
let attributes = ordered_attributes(convention, &values, &[]);
let spelling = payload.map_or_else(String::new, |payload| payload.spelling.clone());
match kind {
UnknownKind::Macro => {
self.open(Some(node), "span", false, &classes, attributes, false);
self.write_text(&spelling);
self.close();
}
UnknownKind::Environment => {
self.open(Some(node), "div", true, &classes, attributes, false);
self.marker(&format!("\\begin{{{spelling}}}"));
let content = body(node);
self.run(Some(node), &content);
self.marker(&format!("\\end{{{spelling}}}"));
self.close();
}
}
}
fn marker(&mut self, text: &str) {
let classes = [String::from(UNKNOWN_MARKER_CLASS)];
self.open(None, "span", true, &classes, Vec::new(), false);
self.write_text(text);
self.close();
}
fn decoration(
&mut self,
node: &NodeRef<'_, Flm>,
convention: &Convention,
) {
self.require_style(convention);
let classes = self.classes(node, convention, None);
self.open(Some(node), "span", false, &classes, Vec::new(), false);
let content = body(node);
self.run(Some(node), &content);
if is_element(node, pres::DECO_RUNIN)
&& !self.options.run_in_stop.is_empty()
&& holds_text(content.iter().copied())
&& !ends_in_sentence_punctuation(content.iter().copied())
{
let stop = self.options.run_in_stop.clone();
self.write_text(&stop);
}
self.close();
}
fn deco_mark(&mut self, carrier: Option<&NodeRef<'_, Flm>>, node: &NodeRef<'_, Flm>) {
let Some(carrier) = carrier else { return };
let Some(deco) = decoration_at(carrier, node) else { return };
let Some(convention) = row(element_of(&deco).name.as_str()) else { return };
self.decoration(&deco, convention);
}
fn subtree(&mut self, node: &NodeRef<'_, Flm>) {
let Some(payload) = payload_of::<SubtreePayload>(node) else { return };
let at = self.sink.len();
self.placements.push((at, payload.tree, node.span().clone()));
}
fn construct(&mut self, node: &NodeRef<'_, Flm>) {
let Some(payload) = payload_of::<HtmlTagPayload>(node) else {
self.unexpected(node);
return;
};
if !is_valid_tag_name(&payload.tag) {
self.diags.push(Diagnostic::error(
InvalidName {
what: String::from("tag"),
name: payload.tag.clone(),
recovery: String::from("the node was written as the unsupported stand-in"),
},
node.span().clone(),
));
self.stand_in(node, super::construct::TAG);
return;
}
for (name, _) in &payload.attributes {
if !is_valid_attribute_name(name) {
self.diags.push(Diagnostic::error(
InvalidName {
what: String::from("attribute"),
name: name.clone(),
recovery: String::from(
"the node was written as the unsupported stand-in",
),
},
node.span().clone(),
));
self.stand_in(node, super::construct::TAG);
return;
}
}
let attributes: Vec<(String, String)> = payload
.attributes
.iter()
.map(|(name, value)| (name.clone(), value.clone()))
.collect();
let attributes = self.writable_in_math(Some(node), attributes);
self.write_open(OpenInMath {
tag: payload.tag.clone(),
block: payload.block,
classes: Vec::new(),
attributes,
preformatted: false,
});
match &payload.body {
TagBody::Markup(markup) => self.sink.markup(markup),
TagBody::Children => {
let content = body(node);
let tex_html = payload.tag == TEX_HTML;
self.tex_html_constructs += usize::from(tex_html);
self.run(Some(node), &content);
self.tex_html_constructs -= usize::from(tex_html);
}
}
self.close();
}
fn require_style(&mut self, convention: &Convention) {
if let Some(style) = convention.style {
self.require(style);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn inline_sequences() -> Vec<Sequence> {
sequences_in_math(&closing_delimiter(MathDisplay::Inline, None))
}
fn broken(text: &str, sequences: &[Sequence]) -> String {
let mut out = String::new();
let mut at = 0;
for point in break_points(text, sequences) {
out.push_str(&text[at..point]);
out.push_str("<span></span>");
at = point;
}
out.push_str(&text[at..]);
out
}
#[test]
fn the_style_writer_writes_nothing_for_a_zero_length() {
let line = row(pres::LINE).expect("the line row");
let zero = Length::tabs(0);
let two = Length::tabs(2);
let align = [("align", String::from("left"))];
let attributes =
ordered_attributes(line, &align, &[("indent_left", &zero), ("indent_right", &zero)]);
assert!(attributes.iter().all(|(name, _)| name != STYLE_ATTRIBUTE), "{attributes:?}");
let attributes =
ordered_attributes(line, &align, &[("indent_left", &two), ("indent_right", &zero)]);
assert_eq!(
attributes.iter().find(|(name, _)| name == STYLE_ATTRIBUTE).map(|(_, value)| value.as_str()),
Some("--flm-element-indent-left: calc(2 * var(--flm-tab))")
);
}
#[test]
fn the_source_span_attribute_is_the_name_the_naming_function_derives() {
assert_eq!(SOURCE_SPAN_ATTRIBUTE, data_attribute("source_span"));
assert!(is_valid_attribute_name(SOURCE_SPAN_ATTRIBUTE));
}
#[test]
fn the_value_of_the_source_span_attribute_is_a_json_array_of_three_items() {
assert_eq!(source_span_value("book/ch1.flm", &(0..8)), "[\"book/ch1.flm\",0,8]");
}
#[test]
fn the_delimiters_are_the_three_shapes_a_formula_is_written_in() {
assert_eq!(opening_delimiter(MathDisplay::Inline, None), "\\(");
assert_eq!(closing_delimiter(MathDisplay::Inline, None).text, "\\)");
assert_eq!(opening_delimiter(MathDisplay::Display, None), "\\[");
assert_eq!(closing_delimiter(MathDisplay::Display, None).text, "\\]");
assert_eq!(
opening_delimiter(MathDisplay::Display, Some("align")),
"\\begin{align}"
);
assert_eq!(
closing_delimiter(MathDisplay::Display, Some("align")).text,
"\\end{align}"
);
assert_eq!(closing_delimiter(MathDisplay::Display, Some("gather")).text, "\\end{gather}");
}
#[test]
fn source_holding_the_tag_gets_an_empty_group_after_its_opening_angle() {
assert_eq!(neutralized_source("a < b"), "a < b");
assert_eq!(neutralized_source("x <tex-html> y"), "x <{}tex-html> y");
assert_eq!(neutralized_source("x </tex-html> y"), "x <{}/tex-html> y");
assert_eq!(
neutralized_source("<tex-html><b>p</b></tex-html>"),
"<{}tex-html><b>p</b><{}/tex-html>"
);
assert_eq!(neutralized_source("<tex-htm"), "<tex-htm");
assert_eq!(neutralized_source("a < tex-html"), "a < tex-html");
}
#[test]
fn source_that_holds_no_tag_is_unchanged_whatever_it_holds() {
for source in ["", "x^2 + y", "a \\le b", "\\text{if}", "α < β", "&\\\\"] {
assert_eq!(neutralized_source(source), source, "{source}");
}
}
#[test]
fn text_inside_the_html_breaks_the_closing_delimiter_and_the_two_tags() {
let sequences = inline_sequences();
assert_eq!(broken("write \\) here", &sequences), "write \\<span></span>) here");
assert_eq!(
broken("write <tex-html> here", &sequences),
"write <<span></span>tex-html> here"
);
assert_eq!(
broken("write </tex-html> here", &sequences),
"write <<span></span>/tex-html> here"
);
assert_eq!(broken("write \\] here", &sequences), "write \\] here");
}
#[test]
fn the_environment_name_is_part_of_the_sequence_that_is_broken() {
let sequences = sequences_in_math(&closing_delimiter(MathDisplay::Display, Some("align")));
assert_eq!(
broken("stop at \\end{align} here", &sequences),
"stop at \\end<span></span>{align} here"
);
assert_eq!(broken("\\end{gather} is not this end", &sequences), "\\end{gather} is not this end");
}
#[test]
fn a_text_that_holds_no_sequence_is_written_as_it_stands() {
let sequences = inline_sequences();
for text in ["", "one half", "a < b", "\\alpha", "( ) \\ ]"] {
assert_eq!(broken(text, &sequences), text, "{text}");
assert!(break_points(text, &sequences).is_empty(), "{text}");
}
}
#[test]
fn every_occurrence_of_a_sequence_is_broken_including_two_in_a_row() {
let sequences = inline_sequences();
assert_eq!(broken("\\)\\)", &sequences), "\\<span></span>)\\<span></span>)");
assert_eq!(break_points("\\)\\)", &sequences), vec![1, 3]);
assert_eq!(broken("\\\\)", &sequences), "\\\\<span></span>)");
}
#[test]
fn an_attribute_value_is_refused_for_the_first_sequence_it_holds() {
let sequences = inline_sequences();
assert_eq!(refused_sequence("eq:one", &sequences), None);
assert_eq!(refused_sequence("eq:\\)one", &sequences).as_deref(), Some("\\)"));
assert_eq!(
refused_sequence("a </tex-html> b", &sequences).as_deref(),
Some("</tex-html")
);
assert_eq!(
refused_sequence("<tex-html \\)", &sequences).as_deref(),
Some("<tex-html")
);
assert_eq!(
refused_sequence("\\) <tex-html", &sequences).as_deref(),
Some("\\)")
);
}
#[test]
fn a_break_point_falls_at_the_sequences_own_joint() {
assert_eq!(closing_delimiter(MathDisplay::Inline, None).break_at, 1);
assert_eq!(closing_delimiter(MathDisplay::Display, None).break_at, 1);
assert_eq!(closing_delimiter(MathDisplay::Display, Some("align")).break_at, 4);
for sequence in tex_html_sequences() {
assert_eq!(sequence.break_at, 1, "{}", sequence.text);
}
}
}