rs-rich-ext 0.0.21

Extensions for the `rich` Rust port: diagnostics, structured data, clap and tracing integration, diffs, workflow renderables and a plugin registry
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
//! The transforms `docutils.core.publish_doctree` applies, in docutils'
//! order, for what `rich-rst` 2.x shows: substitutions, the document title
//! and subtitle, bibliographic fields, footnote numbers, hyperlink targets,
//! the table of contents, and transitions.

use std::collections::HashMap;

use super::doctree::{Element, Node};
use super::inline::normalize_name;

pub(super) fn apply(document: &mut Element) {
    substitutions(document);
    if promote_title(document) {
        promote_subtitle(document);
    }
    docinfo(document);
    embedded_targets(document);
    footnotes(document);
    hyperlinks(document);
    citations(document);
    contents(document);
    transitions(document);
}

/// docutils' `PreBibliographic` nodes: what may stand before the title.
fn pre_bibliographic(node: &Node) -> bool {
    match node {
        Node::Text(_) => false,
        Node::Element(element) => matches!(
            element.tag,
            "title"
                | "subtitle"
                | "meta"
                | "decoration"
                | "comment"
                | "substitution_definition"
                | "target"
                | "pending"
                | "system_message"
                | "raw"
        ),
    }
}

/// `candidate_index`: the lone section after the pre-bibliographic nodes.
fn candidate_index(node: &Element) -> Option<usize> {
    let index = node
        .children
        .iter()
        .position(|child| !pre_bibliographic(child))?;
    (index + 1 == node.children.len() && node.children[index].is("section")).then_some(index)
}

fn promote_title(document: &mut Element) -> bool {
    let Some(index) = candidate_index(document) else {
        return false;
    };
    let Node::Element(section) = document.children.remove(index) else {
        return false;
    };
    document.names.clone_from(&section.names);
    let mut children = section.children.into_iter();
    let title = children.next();
    let before: Vec<Node> = std::mem::take(&mut document.children);
    document.children = title.into_iter().chain(before).chain(children).collect();
    true
}

fn promote_subtitle(document: &mut Element) {
    let Some(index) = candidate_index(document) else {
        return;
    };
    let Node::Element(section) = document.children.remove(index) else {
        return;
    };
    let mut children = section.children.into_iter();
    let Some(Node::Element(title)) = children.next() else {
        return;
    };
    let mut subtitle = Element::new("subtitle");
    subtitle.children = title.children;
    subtitle.names = section.names;
    document.children.insert(1, subtitle.into());
    document.children.extend(children);
}

/// The fields `DocInfo` turns into their own elements.
const BIBLIOGRAPHIC: &[&str] = &[
    "author",
    "organization",
    "address",
    "contact",
    "version",
    "revision",
    "status",
    "date",
    "copyright",
];

/// `DocInfo`: a field list first in the document becomes its bibliographic
/// fields.
fn docinfo(document: &mut Element) {
    let Some(index) = document
        .children
        .iter()
        .position(|child| !pre_bibliographic(child))
    else {
        return;
    };
    if !document.children[index].is("field_list") {
        return;
    }
    let Node::Element(list) = document.children.remove(index) else {
        return;
    };
    let mut info = Element::new("docinfo");
    let mut topics = Vec::new();
    for field in list.children {
        let Node::Element(field) = field else {
            continue;
        };
        let name = field
            .find("field_name")
            .map(Element::astext)
            .unwrap_or_default();
        let key = name.to_lowercase();
        let body = field.find("field_body").cloned().unwrap_or_default();
        let lone_paragraph = match body.children.as_slice() {
            [Node::Element(paragraph)] if paragraph.tag == "paragraph" => Some(paragraph.clone()),
            _ => None,
        };
        if let (Some(tag), Some(paragraph)) = (
            BIBLIOGRAPHIC.iter().find(|tag| **tag == key),
            lone_paragraph.as_ref(),
        ) {
            let mut element = Element::new(tag);
            element.children.clone_from(&paragraph.children);
            info.children.push(element.into());
            continue;
        }
        if key == "authors"
            && let Some(authors) = authors(&body)
        {
            info.children.push(authors.into());
            continue;
        }
        if key == "dedication" || key == "abstract" {
            let title = if key == "dedication" {
                "Dedication"
            } else {
                "Abstract"
            };
            topics.push(
                Element::new("topic")
                    .class(key.clone())
                    .child(Element::text("title", title))
                    .children(body.children)
                    .into(),
            );
            continue;
        }
        let mut field = field;
        field.classes.push(super::parse::make_id(&name));
        info.children.push(field.into());
    }
    let at = document
        .children
        .iter()
        .position(|child| !matches!(child, Node::Element(e) if matches!(e.tag, "title" | "subtitle" | "decoration" | "meta")))
        .unwrap_or(document.children.len());
    let mut nodes: Vec<Node> = Vec::new();
    if !info.children.is_empty() {
        nodes.push(info.into());
    }
    nodes.extend(topics);
    document.children.splice(at..at, nodes);
}

