flm_core/stdlib/features/textstyles/mod.rs
1//! The `textstyles` feature: the inline formatting commands `\emph`, `\textbf`,
2//! `\textit` and `\texttt`.
3//!
4//! The guide to the language describes these commands for authors
5//! ([inline formatting](crate::guide::language_syntax#inline-formatting)).
6//!
7//! # What an author writes
8//!
9//! Each command takes one mandatory argument, its content, and marks that content
10//! with one inline style: `\emph{…}` is semantic emphasis, `\textbf{…}` bold
11//! weight, `\textit{…}` italic shape and `\texttt{…}` a monospaced face. The
12//! content is ordinary document content (text, references, mathematics, other
13//! formatting commands). A command is inline: it is part of the paragraph it is
14//! written in and keeps the whitespace around it. The commands are declared in
15//! text mode only; inside mathematics, the [`math`](crate::stdlib::features::math)
16//! feature declares its own `\textbf`, `\textit` and `\texttt` (see
17//! [`math::text`](crate::stdlib::features::math::text)).
18//!
19//! # What the feature registers
20//!
21//! The `textstyles` feature ([`TextStyles`], a [`FlmFeature`]) registers:
22//!
23//! - the element type [`TEXT_STYLE`] (`flm.textstyle`): the four commands form
24//! one family, declared as one element type with one element value per command
25//! ([elements and
26//! aspects](crate::guide::concepts_overview#elements-and-aspects)): each
27//! element value carries a [`TextStyleElement`], whose [`TextStyle`] says which
28//! style the command applies;
29//! - the lowering rule [`RULE`] (`flm.textstyle.lower.default`), the default on
30//! every backend, and the recomposition rule of [`latex`] for the
31//! `latex-recomposed` backend.
32//!
33//! [`TextStyle`] is the feature's own list of styles. The presentation elements
34//! use a separate list, [`SpanStyle`]; the lowering rule converts one into the
35//! other ([`TextStyle::span_style`]), so that the element never refers to a
36//! presentation type.
37//!
38//! # What a formatting command becomes on each backend
39//!
40//! - **Default rule** ([`RULE`], used by the `text` and `html` backends): the
41//! rule stages (builds into the lowered tree; see
42//! [`Lowerer`]) a
43//! [`flm.pres.span`](crate::stdlib::backends::pres::SPAN) node whose payload
44//! carries the [`SpanStyle`], over the argument lowered through the rules.
45//! - **`text` backend**: it prints the span's content; the style has no form in
46//! plain text and is left out.
47//! - **`html` backend**: it writes the span as the [HTML
48//! contract](crate::guide::rendering#the-html-contract) states for
49//! `flm.pres.span` ([`CONVENTIONS`](crate::stdlib::backends::html::CONVENTIONS)):
50//! an `<em>`, `<strong>`, `<i>` or `<code>` element by the style.
51//! - **`latex-recomposed` backend**: the rule of [`latex`] writes the command
52//! back as the LaTeX macro of the same name.
53//!
54//! A backend that has no way to show a style writes the content without it.
55//!
56//! # Map of the module
57//!
58//! - [`TextStyles`] — the feature; [`feature`] returns it for a package entry.
59//! - [`TEXT_STYLE`], [`TextStyle`], [`TextStyleElement`] — the element type and
60//! the data of each element value.
61//! - [`RULE`], [`TextStyleRule`] — the default lowering rule and its body.
62//! - [`latex`] — the recomposition rule for the `latex-recomposed` backend.
63//! - [`literals`](crate::stdlib::features::literals) — the sibling feature that
64//! declares the commands standing for one character.
65
66// The four commands are one element type because rules and aspects are chosen
67// per element: they share one implementation, and the value's style is the one
68// difference. The command written for a value is what tells the four apart in a
69// dump, since the element type is one.
70
71pub mod latex;
72
73use std::sync::Arc;
74
75use techy::core::node::NodeRef;
76
77use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
78use crate::model::element::{ElementSpec, element_value};
79use crate::core::lowering::{
80 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
81};
82use crate::model::names::ElementName;
83use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
84use crate::lang::Flm;
85use crate::lang::mint::{ArgDef, ElementDef, SyntaxDef};
86use crate::stdlib::backends::lowering::lower_arg_or_nothing;
87use crate::stdlib::backends::pres::{self, SpanPayload, SpanStyle};
88
89/// The feature's registered name, `textstyles`.
90pub const FEATURE: &str = "textstyles";
91
92/// The name of the element type of the four formatting commands,
93/// `flm.textstyle`. The data of each element value is a
94/// [`TextStyleElement`].
95pub const TEXT_STYLE: &str = "flm.textstyle";
96
97/// The name of the default lowering rule of [`TEXT_STYLE`] on every backend,
98/// `flm.textstyle.lower.default`, whose body is [`TextStyleRule`].
99pub const RULE: &str = "flm.textstyle.lower.default";
100
101/// The inline style a formatting command applies: one value per command of the
102/// `textstyles` feature.
103///
104/// [`TextStyle::command`] gives the command's name and
105/// [`TextStyle::span_style`] the [`SpanStyle`] the lowering rule writes into the
106/// span it stages.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
108pub enum TextStyle {
109 /// Semantic emphasis (`\emph`).
110 Emphasis,
111 /// Bold weight (`\textbf`).
112 Bold,
113 /// Italic shape (`\textit`).
114 Italic,
115 /// A monospaced face (`\texttt`).
116 Monospace,
117}
118
119impl TextStyle {
120 /// Every style, in the order the feature registers the commands in.
121 pub const ALL: [TextStyle; 4] =
122 [TextStyle::Emphasis, TextStyle::Bold, TextStyle::Italic, TextStyle::Monospace];
123
124 /// The command name written for this style, without the leading backslash
125 /// (`"emph"`, `"textbf"`, `"textit"`, `"texttt"`).
126 pub fn command(self) -> &'static str {
127 match self {
128 TextStyle::Emphasis => "emph",
129 TextStyle::Bold => "textbf",
130 TextStyle::Italic => "textit",
131 TextStyle::Monospace => "texttt",
132 }
133 }
134
135 /// The [`SpanStyle`] of the presentation elements that corresponds to this
136 /// style: what [`TextStyleRule`] writes into the payload of the span it
137 /// stages.
138 pub fn span_style(self) -> SpanStyle {
139 match self {
140 TextStyle::Emphasis => SpanStyle::Emphasis,
141 TextStyle::Bold => SpanStyle::Bold,
142 TextStyle::Italic => SpanStyle::Italic,
143 TextStyle::Monospace => SpanStyle::Monospace,
144 }
145 }
146}
147
148/// The data of one element value of `flm.textstyle`: the style that the
149/// command applies.
150///
151/// A lowering rule or a stage reads it from a node with [`element_value`].
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153pub struct TextStyleElement {
154 /// The style the command applies.
155 pub style: TextStyle,
156}
157
158/// The element value of one formatting command: a `flm.textstyle` element
159/// carrying `style` and the default inline block role.
160fn element(style: TextStyle) -> Arc<ElementSpec> {
161 Arc::new(
162 ElementSpec::new(TEXT_STYLE)
163 .docs(match style {
164 TextStyle::Emphasis => "Semantic emphasis of its content.",
165 TextStyle::Bold => "Its content in bold weight.",
166 TextStyle::Italic => "Its content in italic shape.",
167 TextStyle::Monospace => "Its content in a monospaced face.",
168 })
169 .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
170 .with_value(Arc::new(TextStyleElement { style })),
171 )
172}
173
174/// The body of [`RULE`]: it stages a
175/// [`flm.pres.span`](crate::stdlib::backends::pres::SPAN) node whose payload
176/// carries the command's [`SpanStyle`] ([`TextStyle::span_style`]), over the
177/// command's argument lowered through the rules.
178///
179/// When the argument is missing (a parse recovery left it absent and the
180/// parse reported it), the span is empty and nothing more is reported.
181///
182/// The rule returns a [`LowerError`] when the node carries no
183/// [`TextStyleElement`], or when the argument or the span could not be
184/// lowered or staged.
185#[derive(Debug, Default)]
186pub struct TextStyleRule;
187
188impl Lower for TextStyleRule {
189 fn lower(
190 &self,
191 node: NodeRef<'_, Flm>,
192 cx: &mut LowerCx<'_>,
193 lw: &mut dyn Lowerer,
194 ) -> Result<Lowering, LowerError> {
195 let value = element_value::<TextStyleElement>(&node)
196 .ok_or_else(|| LowerError::structure("a text-style node without its value"))?;
197 // An argument a parse recovery left absent lowers to nothing: an empty
198 // span, and no second report of what the parse already reported.
199 let body = lower_arg_or_nothing(cx, lw, &node, 0)?;
200 let payload =
201 SpanPayload { style: Some(value.style.span_style()), ..SpanPayload::default() };
202 let span = lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)?;
203 Ok(Lowering::Emit(vec![span]))
204 }
205}
206
207/// The `textstyles` feature: it registers the four formatting commands, their
208/// default lowering rule and the recomposition rule of [`latex`]. See the
209/// module documentation.
210#[derive(Debug, Default, Clone, Copy)]
211pub struct TextStyles;
212
213impl FlmFeature for TextStyles {
214 fn info(&self) -> FeatureInfo {
215 FeatureInfo::new(FEATURE, "Text styles").docs(
216 "The inline formatting commands `\\emph`, `\\textbf`, `\\textit` and `\\texttt`: \
217 four values of the element type `flm.textstyle`, each lowered to a \
218 `flm.pres.span` node that carries its style.",
219 )
220 }
221
222 fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
223 let owner = b.feature().clone();
224 for style in TextStyle::ALL {
225 b.element(
226 ElementDef::new(
227 owner.clone(),
228 [style.command()],
229 SyntaxDef::Macro { args: vec![ArgDef::mandatory("content")] },
230 element(style),
231 )
232 .docs(match style {
233 TextStyle::Emphasis => "Emphasizes its content.",
234 TextStyle::Bold => "Sets its content in bold weight.",
235 TextStyle::Italic => "Sets its content in italic shape.",
236 TextStyle::Monospace => "Sets its content in a monospaced face.",
237 }),
238 )?;
239 }
240 b.element_type_text(
241 TEXT_STYLE,
242 "Inline content set in a text style: emphasis, bold weight, italic shape or a \
243 monospaced face.",
244 )?;
245 b.lowering_rule(
246 LoweringRule::new(
247 RULE,
248 TEXT_STYLE,
249 LoweringDecl::new().produces(pres::SPAN),
250 Arc::new(TextStyleRule),
251 DefaultMark::Everywhere,
252 )
253 .docs("a formatting command lowers to `flm.pres.span` carrying its style"),
254 )?;
255 latex::register(b)?;
256 Ok(())
257 }
258}
259
260/// The [`TextStyles`] feature as a shared value, ready to be listed in a
261/// package entry.
262pub fn feature() -> Arc<dyn FlmFeature> {
263 Arc::new(TextStyles)
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269
270 #[test]
271 fn every_style_names_its_command_and_span_style() {
272 assert_eq!(TextStyle::Emphasis.command(), "emph");
273 assert_eq!(TextStyle::Monospace.span_style(), SpanStyle::Monospace);
274 assert_eq!(TextStyle::ALL.len(), 4);
275 }
276
277 #[test]
278 fn an_element_value_carries_its_style_and_the_inline_role() {
279 let element = element(TextStyle::Bold);
280 assert_eq!(element.name, TEXT_STYLE);
281 assert_eq!(element.value_as::<TextStyleElement>().map(|v| v.style), Some(TextStyle::Bold));
282 assert!(element.has_aspect::<dyn BlockRoleAspect>());
283 }
284}