quicklatex 0.1.0

A program to help me write LaTeX quickly
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
use std::cmp::Ordering;
use std::mem::take;
use std::str;

use anyhow::{bail, Context, Error};

use crate::{noisy::Noisy, replacements::Replacement, Timers};

enum LabelError
{
    BadNumber(String, String),
    DifferentLengths(String, String),
}

fn cmp_piece(a: &str, b: &str, label_a: &str, label_b: &str, is_first_label: bool) -> Result<Ordering, LabelError>
{
    if let (Ok(a), Ok(b)) = (a.parse::<f64>(), b.parse::<f64>())
    {
        Ok(a.partial_cmp(&b)
            .ok_or_else(|| LabelError::BadNumber(label_a.to_owned(), label_b.to_owned()))?)
    }
    else
    {
        // We'll check if `b` successfully parsed and from that infer where the error was.

        if b.parse::<f64>().is_ok()
        {
            if is_first_label
            {
                Err(LabelError::BadNumber(label_a.to_string(), a.to_string()))
            }
            else
            {
                // We have already dealt with it in the previous
                // comparison, so we can skip it.  Ordering::Less does
                // this.
                //
                // If this is the first comparison then there is no
                // previous one, so this is might wrongly skip.  This
                // is an issue if the first two labels are wrong.
                // TODO: Fix this bug.
                Ok(Ordering::Less)
            }
        }
        else
        {
            Err(LabelError::BadNumber(label_b.to_string(), b.to_string()))
        }
    }
}

fn cmp_label(a: &str, b: &str, is_first_label: bool) -> Result<Ordering, Vec<LabelError>>
{
    // To get all noisy we can't short-circuit the comparison, so we
    // have to cache the answer.
    let mut ok_return_value = None;
    let mut errors = vec![];

    let a_splitted = a.split(':').collect::<Vec<_>>();
    let b_splitted = b.split(':').collect::<Vec<_>>();

    match (a_splitted.len(), b_splitted.len())
    {
        (n, m) if n == m =>
        {
            for i in 0..n
            {
                match cmp_piece(a_splitted[i], b_splitted[i], a, b, is_first_label)
                {
                    Ok(Ordering::Less) => ok_return_value = ok_return_value.or(Some(Ordering::Less)),
                    Ok(Ordering::Greater) => ok_return_value = ok_return_value.or(Some(Ordering::Greater)),
                    Ok(Ordering::Equal) =>
                    {}
                    Err(err) => errors.push(err),
                }
            }
        }
        // TODO: Fix the bug that when two labels have different
        // lengths, then there not checked for bad numbers anymore.
        _ => errors.push(LabelError::DifferentLengths(a.to_string(), b.to_string())),
    }

    if !errors.is_empty()
    {
        Err(errors)
    }
    else if let Some(rv) = ok_return_value
    {
        Ok(rv)
    }
    else
    {
        Ok(Ordering::Equal)
    }
}

fn parse(s: &[u8], target: &[u8]) -> Result<Vec<String>, Error>
{
    let mut labels = vec![];

    let mut i = 0;
    let mut line = 1;
    while i + target.len() <= s.len()
    {
        if &s[i..(i + target.len())] == target
        {
            let mut label = vec![];

            i += target.len();

            if i >= s.len()
            {
                bail!("Unclosed label or ref immediately at the end on line {line}");
            }

            while s[i] != b'}'
            {
                label.push(s[i]);

                i += 1;
                if i >= s.len()
                {
                    bail!(
                        "Label or ref {:?} was not closed at line {line}",
                        str::from_utf8(&label).expect("A partial string was not UTF-8")
                    );
                }
            }
            labels.push(String::from_utf8(take(&mut label)).expect("A label or ref was not UTF-8"));
        }
        if s[i] == b'\n'
        {
            line += 1;
        }

        i += 1;
    }

    Ok(labels)
}

