pub mod latex;
pub mod latex_rendered;
pub mod numbers;
pub mod title;
use std::collections::BTreeSet;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef};
use techy::error::{Diagnostic, DiagnosticInfo};
use techy::extract::parse_keyval_drop_annotations;
use crate::core::settings::{SettingsDecl, named};
use crate::model::aspects::{
AcceptedRefTypes, AnchorPolicy, BlockRole, BlockRoleAspect, ContentRef, FixedBlockRole,
NumberSource, Placement, PointId, RefPoint, Referenceable, Sectioning,
};
use crate::model::element::{ElementSpec, element_value};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
chars_at_lowering,
};
use crate::model::names::{CapName, ElementName, Name, RefKind};
use crate::model::options::Bind;
use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature, StyleDef};
use crate::core::run::MissingEntry;
use crate::lang::Flm;
use crate::lang::copy::{
ValueContent, ValuePiece, WrittenPiece, copy_pieces_into_value, key_value_pieces,
};
use crate::lang::guard::{GuardPolicy, on_worker_thread};
use crate::lang::mint::{ArgDef, ArgStdKind, ElementDef, SyntaxDef};
use crate::lang::text::is_space;
use crate::stdlib::backends::lowering::{lower_arg_named_or_nothing, lower_written_pieces};
use crate::stdlib::backends::pres::{self, DecorationPayload, HeadingPayload};
use crate::stdlib::features::numbering::{
COUNTERS, Counters, FormatOptions, NumberTemplate, Within,
};
use crate::stdlib::features::refs::{self, ANCHORS};
use title::{CompileTitles, NumberRule, Titles, DEFAULT_TITLE_NUMBER_FORMAT};
pub const FEATURE: &str = "headings";
fn settings() -> SettingsDecl {
SettingsDecl::new(FEATURE)
.config::<HeadingsConfig>(
"The heading kinds, the heading commands, and the heading kinds that are numbered. \
For each heading kind, the configuration contains its level, its counter and \
counter style, the counter it is numbered within, its number format, the text \
written before the title of a numbered heading, whether its headings are listed in \
a table of contents or set as run-in headings, and the labels and anchors of its \
headings. For each heading command, it contains the heading kind of the headings \
written with the command and the default values of the options `numbered` and \
`toc`. Fixed when the registry is built; it cannot vary per document or per render.",
)
.options::<latex::HeadingsLatexOptions>(
Bind::Render,
"The LaTeX sectioning command of each heading kind in the recomposed LaTeX, given \
by the name of the heading kind. A heading kind that is not listed is written as the \
command of the same name, such as `\\section` for the kind `section`. Set per render \
request.",
)
.merge_entries("headings", || named::to_data(&HeadingsConfig::default().headings, "name"))
.remove_false("headings")
.merge_entries("commands", || named::to_data(&HeadingsConfig::default().commands, "name"))
.remove_false("commands")
.markup("headings.*.within.joiner.joined")
.markup("headings.*.within.joiner.template")
.markup("headings.*.number_format")
.markup("headings.*.title_number_format")
}
pub const HEADING: &str = "flm.heading";
pub const RULE: &str = "flm.heading.lower.default";
pub const STYLE: &str = "flm.headings.style";
pub fn stylesheet() -> StyleDef {
StyleDef {
id: Name::from(STYLE),
content: Vec::new(),
docs: String::from("headings, which need no style rules"),
}
}
pub const KIND: &str = "section";
pub const LABEL_TYPES: [&str; 2] = ["sec", "topic"];
pub const ANCHOR_PREFIX: &str = LABEL_TYPES[0];
pub const STYLE_PREFIX: &str = "flm.headings.style.";
pub const COUNTER_PREFIX: &str = "flm.headings.";
pub const STAR_ARG: &str = "star";
pub const OPTIONS_ARG: &str = "options";
pub const TITLE_ARG: &str = "title";
pub const NUMBERED_KEY: &str = "numbered";
pub const TOC_KEY: &str = "toc";
pub const ALT_KEY: &str = "alt";
pub const RESERVED_KEYS: [&str; 1] = ["pdfbookmark"];
pub const LEVELS_PARENT_SET: &str = "flm.headings.levels";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum HeadingNumbering {
#[default]
NothingNumbered,
AllNumbered,
UpToDepth(u8),
}
impl HeadingNumbering {
pub fn admits(self, level: u8) -> bool {
match self {
HeadingNumbering::NothingNumbered => false,
HeadingNumbering::AllNumbered => true,
HeadingNumbering::UpToDepth(depth) => level <= depth,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(transform = heading_decl_schema)]
pub struct HeadingDecl {
#[schemars(skip)]
pub name: Name,
pub level: u8,
pub counter: Option<Name>,
pub style: Option<Name>,
pub within: Option<Within>,
pub number_format: NumberTemplate,
pub title_number_format: String,
pub skip_toc: bool,
pub run_in: bool,
pub ref_kind: RefKind,
pub label_types: Vec<String>,
pub anchor_prefix: String,
pub docs: String,
}
fn heading_decl_schema(schema: &mut schemars::Schema) {
crate::core::settings::named::require_only(schema, &["level"]);
}
impl HeadingDecl {
pub fn new(name: impl Into<Name>, level: u8) -> HeadingDecl {
let name = name.into();
HeadingDecl {
counter: Some(Name::new(format!("{COUNTER_PREFIX}{}", name.as_str()))),
style: Some(Name::new(format!("{STYLE_PREFIX}{}", name.as_str()))),
name,
level,
within: None,
number_format: NumberTemplate::formats("#{arabic}"),
title_number_format: String::from(DEFAULT_TITLE_NUMBER_FORMAT),
skip_toc: false,
run_in: false,
ref_kind: RefKind::from(KIND),
label_types: LABEL_TYPES.iter().map(|label| String::from(*label)).collect(),
anchor_prefix: String::from(ANCHOR_PREFIX),
docs: String::new(),
}
}
pub fn counter(mut self, counter: impl Into<Name>) -> HeadingDecl {
self.counter = Some(counter.into());
self
}
pub fn no_counter(mut self) -> HeadingDecl {
self.counter = None;
self.style = None;
self
}
pub fn style(mut self, style: impl Into<Name>) -> HeadingDecl {
self.style = Some(style.into());
self
}
pub fn within(mut self, within: Within) -> HeadingDecl {
self.within = Some(within);
self
}
pub fn number_format(mut self, number_format: NumberTemplate) -> HeadingDecl {
self.number_format = number_format;
self
}
pub fn title_number_format(mut self, text: impl Into<String>) -> HeadingDecl {
self.title_number_format = text.into();
self
}
pub fn skip_toc(mut self, skip_toc: bool) -> HeadingDecl {
self.skip_toc = skip_toc;
self
}
pub fn run_in(mut self, run_in: bool) -> HeadingDecl {
self.run_in = run_in;
self
}
pub fn ref_kind(mut self, ref_kind: impl Into<RefKind>) -> HeadingDecl {
self.ref_kind = ref_kind.into();
self
}
pub fn label_types(mut self, types: impl IntoIterator<Item = impl Into<String>>) -> HeadingDecl {
self.label_types = types.into_iter().map(Into::into).collect();
self
}
pub fn anchor_prefix(mut self, prefix: impl Into<String>) -> HeadingDecl {
self.anchor_prefix = prefix.into();
self
}
pub fn docs(mut self, docs: impl Into<String>) -> HeadingDecl {
self.docs = crate::kept_docs(docs);
self
}
fn number_source(&self) -> Option<NumberSource> {
Some(NumberSource {
counter: self.counter.clone()?,
instances: Vec::new(),
style: self.style.clone()?,
advance: vec![0],
number_format: None,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct HeadingCommand {
#[schemars(skip)]
pub name: String,
pub heading: Name,
#[serde(default)]
pub defaults: Vec<(String, String)>,
}
impl HeadingCommand {
pub fn new(name: impl Into<String>, heading: impl Into<Name>) -> HeadingCommand {
HeadingCommand { name: name.into(), heading: heading.into(), defaults: Vec::new() }
}
pub fn default_value(
mut self,
key: impl Into<String>,
value: impl Into<String>,
) -> HeadingCommand {
self.defaults.push((key.into(), value.into()));
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct HeadingsConfig {
#[serde(deserialize_with = "crate::core::settings::named::deserialize")]
#[schemars(
transform = crate::core::settings::named::map_schema,
with = "std::collections::BTreeMap<String, HeadingDecl>"
)]
pub headings: Vec<HeadingDecl>,
#[serde(deserialize_with = "crate::core::settings::named::deserialize")]
#[schemars(
transform = crate::core::settings::named::map_schema,
with = "std::collections::BTreeMap<String, HeadingCommand>"
)]
pub commands: Vec<HeadingCommand>,
pub numbering: HeadingNumbering,
}
impl Default for HeadingsConfig {
fn default() -> HeadingsConfig {
HeadingsConfig::new()
}
}
impl HeadingsConfig {
pub fn new() -> HeadingsConfig {
let letters = || NumberTemplate::formats("#{alph}");
let counter = |kind: &str| format!("{COUNTER_PREFIX}{kind}");
HeadingsConfig::default_commands_for(vec![
HeadingDecl::new("section", 1),
HeadingDecl::new("subsection", 2).within(Within::parent(counter("section"))),
HeadingDecl::new("subsubsection", 3).within(Within::parent(counter("subsection"))),
HeadingDecl::new("paragraph", 4)
.number_format(letters())
.within(
Within::parents(["section", "subsection", "subsubsection"].map(counter))
.displayed_bare(),
),
HeadingDecl::new("subparagraph", 5)
.number_format(letters())
.within(Within::parent(counter("paragraph"))),
])
}
fn default_commands_for(headings: Vec<HeadingDecl>) -> HeadingsConfig {
let commands = headings
.iter()
.map(|kind| HeadingCommand::new(kind.name.as_str(), kind.name.clone()))
.collect();
HeadingsConfig { headings, commands, numbering: HeadingNumbering::default() }
}
pub fn headings(self, headings: impl IntoIterator<Item = HeadingDecl>) -> HeadingsConfig {
HeadingsConfig {
numbering: self.numbering,
..HeadingsConfig::default_commands_for(headings.into_iter().collect())
}
}
pub fn numbering(mut self, numbering: HeadingNumbering) -> HeadingsConfig {
self.numbering = numbering;
self
}
pub fn numbers(&self, kind: &HeadingDecl) -> bool {
kind.counter.is_some() && self.numbering.admits(kind.level)
}
pub fn commands(mut self, commands: impl IntoIterator<Item = HeadingCommand>) -> HeadingsConfig {
self.commands = commands.into_iter().collect();
self
}
pub fn command(mut self, command: HeadingCommand) -> HeadingsConfig {
self.commands.push(command);
self
}
pub fn run_in_levels(mut self, levels: impl IntoIterator<Item = u8>) -> HeadingsConfig {
let levels: BTreeSet<u8> = levels.into_iter().collect();
for kind in &mut self.headings {
kind.run_in = levels.contains(&kind.level);
}
self
}
pub fn heading(&self, name: &str) -> Option<&HeadingDecl> {
self.headings.iter().find(|kind| kind.name.as_str() == name)
}
pub fn commands_of<'c>(&'c self, name: &'c str) -> impl Iterator<Item = &'c HeadingCommand> {
self.commands.iter().filter(move |command| command.heading.as_str() == name)
}
pub fn validate(&self) -> Result<(), String> {
let mut names = BTreeSet::new();
let mut counters = BTreeSet::new();
let mut styles = BTreeSet::new();
for kind in &self.headings {
if !names.insert(kind.name.as_str()) {
return Err(format!("Duplicate heading kind ‘{}’", kind.name));
}
if let Some(counter) = &kind.counter {
if !counters.insert(counter.as_str()) {
return Err(format!(
"Duplicate counter ‘{counter}’ for heading kind ‘{}’: each heading kind \
must have a counter of its own",
kind.name
));
}
if kind.style.is_none() {
return Err(format!(
"Missing counter style for heading kind ‘{}’ with counter ‘{counter}’",
kind.name
));
}
}
if let Some(style) = &kind.style {
if !styles.insert(style.as_str()) {
return Err(format!(
"Duplicate counter style ‘{style}’ for heading kind ‘{}’: each heading \
kind must have a counter style of its own",
kind.name
));
}
}
}
let mut commands = BTreeSet::new();
for command in &self.commands {
if !commands.insert(command.name.as_str()) {
return Err(format!("Duplicate heading command ‘\\{}’", command.name));
}
if !names.contains(command.heading.as_str()) {
return Err(format!(
"Unknown heading kind ‘{}’ of heading command ‘\\{}’",
command.heading, command.name
));
}
for (key, value) in &command.defaults {
if key != NUMBERED_KEY && key != TOC_KEY {
return Err(format!(
"Invalid default option ‘{key}’ of heading command ‘\\{}’: default \
options must be ‘{NUMBERED_KEY}’ or ‘{TOC_KEY}’",
command.name
));
}
if boolean(value).is_none() {
return Err(format!(
"Invalid default option ‘{key}={value}’ of heading command ‘\\{}’: the \
value must be ‘true’ or ‘false’",
command.name
));
}
}
}
Ok(())
}
pub fn digest_bytes(&self) -> Vec<u8> {
let mut out = Vec::new();
push_len(&mut out, self.headings.len());
for kind in &self.headings {
push_text(&mut out, kind.name.as_str());
out.push(kind.level);
push_opt_text(&mut out, kind.counter.as_ref().map(|name| name.as_str()));
push_opt_text(&mut out, kind.style.as_ref().map(|name| name.as_str()));
match &kind.within {
None => out.push(0),
Some(within) => {
out.push(1);
within.digest_into(&mut out);
}
}
match &kind.number_format {
NumberTemplate::Formats(text) => {
out.push(0);
push_text(&mut out, text);
}
NumberTemplate::Initial(text) => {
out.push(1);
push_text(&mut out, text);
}
}
push_text(&mut out, &kind.title_number_format);
out.push(u8::from(kind.skip_toc));
out.push(u8::from(kind.run_in));
push_text(&mut out, kind.ref_kind.as_str());
push_len(&mut out, kind.label_types.len());
for label in &kind.label_types {
push_text(&mut out, label);
}
push_text(&mut out, &kind.anchor_prefix);
}
push_len(&mut out, self.commands.len());
for command in &self.commands {
push_text(&mut out, &command.name);
push_text(&mut out, command.heading.as_str());
push_len(&mut out, command.defaults.len());
for (key, value) in &command.defaults {
push_text(&mut out, key);
push_text(&mut out, value);
}
}
match self.numbering {
HeadingNumbering::NothingNumbered => out.push(0),
HeadingNumbering::AllNumbered => out.push(1),
HeadingNumbering::UpToDepth(depth) => {
out.push(2);
out.push(depth);
}
}
out
}
}
fn push_len(out: &mut Vec<u8>, len: usize) {
out.extend_from_slice(&(len as u64).to_le_bytes());
}
fn push_text(out: &mut Vec<u8>, text: &str) {
push_len(out, text.len());
out.extend_from_slice(text.as_bytes());
}
fn push_opt_text(out: &mut Vec<u8>, text: Option<&str>) {
match text {
None => out.push(0),
Some(text) => {
out.push(1);
push_text(out, text);
}
}
}
impl Hash for HeadingsConfig {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(&self.digest_bytes());
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeadingElement {
pub decl: HeadingDecl,
pub commands: Vec<HeadingCommand>,
pub numbered: bool,
}
impl HeadingElement {
pub fn command_of(&self, node: &NodeRef<'_, Flm>) -> Option<&HeadingCommand> {
let name = node.name()?;
self.commands.iter().find(|command| command.name == name)
}
pub fn occurrence(&self, node: &NodeRef<'_, Flm>) -> HeadingOccurrence {
heading_options(node, self.command_of(node))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HeadingOccurrence {
pub numbered: bool,
pub toc: bool,
}
pub fn starred(node: &NodeRef<'_, Flm>) -> bool {
node.arguments()
.and_then(|args| args.get_named(STAR_ARG))
.is_some_and(|arg| arg.is_provided())
}
pub fn heading_options(
node: &NodeRef<'_, Flm>,
command: Option<&HeadingCommand>,
) -> HeadingOccurrence {
read_options(node, command).0
}
pub fn heading_alt<'t>(node: &NodeRef<'t, Flm>) -> Option<Vec<WrittenPiece<'t>>> {
let content = node.argument_content_nodes_named(OPTIONS_ARG).ok().flatten()?;
let keyvals = parse_keyval_drop_annotations(content).ok()?;
let entry = keyvals.iter().filter(|entry| entry.key() == ALT_KEY && entry.value().is_some()).last()?;
let pieces = key_value_pieces(&content, entry.value()?);
match pieces.as_slice() {
[WrittenPiece::Node(group)] if group.is_group() => {
Some(key_value_pieces(&group.children(), group.children()))
}
_ => Some(pieces),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum OptionProblem {
NotImplemented(String),
MissingValue(String),
Unknown(String),
BadValue(String, String),
Unreadable,
Placeholder,
}
fn boolean(value: &str) -> Option<bool> {
match value {
"true" => Some(true),
"false" => Some(false),
_ => None,
}
}
fn apply(occurrence: &mut HeadingOccurrence, key: &str, value: bool) {
if key == NUMBERED_KEY {
occurrence.numbered = value;
} else if key == TOC_KEY {
occurrence.toc = value;
}
}
fn read_options(
node: &NodeRef<'_, Flm>,
command: Option<&HeadingCommand>,
) -> (HeadingOccurrence, Vec<OptionProblem>) {
let mut occurrence = HeadingOccurrence { numbered: true, toc: true };
let mut problems = Vec::new();
for (key, value) in command.map(|command| command.defaults.as_slice()).unwrap_or_default() {
if let Some(value) = boolean(value) {
apply(&mut occurrence, key, value);
}
}
if starred(node) {
apply(&mut occurrence, NUMBERED_KEY, false);
}
let Ok(Some(content)) = node.argument_content_nodes_named(OPTIONS_ARG) else {
return (occurrence, problems);
};
let Ok(keyvals) = parse_keyval_drop_annotations(content) else {
problems.push(OptionProblem::Unreadable);
return (occurrence, problems);
};
for entry in keyvals.iter() {
let key = entry.key();
if key.is_empty() {
continue;
}
if RESERVED_KEYS.contains(&key) {
problems.push(OptionProblem::NotImplemented(key.to_string()));
continue;
}
if key == ALT_KEY {
if entry.value().is_none() {
problems.push(OptionProblem::MissingValue(key.to_string()));
}
continue;
}
if key != NUMBERED_KEY && key != TOC_KEY {
problems.push(OptionProblem::Unknown(key.to_string()));
continue;
}
let text = match entry.value_content() {
None => Some(String::from("true")),
Some(value) => match chars_at_lowering(value.iter()) {
Ok(read) => read.ok().map(|text| text.trim_matches(is_space).to_string()),
Err(_) => {
problems.push(OptionProblem::Placeholder);
continue;
}
},
};
match text.as_deref().and_then(boolean) {
Some(value) => apply(&mut occurrence, key, value),
None => problems.push(OptionProblem::BadValue(
key.to_string(),
text.unwrap_or_else(|| String::from("(not plain text)")),
)),
}
}
(occurrence, problems)
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.heading.key-not-implemented",
message = "Unsupported heading option ‘{key}’"
)]
pub struct KeyNotImplemented {
pub key: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.heading.unknown-key",
message = "Unknown heading option ‘{key}’: the heading options are ‘numbered’, ‘toc’ \
and ‘alt’"
)]
pub struct UnknownKey {
pub key: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.heading.bad-value",
message = "Invalid value ‘{value}’ of heading option ‘{key}’: the value must be ‘true’ \
or ‘false’"
)]
pub struct BadValue {
pub key: String,
pub value: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.heading.missing-value",
message = "Missing value for heading option ‘{key}’"
)]
pub struct MissingValue {
pub key: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.heading.unreadable-options",
message = "Invalid heading options: each key must be plain text"
)]
pub struct UnreadableOptions;
fn report_option_problems(
node: &NodeRef<'_, Flm>,
value: &HeadingElement,
lw: &mut dyn Lowerer,
) -> Result<(), LowerError> {
let (_, problems) = read_options(node, value.command_of(node));
if problems.contains(&OptionProblem::Placeholder) {
return Err(LowerError::PlaceholderCharacters);
}
for problem in problems {
let span = node.span().clone();
lw.diagnose(match problem {
OptionProblem::NotImplemented(key) => {
Diagnostic::warning(KeyNotImplemented { key }, span)
}
OptionProblem::MissingValue(key) => Diagnostic::error(MissingValue { key }, span),
OptionProblem::Unknown(key) => Diagnostic::error(UnknownKey { key }, span),
OptionProblem::BadValue(key, value) => {
Diagnostic::error(BadValue { key, value }, span)
}
OptionProblem::Unreadable => Diagnostic::error(UnreadableOptions, span),
OptionProblem::Placeholder => continue,
});
}
Ok(())
}
impl Sectioning for HeadingElement {
fn level(&self, _node: &NodeRef<'_, Flm>) -> u32 {
u32::from(self.decl.level)
}
fn in_toc(&self, node: &NodeRef<'_, Flm>) -> bool {
!self.decl.skip_toc && self.occurrence(node).toc
}
fn toc_title(&self, node: &NodeRef<'_, Flm>) -> Option<ContentRef> {
let Some(alt) = heading_alt(node) else {
return Some(ContentRef::ArgumentNamed(TITLE_ARG.to_string()));
};
let pieces: Vec<ValuePiece<'_, '_>> = alt.iter().map(WrittenPiece::as_value_piece).collect();
on_worker_thread(|| {
copy_pieces_into_value(&pieces, node, ValueContent::Shown, GuardPolicy::StackBudget)
})
.ok()?
.ok()
.map(ContentRef::Synthesized)
}
}
impl Referenceable for HeadingElement {
fn points(&self, node: &NodeRef<'_, Flm>) -> Vec<RefPoint> {
let (labels, malformed) = refs::point_labels(refs::label_uses(node).iter());
let anchor = if labels.is_empty() {
AnchorPolicy::Slug {
prefix: self.decl.anchor_prefix.clone(),
content: ContentRef::ArgumentNamed(TITLE_ARG.to_string()),
}
} else {
AnchorPolicy::FromFirstLabel
};
let numbered = self.numbered && self.occurrence(node).numbered;
let number = if numbered { self.decl.number_source() } else { None };
vec![RefPoint {
kind: self.decl.ref_kind.clone(),
labels,
malformed,
computed: 0,
anchor,
number,
content: Some(ContentRef::ArgumentNamed(TITLE_ARG.to_string())),
accepts: AcceptedRefTypes::these(self.decl.label_types.iter().map(String::as_str)),
}]
}
}
fn block_role(kind: &HeadingDecl) -> BlockRole {
if kind.run_in { BlockRole::BlockDecorator(Placement::Leads) } else { BlockRole::Block }
}
fn kind_docs(kind: &HeadingDecl) -> String {
if kind.docs.is_empty() { format!("A heading of level {}.", kind.level) } else { kind.docs.clone() }
}
fn command_docs(kind: &HeadingDecl) -> String {
format!("Starts a heading of level {}.", kind.level)
}
fn element(kind: &HeadingDecl, commands: Vec<HeadingCommand>, numbered: bool) -> Arc<ElementSpec> {
let value = Arc::new(HeadingElement { decl: kind.clone(), commands, numbered });
Arc::new(
ElementSpec::new(HEADING)
.docs(format!("`{}`: {}", kind.name, kind_docs(kind)))
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(block_role(kind))))
.with::<dyn Sectioning>(Arc::clone(&value) as Arc<dyn Sectioning>)
.with::<dyn Referenceable>(Arc::clone(&value) as Arc<dyn Referenceable>)
.with_value(value),
)
}
pub fn heading_args() -> Vec<ArgDef> {
vec![
ArgDef::named(STAR_ARG, ArgStdKind::Star)
.docs("With a star, the heading is not numbered, as with `numbered=false`."),
ArgDef::named(OPTIONS_ARG, ArgStdKind::KeyVals).docs(
"The options of the heading, as key-value pairs: `numbered=true|false`, \
`toc=true|false`, and `alt={…}` for the title in a table of contents.",
),
ArgDef::mandatory(TITLE_ARG).docs("The heading's title."),
refs::label_fields_arg(),
]
}
#[derive(Debug, Clone)]
pub struct HeadingRule {
titles: Arc<Titles>,
}
impl HeadingRule {
fn number(
&self,
kind: &Name,
point: PointId,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Vec<BuildId>, LowerError> {
let options = FormatOptions::new().without_word().without_delimiters();
let written = {
let Some(counters) = lw.get(COUNTERS)? else { return Ok(Vec::new()) };
if counters.record(point).is_none() {
return Ok(Vec::new());
}
title::title_number(&self.titles, kind, |keys| {
counters
.format_with_keys(point, keys, &options)
.map(|result| result.map_err(|error| error.to_string()))
})?
};
let Some(written) = written else { return Ok(Vec::new()) };
lw.splice(cx, &written)
}
}
impl Lower for HeadingRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let value = element_value::<HeadingElement>(&node)
.ok_or_else(|| LowerError::structure("a heading without its element's data"))?;
report_option_problems(&node, value, lw)?;
let point = PointId { addr: lw.addr(), index: 0 };
let anchor: Option<String> = match lw.get(ANCHORS)? {
None => None,
Some(anchors) => {
let Some(entry) = anchors.lookup(point) else {
let table = CapName::from(ANCHORS.name());
let producer = lw
.producer_of(&table)
.map(|stage| stage.to_string())
.unwrap_or_else(|| "nobody".to_string());
lw.diagnose(Diagnostic::error(
MissingEntry {
table: table.to_string(),
producer,
element: HEADING.to_string(),
},
node.span().clone(),
));
return Err(LowerError::structure("the heading has no anchor entry"));
};
entry.map(String::from)
}
};
self.write(&node, value, point, anchor, cx, lw)
}
}
impl HeadingRule {
fn write(
&self,
node: &NodeRef<'_, Flm>,
value: &HeadingElement,
point: PointId,
anchor: Option<String>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let level = value.decl.level;
let mut body = self.number(&value.decl.name, point, cx, lw)?;
body.extend(lower_arg_named_or_nothing(cx, lw, node, TITLE_ARG)?);
let alt = match heading_alt(node) {
Some(pieces) => Some(lower_written_pieces(cx, lw, &pieces)?),
None => None,
};
let payload = HeadingPayload {
name: value.decl.name.clone(),
level,
in_toc: value.in_toc(node),
anchor,
number: number_text(point, lw)?,
};
lw.require(&Name::from(STYLE));
let element = ElementName::from(if value.decl.run_in {
pres::RUNIN_HEADING
} else {
pres::BLOCK_HEADING
});
let heading = match alt {
None => lw.pres_with(cx, &element, payload, body)?,
Some(alt) => lw.pres_slots_with(
cx,
&element,
payload,
vec![(String::from(pres::BODY_SLOT), body), (String::from(pres::ALT_SLOT), alt)],
)?,
};
if value.decl.run_in {
let title = heading;
let deco = lw.pres_with(
cx,
&ElementName::from(pres::DECO_RUNIN),
DecorationPayload,
vec![title],
)?;
return Ok(Lowering::Emit(vec![deco]));
}
Ok(Lowering::Emit(vec![heading]))
}
}
fn number_text(point: PointId, lw: &mut dyn Lowerer) -> Result<Option<String>, LowerError> {
let options = FormatOptions::new().without_word().without_delimiters();
let Some(counters) = lw.get(COUNTERS)? else { return Ok(None) };
let Some(segments) = counters.format(point, &options) else { return Ok(None) };
let segments = segments.map_err(|error| LowerError::other(error.to_string()))?;
let text = segments
.iter()
.map(|segment| pres::plain_text(segment.content().root().children().iter()))
.collect::<String>();
Ok(Some(text))
}
#[derive(Debug, Default, Clone)]
pub struct Headings {
config: HeadingsConfig,
}
impl Headings {
pub fn new(config: HeadingsConfig) -> Headings {
Headings { config }
}
pub fn config(&self) -> &HeadingsConfig {
&self.config
}
}
impl FlmFeature for Headings {
fn info(&self) -> FeatureInfo {
FeatureInfo::new(FEATURE, "Headings").docs(
"The headings of a document, such as sections and subsections, written with the \
heading commands `\\section` to `\\subparagraph` by default. Each heading kind has \
a level. A heading can be numbered, listed in a table of contents, and referred \
to with a label.",
)
}
fn settings(&self) -> Option<SettingsDecl> {
Some(settings())
}
fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
let owner = b.feature().clone();
self.config
.validate()
.map_err(|detail| BuildError::Feature { feature: owner.clone(), detail })?;
b.peer_argument_role(refs::DEFINED_LABEL_ARG_ROLE)?;
for kind in &self.config.headings {
let commands: Vec<HeadingCommand> =
self.config.commands_of(kind.name.as_str()).cloned().collect();
let names: Vec<String> = commands.iter().map(|command| command.name.clone()).collect();
let (syntax, docs) = if names.is_empty() {
let docs = format!(
"`{}`: {} This heading kind has no heading command; only a program can \
create its headings.",
kind.name,
kind_docs(kind)
);
(SyntaxDef::Synthesized, docs)
} else {
(SyntaxDef::Macro { args: heading_args() }, command_docs(kind))
};
b.element(
ElementDef::new(
owner.clone(),
names,
syntax,
element(kind, commands, self.config.numbers(kind)),
)
.docs(docs),
)?;
}
b.peer_table::<refs::Anchors>(
ANCHORS.name(),
"the anchors table of the `refs` feature, from which the lowering rule of \
headings reads the anchor of each heading",
)?;
b.peer_table::<Counters>(
COUNTERS.name(),
"the counter table of the `numbering` feature, from which the lowering rule of \
headings reads the number of each heading",
)?;
numbers::declare(b, &self.config)?;
let number_element = title::number_element();
b.element(
ElementDef::new(
owner.clone(),
Vec::<&str>::new(),
SyntaxDef::Synthesized,
Arc::clone(&number_element),
)
.docs(
"The number of a heading, placed in its title where the heading title template \
of the heading kind contains `#{number}`. This element cannot be written in a \
document; the lowering rule of the heading inserts it.",
),
)?;
b.element_type_text(
HEADING,
"A heading that starts a part of the document, such as a section or a subsection. \
A heading has the level of its heading kind, and it can be numbered.",
)?;
b.element_type_text(
title::NUMBER_ELEMENT,
"The number of a heading, placed in its title where the heading title template of \
the heading kind contains `#{number}`.",
)?;
b.lowering_rule(
LoweringRule::new(
title::NUMBER_RULE,
title::NUMBER_ELEMENT,
LoweringDecl::new().produces(pres::SPAN),
Arc::new(NumberRule),
DefaultMark::Everywhere,
)
.docs(
"the number of a heading lowers to a `flm.pres.span` node with the role \
`flm.heading.number` that contains the number",
),
)?;
let titles = Arc::new(Titles::new(
self.config
.headings
.iter()
.map(|kind| (kind.name.clone(), kind.title_number_format.clone()))
.collect(),
number_element,
));
b.late_init(Arc::new(CompileTitles { titles: Arc::clone(&titles) }))?;
let mut decl = LoweringDecl::new()
.reads_opt(ANCHORS)
.reads_opt(COUNTERS)
.produces(pres::BLOCK_HEADING);
if self.config.headings.iter().any(|kind| kind.run_in) {
decl = decl.produces(pres::DECO_RUNIN).produces(pres::RUNIN_HEADING);
}
b.lowering_rule(
LoweringRule::new(
RULE,
HEADING,
decl,
Arc::new(HeadingRule { titles }),
DefaultMark::Everywhere,
)
.docs(
"a heading lowers to a `flm.pres.block-heading` node that contains the number of \
the heading, if the heading is numbered, followed by the title; a run-in \
heading lowers to a `flm.pres.deco.runin` decoration that contains a \
`flm.pres.runin-heading` node with the same content",
),
)?;
b.style_def(stylesheet())?;
b.digest_input(&self.config.digest_bytes())?;
latex::register(b)?;
latex_rendered::register(b)?;
Ok(())
}
}
pub fn feature() -> Arc<dyn FlmFeature> {
Arc::new(Headings::default())
}
impl named::NamedEntry for HeadingDecl {
fn read_entry(name: &str, data: serde_json::Value) -> Result<HeadingDecl, String> {
let level = named::required(name, &data, "level")?;
let mut kind: HeadingDecl = named::read_over(&HeadingDecl::new(name, level), "name", name, data)?;
let docs = std::mem::take(&mut kind.docs);
Ok(kind.docs(docs))
}
}
impl named::NamedEntry for HeadingCommand {
fn read_entry(name: &str, data: serde_json::Value) -> Result<HeadingCommand, String> {
named::read_with_name("name", name, data)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_heading_value_is_a_block_carrying_its_declaration_and_aspects() {
let config = HeadingsConfig::new();
let kind = config.heading("subsection").expect("declared");
let element = element(kind, config.commands_of("subsection").cloned().collect(), true);
assert_eq!(element.name, HEADING);
let value = element.value_as::<HeadingElement>().expect("valued");
assert_eq!(value.decl.level, 2);
assert!(value.numbered);
assert_eq!(value.commands.len(), 1);
assert!(element.has_aspect::<dyn Sectioning>());
assert!(element.has_aspect::<dyn Referenceable>());
}
#[test]
fn a_run_in_kind_is_a_leading_decorator_and_every_other_kind_a_block() {
let config = HeadingsConfig::new().run_in_levels([4]);
let role = |name: &str| block_role(config.heading(name).expect("declared"));
assert_eq!(role("paragraph"), BlockRole::BlockDecorator(Placement::Leads));
assert_eq!(role("subsubsection"), BlockRole::Block);
let shipped = HeadingsConfig::new();
assert_eq!(block_role(shipped.heading("paragraph").expect("declared")), BlockRole::Block);
}
#[test]
fn the_digest_bytes_change_with_every_field_but_the_documentation_texts() {
let bytes = |config: &HeadingsConfig| config.digest_bytes();
let shipped = bytes(&HeadingsConfig::new());
assert_eq!(shipped, bytes(&HeadingsConfig::new()));
assert_ne!(shipped, bytes(&HeadingsConfig::new().run_in_levels([4])));
let edit = |f: fn(HeadingDecl) -> HeadingDecl| {
let mut config = HeadingsConfig::new();
config.headings[0] = f(config.headings[0].clone());
bytes(&config)
};
for changed in [
edit(|kind| HeadingDecl { level: 7, ..kind }),
edit(|kind| kind.counter("other")),
edit(|kind| kind.no_counter()),
edit(|kind| kind.style("other.style")),
edit(|kind| kind.within(Within::parent("part"))),
edit(|kind| kind.within(Within::parents(["part"]))),
edit(|kind| kind.within(Within::parent_set("part"))),
edit(|kind| kind.within(Within::parent("part").no_restart())),
edit(|kind| kind.number_format(NumberTemplate::initial("1"))),
edit(|kind| kind.title_number_format("#{number} ")),
edit(|kind| kind.skip_toc(true)),
edit(|kind| kind.run_in(true)),
edit(|kind| kind.ref_kind("chapter")),
edit(|kind| kind.label_types(["sec"])),
edit(|kind| kind.anchor_prefix("s")),
] {
assert_ne!(shipped, changed);
}
assert_eq!(shipped, edit(|kind| HeadingDecl { docs: String::from("Other."), ..kind }));
let with_default =
HeadingsConfig::new().command(HeadingCommand::new("q", "section").default_value("toc", "false"));
let with_other_default =
HeadingsConfig::new().command(HeadingCommand::new("q", "section").default_value("toc", "true"));
assert_ne!(bytes(&with_default), bytes(&with_other_default));
let depths = [
HeadingNumbering::NothingNumbered,
HeadingNumbering::AllNumbered,
HeadingNumbering::UpToDepth(1),
HeadingNumbering::UpToDepth(2),
];
for (index, depth) in depths.iter().enumerate() {
for other in &depths[index + 1..] {
assert_ne!(
bytes(&HeadingsConfig::new().numbering(*depth)),
bytes(&HeadingsConfig::new().numbering(*other))
);
}
}
}
#[test]
fn the_depth_numbers_the_kinds_with_a_counter_it_admits() {
let config = HeadingsConfig::new();
let numbered = |config: &HeadingsConfig| {
config
.headings
.iter()
.filter(|kind| config.numbers(kind))
.map(|kind| kind.name.to_string())
.collect::<Vec<_>>()
};
assert!(numbered(&config).is_empty());
assert_eq!(numbered(&config.clone().numbering(HeadingNumbering::UpToDepth(2))), ["section", "subsection"]);
assert_eq!(numbered(&config.clone().numbering(HeadingNumbering::AllNumbered)).len(), 5);
let mut kinds = config.headings.clone();
kinds.push(HeadingDecl::new("aside", 1).no_counter());
let with_aside = config.headings(kinds).numbering(HeadingNumbering::AllNumbered);
assert!(!with_aside.numbers(with_aside.heading("aside").expect("declared")));
assert_eq!(with_aside.numbering, HeadingNumbering::AllNumbered);
}
#[test]
fn the_shipped_kinds_run_from_section_to_subparagraph() {
let config = HeadingsConfig::new();
let kinds: Vec<(&str, u8)> =
config.headings.iter().map(|kind| (kind.name.as_str(), kind.level)).collect();
assert_eq!(
kinds,
[
("section", 1),
("subsection", 2),
("subsubsection", 3),
("paragraph", 4),
("subparagraph", 5)
]
);
let commands: Vec<&str> =
config.commands.iter().map(|command| command.name.as_str()).collect();
assert_eq!(commands, ["section", "subsection", "subsubsection", "paragraph", "subparagraph"]);
assert!(config.commands.iter().all(|command| command.defaults.is_empty()));
assert_eq!(config.validate(), Ok(()));
}
#[test]
fn a_configuration_that_clashes_is_refused() {
let refused = |config: HeadingsConfig| config.validate().is_err();
assert!(refused(HeadingsConfig::new().command(HeadingCommand::new("x", "nokind"))));
let mut kinds = HeadingsConfig::new().headings;
kinds.push(HeadingDecl::new("section", 1));
assert!(refused(HeadingsConfig::new().headings(kinds)));
let twice = HeadingsConfig::new().command(HeadingCommand::new("section", "section"));
assert!(refused(twice));
let mut kinds = HeadingsConfig::new().headings;
kinds.push(HeadingDecl::new("appendix", 1).counter("flm.headings.section"));
assert!(refused(HeadingsConfig::new().headings(kinds)));
let mut kinds = HeadingsConfig::new().headings;
kinds.push(HeadingDecl::new("appendix", 1).style("flm.headings.style.section"));
assert!(refused(HeadingsConfig::new().headings(kinds)));
let bad_default = HeadingsConfig::new()
.command(HeadingCommand::new("q", "section").default_value("alt", "x"));
assert!(refused(bad_default));
let bad_value = HeadingsConfig::new()
.command(HeadingCommand::new("q", "section").default_value("toc", "maybe"));
assert!(refused(bad_value));
let mut kinds = HeadingsConfig::new().headings;
kinds.push(HeadingDecl::new("part", 0));
let part = HeadingsConfig::new().headings(kinds);
assert_eq!(part.validate(), Ok(()), "a kind of level 0 is accepted");
let mut kinds = HeadingsConfig::new().headings;
kinds.push(HeadingDecl::new("orphan", 2));
let commands = HeadingsConfig::new().commands;
let orphan = HeadingsConfig::new().headings(kinds).commands(commands);
assert_eq!(orphan.validate(), Ok(()), "a kind no command writes is accepted");
}
}