/// The `authors` field: one paragraph split on `;` (or `,`), or a bullet
/// list of one paragraph each.
fn authors(body: &Element) -> Option<Element> {
    let mut out = Element::new("authors");
    match body.children.as_slice() {
        [Node::Element(paragraph)] if paragraph.tag == "paragraph" => {
            let text = paragraph.astext();
            let separator = if text.contains(';') { ';' } else { ',' };
            for name in text
                .split(separator)
                .map(str::trim)
                .filter(|n| !n.is_empty())
            {
                out.children.push(Element::text("author", name).into());
            }
        }
        [Node::Element(list)] if list.tag == "bullet_list" => {
            for item in list.elements() {
                let [Node::Element(paragraph)] = item.children.as_slice() else {
                    return None;
                };
                let mut author = Element::new("author");
                author.children.clone_from(&paragraph.children);
                out.children.push(author.into());
            }
        }
        _ => return None,
    }
    (!out.children.is_empty()).then_some(out)
}

/// Every substitution definition, by name.
fn definitions(element: &Element, found: &mut HashMap<String, Vec<Node>>) {
    for child in element.elements() {
        if child.tag == "substitution_definition" {
            if let Some(name) = child.get("name") {
                found
                    .entry(name.to_string())
                    .or_insert_with(|| child.children.clone());
                found
                    .entry(normalize_name(name))
                    .or_insert_with(|| child.children.clone());
            }
        } else {
            definitions(child, found);
        }
    }
}

/// `Substitutions`: each reference is replaced by its definition's
/// content; an unknown one is problematic, shown as its source.
fn substitutions(document: &mut Element) {
    let mut defined = HashMap::new();
    definitions(document, &mut defined);
    replace_substitutions(document, &defined);
}

fn replace_substitutions(element: &mut Element, defined: &HashMap<String, Vec<Node>>) {
    if element.tag == "substitution_definition" {
        return;
    }
    let mut out = Vec::with_capacity(element.children.len());
    for child in std::mem::take(&mut element.children) {
        let Node::Element(mut child) = child else {
            out.push(child);
            continue;
        };
        if child.tag == "substitution_reference" {
            let name = child.astext();
            match defined
                .get(&name)
                .or_else(|| defined.get(&normalize_name(&name)))
            {
                Some(content) => out.extend(content.iter().cloned()),
                None => out.push(Element::text("problematic", format!("|{name}|")).into()),
            }
            continue;
        }
        // `|name|_`: the reference around a substitution.
        if child.tag == "reference"
            && matches!(child.children.as_slice(), [Node::Element(s)] if s.tag == "substitution_reference")
        {
            let name = child.children[0].astext();
            match defined
                .get(&name)
                .or_else(|| defined.get(&normalize_name(&name)))
            {
                Some(content) => child.children = content.clone(),
                None => {
                    let end = if child.get("anonymous").is_some() {
                        "__"
                    } else {
                        "_"
                    };
                    out.push(Element::text("problematic", format!("|{name}|{end}")).into());
                    continue;
                }
            }
        }
        replace_substitutions(&mut child, defined);
        out.push(child.into());
    }
    element.children = out;
}

