aspero-core 0.6.2

Core types, identifiers and Provider trait for aspero (no I/O)
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
671
672
673
674
675
676
677
//! Splitting a pasted reference list into one citation each, offline.
//!
//! Lists arrive numbered (`1.`, `[1]`, `(1)`), bulleted, separated by blank
//! lines, or one per line, with lines wrapped by PDFs and word processors.
//! The heuristics, in order:
//!
//! 1. **Numbered or bulleted**: two or more lines start with a marker
//!    (numbers in sequence, so `2015. Title` inside a reference doesn't
//!    count). Each marker starts a reference; other lines continue it.
//! 2. **Paragraphs**: blank lines separate references; within one, a line
//!    starts another reference only if it looks like an author list after
//!    a line that ended a sentence.
//! 3. **Lines**: one reference per line when every line has a year or an
//!    identifier, ends as a reference ends, and doesn't start in lower
//!    case; otherwise wrapped, split as within a paragraph.
//!
//! Wrapped lines are joined with a space; a word hyphenated across lines
//! is mended, and DOIs and URLs broken after `/` or `-` are rejoined.
//! Headings such as "References" are dropped.

use std::ops::Range;

use crate::Alternative;
use crate::fold::Folded;

/// One reference found in a list.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Reference {
    /// On one line, without its number or bullet.
    pub text: String,
    /// Byte range in the list: from after the marker to the end of its
    /// last line.
    pub span: Range<usize>,
    /// DOIs broken across lines at a hyphen, read without it: to try if
    /// the DOI as printed doesn't exist.
    pub alternatives: Vec<Alternative>,
}

/// The references in `text`, in order. Text from PDFs is cleaned first
/// (ligatures, invisible characters, look-alike dashes and quotes); spans
/// point into `text` as given.
pub fn split_references(text: &str) -> Vec<Reference> {
    let folded = Folded::new(text);
    let list = List::new(&folded.text);
    let groups = list.groups();
    references(text, &folded, &list, groups)
}

/// A line of a reference list as laid out, with its distance from the
/// left edge (any unit, such as PDF points).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct IndentedLine {
    pub text: String,
    pub indent: f64,
}

impl IndentedLine {
    pub fn new(text: impl Into<String>, indent: f64) -> Self {
        IndentedLine {
            text: text.into(),
            indent,
        }
    }
}

/// One reference found in laid-out lines.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LineReference {
    /// On one line, without its number or bullet.
    pub text: String,
    /// Indices of the lines it spans.
    pub lines: Range<usize>,
    pub alternatives: Vec<Alternative>,
}

/// The references in laid-out lines (as from a PDF), using the layout
/// plain text loses: with a hanging indent, references start at the
/// margin; with a first-line indent, indented. Numbered lists, and lines
/// all at one indent, are split by the text rules of [`split_references`].
pub fn split_lines(lines: &[IndentedLine]) -> Vec<LineReference> {
    let text = lines
        .iter()
        .map(|l| l.text.replace(['\r', '\n'], " "))
        .collect::<Vec<_>>()
        .join("\n");
    let folded = Folded::new(&text);
    let list = List::new(&folded.text);
    let groups = match starts_by_indent(lines) {
        Some(starts) if list.numbered().is_none() => {
            let mut groups: Vec<Vec<Range<usize>>> = Vec::new();
            for (i, line) in list.lines.iter().enumerate() {
                let Some(line) = line else { continue };
                match groups.last_mut() {
                    Some(group) if !starts[i] => group.push(line.clone()),
                    _ => groups.push(vec![line.clone()]),
                }
            }
            groups
        }
        _ => list.groups(),
    };
    let line_starts: Vec<usize> = std::iter::once(0)
        .chain(text.match_indices('\n').map(|(i, _)| i + 1))
        .collect();
    let line_of = |byte: usize| line_starts.partition_point(|&s| s <= byte) - 1;
    references(&text, &folded, &list, groups)
        .into_iter()
        .map(|r| LineReference {
            lines: line_of(r.span.start)..line_of(r.span.end.saturating_sub(1)) + 1,
            text: r.text,
            alternatives: r.alternatives,
        })
        .collect()
}

