Skip to main content

flm_core/stdlib/features/refs/
content.rs

1//! Two jobs of the [`refs`](super) feature: copying the content a reference
2//! shows out of the frozen tree, and encoding the anchor of a reference
3//! point.
4//!
5//! **Copying content.** The content a reference to a point shows (a heading's
6//! title, for instance) is stored as a [synthesized
7//! value](crate::guide::concepts_overview#synthesized-values), a small tree
8//! held in a table rather than in the document. [`ContentRef::nodes`] finds
9//! the nodes a content reference designates on the node that carries it,
10//! [`value_of`] copies a run of nodes into a synthesized value through the
11//! language's copy function
12//! ([`crate::lang::copy::copy_run_into_value`]), and [`content_value`] does
13//! both in one call. The language's [`crate::lang::text`] module reads the
14//! characters of such a tree.
15//!
16//! **Encoding anchors.** An anchor is the identifier a link points at for a
17//! reference point, computed once by the anchors stage ([`ANCHORS`](super::ANCHORS)
18//! defines the term). [`encode_anchor`] encodes one text for an anchor, and
19//! four functions build an anchor from it: [`label_anchor`] from a label,
20//! [`title_anchor`] from a title, [`auto_anchor`] from a point's position, and
21//! [`value_anchor`] from the number the document gave the point.
22
23use std::sync::Arc;
24
25use techy::core::node::{NodeRef, NodeTree};
26use unicode_normalization::UnicodeNormalization;
27
28use crate::model::aspects::{ContentRef, Label};
29use crate::lang::copy::{ValueContent, copy_run_into_value};
30use crate::lang::guard::GuardPolicy;
31use crate::lang::Flm;
32
33pub use crate::lang::copy::CopyError;
34
35/// Copies `nodes` into a synthesized value under the recursion guard policy
36/// `guard`, as content of the document shown a second time
37/// ([`ValueContent::Shown`]): the content that a reference shows of the point
38/// it designates. `anchor` is a node of the tree that holds `nodes` (usually
39/// the node that carries the point); `nodes` must belong to `anchor`'s tree,
40/// and when `nodes` is empty, the copy's root takes its span and parsing
41/// state from `anchor`. It calls [`copy_run_into_value`].
42///
43/// # Errors
44///
45/// Returns the [`CopyError`] that the copy raises: `guard` refused to descend
46/// further into the run, or the copy could not be built.
47pub fn value_of(
48    nodes: &[NodeRef<'_, Flm>],
49    anchor: &NodeRef<'_, Flm>,
50    guard: GuardPolicy,
51) -> Result<Arc<NodeTree<Flm>>, CopyError> {
52    copy_run_into_value(nodes, anchor, ValueContent::Shown, guard)
53}
54
55/// The synthesized value of the content reference `content` on `node`: the
56/// nodes [`ContentRef::nodes`] designates, copied through [`value_of`];
57/// `Ok(None)` when the reference designates nothing on `node`.
58///
59/// A [`ContentRef::Synthesized`] tree already has the shape of a synthesized
60/// value and is returned unchanged, shared rather than copied, so that the
61/// tree an element built once serves every reference to its points.
62///
63/// # Errors
64///
65/// Returns the [`CopyError`] that [`value_of`] raises for the designated
66/// nodes.
67pub fn content_value(
68    node: &NodeRef<'_, Flm>,
69    content: &ContentRef,
70    guard: GuardPolicy,
71) -> Result<Option<Arc<NodeTree<Flm>>>, CopyError> {
72    if let ContentRef::Synthesized(tree) = content {
73        return Ok(Some(Arc::clone(tree)));
74    }
75    match content.nodes(node) {
76        Some(nodes) => value_of(&nodes, node, guard).map(Some),
77        None => Ok(None),
78    }
79}
80
81/// The FNV-1a 64-bit offset basis, the standard constant of the algorithm the
82/// anchor tag is taken from.
83const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
84
85/// The FNV-1a 64-bit prime, the standard constant of the algorithm.
86const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
87
88/// FNV-1a over 64 bits: start at the offset basis, and for every byte take the
89/// exclusive or with the byte and multiply by the prime, wrapping on overflow.
90/// Written out here rather than taken from a crate, because the tag it
91/// produces is part of the published form of an anchor and must never change.
92fn fnv1a_64(bytes: &[u8]) -> u64 {
93    let mut hash = FNV_OFFSET_BASIS;
94    for byte in bytes {
95        hash ^= u64::from(*byte);
96        hash = hash.wrapping_mul(FNV_PRIME);
97    }
98    hash
99}
100
101/// The anchor tag of `text`: the first six digits of the sixteen lowercase
102/// hexadecimal digits of [`fnv1a_64`] over the text's UTF-8 bytes — that is,
103/// the hash's top twenty-four bits.
104fn anchor_tag(text: &str) -> String {
105    format!("{:06x}", fnv1a_64(text.as_bytes()) >> 40)
106}
107
108/// How many letters [`anchor_letters`] writes.
109const ANCHOR_LETTERS: u32 = 4;
110
111/// The four letters ending a position-derived anchor: the top thirty-two bits
112/// of [`fnv1a_64`] over `text`, reduced modulo twenty-six to the fourth power
113/// and written as four base-twenty-six digits, `a` for zero through `z` for
114/// twenty-five, the most significant digit first.
115///
116/// The top bits are the ones taken, as they are for [`anchor_tag`]: the
117/// multiplication of the hash carries every bit upwards, so the high bits
118/// depend on the whole text.
119fn anchor_letters(text: &str) -> String {
120    let mut value = (fnv1a_64(text.as_bytes()) >> 32) % 26u64.pow(ANCHOR_LETTERS);
121    let mut letters = vec![b'a'; ANCHOR_LETTERS as usize];
122    for slot in letters.iter_mut().rev() {
123        *slot = b'a' + u8::try_from(value % 26).expect("a remainder below twenty-six");
124        value /= 26;
125    }
126    String::from_utf8(letters).expect("ASCII lowercase letters")
127}
128
129/// Whether `ch` is written into an anchor as itself: an ASCII letter, an
130/// ASCII digit, `.` or `-`.
131fn passes_through(ch: char) -> bool {
132    ch.is_ascii_alphanumeric() || ch == '.' || ch == '-'
133}
134
135/// Whether `text` takes the *exact path* of [`encode_anchor`]: it is not
136/// empty, it neither begins nor ends with a hyphen, every character passes
137/// through or is a space, and no space is leading, trailing or doubled.
138fn is_exact(text: &str) -> bool {
139    !text.is_empty()
140        && !text.starts_with('-')
141        && !text.ends_with('-')
142        && !text.starts_with(' ')
143        && !text.ends_with(' ')
144        && !text.contains("  ")
145        && text.chars().all(|ch| passes_through(ch) || ch == ' ')
146}
147
148/// Encodes one text for an anchor (the identifier a link points at; see
149/// [`ANCHORS`](super::ANCHORS)): a label's type, the label after the colon,
150/// or a heading title's plain text.
151///
152/// The encoding depends on the text alone: no document-order counter takes
153/// part, so one text always yields one encoding, in this document and in any
154/// other.
155///
156/// There are two paths.
157///
158/// - The **exact path**, taken when the text holds only ASCII letters, ASCII
159///   digits, `.`, `-` and single spaces (none leading, trailing or doubled),
160///   is not empty and neither begins nor ends with a hyphen: the text is
161///   reproduced character for character, case preserved, with every space
162///   written `_`.
163///   `intro` stays `intro`; `quantum error-correcting code` becomes
164///   `quantum_error-correcting_code`; `main.v2` stays `main.v2`.
165/// - The **tagged path**, taken for every other text: the text is
166///   NFKD-decomposed (a compatibility decomposition, which splits an accented
167///   letter into its base letter and a combining accent), the combining marks
168///   are dropped, and what is left is reduced: an ASCII letter, an ASCII
169///   digit, `.` and `-` are written as themselves, and every maximal run of
170///   other characters becomes one `_` when the run is whitespace only and one
171///   `-` otherwise; `-` and `_` are trimmed from both ends. A `~` and a tag of
172///   six hexadecimal digits computed from the text as written (before the
173///   decomposition) are appended, so that two texts that reduce alike still
174///   differ. `Éléments 2` becomes
175///   `Elements_2~<tag>`; `\(\mathcal{C}_\alpha^\infty\)` becomes
176///   `mathcal-C-alpha-infty~<tag>`; the empty text becomes `~<tag>`.
177///
178/// A `~` never appears on the exact path and always on the tagged one, so the
179/// two paths cannot produce the same encoding.
180///
181/// **Why a hyphen at either end leaves the exact path.** An anchor made from
182/// a label joins its two encoded parts with one hyphen ([`label_anchor`]),
183/// and one made from a title or a position joins its parts with two
184/// ([`title_anchor`], [`auto_anchor`]), so the separators tell the two kinds
185/// apart, unless a hyphen of the encoded text falls beside the joining one.
186/// That happens at both ends: a label whose own text begins with a hyphen
187/// would turn `sec:-Foo` into `sec--Foo`, the anchor of an unlabeled heading
188/// titled `Foo`, and `eq:-7` into `eq--7…`, the shape of an unlabeled
189/// equation line's anchor; a label whose *type* ends with a hyphen would turn
190/// `sec-:Foo` into the same `sec--Foo`. On the tagged path the hyphen is
191/// trimmed and a tag is appended, so the anchor of a label never takes the
192/// shape of the other kinds, regardless of what the label says. No standard
193/// construct accepts such a label type, since each accepts a fixed list of
194/// types; a reference point that accepts any type can receive one.
195///
196/// # Examples
197///
198/// ```
199/// use flm_core::stdlib::features::refs::encode_anchor;
200///
201/// assert_eq!(encode_anchor("intro"), "intro");
202/// assert_eq!(encode_anchor("main.v2"), "main.v2");
203/// assert_eq!(encode_anchor("quantum error-correcting code"),
204///            "quantum_error-correcting_code");
205///
206/// // Anything else takes the tagged path.
207/// let tagged = encode_anchor("Éléments 2");
208/// assert!(tagged.starts_with("Elements_2~"));
209/// assert_eq!(tagged, encode_anchor("Éléments 2"));
210/// ```
211pub fn encode_anchor(text: &str) -> String {
212    if is_exact(text) {
213        return text.replace(' ', "_");
214    }
215    let folded: String =
216        text.nfkd().filter(|ch| !unicode_normalization::char::is_combining_mark(*ch)).collect();
217    // A separator is written only before the next character that passes
218    // through, so a leading or a trailing run writes nothing: that is the
219    // trimming of the ends.
220    let mut slug = String::with_capacity(folded.len() + 7);
221    let mut run: Option<bool> = None;
222    for ch in folded.chars() {
223        if passes_through(ch) {
224            if let Some(whitespace_only) = run.take() {
225                if !slug.is_empty() {
226                    slug.push(if whitespace_only { '_' } else { '-' });
227                }
228            }
229            slug.push(ch);
230        } else {
231            run = Some(run.unwrap_or(true) && ch.is_whitespace());
232        }
233    }
234    let mut anchor = slug.trim_matches(|ch| ch == '-' || ch == '_').to_string();
235    anchor.push('~');
236    anchor.push_str(&anchor_tag(text));
237    anchor
238}
239
240/// The anchor formed from a label: `<type>-<label>`, each part through
241/// [`encode_anchor`].
242///
243/// The anchors stage ([`ANCHORS_STAGE`](super::ANCHORS_STAGE)) gives it to a
244/// point whose anchor policy is
245/// [`AnchorPolicy::FromFirstLabel`](crate::model::aspects::AnchorPolicy), from
246/// the first label the point keeps, and to a labeled point of the other
247/// policies that fall back to a label (`Auto`, and `FromValue` for a point
248/// the document did not number).
249///
250/// # Examples
251///
252/// ```
253/// use flm_core::model::aspects::Label;
254/// use flm_core::stdlib::features::refs::label_anchor;
255///
256/// assert_eq!(label_anchor(&Label::new("sec", "intro")), "sec-intro");
257/// assert!(label_anchor(&Label::new("sec", "Éléments 2"))
258///     .starts_with("sec-Elements_2~"));
259/// ```
260pub fn label_anchor(label: &Label) -> String {
261    format!("{}-{}", encode_anchor(&label.ref_type), encode_anchor(&label.ref_label))
262}
263
264/// The anchor formed from a title, for an unlabeled heading:
265/// `<prefix>--<title>`, each part through [`encode_anchor`].
266///
267/// The anchors stage ([`ANCHORS_STAGE`](super::ANCHORS_STAGE)) gives it to a
268/// point whose anchor policy is
269/// [`AnchorPolicy::Slug`](crate::model::aspects::AnchorPolicy); the policy
270/// carries the prefix. A heading states `sec`, the label type it accepts, so
271/// that a heading's anchor begins the same way whether it was labeled or not.
272/// The separator is a double hyphen, so that an anchor made from a title
273/// cannot equal one made from a label, whose separator is a single hyphen;
274/// [`encode_anchor`] sends a label text that could produce a double hyphen
275/// down its tagged path for that reason.
276///
277/// This function only encodes; the anchors stage makes the result unique. An
278/// anchor made from a title that another point already holds takes the next
279/// free number (`sec--Intro-2`), so it is never refused.
280///
281/// # Examples
282///
283/// ```
284/// use flm_core::stdlib::features::refs::title_anchor;
285///
286/// assert_eq!(title_anchor("sec", "Intro"), "sec--Intro");
287/// ```
288pub fn title_anchor(prefix: &str, title: &str) -> String {
289    format!("{}--{}", encode_anchor(prefix), encode_anchor(title))
290}
291
292/// The anchor formed from a point's position, for an unlabeled point such as
293/// an equation line: `<prefix>--<position><four letters>`, as in `eq--8otbc`.
294///
295/// The anchors stage ([`ANCHORS_STAGE`](super::ANCHORS_STAGE)) gives it to a
296/// point whose anchor policy is
297/// [`AnchorPolicy::Auto`](crate::model::aspects::AnchorPolicy) and that has
298/// no label. The policy carries the prefix, as for an anchor made from a
299/// title, so that a labeled line (`eq-euler`) and an unlabeled one begin the
300/// same way; the separator is a double hyphen, for the reason
301/// [`title_anchor`] gives. `position` is the point's place among the points
302/// of its kind in the document, counting from one, and makes the anchor
303/// unique.
304///
305/// **The four letters** keep `eq--8` from reading as equation (8), which it
306/// is not as soon as one unnumbered equation comes before it: they show that
307/// the anchor is not the document's own number. They are computed from the
308/// prefix and the position alone: the FNV-1a hash of the text before them,
309/// its top thirty-two bits reduced modulo twenty-six to the fourth power and
310/// written as four base-twenty-six digits, `a` for zero through `z` for
311/// twenty-five, the most significant first. The same position therefore
312/// gives the same anchor in every document, on every run and on every
313/// platform. They are letters rather than hexadecimal digits because a hash
314/// made only of digits would read as one long number again.
315///
316/// # Examples
317///
318/// ```
319/// use flm_core::stdlib::features::refs::auto_anchor;
320///
321/// let eighth = auto_anchor("eq", 8);
322/// assert!(eighth.starts_with("eq--8"));
323/// assert_eq!(eighth.len(), "eq--8".len() + 4);
324/// // The same position always gives the same identifier.
325/// assert_eq!(eighth, auto_anchor("eq", 8));
326/// assert_ne!(eighth, auto_anchor("eq", 9));
327/// ```
328pub fn auto_anchor(prefix: &str, position: u32) -> String {
329    let base = format!("{}--{position}", encode_anchor(prefix));
330    let letters = anchor_letters(&base);
331    format!("{base}{letters}")
332}
333
334/// The anchor formed from the number the document gave a point:
335/// `<prefix>-<numbers>`, as in `theorem-2-3`.
336///
337/// The anchors stage ([`ANCHORS_STAGE`](super::ANCHORS_STAGE)) gives it to a
338/// point whose anchor policy is
339/// [`AnchorPolicy::FromValue`](crate::model::aspects::AnchorPolicy) and that
340/// the document numbered. The policy carries the prefix, as for an anchor
341/// made from a title or a position. `numbers` is the text that
342/// [`identifier_text`](crate::stdlib::features::numbering::identifier_text)
343/// writes for the point's counter value: the values of the counters it is
344/// numbered within, outermost first, then its own number, each in decimal and
345/// joined by hyphens, regardless of how the counter style shows them. Both
346/// parts go through [`encode_anchor`].
347///
348/// The separator is a single hyphen, the same as in an anchor made from a
349/// label, because a number identifies a point as a label does: `theorem-2-3`
350/// and the anchor of a label `\label{theorem:2-3}` are equal, and the anchors
351/// stage reports that as a collision
352/// ([`AnchorCollision`](super::AnchorCollision)).
353///
354/// # Examples
355///
356/// ```
357/// use flm_core::stdlib::features::refs::value_anchor;
358///
359/// assert_eq!(value_anchor("theorem", "2-3"), "theorem-2-3");
360/// ```
361pub fn value_anchor(prefix: &str, numbers: &str) -> String {
362    format!("{}-{}", encode_anchor(prefix), encode_anchor(numbers))
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368
369    #[test]
370    fn the_exact_path_reproduces_a_plain_label_with_spaces_as_underscores() {
371        assert_eq!(encode_anchor("intro"), "intro");
372        let phrase = "quantum error-correcting code";
373        assert_eq!(encode_anchor(phrase), "quantum_error-correcting_code");
374        assert_eq!(encode_anchor("main.v2"), "main.v2");
375        assert_eq!(encode_anchor("Mixed-Case.42"), "Mixed-Case.42");
376    }
377
378    #[test]
379    fn the_exact_path_stops_at_a_leading_a_trailing_or_a_doubled_space() {
380        assert!(encode_anchor(" x").contains('~'));
381        assert!(encode_anchor("x ").contains('~'));
382        assert!(encode_anchor("a  b").contains('~'));
383        assert!(!encode_anchor("a b").contains('~'));
384    }
385
386    /// A text beginning or ending with a hyphen takes the tagged path, so
387    /// that a label's identifier can never take the shape of a title-derived
388    /// or a position-derived one, whose separator is a double hyphen.
389    #[test]
390    fn the_exact_path_stops_at_a_hyphen_at_either_end() {
391        assert!(encode_anchor("-7").contains('~'));
392        assert!(encode_anchor("-Foo").contains('~'));
393        assert!(encode_anchor("a-").contains('~'));
394        // The hyphen is trimmed off the slug, and the tag is what keeps the
395        // result apart from the same text without it.
396        assert_eq!(encode_anchor("-7"), format!("7~{}", anchor_tag("-7")));
397        assert_eq!(encode_anchor("a-"), format!("a~{}", anchor_tag("a-")));
398        assert_eq!(encode_anchor("7"), "7");
399        assert_eq!(encode_anchor("a"), "a");
400        // A hyphen anywhere else still passes through.
401        assert_eq!(encode_anchor("a-b"), "a-b");
402    }
403
404    /// The hole this closes, one test per prefix: `sec:-Foo` used to encode
405    /// to `sec--Foo`, the identifier of an unlabeled heading titled `Foo`,
406    /// and `eq:-7` to `eq--7`, the shape of an unlabeled equation line's.
407    #[test]
408    fn a_label_beginning_with_a_hyphen_cannot_take_a_double_hyphen_shape() {
409        let section = label_anchor(&Label::new("sec", "-Foo"));
410        assert!(!section.starts_with("sec--"), "{section}");
411        assert_ne!(section, title_anchor("sec", "Foo"));
412        let equation = label_anchor(&Label::new("eq", "-7"));
413        assert!(!equation.starts_with("eq--"), "{equation}");
414        assert_ne!(equation, auto_anchor("eq", 7));
415    }
416
417    /// The same hole at the other end: a label whose *type* ends with a
418    /// hyphen, which no standard point accepts and a point accepting any type
419    /// can be written with. `sec-:Foo` used to encode to `sec--Foo` as well.
420    #[test]
421    fn a_label_type_ending_in_a_hyphen_cannot_take_a_double_hyphen_shape() {
422        let section = label_anchor(&Label::new("sec-", "Foo"));
423        assert!(!section.starts_with("sec--"), "{section}");
424        assert_ne!(section, title_anchor("sec", "Foo"));
425    }
426
427    #[test]
428    fn the_exact_path_stops_at_a_character_it_cannot_write() {
429        assert!(encode_anchor("a_b").contains('~'));
430        assert!(encode_anchor("a:b").contains('~'));
431        assert!(encode_anchor("é").contains('~'));
432    }
433
434    #[test]
435    fn the_tagged_path_strips_the_accents_of_an_nfkd_decomposition() {
436        let text = "Éléments 2";
437        assert_eq!(encode_anchor(text), format!("Elements_2~{}", anchor_tag(text)));
438    }
439
440    #[test]
441    fn the_tagged_path_writes_one_dash_per_run_and_trims_the_ends() {
442        let raw = r"\(\mathcal{C}_\alpha^\infty\)";
443        assert_eq!(encode_anchor(raw), format!("mathcal-C-alpha-infty~{}", anchor_tag(raw)));
444    }
445
446    #[test]
447    fn the_tagged_path_allows_an_empty_slug() {
448        assert_eq!(encode_anchor("!!"), format!("~{}", anchor_tag("!!")));
449        assert_eq!(encode_anchor(""), format!("~{}", anchor_tag("")));
450    }
451
452    /// The tag is part of the published form of an anchor: these values are
453    /// pinned so that a change of the hash is a test failure, not a silent
454    /// change of everybody's anchors.
455    #[test]
456    fn the_tag_is_the_fixed_fnv_1a_64_hash_of_the_raw_text() {
457        assert_eq!(fnv1a_64(b""), FNV_OFFSET_BASIS);
458        assert_eq!(fnv1a_64(b"a"), 0xaf63_dc4c_8601_ec8c);
459        assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8);
460        assert_eq!(anchor_tag(""), "cbf29c");
461        assert_eq!(anchor_tag("a"), "af63dc");
462    }
463
464    #[test]
465    fn a_label_anchor_joins_the_type_and_the_label_with_one_hyphen() {
466        assert_eq!(label_anchor(&Label::new("sec", "intro")), "sec-intro");
467        assert_eq!(
468            label_anchor(&Label::new("term", "quantum error-correcting code")),
469            "term-quantum_error-correcting_code"
470        );
471        assert_eq!(label_anchor(&Label::new("eq", "main.v2")), "eq-main.v2");
472    }
473
474    /// The letters are part of the published form of an anchor, so these
475    /// values are pinned: a change of the reduction is a test failure, not a
476    /// silent change of everybody's identifiers.
477    #[test]
478    fn the_letters_are_the_fixed_base_twenty_six_reduction_of_the_hash() {
479        assert_eq!(anchor_letters(""), "qvaa");
480        assert_eq!(anchor_letters("eq--8"), "otbc");
481        for text in ["", "eq--8", "eq--1", "sec--12"] {
482            let letters = anchor_letters(text);
483            assert_eq!(letters.len(), 4, "{text}: {letters}");
484            assert!(letters.bytes().all(|b| b.is_ascii_lowercase()), "{text}: {letters}");
485        }
486    }
487
488    #[test]
489    fn a_position_anchor_is_the_prefix_the_position_and_four_letters() {
490        assert_eq!(auto_anchor("eq", 8), format!("eq--8{}", anchor_letters("eq--8")));
491        // Two positions differ in the position itself, whatever the letters.
492        assert_ne!(auto_anchor("eq", 8), auto_anchor("eq", 9));
493        assert_ne!(auto_anchor("eq", 8), auto_anchor("sec", 8));
494        // The prefix is encoded, as it is for a title-derived anchor.
495        assert_eq!(auto_anchor("a b", 1), format!("a_b--1{}", anchor_letters("a_b--1")));
496    }
497
498    #[test]
499    fn a_value_anchor_joins_the_prefix_and_the_numbers_with_one_hyphen() {
500        assert_eq!(value_anchor("theorem", "2-3"), "theorem-2-3");
501        assert_eq!(value_anchor("theorem", "13"), "theorem-13");
502        // The prefix is encoded, as it is everywhere else.
503        assert_eq!(value_anchor("a b", "1"), "a_b-1");
504        // A number is a name of the same standing as a label, so the two
505        // shapes meet; the anchors stage reports that as a collision.
506        assert_eq!(value_anchor("theorem", "2-3"), label_anchor(&Label::new("theorem", "2-3")));
507    }
508
509    #[test]
510    fn a_title_anchor_joins_the_prefix_and_the_title_with_two_hyphens() {
511        let title = "The Sum, of Things";
512        assert_eq!(
513            title_anchor("sec", title),
514            format!("sec--The_Sum-of_Things~{}", anchor_tag(title))
515        );
516        assert_eq!(title_anchor("sec", "Intro"), "sec--Intro");
517    }
518}