/// A reference with an embedded URI and a name is also a target for that
/// name, standing after it.
fn embedded_targets(element: &mut Element) {
    let mut out = Vec::with_capacity(element.children.len());
    for child in std::mem::take(&mut element.children) {
        let Node::Element(mut child) = child else {
            out.push(child);
            continue;
        };
        embedded_targets(&mut child);
        let target = child.attrs.remove("__target").map(|name| {
            let mut target = Element::new("target").with(
                "refuri",
                child.get("refuri").unwrap_or_default().to_string(),
            );
            target.names = vec![name];
            target
        });
        out.push(child.into());
        if let Some(target) = target {
            out.push(target.into());
        }
    }
    element.children = out;
}

const SYMBOLS: [&str; 10] = [
    "*", "\u{2020}", "\u{2021}", "\u{a7}", "\u{b6}", "#", "\u{2660}", "\u{2665}", "\u{2666}",
    "\u{2663}",
];

/// `Footnotes`: auto-numbered footnotes get the numbers not taken, their
/// references the same, and auto-symbol footnotes their symbols.
fn footnotes(document: &mut Element) {
    let mut taken: Vec<String> = Vec::new();
    document.walk(&mut |element| {
        taken.extend(element.names.iter().cloned());
    });
    // Number the auto-numbered footnotes, in order.
    let mut number = 1;
    let mut labels: Vec<String> = Vec::new();
    let mut named: HashMap<String, String> = HashMap::new();
    let mut symbols = 0;
    document.walk_mut(&mut |element| {
        if element.tag != "footnote" {
            return;
        }
        match element.get("auto") {
            Some("1") => {
                while taken.contains(&number.to_string()) {
                    number += 1;
                }
                let label = number.to_string();
                taken.push(label.clone());
                number += 1;
                element
                    .children
                    .insert(0, Element::text("label", label.clone()).into());
                match element.names.first() {
                    Some(name) => {
                        named.insert(name.clone(), label.clone());
                    }
                    None => {
                        labels.push(label.clone());
                        element.names = vec![label];
                    }
                }
            }
            Some("*") => {
                let symbol = SYMBOLS[symbols % SYMBOLS.len()].repeat(symbols / SYMBOLS.len() + 1);
                symbols += 1;
                element
                    .children
                    .insert(0, Element::text("label", symbol).into());
            }
            _ => {}
        }
    });
    let mut footnote_names: Vec<String> = Vec::new();
    document.walk(&mut |element| {
        if element.tag == "footnote" {
            footnote_names.extend(element.names.iter().cloned());
        }
    });
    let mut next_label = labels.into_iter();
    let mut symbol_refs = 0;
    resolve_footnote_references(document, &mut |reference| match reference.get("auto") {
        Some("1") => {
            let label = match reference.get("refname") {
                Some(name) => named.get(name).cloned(),
                None => next_label.next(),
            };
            label.map(|label| {
                reference.attrs.remove("refname");
                reference.children = vec![Node::Text(label)];
            })
        }
        Some("*") => {
            let symbol =
                SYMBOLS[symbol_refs % SYMBOLS.len()].repeat(symbol_refs / SYMBOLS.len() + 1);
            symbol_refs += 1;
            (symbol_refs <= symbols).then(|| {
                reference.children = vec![Node::Text(symbol)];
            })
        }
        _ => {
            let name = reference.get("refname").unwrap_or_default().to_string();
            footnote_names.contains(&name).then(|| {
                reference.attrs.remove("refname");
            })
        }
    });
}