/// Which lines start a reference, by indent: `None` if the lines don't
/// differ enough to tell. Indents within half the gap to the next level
/// count as the same, so jitter in a PDF's positions doesn't matter.
fn starts_by_indent(lines: &[IndentedLine]) -> Option<Vec<bool>> {
    let content: Vec<&IndentedLine> = lines.iter().filter(|l| !l.text.trim().is_empty()).collect();
    let margin = content
        .iter()
        .map(|l| l.indent)
        .fold(f64::INFINITY, f64::min);
    let next = content
        .iter()
        .map(|l| l.indent)
        .filter(|&i| i > margin + 1.0)
        .fold(f64::INFINITY, f64::min);
    if !next.is_finite() {
        return None;
    }
    let at_margin = |l: &IndentedLine| l.indent - margin < (next - margin) / 2.0;
    let first = content.iter().find(|l| !is_heading(l.text.trim()))?;
    let starting = at_margin(first);
    Some(
        lines
            .iter()
            .map(|l| !l.text.trim().is_empty() && at_margin(l) == starting)
            .collect(),
    )
}

/// Groups of lines (ranges in `folded`) as references in `text`.
fn references(
    text: &str,
    folded: &Folded,
    list: &List,
    groups: Vec<Vec<Range<usize>>>,
) -> Vec<Reference> {
    groups
        .into_iter()
        .map(|g| {
            let span = folded.original(&(g[0].start..g[g.len() - 1].end));
            let written = &text[span.clone()];
            let alternatives = crate::id::scan(written)
                .iter()
                .filter_map(|m| Some(Alternative::new(m.id.clone(), m.alternative(written)?)))
                .collect();
            Reference {
                text: list.join(&g),
                span,
                alternatives,
            }
        })
        .filter(|r| !is_heading(&r.text))
        .collect()
}

struct List<'a> {
    text: &'a str,
    /// Every line trimmed, as a byte range; `None` for blank ones.
    lines: Vec<Option<Range<usize>>>,
}

impl<'a> List<'a> {
    fn new(text: &'a str) -> Self {
        let mut lines = Vec::new();
        let mut at = 0;
        for raw in text.split_inclusive('\n') {
            let trimmed = raw.trim();
            lines.push((!trimmed.is_empty()).then(|| {
                let start = at + (raw.len() - raw.trim_start().len());
                start..start + trimmed.len()
            }));
            at += raw.len();
        }
        List { text, lines }
    }

    /// Groups by the text rules: numbers or bullets, else paragraphs, else
    /// lines.
    fn groups(&self) -> Vec<Vec<Range<usize>>> {
        self.numbered().unwrap_or_else(|| {
            let paragraphs: Vec<Vec<Range<usize>>> = self
                .lines
                .split(Option::is_none)
                .filter(|p| !p.is_empty())
                .map(|p| p.iter().flatten().cloned().collect())
                .collect();
            let alone = paragraphs.len() == 1;
            paragraphs
                .into_iter()
                .flat_map(|p| self.unnumbered(p, alone))
                .collect()
        })
    }

