Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.4.01085.8 KB2026-10-160.3.21087.6 KB2026-10-160.3.11087.5 KB2026-10-160.3.0117.8 KB2026-10-160.2.1106.1 KB2026-10-150.2.0105.5 KB2026-10-15
Version
0.3.1
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-10-16
Size
1087.5 KB
Downloads
24
Checksum
656aa128e98955e746555e14f8366cdca6c6761d61e1b74fa77a4797476f12dd
Dependencies
rust/[email protected]
rust/[email protected]

number.rs

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
//! Assigns numbers and resolves references
//!
//! Headings, figures, tables, equations, and bibliography entries get numbers. A `\label` is
//! tied to the number assigned just before it.
//! Only page numbers cannot be decided until after pagination, so [`crate::page`] fills them in
//! later.

use crate::node::{Document, FloatKind, Node, walk};
use crate::text;
use std::collections::HashMap;


/// An entry to show in the table of contents
#[derive(Debug, Clone, PartialEq)]
pub struct Contents {
    pub level: usize,
    pub number: String,
    pub title: String,
}


/// Numbers and references
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Numbering {
    /// From the name of a `\label` to its number
    pub reference: HashMap<String, String>,
    /// From the name of a `\label` to its page number
    pub page: HashMap<String, usize>,
    /// The entries to show in the table of contents
    pub contents: Vec<Contents>,
    /// From the key of a bibliography entry to its number
    pub citation: HashMap<String, String>,
}


/// The deepest level that gets a number. Headings deeper than this get no number
const DEEPEST: usize = 4;


/// Whether the document has chapters. article has no chapters, so counting starts at sections
pub fn has_chapter(class: &str) -> bool {
    !matches!(class, "article" | "jarticle" | "letter" | "slides")
}


/// Assigns the numbers in a document
pub fn assign(document: &mut Document) -> Numbering {
    let base = if has_chapter(&document.class) {1} else {2};
    let mut found = Numbering::default();
    let mut counter = [0usize; 7];
    let mut figure = 0;
    let mut table = 0;
    let mut equation = 0;
    let mut appendix = false;
    let mut last = String::new();

    walk(&mut document.body, &mut |node| match node {
        Node::Appendix => {
            appendix = true;

            for slot in counter.iter_mut().skip(base) {
                *slot = 0;
            }
        }
        Node::Heading {level, numbered, title, number} => {
            if *numbered && *level <= DEEPEST {
                counter[*level] += 1;

                for slot in counter.iter_mut().skip(*level + 1) {
                    *slot = 0;
                }

                *number = shape(&counter, base, *level, appendix);
                last = number.clone();
            }

            if *level <= DEEPEST {
                found.contents.push(Contents {
                    level: *level,
                    number: number.clone(),
                    title: crate::node::plain(title),
                });
            }
        }
        Node::Caption {number, kind, ..} => {
            let count = match kind {
                FloatKind::Figure => {
                    figure += 1;
                    figure
                }
                FloatKind::Table => {
                    table += 1;
                    table
                }
            };
            *number = count.to_string();
            last = number.clone();
        }
        Node::Math {row, ..} => {
            for one in row.iter_mut() {
                if !one.numbered {
                    continue;
                }

                equation += 1;
                one.number = equation.to_string();

                if let Some(name) = &one.label {
                    found.reference.insert(name.clone(), one.number.clone());
                }

                last = one.number.clone();
            }
        }
        Node::Label(name) => {
            found.reference.insert(name.clone(), last.clone());
        }
        Node::Bibliography(entry) => {
            for (index, one) in entry.iter_mut().enumerate() {
                one.number = match &one.mark {
                    Some(mark) => mark.clone(),
                    None => (index + 1).to_string(),
                };
                found.citation.insert(one.key.clone(), one.number.clone());
            }
        }
        _ => {}
    });

    found
}


/// Builds a number
fn shape(counter: &[usize], base: usize, level: usize, appendix: bool) -> String {
    if level == 0 {
        return text::roman(counter[0]).to_uppercase();
    }

    let mut part = Vec::new();

    for (index, value) in counter.iter().enumerate().take(level + 1).skip(base) {
        if index == base && appendix {
            part.push(text::alphabet(*value));

        } else {
            part.push(value.to_string());
        }
    }

    if part.is_empty() {
        return counter[level].to_string();
    }

    part.join(".")
}


/// Looks up a number by name. Returns `??` if it is not found
pub fn look(numbering: &Numbering, name: &str) -> String {
    match numbering.reference.get(name) {
        Some(found) if !found.is_empty() => found.clone(),
        _ => "??".to_string(),
    }
}


/// Looks up a page number by name
pub fn look_page(numbering: &Numbering, name: &str) -> String {
    match numbering.page.get(name) {
        Some(found) => found.to_string(),
        None => "??".to_string(),
    }
}


/// Looks up a number by the key of a bibliography entry
pub fn look_citation(numbering: &Numbering, key: &str) -> String {
    match numbering.citation.get(key) {
        Some(found) => found.clone(),
        None => "?".to_string(),
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse;

    fn read(source: &str) -> (Document, Numbering) {
        let characters: Vec<char> = source.chars().collect();
        let mut document = parse::parse(&characters).unwrap();
        let numbering = assign(&mut document);

        (document, numbering)
    }

    #[test]
    fn sections_are_numbered_in_order() {
        let (document, _) = read(
            "\\documentclass{article}\\begin{document}\
\\section{A}\\subsection{B}\\subsection{C}\\section{D}\\end{document}",
        );
        let mut found = Vec::new();

        for node in &document.body {
            if let Node::Heading {number, ..} = node {
                found.push(number.clone());
            }
        }

        assert_eq!(found, vec!["1", "1.1", "1.2", "2"]);
    }

    #[test]
    fn a_label_points_at_the_number_before_it() {
        let (_, numbering) = read(
            "\\documentclass{article}\\begin{document}\
\\section{A}\\label{one}\\section{B}\\label{two}\\end{document}",
        );
        assert_eq!(look(&numbering, "one"), "1");
        assert_eq!(look(&numbering, "two"), "2");
        assert_eq!(look(&numbering, "none"), "??");
    }

    #[test]
    fn a_starred_section_gets_no_number_but_reaches_the_contents() {
        let (_, numbering) = read(
            "\\documentclass{article}\\begin{document}\\section*{A}\\section{B}\\end{document}",
        );
        assert_eq!(numbering.contents.len(), 2);
        assert_eq!(numbering.contents[0].number, "");
        assert_eq!(numbering.contents[1].number, "1");
    }

    #[test]
    fn equations_are_numbered_on_their_own() {
        let (_, numbering) = read(
            "\\documentclass{article}\\begin{document}\
\\begin{equation}\\label{e}x=1\\end{equation}\\end{document}",
        );
        assert_eq!(look(&numbering, "e"), "1");
    }

    #[test]
    fn the_appendix_changes_the_shape_of_the_number() {
        let (document, _) = read(
            "\\documentclass{article}\\begin{document}\
\\section{A}\\appendix\\section{B}\\subsection{C}\\end{document}",
        );
        let mut found = Vec::new();

        for node in &document.body {
            if let Node::Heading {number, ..} = node {
                found.push(number.clone());
            }
        }

        assert_eq!(found, vec!["1", "A", "A.1"]);
    }
}