pub fn check_labels(s: &str, repls: &[Replacement], noisy: &mut Noisy, timers: &mut Timers) -> Result<String, Error>
{
    let s_bytes = s.as_bytes();

    let labels = parse(s_bytes, b"\\label{").context("Couldn't parse labels")?;
    let refs = parse(s_bytes, b"\\ref{").context("Couldn't parse refs")?;

    let missing_one_kind = |a: &[String], b: &[String]| {
        b.iter()
            .filter_map(|b_| {
                if a.iter().all(|a_| a_ != b_)
                {
                    Some(b_.clone())
                }
                else
                {
                    None
                }
            })
            .collect()
    };

    let mut missing_labels = missing_one_kind(&labels, &refs);

    // This duplication check has an asymptotic performance of
    // `O(n^2)` with `n` being the number of labels.  By sorting first
    // and only then comparing with the previous label this could be
    // reduced to `O(n ln(n))`, but I think that this is more complex
    // and – given the usual file sizes – in practice slower.  Even if
    // it isn't slower, all my own usage of `quicklatex` suggests that
    // this is a premature optimization.  If it is an issue for you,
    // please fill one on Codeberg.
    let mut duplicated_labels = labels
        .iter()
        .enumerate()
        .filter_map(|(i, label)| {
            if (0..i).any(|j| label == &labels[j])
            {
                Some(label.clone())
            }
            else
            {
                None
            }
        })
        .collect();

    let mut disordered_labels = vec![];
    let mut malformatted_numbers_in_label = vec![];
    let mut inconsistent_lengths_of_labels = vec![];

    for i in 0..labels.len().saturating_sub(1)
    {
        match cmp_label(&labels[i], &labels[i + 1], i == 0)
        {
            Ok(Ordering::Greater) =>
            {
                disordered_labels.push((labels[i].clone(), labels[i + 1].clone()));
            }
            Ok(_) =>
            {}
            Err(errs) =>
            {
                for err in errs
                {
                    match err
                    {
                        LabelError::BadNumber(label, bad_num) =>
                        {
                            malformatted_numbers_in_label.push((label, bad_num));
                        }
                        LabelError::DifferentLengths(a, b) => inconsistent_lengths_of_labels.push((a, b)),
                    }
                }
            }
        }
    }

    noisy.append_labels(
        &mut missing_labels,
        &mut duplicated_labels,
        &mut disordered_labels,
        &mut malformatted_numbers_in_label,
        &mut inconsistent_lengths_of_labels,
    );

    timers.start("remove_labels")?;

    let missing_refs = missing_one_kind(&refs, &labels);

    let mut s = s.to_string();

    for label in missing_refs
    {
        s = s.replace(&format!("\\label{{{label}}}"), "");
    }

    for replacement in repls
    {
        if replacement.refkind
        {
            if let Some(condition) = &replacement.condition
            {
                if !s.contains(condition)
                {
                    continue;
                }
            }

            if s.contains(&replacement.from)
            {
                s = s.replace(&format!("{}\\ref", replacement.from), &replacement.to);
                if replacement.noisy
                {
                    noisy.repls.push(replacement.clone());
                }
            }
        }
    }

    timers.stop("remove_labels")?;

    Ok(s)
}

#[cfg(test)]
mod tests
{
    use crate::{labels::check_labels, Noisy, Replacement, Timers};