    fn line(&self, r: &Range<usize>) -> &'a str {
        &self.text[r.clone()]
    }

    /// Groups by number or bullet, if two or more lines start with one.
    /// Lines before the first marker are dropped (a heading, usually).
    fn numbered(&self) -> Option<Vec<Vec<Range<usize>>>> {
        let mut groups: Vec<Vec<Range<usize>>> = Vec::new();
        let mut last: Option<Marker> = None;
        for line in self.lines.iter().flatten() {
            let starts = marker(self.line(line)).filter(|(m, _)| match (last, m) {
                (None, _) => true,
                (Some(Marker::Number(n)), Marker::Number(m)) => *m == n + 1,
                (Some(Marker::Bullet), Marker::Bullet) => true,
                _ => false,
            });
            match (starts, groups.last_mut()) {
                (Some((m, used)), _) => {
                    last = Some(m);
                    // A marker alone on its line: the text follows.
                    let first = line.start + used..line.end;
                    groups.push(Vec::new());
                    if !first.is_empty() {
                        groups.last_mut().expect("just pushed").push(first);
                    }
                }
                (None, Some(group)) => group.push(line.clone()),
                (None, None) => {}
            }
        }
        // One marker counts only on the first line ("1. Smith J. …"): later,
        // it may be a wrapped line ("2. ed. Berlin").
        let first_marked = self
            .lines
            .iter()
            .flatten()
            .next()
            .is_some_and(|l| marker(self.line(l)).is_some());
        groups.retain(|g| !g.is_empty());
        (groups.len() >= 2 || groups.len() == 1 && first_marked).then_some(groups)
    }

    /// Groups lines without markers: each its own reference if `alone`
    /// (the whole list) and they read as one per line; otherwise split
    /// where an author list follows a finished sentence.
    fn unnumbered(&self, lines: Vec<Range<usize>>, alone: bool) -> Vec<Vec<Range<usize>>> {
        let one_per_line = alone
            && lines.iter().all(|l| dated(self.line(l)))
            && lines.windows(2).all(|w| {
                let (line, next) = (self.line(&w[0]), self.line(&w[1]));
                ends_reference(line) && !continues(next) && !link_continues(line, next)
            });
        if one_per_line {
            return lines.into_iter().map(|l| vec![l]).collect();
        }
        let mut groups: Vec<Vec<Range<usize>>> = Vec::new();
        for line in lines {
            let text = self.line(&line);
            match groups.last_mut() {
                Some(group) if !(ends_sentence(&self.join(group)) && starts_with_author(text)) => {
                    group.push(line)
                }
                _ => groups.push(vec![line]),
            }
        }
        groups
    }

    /// A group's lines as one: joined with a space, or with none where a
    /// word, DOI or URL was broken across lines.
    fn join(&self, group: &[Range<usize>]) -> String {
        let mut out = String::new();
        for line in group {
            let next = self.line(line);
            let first = next.chars().next().unwrap_or(' ');
            if out.is_empty() {
                // Nothing to join to.
            } else if out.ends_with('-') && first.is_lowercase() && hyphenated_word(&out) {
                out.pop();
            } else if !link_continues(&out, next) {
                out.push(' ');
            }
            out.push_str(next);
        }
        out
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Marker {
    Number(u32),
    Bullet,
}

/// The marker a line starts with, and its length with the space after.
fn marker(line: &str) -> Option<(Marker, usize)> {
    let spaced = |rest: &str, used: usize, needs_space: bool| {
        let gap = rest.len() - rest.trim_start().len();
        (gap > 0 || !needs_space).then_some(used + gap)
    };
    if let Some(rest) = line.strip_prefix(['•', '–', '-', '*', '·']) {
        return Some((Marker::Bullet, spaced(rest, line.len() - rest.len(), true)?));
    }
    let (open, close): (usize, &[char]) = match line.as_bytes().first()? {
        b'[' => (1, &[']']),
        b'(' => (1, &[')']),
        _ => (0, &['.', ')']),
    };
    let inner = &line[open..];
    let digits = inner.len() - inner.trim_start_matches(|c: char| c.is_ascii_digit()).len();
    if !(1..=4).contains(&digits) {
        return None;
    }
    let n: u32 = inner[..digits].parse().ok()?;
    let rest = inner[digits..].strip_prefix(close)?;
    // `[1]Smith` is unambiguous; `1.` needs a space, so `1.5` isn't one.
    Some((
        Marker::Number(n),
        spaced(rest, line.len() - rest.len(), open == 0)?,
    ))
}

/// Ends as a reference does: a full stop, page numbers, a closing bracket,
/// or an identifier.
fn ends_reference(line: &str) -> bool {
    ends_sentence(line) || line.ends_with(|c: char| c.is_ascii_digit() || c == ')' || c == ']')
}

/// Ends with a full stop (or `?`, `!`), or with a whole DOI or URL, as
/// references often do without one.
fn ends_sentence(line: &str) -> bool {
    line.ends_with(['.', '?', '!']) || in_link(line) && !line.ends_with(['/', '-'])
}

/// Has a year (1600 to 2099) or an identifier, as a whole reference does.
fn dated(line: &str) -> bool {
    let year = line
        .split(|c: char| !c.is_ascii_digit())
        .any(|n| n.len() == 4 && ("1600".."2100").contains(&n));
    year || line.contains("doi") || line.contains("10.") || line.contains("http")
}

/// Starts as a wrapped line's continuation does: in lower case, or with
/// punctuation.
fn continues(line: &str) -> bool {
    line.starts_with(|c: char| c.is_lowercase() || ",;:)&".contains(c))
}

/// Starts with a surname and initials or a comma, as author lists do:
/// "Smith J,", "Smith JA.", "Smith, J.", "SMITH, J.", "O'Neil, K.".
fn starts_with_author(line: &str) -> bool {
    let surname_len = line
        .char_indices()
        .take_while(|(_, c)| c.is_alphabetic() || "'’-".contains(*c))
        .last()
        .map_or(0, |(i, c)| i + c.len_utf8());
    let surname = &line[..surname_len];
    if surname.chars().count() < 2 || !surname.starts_with(char::is_uppercase) {
        return false;
    }
    let rest = &line[surname_len..];
    if rest.starts_with(',') {
        return true;
    }
    // Initials: one to three capitals, maybe dotted, then a break.
    let Some(rest) = rest.strip_prefix(' ') else {
        return false;
    };
    let initials: String = rest
        .chars()
        .take_while(|c| c.is_uppercase() || *c == '.')
        .collect();
    let capitals = initials.chars().filter(|c| c.is_uppercase()).count();
    let after = rest[initials.len()..].chars().next();
    (1..=3).contains(&capitals) && after.is_none_or(|c| ", .;".contains(c))
}

/// A word broken with a hyphen at the end of `text`: letters before it.
fn hyphenated_word(text: &str) -> bool {
    let word = text.rsplit(char::is_whitespace).next().unwrap_or_default();
    !in_link(text) && word.trim_end_matches('-').chars().all(char::is_alphabetic)
}

/// `next` continues a DOI or URL that `text` ends with, broken where PDFs
/// break them: after `/`, `-` or `_` (`10.1038/s41586-` + `020-2649-2`),
/// after a dot before a digit or lower case (`j.cell.` + `2020.01.001`),
/// or mid-word before more of the link (`j.ce` + `ll.2020.01.001`, not
/// `2015` or `2015.`).
/// Hyphens are kept as printed: DOIs have real ones, and typesetters
/// rarely add their own inside a link.
pub(crate) fn link_continues(text: &str, next: &str) -> bool {
    let token = next.split_whitespace().next().unwrap_or_default();
    let Some(first) = token.chars().next() else {
        return false;
    };
    if !in_link(text) || !first.is_alphanumeric() {
        return false;
    }
    let lower_or_digit = first.is_lowercase() || first.is_ascii_digit();
    if text.ends_with(['/', '-', '_']) {
        true
    } else if text.ends_with('.') {
        lower_or_digit
    } else {
        // Mid-word: only before more of a link, never a word or a year.
        let inner = token.trim_end_matches(|c: char| !c.is_alphanumeric());
        lower_or_digit && inner.contains(|c: char| "./-_".contains(c))
    }
}

/// `text` ends inside a DOI or URL.
fn in_link(text: &str) -> bool {
    let word = text.rsplit(char::is_whitespace).next().unwrap_or_default();
    let word = word.to_ascii_lowercase();
    word.starts_with("http") || word.starts_with("doi:") || word.starts_with("10.")
}

fn is_heading(text: &str) -> bool {
    let t = text.trim_end_matches(':').trim().to_lowercase();
    matches!(
        t.as_str(),
        "references"
            | "reference list"
            | "bibliography"
            | "works cited"
            | "literature cited"
            | "sources"
            | "citations"
    )
}

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

    fn texts(list: &str) -> Vec<String> {
        split_references(list).into_iter().map(|r| r.text).collect()
    }

    #[test]
    fn numbered_lists_split_at_each_number_in_sequence() {
        let list = "References\n\
            1. LeCun Y, Bengio Y, Hinton G. Deep learning. Nature.\n\
            2015;521:436-44.\n\
            2. Vaswani A, et al. Attention is all you need. NeurIPS 2017.\n";
        assert_eq!(
            texts(list),
            [
                "LeCun Y, Bengio Y, Hinton G. Deep learning. Nature. 2015;521:436-44.",
                "Vaswani A, et al. Attention is all you need. NeurIPS 2017.",
            ]
        );
    }

    #[test]
    fn bracketed_and_parenthesised_numbers() {
        let list = "[1] Smith J. One. 2020.\n[2]Jones K. Two. 2021.\n";
        assert_eq!(texts(list), ["Smith J. One. 2020.", "Jones K. Two. 2021."]);
        let list = "(1) Smith J. One. 2020.\n(2) Jones K. Two. 2021.\n";
        assert_eq!(texts(list), ["Smith J. One. 2020.", "Jones K. Two. 2021."]);
    }

    #[test]
    fn numbers_out_of_sequence_continue_the_reference() {
        let list = "1. Smith J. A study of things. Journal\n\
            2015. 12(3):1-9.\n\
            2. Jones K. Another. 2021.\n";
        assert_eq!(
            texts(list),
            [
                "Smith J. A study of things. Journal 2015. 12(3):1-9.",
                "Jones K. Another. 2021.",
            ]
        );
    }

    #[test]
    fn bullets_mark_references() {
        let list = "• Smith J. One. 2020.\n• Jones K. Two,\n  continued. 2021.\n";
        assert_eq!(
            texts(list),
            ["Smith J. One. 2020.", "Jones K. Two, continued. 2021."]
        );
    }

    #[test]
    fn blank_lines_separate_wrapped_references() {
        let list = "Vaswani A, Shazeer N. Attention is all you need.\n\
            Advances in Neural Information Processing Systems. 2017.\n\
            \n\
            LeCun Y, Bengio Y, Hinton G. Deep learning.\n\
            Nature. 2015;521:436-44.\n";
        assert_eq!(
            texts(list),
            [
                "Vaswani A, Shazeer N. Attention is all you need. Advances in Neural Information Processing Systems. 2017.",
                "LeCun Y, Bengio Y, Hinton G. Deep learning. Nature. 2015;521:436-44.",
            ]
        );
    }

    #[test]
    fn one_per_line() {
        let list = "Smith J. One. 2020.\n\
            World Health Organization. Two. 2021.\n\
            Jones K. Three. https://example.org/three\n";
        assert_eq!(texts(list).len(), 3);
    }

    #[test]
    fn wrapped_lines_without_blank_lines_split_at_authors() {
        let list = "Smith, J. (2020). A study of\n\
            things. Journal of Studies, 12, 1-9.\n\
            Jones, K. (2021). Another study. Nature,\n\
            521, 436.\n";
        assert_eq!(
            texts(list),
            [
                "Smith, J. (2020). A study of things. Journal of Studies, 12, 1-9.",
                "Jones, K. (2021). Another study. Nature, 521, 436.",
            ]
        );
    }

    #[test]
    fn hyphenation_and_broken_links_are_mended() {
        let list = "1. Smith J. Neuro-\nlogical find-\nings. doi:10.1038/\nnature14539\n\
            2. Jones K. https://example.org/a-\nb/c\n";
        assert_eq!(
            texts(list),
            [
                "Smith J. Neurological findings. doi:10.1038/nature14539",
                "Jones K. https://example.org/a-b/c",
            ]
        );
    }

    #[test]
    fn links_broken_by_pdf_extraction_are_rejoined_as_printed() {
        let list = "[1] Smith J. Cells. Cell. 2020. https://doi.org/10.1016/j.cell.\n\
            2020.01.001\n\
            [2] Jones K. Folds. Nature. 2020. doi:10.1038/s41586-\n\
            020-2649-2\n\
            [3] Brown L. Stems. https://doi.org/10.1016/j.ce\n\
            ll.2021.02.003\n";
        assert_eq!(
            texts(list),
            [
                "Smith J. Cells. Cell. 2020. https://doi.org/10.1016/j.cell.2020.01.001",
                "Jones K. Folds. Nature. 2020. doi:10.1038/s41586-020-2649-2",
                "Brown L. Stems. https://doi.org/10.1016/j.cell.2021.02.003",
            ]
        );
        // Unnumbered, the continuation isn't a reference of its own.
        let list = "Smith J. Cells. Cell. 2020. doi:10.1016/j.cell.\n2020.01.001\n\
            Jones K. Folds. Nature. 2020.\n";
        assert_eq!(texts(list).len(), 2);
        // A link that ends the line, then a new sentence, stays apart.
        assert_eq!(
            texts("1. Smith J. doi:10.1038/x.\nNature. 2020.\n2. Jones K. 2021.")[0],
            "Smith J. doi:10.1038/x. Nature. 2020."
        );
    }

    #[test]
    fn a_single_numbered_reference_loses_its_number() {
        assert_eq!(
            texts("1. LeCun Y. Deep learning. Nature. 2015."),
            ["LeCun Y. Deep learning. Nature. 2015."]
        );
        // A number further down is part of the reference.
        assert_eq!(
            texts("Smith J. A book.\n2. ed. Berlin: Springer; 2010."),
            ["Smith J. A book. 2. ed. Berlin: Springer; 2010."]
        );
    }

    #[test]
    fn markers_alone_on_their_line_number_the_next() {
        assert_eq!(
            texts("[1]\nSmith J. One. 2020.\n[2]\nJones K. Two. 2021.\n[3] "),
            ["Smith J. One. 2020.", "Jones K. Two. 2021."]
        );
    }

    #[test]
    fn pdf_text_is_cleaned_and_spans_point_into_it() {
        let list = "1. Smith J. Neuro\u{AD}\nlogical findings. doi:10.1038/s41586\u{2010}020-2649-2\n\
            2. Jones K. Two. 2021.";
        let refs = split_references(list);
        assert_eq!(
            refs[0].text,
            "Smith J. Neurological findings. doi:10.1038/s41586-020-2649-2"
        );
        assert!(list[refs[0].span.clone()].starts_with("Smith J. Neuro\u{AD}"));
        assert!(list[refs[0].span.clone()].ends_with("\u{2010}020-2649-2"));
    }

    #[test]
    fn dois_broken_at_a_hyphen_carry_the_reading_without_it() {
        let refs = split_references("1. Smith J. doi:10.1038/nat-\nure14539\n2. Jones K. 2021.");
        assert_eq!(refs[0].text, "Smith J. doi:10.1038/nat-ure14539");
        let alt = &refs[0].alternatives[0];
        assert_eq!(alt.claimed.to_string(), "doi:10.1038/nat-ure14539");
        assert_eq!(alt.alternative.to_string(), "doi:10.1038/nature14539");
        assert!(refs[1].alternatives.is_empty());
    }

    #[test]
    fn hanging_indents_mark_starts_that_text_cannot() {
        // Each line ends a sentence and the next starts with a capital,
        // so the text alone reads three references.
        let lines = [
            IndentedLine::new("References", 72.4),
            IndentedLine::new("World Health Organization. Global report.", 72.0),
            IndentedLine::new("Geneva: WHO; 2020.", 90.2),
            IndentedLine::new("Smith J. A study. Nature. 2021.", 71.8),
        ];
        let refs = split_lines(&lines);
        assert_eq!(
            refs.iter().map(|r| r.text.as_str()).collect::<Vec<_>>(),
            [
                "World Health Organization. Global report. Geneva: WHO; 2020.",
                "Smith J. A study. Nature. 2021.",
            ]
        );
        assert_eq!(refs[0].lines, 1..3);
        assert_eq!(refs[1].lines, 3..4);
    }

    #[test]
    fn first_line_indents_and_flat_lists() {
        let lines = [
            IndentedLine::new("Smith J. A study of", 90.0),
            IndentedLine::new("Things. Nature. 2021.", 72.0),
            IndentedLine::new("Jones K. Another. 2022.", 90.0),
        ];
        assert_eq!(split_lines(&lines).len(), 2);
        // One indent throughout: the text rules decide.
        let flat = [
            IndentedLine::new("1. Smith J. One.", 72.0),
            IndentedLine::new("2020.", 72.0),
            IndentedLine::new("2. Jones K. Two. 2021.", 72.0),
        ];
        let refs = split_lines(&flat);
        assert_eq!(refs[0].text, "Smith J. One. 2020.");
        assert_eq!(refs[1].lines, 2..3);
    }

    #[test]
    fn spans_cover_the_reference_without_its_marker() {
        let list = "1. Smith J. One.\r\n   2020.\r\n2. Jones K. Two. 2021.";
        let refs = split_references(list);
        assert_eq!(&list[refs[0].span.clone()], "Smith J. One.\r\n   2020.");
        assert_eq!(&list[refs[1].span.clone()], "Jones K. Two. 2021.");
    }

    #[test]
    fn a_single_reference_is_one() {
        assert_eq!(
            texts("Smith J. A study.\nJournal 2020;1:2."),
            ["Smith J. A study. Journal 2020;1:2."]
        );
        assert!(texts("  \n\n").is_empty());
    }
}