/// Call `resolve` on each footnote reference; one it cannot resolve
/// (`None`) is problematic, shown as its source.
fn resolve_footnote_references(
    element: &mut Element,
    resolve: &mut dyn FnMut(&mut Element) -> Option<()>,
) {
    for child in &mut element.children {
        let Node::Element(child_element) = child else {
            continue;
        };
        if child_element.tag == "footnote_reference" {
            if resolve(child_element).is_none() {
                let source = match (child_element.get("auto"), child_element.get("refname")) {
                    (Some("*"), _) => "[*]_".to_string(),
                    (Some(_), Some(name)) => format!("[#{name}]_"),
                    (Some(_), None) => "[#]_".to_string(),
                    (None, _) => format!("[{}]_", child_element.astext()),
                };
                *child = Element::text("problematic", source).into();
            }
            continue;
        }
        resolve_footnote_references(child_element, resolve);
    }
}

/// `citation_reference`s to an unknown citation are problematic.
fn citations(document: &mut Element) {
    let mut names = Vec::new();
    document.walk(&mut |element| {
        if element.tag == "citation" {
            names.extend(element.names.iter().cloned());
        }
    });
    fn walk(element: &mut Element, names: &[String]) {
        for child in &mut element.children {
            let Node::Element(child_element) = child else {
                continue;
            };
            if child_element.tag == "citation_reference" {
                let name = child_element.get("refname").unwrap_or_default().to_string();
                if names.contains(&name) {
                    child_element.attrs.remove("refname");
                } else {
                    let text = format!("[{}]_", child_element.astext());
                    *child = Element::text("problematic", text).into();
                }
                continue;
            }
            walk(child_element, names);
        }
    }
    walk(document, &names);
}

/// Where a name leads: a URI, or somewhere in the document.
#[derive(Clone, Debug)]
enum Destination {
    Uri(String),
    Internal,
    /// Another name (an indirect target).
    Name(String),
}

/// The hyperlink transforms: anonymous references take the anonymous
/// targets in order, named references their target's URI; one with no
/// target is problematic, shown as its source.
fn hyperlinks(document: &mut Element) {
    let mut named: HashMap<String, Destination> = HashMap::new();
    let mut anonymous: Vec<Destination> = Vec::new();
    let mut anonymous_refs = 0;
    document.walk(&mut |element| match element.tag {
        "target" => {
            let destination = match (element.get("refuri"), element.get("refname")) {
                (Some(uri), _) => Destination::Uri(uri.to_string()),
                (None, Some(name)) => Destination::Name(name.to_string()),
                (None, None) => Destination::Internal,
            };
            if element.get("anonymous").is_some() {
                anonymous.push(destination);
            } else {
                for name in &element.names {
                    named.entry(name.clone()).or_insert(destination.clone());
                }
            }
        }
        "section" | "footnote" | "citation" => {
            for name in &element.names {
                named.entry(name.clone()).or_insert(Destination::Internal);
            }
        }
        "reference" if element.get("anonymous").is_some() && element.get("refuri").is_none() => {
            anonymous_refs += 1;
        }
        _ => {}
    });
    let resolve = |name: &str| -> Option<Destination> {
        let mut name = name.to_string();
        for _ in 0..32 {
            match named.get(&name)? {
                Destination::Name(next) => name.clone_from(next),
                other => return Some(other.clone()),
            }
        }
        None
    };
    let anonymous: Vec<Option<Destination>> = anonymous
        .into_iter()
        .map(|destination| match destination {
            Destination::Name(name) => resolve(&name),
            other => Some(other),
        })
        .collect();
    let matched = anonymous.len() == anonymous_refs;
    let mut next_anonymous = anonymous.into_iter();
    fn walk(
        element: &mut Element,
        resolve: &dyn Fn(&str) -> Option<Destination>,
        anonymous: &mut dyn Iterator<Item = Option<Destination>>,
        matched: bool,
    ) {
        for child in &mut element.children {
            let Node::Element(reference) = child else {
                continue;
            };
            if reference.tag != "reference" {
                walk(reference, resolve, anonymous, matched);
                continue;
            }
            let destination = if reference.get("refuri").is_some() {
                walk(reference, resolve, anonymous, matched);
                continue;
            } else if reference.get("anonymous").is_some() {
                if matched {
                    anonymous.next().flatten()
                } else {
                    None
                }
            } else if let Some(name) = reference.get("refname") {
                resolve(name)
            } else {
                walk(reference, resolve, anonymous, matched);
                continue;
            };
            match destination {
                Some(Destination::Uri(uri)) => {
                    reference.attrs.remove("refname");
                    reference.attrs.insert("refuri", uri);
                }
                Some(_) => {
                    reference.attrs.remove("refname");
                }
                None => {
                    let raw = reference
                        .get("__raw")
                        .map_or_else(|| format!("{}_", reference.astext()), String::from);
                    *child = Element::text("problematic", raw).into();
                    continue;
                }
            }
            walk(reference, resolve, anonymous, matched);
        }
    }
    walk(document, &resolve, &mut next_anonymous, matched);
    document.walk_mut(&mut |element| {
        element.attrs.remove("__raw");
    });
}

