flm_core/lang/text.rs
1//! Reading the characters of content: the plain text of a run of nodes or of a
2//! synthesized value ([`plain_text_of`], [`plain_text`]), the characters of an
3//! argument that holds only characters, read by segments ([`read_chars`],
4//! [`chars_text`]), and the whitespace of FLM text.
5//!
6//! # Plain text
7//!
8//! The **plain text** of content is the characters of its text nodes, in
9//! document order. Everything else (comments, delimiters, the text of a macro or
10//! environment command) is dropped, and nothing is put in its place. Content
11//! that an element declares as not part of the text around it
12//! ([`ApartFromText`](crate::model::aspects::ApartFromText)), such as a
13//! footnote's words inside a heading's title, is dropped too. Use the plain
14//! text where the words of some content are needed rather than a rendering of
15//! it: the text of a reference point's content when a table is printed for
16//! inspection (the [projection](crate::dump::project) of the table), or a
17//! label compared with the text it refers to. [`plain_text`] reads the plain
18//! text of a [synthesized
19//! value](crate::guide::concepts_overview#synthesized-values), a small tree
20//! held outside the document, which [`copy`](super::copy) builds.
21//!
22//! # Reading an argument as characters
23//!
24//! A label, a reference target and an address are written in arguments whose
25//! content is characters: the characters-only group of `\label{…}` and
26//! `\ref{…}`, verbatim content, or an ordinary argument that a command reads as
27//! characters. [`read_chars`] is the function that reads such content. Where
28//! [`plain_text_of`] skips everything that is not text, [`read_chars`] refuses it:
29//! content holding a command (`\ref{\emph{x}}`, after a user definition put
30//! `\emph{x}` into the target) or mathematics has no characters to read, and
31//! [`read_chars`] returns [`NotCharacters`].
32//!
33//! One kind of node is neither characters nor refused: the **placeholder** of a
34//! [user definition](crate::lang::rewrites::userdefs::Definition)'s template
35//! (`#1`, `#{name}`, `#[…]{ref}`). A template that is lowered unexpanded (the
36//! template of a [kept definition](crate::stdlib::features::userdefs::kept),
37//! which the [recomposed LaTeX
38//! backend](crate::stdlib::backends::latex_recomposed) writes back as a LaTeX
39//! definition) still holds its placeholders when a label or a target inside it
40//! is read. [`read_chars`] therefore returns the content as
41//! [segments](CharsSegment), in order: runs of characters and placeholder
42//! nodes. Each caller decides what a placeholder means:
43//!
44//! - A placeholder stands for characters that are not known yet (each use of
45//! the definition supplies them). A reader of facts about the document (a
46//! label, the target of a reference) therefore reads no label and no target
47//! where one is written; [`CharsContent::text`] and [`chars_text`] return
48//! `None` then.
49//! - A lowering rule, which needs the characters to write them, reads them
50//! through [`chars_at_lowering`](crate::core::lowering::chars_at_lowering).
51//! For a placeholder, that function returns an error
52//! ([`LowerError::PlaceholderCharacters`](crate::core::lowering::LowerError::PlaceholderCharacters))
53//! that the rule passes on to the rule that inserted the template: the
54//! user-definitions feature then expands the use sites of the definition
55//! whose template it was lowering, and the lists feature reports a number
56//! format in a list's own label template.
57//!
58//! Only a template lowered as it stands holds placeholders (on the recomposed
59//! LaTeX backend, the template of a kept definition or a list's own label
60//! template); everywhere else no placeholder remains, and the content is all
61//! characters.
62//!
63//! # Whitespace
64//!
65//! Whitespace in FLM text is the four ASCII whitespace characters: the space,
66//! the tab, the carriage return and the line feed. Every reader of parsed FLM
67//! content (a document, a template) counts whitespace this way: the
68//! block-structure pass, the lowering helpers' blank test
69//! ([`is_blank`](crate::stdlib::backends::lowering::is_blank)), and each
70//! feature's reader where it trims what it reads, splits it at whitespace or
71//! tests whether content is blank. Content is blank when it is text made of
72//! whitespace alone, or a node whose element carries the
73//! [`Whitespace`](crate::model::aspects::Whitespace) aspect, such as `~` and
74//! `\ `. Every other character is a character of the text, the no-break space
75//! U+00A0 typed directly in the text among them.
76//!
77//! The one exception is the key of a `key=value` entry. techy's key-value
78//! reader ([`parse_keyval`](techy::extract::parse_keyval)), through which the
79//! features read such entries, trims each key with [`str::trim`], which removes
80//! every Unicode whitespace character. A no-break space U+00A0 typed at either
81//! end of a key is therefore removed, and the key is read without it; the
82//! entry's value is trimmed by the rule above
83//! ([`key_value_pieces`](crate::lang::copy::key_value_pieces)).
84
85use std::collections::HashSet;
86use std::fmt;
87
88use techy::core::node::{NodeId, NodeKind, NodeRef, NodeTree};
89
90use crate::lang::{Flm, FlmCallableType, FlmGroupType};
91use crate::model::aspects::{apart_from_text_of, is_whitespace_of, ContentRef};
92
93/// Returns the plain text of a run of nodes: the characters of every text node
94/// among the nodes and their descendants, in document order.
95///
96/// Comments, delimiters and the text of commands contribute nothing, and
97/// neither does the content an element declares as apart from the text around
98/// it ([`apart_from_text_of`]), with its descendants. The nodes may belong to
99/// different trees. See the [module documentation](self#plain-text).
100pub fn plain_text_of<'t>(nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>) -> String {
101 text_of(nodes, "")
102}
103
104/// Returns the text of a run of nodes as [`plain_text_of`] reads it, with
105/// `whitespace_node` written for each node whose element is whitespace
106/// ([`is_whitespace_of`]: `~`, `\ `) and that no element set apart.
107pub(crate) fn text_of<'t>(
108 nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>,
109 whitespace_node: &str,
110) -> String {
111 let mut out = String::new();
112 // Document order without recursion: the nodes still to read, the next one
113 // last; the ones an element set apart are passed over whole.
114 let mut pending: Vec<NodeRef<'t, Flm>> = nodes.into_iter().collect();
115 pending.reverse();
116 // Keyed by tree as well as node, since a run may join nodes of two trees.
117 let mut apart: HashSet<(*const NodeTree<Flm>, NodeId)> = HashSet::new();
118 while let Some(node) = pending.pop() {
119 if apart.contains(&key(&node)) {
120 continue;
121 }
122 if is_whitespace_of(&node) {
123 out.push_str(whitespace_node);
124 }
125 if let Some(text) = node.chars() {
126 out.push_str(text);
127 }
128 for content in apart_from_text_of(&node) {
129 // A synthesized tree is no part of this one: nothing to pass over.
130 if matches!(content, ContentRef::Synthesized(_)) {
131 continue;
132 }
133 apart.extend(content.nodes(&node).into_iter().flatten().map(|inner| key(&inner)));
134 }
135 let first = pending.len();
136 pending.extend(node.children().iter());
137 pending[first..].reverse();
138 }
139 out
140}
141
142/// Returns the key by which [`plain_text_of`] identifies a node to skip: its
143/// tree and its place there.
144fn key(node: &NodeRef<'_, Flm>) -> (*const NodeTree<Flm>, NodeId) {
145 (std::ptr::from_ref(node.tree()), node.id())
146}
147
148/// Returns the plain text of a synthesized value's tree: [`plain_text_of`] over
149/// its root.
150pub fn plain_text(tree: &NodeTree<Flm>) -> String {
151 plain_text_of(std::iter::once(tree.root()))
152}
153
154// --- whitespace -----------------------------------------------------------------------
155
156/// Whether `ch` is whitespace in FLM text: the space, the tab, the carriage
157/// return or the line feed (see the [module documentation](self#whitespace)).
158/// Every other character is content, the no-break space U+00A0 among them.
159pub(crate) fn is_space(ch: char) -> bool {
160 matches!(ch, ' ' | '\t' | '\r' | '\n')
161}
162
163/// Whether the byte `byte` of UTF-8 text is whitespace ([`is_space`]); a byte
164/// of a character beyond ASCII never is.
165pub(crate) fn is_space_byte(byte: u8) -> bool {
166 is_space(char::from(byte))
167}
168
169/// Whether `text` is blank: empty, or whitespace ([`is_space`]) alone.
170pub(crate) fn is_blank_text(text: &str) -> bool {
171 text.bytes().all(is_space_byte)
172}
173
174/// Whether `node` is blank: text that is blank ([`is_blank_text`]), or a node
175/// that is whitespace, such as `~` and `\ ` (its element carries the
176/// [`Whitespace`](crate::model::aspects::Whitespace) aspect,
177/// [`is_whitespace_of`]). A comment is not blank: a reader that looks past
178/// comments tests for them itself.
179pub(crate) fn is_blank(node: &NodeRef<'_, Flm>) -> bool {
180 is_whitespace_of(node) || node.chars().is_some_and(is_blank_text)
181}
182
183/// Returns `text` with every run of whitespace ([`is_space`]) made one space
184/// and the whitespace at both ends removed: the rule by which two written
185/// texts are the same however their whitespace is laid out.
186/// [`spelling_identity`](crate::stdlib::backends::pres::spelling_identity)
187/// reads a citation key and a term's identity with it, and
188/// [`Label::parse`](crate::model::aspects::Label::parse) each part of a label.
189pub(crate) fn collapse_whitespace(text: &str) -> String {
190 text.split(is_space).filter(|word| !word.is_empty()).collect::<Vec<_>>().join(" ")
191}
192
193// --- reading an argument as characters ------------------------------------------------
194
195/// One segment of content read as characters by [`read_chars`]: a run of
196/// characters, or a placeholder node of a user definition's template.
197#[derive(Debug, Clone)]
198pub enum CharsSegment<'t> {
199 /// A run of characters: the text of one or more consecutive text nodes,
200 /// joined, without the comments and group delimiters between them.
201 Text(String),
202 /// A placeholder node (`#1`, `#{name}`, `#[…]{ref}`) among the characters,
203 /// in a template that was not expanded: characters that each use of the
204 /// definition supplies, not known yet. The segment holds the node, so that a
205 /// caller can read which argument it refers to.
206 Placeholder(NodeRef<'t, Flm>),
207}
208
209impl CharsSegment<'_> {
210 /// Returns the characters of a [`Text`](Self::Text) segment; `None` for a
211 /// placeholder.
212 pub fn as_text(&self) -> Option<&str> {
213 match self {
214 CharsSegment::Text(text) => Some(text),
215 CharsSegment::Placeholder(_) => None,
216 }
217 }
218}
219
220/// Content read as characters by [`read_chars`]: its [segments](CharsSegment),
221/// in order. Adjacent characters form one segment, so two text segments never
222/// follow each other; empty content has no segment at all.
223///
224/// Read the characters with [`text`](Self::text) when a placeholder makes the
225/// content unusable, or go through the [segments](Self::segments) to handle
226/// placeholders.
227#[derive(Debug, Clone, Default)]
228pub struct CharsContent<'t> {
229 segments: Vec<CharsSegment<'t>>,
230}
231
232impl<'t> CharsContent<'t> {
233 /// Returns the segments, in document order.
234 pub fn segments(&self) -> &[CharsSegment<'t>] {
235 &self.segments
236 }
237
238 /// Returns the segments, consuming the content.
239 pub fn into_segments(self) -> Vec<CharsSegment<'t>> {
240 self.segments
241 }
242
243 /// Returns whether a placeholder is among the segments.
244 pub fn has_placeholder(&self) -> bool {
245 self.segments.iter().any(|segment| matches!(segment, CharsSegment::Placeholder(_)))
246 }
247
248 /// Returns the characters when no placeholder is among them (the empty
249 /// string for empty content), and `None` when one is.
250 ///
251 /// Use it when a placeholder makes the content unusable: a label or a
252 /// target holding a placeholder is not a label and refers to nothing.
253 pub fn text(&self) -> Option<String> {
254 let mut out = String::new();
255 for segment in &self.segments {
256 out.push_str(segment.as_text()?);
257 }
258 Some(out)
259 }
260}
261
262/// The error [`read_chars`] returns for content it cannot read as characters:
263/// the content holds a callable node that is not a placeholder (a command, an
264/// environment, a special character sequence) or a mathematics group, none of
265/// which has characters to read.
266#[derive(Debug, Clone, Copy, PartialEq, Eq)]
267pub struct NotCharacters {
268 /// The first such node, in the tree the content belongs to.
269 pub node: NodeId,
270}
271
272impl fmt::Display for NotCharacters {
273 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274 write!(
275 f,
276 "the content must be plain characters, without a command, an environment, a \
277 special character sequence or mathematics"
278 )
279 }
280}
281
282impl std::error::Error for NotCharacters {}
283
284/// Reads a run of nodes as characters and returns them by segments: text nodes
285/// give their characters, comments nothing, groups other than mathematics their
286/// children's characters without the delimiters, and a placeholder node of a
287/// user definition's template becomes a segment of its own (see the [module
288/// documentation](self#reading-an-argument-as-characters)).
289///
290/// Whitespace is kept as written; the caller trims what it needs to. The input
291/// is any run of sibling nodes, typically an argument's content
292/// ([`NodeRef::argument_content_nodes`]). A caller that has no use for
293/// placeholders can call [`chars_text`] instead.
294///
295/// # Errors
296///
297/// [`NotCharacters`] when the content holds, at any depth, a callable node that
298/// is not a placeholder, or a mathematics group.
299///
300/// # Examples
301///
302/// ```
303/// use std::sync::Arc;
304/// use flm_core::core::registry::{PackageEntry, RegistryBuilder, RegistryInputs};
305/// use flm_core::lang::text::read_chars;
306/// use flm_core::lang::{parse_fragment, FlmOrigin, FlmSource, ParseOptions};
307/// use flm_core::model::doc::FragmentLayout;
308/// use flm_core::stdlib::{self, StdlibConfig};
309///
310/// let mut builder = RegistryBuilder::new();
311/// builder.use_package(stdlib::add_features(PackageEntry::new("std"), StdlibConfig::new()));
312/// builder.use_package(flm_core::math_passthrough::package());
313/// let registry = builder.build(&RegistryInputs::new())?;
314/// let source = FlmSource::new(r"See \ref{sec:{intro}}.");
315/// let fragment = parse_fragment(
316/// registry.lang(),
317/// Arc::new(source.with_origin(FlmOrigin::none())),
318/// FragmentLayout::default(),
319/// &ParseOptions::default(),
320/// )?;
321/// let reference = fragment.tree().root().descendants()
322/// .find(|node| node.name() == Some("ref"))
323/// .expect("the reference");
324/// let target = reference.argument_content_nodes_named("target")?.expect("written");
325/// let content = read_chars(target.iter())?;
326/// assert_eq!(content.text().as_deref(), Some("sec:intro"));
327/// assert!(!content.has_placeholder());
328/// # Ok::<(), Box<dyn std::error::Error>>(())
329/// ```
330pub fn read_chars<'t>(
331 nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>,
332) -> Result<CharsContent<'t>, NotCharacters> {
333 let mut segments: Vec<CharsSegment<'t>> = Vec::new();
334 // Document order without recursion, as in `plain_text_of`.
335 let mut pending: Vec<NodeRef<'t, Flm>> = nodes.into_iter().collect();
336 pending.reverse();
337 while let Some(node) = pending.pop() {
338 match node.kind() {
339 NodeKind::Chars { .. } => {
340 let text = node.chars().unwrap_or_default();
341 match segments.last_mut() {
342 Some(CharsSegment::Text(run)) => run.push_str(text),
343 _ => segments.push(CharsSegment::Text(text.to_string())),
344 }
345 }
346 NodeKind::Comment(_) => {}
347 NodeKind::Group(_) if matches!(node.group_type(), Some(FlmGroupType::Math(_))) => {
348 return Err(NotCharacters { node: node.id() });
349 }
350 NodeKind::Group(_) | NodeKind::List => {
351 let first = pending.len();
352 pending.extend(node.children().iter());
353 pending[first..].reverse();
354 }
355 NodeKind::Callable(_) => {
356 if node.callable_type() != Some(FlmCallableType::Placeholder) {
357 return Err(NotCharacters { node: node.id() });
358 }
359 segments.push(CharsSegment::Placeholder(node));
360 }
361 }
362 }
363 Ok(CharsContent { segments })
364}
365
366/// Returns the characters of a run of nodes when it holds only characters, and
367/// `None` when it holds a command, mathematics or a placeholder. This is
368/// [`read_chars`] followed by [`CharsContent::text`].
369///
370/// Use it when a placeholder makes the content unusable: a label, a target or
371/// an address holding a placeholder is treated as absent.
372pub fn chars_text<'t>(nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>) -> Option<String> {
373 read_chars(nodes).ok()?.text()
374}