    // Test just often are long, it wouldn't be better to split this
    // into multiple functions.  Also pedantic lint.
    #[allow(clippy::too_many_lines)]
    // Normally good warning, but here it's a false positive because
    // that's just how labels are.
    #[allow(clippy::literal_string_with_formatting_args)]
    #[test]
    fn labels_test()
    {
        let tests = vec![
            ("", "", Noisy::default()),
            (
                r"\ref{6:2:1}\label{4:3:2}
\label{6:2:1}
AbCdEf
\ref{4:3:2}",
                r"\ref{6:2:1}\label{4:3:2}
\label{6:2:1}
AbCdEf
\ref{4:3:2}",
                Noisy::default(),
            ),
            (r"abc\label{3:1}def", "abcdef", Noisy::default()),
            (
                r"abc\label{3:1}de\label{2:3:1}f",
                "abcdef",
                Noisy {
                    inconsistent_length_of_labels: vec![("3:1".to_owned(), "2:3:1".to_owned())],
                    ..Noisy::default()
                },
            ),
            (
                r"abc\label{3:1:1}de\label{2:3:1}f",
                "abcdef",
                Noisy {
                    disordered_labels: vec![("3:1:1".to_owned(), "2:3:1".to_owned())],
                    ..Noisy::default()
                },
            ),
            (
                r"\label{7}abc\label{3:1:1}de\label{2:3:1}f",
                "abcdef",
                Noisy {
                    inconsistent_length_of_labels: vec![("7".to_owned(), "3:1:1".to_owned())],
                    disordered_labels: vec![("3:1:1".to_owned(), "2:3:1".to_owned())],
                    ..Noisy::default()
                },
            ),
            (
                r"\label{7}abc\label{3:1:1}d\ref{7}e\label{2:3:1}f",
                r"\label{7}abcd\ref{7}ef",
                Noisy {
                    inconsistent_length_of_labels: vec![("7".to_owned(), "3:1:1".to_owned())],
                    disordered_labels: vec![("3:1:1".to_owned(), "2:3:1".to_owned())],
                    ..Noisy::default()
                },
            ),
            (
                r"\label{7}abc\label{3:1:1}d\label{abc}\ref{7}e\label{2:3:1}f",
                r"\label{7}abcd\ref{7}ef",
                Noisy {
                    inconsistent_length_of_labels: vec![
                        ("7".to_owned(), "3:1:1".to_owned()),
                        ("3:1:1".to_owned(), "abc".to_owned()),
                        ("abc".to_owned(), "2:3:1".to_owned()),
                    ],
                    ..Noisy::default()
                },
            ),
            (
                r"\label{7}abc\label{3:1:1}d\label{4:abc:22}\ref{7}e\label{2:3:1}f",
                r"\label{7}abcd\ref{7}ef",
                Noisy {
                    inconsistent_length_of_labels: vec![("7".to_owned(), "3:1:1".to_owned())],
                    malformatted_number_in_label: vec![("4:abc:22".to_owned(), "abc".to_owned())],
                    disordered_labels: vec![("4:abc:22".to_owned(), "2:3:1".to_owned())],
                    ..Noisy::default()
                },
            ),
            (
                r"\label{7}abc\label{3:1:1}d\label{7}\label{4:abc:22}\ref{7}e\label{2:3:1}f",
                r"\label{7}abcd\label{7}\ref{7}ef",
                Noisy {
                    duplicated_labels: vec!["7".to_owned()],
                    inconsistent_length_of_labels: vec![
                        ("7".to_owned(), "3:1:1".to_owned()),
                        ("3:1:1".to_owned(), "7".to_owned()),
                        ("7".to_owned(), "4:abc:22".to_owned()),
                    ],
                    disordered_labels: vec![("4:abc:22".to_owned(), "2:3:1".to_owned())],
                    ..Noisy::default()
                },
            ),
            (
                r"\label{7}abc\label{3:1:1}d\label{7}\ref{2:3:2}\label{4:abc:22}\ref{7}e\label{2:3:1}f",
                r"\label{7}abcd\label{7}\ref{2:3:2}\ref{7}ef",
                Noisy {
                    missing_labels: vec!["2:3:2".to_owned()],
                    duplicated_labels: vec!["7".to_owned()],
                    inconsistent_length_of_labels: vec![
                        ("7".to_owned(), "3:1:1".to_owned()),
                        ("3:1:1".to_owned(), "7".to_owned()),
                        ("7".to_owned(), "4:abc:22".to_owned()),
                    ],
                    disordered_labels: vec![("4:abc:22".to_owned(), "2:3:1".to_owned())],
                    ..Noisy::default()
                },
            ),
            (r"\label{7:}\ref{7:}", r"\label{7:}\ref{7:}", Noisy::default()),
            (r"\ref{:7}\label{:7}", r"\ref{:7}\label{:7}", Noisy::default()),
        ];

        for (input, output, noisy_output) in tests
        {
            let mut noisy = Noisy::default();
            let mut timers = Timers::default();

            assert_eq!(check_labels(input, &[], &mut noisy, &mut timers).unwrap(), output);
            assert_eq!(noisy, noisy_output);
        }
    }