/// `Contents`: a `contents` topic gets a bullet list of the section titles
/// after it (or, `:local:`, of the sections it stands in).
fn contents(document: &mut Element) {
    fn entries(element: &Element, depth: Option<usize>, level: usize) -> Option<Element> {
        if depth.is_some_and(|depth| level > depth) {
            return None;
        }
        let mut list = Element::new("bullet_list");
        for section in element.elements().filter(|e| e.tag == "section") {
            let Some(title) = section.find("title") else {
                continue;
            };
            let mut reference = Element::new("reference");
            reference.children = title
                .children
                .iter()
                .filter(|child| !child.is("target") && !child.is("footnote_reference"))
                .cloned()
                .collect();
            let mut item =
                Element::new("list_item").child(Element::new("paragraph").child(reference));
            if let Some(sub) = entries(section, depth, level + 1) {
                item = item.child(sub);
            }
            list = list.child(item);
        }
        (!list.children.is_empty()).then_some(list)
    }
    fn walk(element: &mut Element, root: &Element) {
        // Only what holds a `contents` topic needs a copy of its sections.
        let holds = element
            .elements()
            .any(|child| child.get("__contents").is_some());
        let snapshot = if holds {
            element.clone()
        } else {
            Element::new("none")
        };
        let mut empty = Vec::new();
        for (index, child) in element.children.iter_mut().enumerate() {
            let Node::Element(child) = child else {
                continue;
            };
            if child.tag == "topic" && child.attrs.remove("__contents").is_some() {
                let depth = child
                    .attrs
                    .remove("__depth")
                    .and_then(|depth| depth.parse::<usize>().ok());
                let local = child.attrs.remove("__local").is_some();
                // The document's sections, or (local) those of its section.
                let scope = if local { &snapshot } else { root };
                match entries(scope, depth, 1) {
                    Some(list) => child.children.push(list.into()),
                    // No sections: the topic goes.
                    None => empty.push(index),
                }
                continue;
            }
            walk(child, root);
        }
        for index in empty.into_iter().rev() {
            element.children.remove(index);
        }
    }
    let mut any = false;
    document.walk(&mut |element| any |= element.get("__contents").is_some());
    if any {
        let root = document.clone();
        walk(document, &root);
    }
}

/// `Transitions`: one ending a section moves after the section.
fn transitions(element: &mut Element) {
    for child in &mut element.children {
        if let Node::Element(child) = child
            && child.tag == "section"
        {
            transitions(child);
        }
    }
    let mut index = 0;
    while index < element.children.len() {
        let moved = match &mut element.children[index] {
            Node::Element(section) if section.tag == "section" => {
                // A section that ends with a transition gives it up.
                if section
                    .children
                    .last()
                    .is_some_and(|last| last.is("transition"))
                {
                    section.children.pop()
                } else {
                    None
                }
            }
            _ => None,
        };
        if let Some(transition) = moved {
            element.children.insert(index + 1, transition);
        }
        index += 1;
    }
}