    #[test]
    fn labels_repl_tests()
    {
        let tests = vec![
            (r"", r"", Noisy::default(), vec![]),
            (r"\label{}", r"", Noisy::default(), vec![]),
            (
                r"\ref{}",
                r"\ref{}",
                Noisy {
                    missing_labels: vec![String::new()],
                    ..Noisy::default()
                },
                vec![],
            ),
            (
                r"\label{7}abc\label{3:1:1}d\label{7}\ref{2:3:2}\label{4:abc:22}\ref{7}e\label{2:3:1}f",
                r"\label{7}abcd\label{7}\ref{2:3:2}\ref{7}ef",
                Noisy {
                    missing_labels: vec!["2:3:2".to_owned()],
                    duplicated_labels: vec!["7".to_owned()],
                    inconsistent_length_of_labels: vec![
                        ("7".to_owned(), "3:1:1".to_owned()),
                        ("3:1:1".to_owned(), "7".to_owned()),
                        ("7".to_owned(), "4:abc:22".to_owned()),
                    ],
                    disordered_labels: vec![("4:abc:22".to_owned(), "2:3:1".to_owned())],
                    ..Noisy::default()
                },
                vec![],
            ),
            (
                r"\label{7}abc\label{3:1:1}dhyper\ref{3:1:1}\label{7}\ref{2:3:2}\label{4:abc:22}\ref{7}e\label{2:3:1}f",
                r"\label{7}abc\label{3:1:1}dhyper\ref{3:1:1}\label{7}\ref{2:3:2}\ref{7}ef",
                Noisy {
                    missing_labels: vec!["2:3:2".to_owned()],
                    duplicated_labels: vec!["7".to_owned()],
                    inconsistent_length_of_labels: vec![
                        ("7".to_owned(), "3:1:1".to_owned()),
                        ("3:1:1".to_owned(), "7".to_owned()),
                        ("7".to_owned(), "4:abc:22".to_owned()),
                    ],
                    disordered_labels: vec![("4:abc:22".to_owned(), "2:3:1".to_owned())],
                    ..Noisy::default()
                },
                vec![],
            ),
            (
                r"\label{7}abc\label{3:1:1}dhyper\ref{3:1:1}\label{7}\ref{2:3:2}\label{4:abc:22}\ref{7}e\label{2:3:1}f",
                r"\label{7}abc\label{3:1:1}d\hyperrefzvav{3:1:1}\label{7}\ref{2:3:2}\ref{7}ef",
                Noisy {
                    missing_labels: vec!["2:3:2".to_owned()],
                    duplicated_labels: vec!["7".to_owned()],
                    inconsistent_length_of_labels: vec![
                        ("7".to_owned(), "3:1:1".to_owned()),
                        ("3:1:1".to_owned(), "7".to_owned()),
                        ("7".to_owned(), "4:abc:22".to_owned()),
                    ],
                    disordered_labels: vec![("4:abc:22".to_owned(), "2:3:1".to_owned())],
                    ..Noisy::default()
                },
                vec![Replacement {
                    from: "hyper".to_owned(),
                    to: "\\hyperrefzvav".to_owned(),
                    refkind: true,
                    ..Replacement::default()
                }],
            ),
            (
                r"\label{7}abc\label{3:1.4:1}dhyper\ref{3:1.4:1}\label{7}\ref{2:3:2}\label{4:abc:22}\ref{7}e\label{2:3:1}f",
                r"\label{7}abc\label{3:1.4:1}d\hyperrefzvav{3:1.4:1}\label{7}\ref{2:3:2}\ref{7}ef",
                Noisy {
                    missing_labels: vec!["2:3:2".to_owned()],
                    duplicated_labels: vec!["7".to_owned()],
                    inconsistent_length_of_labels: vec![
                        ("7".to_owned(), "3:1.4:1".to_owned()),
                        ("3:1.4:1".to_owned(), "7".to_owned()),
                        ("7".to_owned(), "4:abc:22".to_owned()),
                    ],
                    disordered_labels: vec![("4:abc:22".to_owned(), "2:3:1".to_owned())],
                    ..Noisy::default()
                },
                vec![Replacement {
                    from: "hyper".to_owned(),
                    to: "\\hyperrefzvav".to_owned(),
                    refkind: true,
                    ..Replacement::default()
                }],
            ),
        ];

        for (input, output, noisy_output, repls) in tests
        {
            let mut noisy = Noisy::default();
            let mut timers = Timers::default();

            assert_eq!(check_labels(input, &repls, &mut noisy, &mut timers).unwrap(), output);
            assert_eq!(noisy, noisy_output);
        }
    }

    #[test]
    fn labels_fail_tests()
    {
        let tests = vec![
            (r"\label{abc", "Couldn't parse labels"),
            (r"\ref{abc", "Couldn't parse refs"),
            (r"def\label{abc", "Couldn't parse labels"),
            (r"def\ref{abc", "Couldn't parse refs"),
            (r"\label{", "Couldn't parse labels"),
            (r"\ref{", "Couldn't parse refs"),
            (r"def\label{", "Couldn't parse labels"),
            (r"def\ref{", "Couldn't parse refs"),
        ];

        for (input, err_msg) in tests
        {
            assert_eq!(
                check_labels(input, &[], &mut Noisy::default(), &mut Timers::default())
                    .unwrap_err()
                    .to_string(),
                err_msg
            );
        }
    }

    #[test]
    fn labels_timer_fail_test()
    {
        let mut timers = Timers::default();

        check_labels("", &[], &mut Noisy::default(), &mut timers).unwrap();
        assert_eq!(
            check_labels("", &[], &mut Noisy::default(), &mut timers)
                .unwrap_err()
                .to_string(),
            "Timer \"remove_labels\" already used"
        );
    }
}