shoin 0.2.1

A no-clutter terminal Markdown editor with modal editing
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
//! List items as units — the foundation of structural list editing (#29, #30).
//!
//! An ITEM is an item line plus everything that belongs to it: wrapped and
//! lazy continuation lines, nested paragraphs, fenced blocks, and child items
//! with their own subtrees. The `al`/`aL` objects, item moves and renumbering
//! are all built on the bounds computed here.
//!
//! Nesting follows the rule HTML export uses (`export/html.rs`
//! `adjust_lists`): an item's parent is the nearest item above it with a
//! smaller indent, not CommonMark's content column. Editing and export have to
//! agree on what is nested under what.
//!
//! Lines are classified by the block cache rather than re-parsed here, which is
//! the one place the text layer reads a render type: `BlockKind` already knows
//! fences, headings and list markers, and a second parser would drift from it.
//! Indents, though, are measured here, in columns with a tab counting as
//! `tab_width` — the cache's `depth` counts a tab as one.
//!
//! Every function is pure over the buffer text and the kinds, and every range
//! is a pair of line numbers, END INCLUSIVE, like `object::paragraph_bounds`.

use std::ops::Range;

use super::buffer::Buffer;
use crate::render::markdown::block::{BlockKind, Marker};

/// Leading whitespace in columns, a tab counting as `tab_width`. Matches how
/// the renderer lays out a tabbed list (`render::layout::content_column`).
pub fn indent_cols(line: &str, tab_width: usize) -> usize {
    line.chars()
        .map_while(|c| match c {
            ' ' => Some(1),
            '\t' => Some(tab_width.max(1)),
            _ => None,
        })
        .sum()
}

/// One ordinal to rewrite: the digits at `cols` (chars) on `line` become
/// `number`. The delimiter after them is left as it is.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Renumber {
    pub line: usize,
    pub cols: Range<usize>,
    pub number: String,
}

/// A view of one document's lists. Cheap to build; holds no state of its own.
/// `kinds` must be the block cache for `buffer`'s current text.
pub struct Lists<'a> {
    buffer: &'a Buffer,
    kinds: &'a [BlockKind],
    tab_width: usize,
}

impl<'a> Lists<'a> {
    pub fn new(buffer: &'a Buffer, kinds: &'a [BlockKind], tab_width: usize) -> Self {
        Lists {
            buffer,
            kinds,
            tab_width,
        }
    }

    /// The item containing `line`, children included — the `al` range. On a
    /// continuation line or a child paragraph it is the innermost item around
    /// it; outside any list, `None`.
    pub fn item_bounds(&self, line: usize) -> Option<(usize, usize)> {
        self.item_at(line).map(|s| self.bounds(s))
    }

    /// The item containing `line` without its children — the `il` range: its
    /// own line, its continuation lines, and anything else of its own before
    /// the first child item. Never ends on a blank line.
    pub fn own_bounds(&self, line: usize) -> Option<(usize, usize)> {
        let start = self.item_at(line)?;
        let mut e = match self.first_child(start) {
            Some(child) => child - 1,
            None => self.bounds(start).1,
        };
        while e > start && self.blank(e) {
            e -= 1;
        }
        Some((start, e))
    }

    /// The item line of the first child of the item containing `line`.
    pub fn first_child(&self, line: usize) -> Option<usize> {
        let start = self.item_at(line)?;
        let (_, end) = self.bounds(start);
        let d = self.indent(start);
        (start + 1..=end).find(|&l| self.is_item(l) && self.indent(l) > d)
    }

    /// The first line of the parent of the item containing `line`. `None` for
    /// a top-level item, or outside a list.
    pub fn parent(&self, line: usize) -> Option<usize> {
        self.parent_of(self.item_at(line)?)
    }

    /// The previous sibling of the item containing `line`: same parent, same
    /// kind of list. `None` for a first child.
    pub fn prev_sibling_bounds(&self, line: usize) -> Option<(usize, usize)> {
        self.prev_sibling(self.item_at(line)?).map(|s| self.bounds(s))
    }

    /// The next sibling of the item containing `line`. `None` for a last child.
    pub fn next_sibling_bounds(&self, line: usize) -> Option<(usize, usize)> {
        self.next_sibling(self.item_at(line)?).map(|s| self.bounds(s))
    }

    /// Every sibling of the item containing `line`, first through last, each
    /// with its children — the `aL` range.
    pub fn level_bounds(&self, line: usize) -> Option<(usize, usize)> {
        let items = self.level_items(line);
        Some((*items.first()?, self.bounds(*items.last()?).1))
    }

    /// The item lines of every sibling of the item containing `line`, in
    /// order. Empty outside a list.
    pub fn level_items(&self, line: usize) -> Vec<usize> {
        let Some(item) = self.item_at(line) else {
            return Vec::new();
        };
        let mut items = vec![item];
        while let Some(p) = self.prev_sibling(items[0]) {
            items.insert(0, p);
        }
        while let Some(n) = self.next_sibling(*items.last().unwrap_or(&item)) {
            items.push(n);
        }
        items
    }

    /// How far this document nests a child inside its parent, in columns: the
    /// parent→child step of the nesting nearest to `line`, so a file that
    /// nests by 2 keeps nesting by 2 whatever `tab_width` says. `None` when no
    /// list in the document nests. Items in `skip` are not measured: a level
    /// being shifted would otherwise count its own distance from its parent.
    pub fn step(&self, line: usize, skip: &[usize]) -> Option<usize> {
        let last = self.buffer.last_line();
        // Outward from `line`, alternating below and above.
        let near = (0..=last).flat_map(|d| {
            let below = (d > 0).then(|| line.checked_add(d)).flatten();
            [line.checked_sub(d), below]
        });
        near.flatten()
            .filter(|&l| l <= last && self.is_item(l) && !skip.contains(&l))
            .find_map(|l| {
                let parent = self.parent_of(l)?;
                Some(self.indent(l) - self.indent(parent))
            })
    }

    /// The column the item containing `line` sits at.
    pub fn item_indent(&self, line: usize) -> Option<usize> {
        self.item_at(line).map(|s| self.indent(s))
    }

    /// The number of the ordered item on `line`, and the chars its digits
    /// span. `None` for a bullet, a line that is not an item, or a number too
    /// long to count with.
    pub fn ordinal(&self, line: usize) -> Option<(u64, Range<usize>)> {
        if !self.ordered(line) {
            return None;
        }
        let text = self.buffer.line_text(line);
        let ws = text.chars().take_while(|c| *c == ' ' || *c == '\t').count();
        let digits: String = text.chars().skip(ws).take_while(char::is_ascii_digit).collect();
        Some((digits.parse().ok()?, ws..ws + digits.len()))
    }

    /// The edits that number the ordered level containing `line` in sequence,
    /// counting up from `start` — or, with `None`, from its first item's own
    /// number, so a list that starts at `3.` keeps starting there. Each item
    /// keeps its own `.` or `)`. Nothing for a bullet list, or one already in
    /// sequence.
    ///
    /// The edits are returned, not made, so the caller can put them in the
    /// same undo step as whatever disturbed the numbering.
    pub fn renumber(&self, line: usize, start: Option<u64>) -> Vec<Renumber> {
        let ordinals: Option<Vec<(usize, u64, Range<usize>)>> = self
            .level_items(line)
            .into_iter()
            .map(|l| self.ordinal(l).map(|(n, cols)| (l, n, cols)))
            .collect();
        // A bullet list, or an ordinal too long to parse: leave it as written.
        let Some(ordinals) = ordinals.filter(|o| !o.is_empty()) else {
            return Vec::new();
        };
        let first = start.unwrap_or(ordinals[0].1);
        ordinals
            .into_iter()
            .zip(first..)
            .filter(|((_, n, _), want)| n != want)
            .map(|((line, _, cols), want)| Renumber {
                line,
                cols,
                number: want.to_string(),
            })
            .collect()
    }

    fn kind(&self, line: usize) -> Option<&BlockKind> {
        self.kinds.get(line)
    }

    fn is_item(&self, line: usize) -> bool {
        matches!(self.kind(line), Some(BlockKind::ListItem { .. }))
    }

    /// Ordered or bullet. Switching between the two at one depth starts a new
    /// list; `-`, `*` and `+` are all one kind, as in export.
    fn ordered(&self, line: usize) -> bool {
        matches!(
            self.kind(line),
            Some(BlockKind::ListItem {
                marker: Marker::Ordered,
                ..
            })
        )
    }

    fn blank(&self, line: usize) -> bool {
        matches!(self.kind(line), Some(BlockKind::Blank))
    }

    fn indent(&self, line: usize) -> usize {
        indent_cols(&self.buffer.line_text(line), self.tab_width)
    }

    /// The extent of the item whose item line is `start`.
    fn bounds(&self, start: usize) -> (usize, usize) {
        let last = self.buffer.last_line();
        let d = self.indent(start);
        let mut end = start;
        let mut in_fence = false;
        let mut i = start + 1;
        while i <= last {
            let Some(kind) = self.kind(i) else { break };
            match kind {
                // A fence that opened inside the item keeps every line up to
                // its close, whatever their indentation: they are text, not
                // structure.
                BlockKind::FenceBody { .. } | BlockKind::FenceClose if in_fence => {
                    in_fence = !matches!(kind, BlockKind::FenceClose);
                }
                // A blank run belongs only if what follows it is deeper — a
                // loose item's child. Trailing blank lines never do.
                BlockKind::Blank => {
                    let mut j = i + 1;
                    while j <= last && self.blank(j) {
                        j += 1;
                    }
                    if j > last || self.indent(j) <= d {
                        break;
                    }
                    i = j;
                    continue;
                }
                _ if self.indent(i) > d => {
                    in_fence = matches!(kind, BlockKind::FenceOpen(_));
                }
                // Lazy continuation: a paragraph line may drop its indent when
                // it directly follows paragraph text (`- one\ntwo`).
                BlockKind::Paragraph
                    if matches!(
                        self.kind(i - 1),
                        Some(BlockKind::Paragraph | BlockKind::ListItem { .. })
                    ) => {}
                _ => break,
            }
            end = i;
            i += 1;
        }
        (start, end)
    }

    /// The innermost item whose bounds contain `line`, as its item line.
    fn item_at(&self, line: usize) -> Option<usize> {
        let mut k = (0..=line).rev().find(|&l| self.is_item(l))?;
        // Nothing above the nearest item line can contain `line` without
        // containing that item line too — so climb its ancestors.
        while self.bounds(k).1 < line {
            k = self.shallower_above(k)?;
        }
        Some(k)
    }

    /// The nearest item line above `line` with a smaller indent than it.
    fn shallower_above(&self, line: usize) -> Option<usize> {
        let d = self.indent(line);
        if d == 0 {
            return None;
        }
        (0..line)
            .rev()
            .find(|&l| self.is_item(l) && self.indent(l) < d)
    }

    /// Nearest shallower item above `item` whose bounds contain it.
    fn parent_of(&self, item: usize) -> Option<usize> {
        let mut k = self.shallower_above(item)?;
        while self.bounds(k).1 < item {
            k = self.shallower_above(k)?;
        }
        Some(k)
    }

    fn same_list(&self, a: usize, b: usize) -> bool {
        self.ordered(a) == self.ordered(b) && self.parent_of(a) == self.parent_of(b)
    }

    fn next_sibling(&self, item: usize) -> Option<usize> {
        let last = self.buffer.last_line();
        let mut j = self.bounds(item).1 + 1;
        while j <= last && self.blank(j) {
            j += 1;
        }
        (j <= last && self.is_item(j) && self.same_list(item, j)).then_some(j)
    }

    /// Found from the line just above `item` (past any blank run): the
    /// previous sibling's subtree ends there, so it is that line's innermost
    /// item or one of its ancestors.
    fn prev_sibling(&self, item: usize) -> Option<usize> {
        let mut p = item.checked_sub(1)?;
        while self.blank(p) {
            p = p.checked_sub(1)?;
        }
        let parent = self.parent_of(item);
        let mut x = self.item_at(p)?;
        while self.parent_of(x) != parent {
            if Some(x) == parent {
                return None;
            }
            x = self.parent_of(x)?;
        }
        (self.next_sibling(x) == Some(item)).then_some(x)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::render::markdown::block::BlockCache;
    use ropey::Rope;

    fn buf(text: &str) -> Buffer {
        let mut b = Buffer::empty();
        b.rope = Rope::from_str(text);
        b
    }

    /// Runs `f` against the lists of `text` with a tab width of 4.
    fn with<T>(text: &str, f: impl FnOnce(&Lists) -> T) -> T {
        let b = buf(text);
        let cache = BlockCache::build(&b);
        f(&Lists::new(&b, &cache.kinds, 4))
    }

    #[test]
    fn indent_counts_a_tab_as_tab_width() {
        assert_eq!(indent_cols("  - a", 4), 2);
        assert_eq!(indent_cols("\t- a", 4), 4);
        assert_eq!(indent_cols(" \t- a", 2), 3);
        assert_eq!(indent_cols("- a", 4), 0);
    }

    #[test]
    fn tight_list_items_carry_their_children() {
        let t = "- a\n  - a1\n  - a2\n    - a2x\n- b\n";
        with(t, |l| {
            assert_eq!(l.item_bounds(0), Some((0, 3)));
            assert_eq!(l.item_bounds(1), Some((1, 1)));
            assert_eq!(l.item_bounds(2), Some((2, 3)));
            assert_eq!(l.item_bounds(4), Some((4, 4)));
        });
    }

    #[test]
    fn loose_items_keep_inner_blanks_but_never_trailing_ones() {
        let t = "- a\n\n  - a1\n\n- b\n\nafter\n";
        with(t, |l| {
            assert_eq!(l.item_bounds(0), Some((0, 2)));
            // A blank inside a loose item belongs to it.
            assert_eq!(l.item_bounds(1), Some((0, 2)));
            // A blank between two top-level items belongs to neither.
            assert_eq!(l.item_bounds(3), None);
            assert_eq!(l.item_bounds(4), Some((4, 4)));
            assert_eq!(l.item_bounds(6), None);
        });
    }

    #[test]
    fn lazy_continuation_under_a_nested_item() {
        let t = "- a\n  - b\nlazy\n- c\n";
        with(t, |l| {
            assert_eq!(l.item_bounds(1), Some((1, 2)));
            assert_eq!(l.item_bounds(0), Some((0, 2)));
            // The cursor on the lazy line is in the innermost item.
            assert_eq!(l.item_bounds(2), Some((1, 2)));
        });
    }

    #[test]
    fn fence_body_less_indented_than_the_item_stays_in_it() {
        let t = "- a\n  ```\nbody\n  ```\n- b\n";
        with(t, |l| {
            assert_eq!(l.item_bounds(0), Some((0, 3)));
            assert_eq!(l.item_bounds(2), Some((0, 3)));
            assert_eq!(l.next_sibling_bounds(0), Some((4, 4)));
        });
    }

    #[test]
    fn child_paragraph_and_continuation_lines() {
        let t = "- a\n  wrapped\n\n  para\n- b\n";
        with(t, |l| {
            assert_eq!(l.item_bounds(0), Some((0, 3)));
            assert_eq!(l.item_bounds(1), Some((0, 3)));
            assert_eq!(l.item_bounds(3), Some((0, 3)));
        });
    }

    #[test]
    fn a_list_ends_at_a_heading_rule_or_table_without_a_blank() {
        for t in [
            "- a\n# h\n",
            "- a\n---\n",
            "- a\n| x | y |\n|---|---|\n",
        ] {
            with(t, |l| assert_eq!(l.item_bounds(0), Some((0, 0)), "{t:?}"));
        }
    }

    #[test]
    fn outside_any_list_there_is_no_item() {
        with("para\n\n# h\n", |l| {
            assert_eq!(l.item_bounds(0), None);
            assert_eq!(l.parent(0), None);
            assert_eq!(l.level_bounds(2), None);
        });
    }

    #[test]
    fn last_item_without_a_trailing_newline() {
        with("- a\n- b\n  - c", |l| {
            assert_eq!(l.item_bounds(1), Some((1, 2)));
            assert_eq!(l.prev_sibling_bounds(2), None);
            assert_eq!(l.prev_sibling_bounds(1), Some((0, 0)));
        });
    }

    /// The spec's example: `b` at 3 columns and `c` at 2 are both children of
    /// `a`, so they are siblings.
    #[test]
    fn inconsistent_child_indents_are_still_siblings() {
        let t = "- a\n   - b\n  - c\n";
        with(t, |l| {
            assert_eq!(l.parent(1), Some(0));
            assert_eq!(l.parent(2), Some(0));
            assert_eq!(l.next_sibling_bounds(1), Some((2, 2)));
            assert_eq!(l.prev_sibling_bounds(2), Some((1, 1)));
            assert_eq!(l.item_bounds(0), Some((0, 2)));
        });
    }

    #[test]
    fn tabs_and_spaces_nest_by_columns() {
        // A tab is 4 columns: `\t- b` is as deep as `    - c`, and deeper
        // than `  - x`.
        let t = "- a\n  - x\n\t- b\n    - c\n";
        with(t, |l| {
            assert_eq!(l.parent(2), Some(1));
            assert_eq!(l.next_sibling_bounds(2), Some((3, 3)));
            assert_eq!(l.item_bounds(1), Some((1, 3)));
        });
    }

    #[test]
    fn siblings_skip_children_and_stop_at_the_ends() {
        let t = "- a\n  - a1\n- b\n- c\n  - c1\n";
        with(t, |l| {
            assert_eq!(l.next_sibling_bounds(0), Some((2, 2)));
            assert_eq!(l.prev_sibling_bounds(3), Some((2, 2)));
            assert_eq!(l.prev_sibling_bounds(2), Some((0, 1)));
            assert_eq!(l.prev_sibling_bounds(0), None);
            assert_eq!(l.next_sibling_bounds(3), None);
            // A first child's previous line is its parent, not a sibling.
            assert_eq!(l.prev_sibling_bounds(4), None);
            assert_eq!(l.next_sibling_bounds(1), None);
        });
    }

    #[test]
    fn loose_siblings_across_blank_lines() {
        with("- a\n\n- b\n\n\n- c\n", |l| {
            assert_eq!(l.next_sibling_bounds(0), Some((2, 2)));
            assert_eq!(l.next_sibling_bounds(2), Some((5, 5)));
            assert_eq!(l.prev_sibling_bounds(5), Some((2, 2)));
        });
    }

    #[test]
    fn bullet_and_ordered_at_one_depth_are_different_lists() {
        let t = "- a\n- b\n1. c\n2. d\n";
        with(t, |l| {
            assert_eq!(l.next_sibling_bounds(1), None);
            assert_eq!(l.prev_sibling_bounds(2), None);
            assert_eq!(l.level_bounds(0), Some((0, 1)));
            assert_eq!(l.level_bounds(3), Some((2, 3)));
        });
    }

    #[test]
    fn mixed_bullet_markers_are_one_list() {
        with("- a\n* b\n+ c\n", |l| assert_eq!(l.level_bounds(1), Some((0, 2))));
    }

    #[test]
    fn ordered_inside_bullet_and_the_reverse() {
        let t = "- a\n  1. x\n  2) y\n- b\n  - z\n";
        with(t, |l| {
            assert_eq!(l.parent(2), Some(0));
            assert_eq!(l.level_bounds(1), Some((1, 2)));
            assert_eq!(l.level_bounds(4), Some((4, 4)));
        });
        let t = "1. a\n   - x\n   - y\n2. b\n";
        with(t, |l| {
            assert_eq!(l.parent(2), Some(0));
            assert_eq!(l.next_sibling_bounds(0), Some((3, 3)));
        });
    }

    #[test]
    fn level_takes_every_sibling_with_children() {
        let t = "- p\n  - a\n    - a1\n  - b\n  - c\n    - c1\n- q\n";
        with(t, |l| {
            assert_eq!(l.level_bounds(3), Some((1, 5)));
            assert_eq!(l.level_bounds(0), Some((0, 6)));
        });
    }

    #[test]
    fn task_items_are_items() {
        let t = "- [ ] a\n  - [x] b\n- [ ] c\n";
        with(t, |l| {
            assert_eq!(l.item_bounds(0), Some((0, 1)));
            assert_eq!(l.parent(1), Some(0));
            assert_eq!(l.next_sibling_bounds(0), Some((2, 2)));
        });
    }

    #[test]
    fn step_is_the_nearest_nesting() {
        // Its own list nests by 2.
        assert_eq!(with("- a\n  - b\n- c\n", |l| l.step(2, &[])), Some(2));
        // A flat list takes the step of the nearest list that nests.
        let t = "- x\n   - y\n\np\n\n- a\n- b\n\np\n\n- m\n  - n\n";
        assert_eq!(with(t, |l| l.step(6, &[])), Some(3));
        assert_eq!(with(t, |l| l.step(10, &[])), Some(2));
        // A tab is `tab_width` columns.
        assert_eq!(with("- a\n\t- b\n", |l| l.step(0, &[])), Some(4));
        // Nothing nests.
        assert_eq!(with("- a\n- b\n", |l| l.step(0, &[])), None);
    }

    #[test]
    fn own_bounds_stop_before_the_first_child() {
        let t = "- a\n  wrapped\n\n  para\n\n  - b\n    - c\n- d\n";
        with(t, |l| {
            assert_eq!(l.own_bounds(0), Some((0, 3)));
            assert_eq!(l.own_bounds(3), Some((0, 3)));
            assert_eq!(l.own_bounds(5), Some((5, 5)));
            assert_eq!(l.own_bounds(7), Some((7, 7)));
        });
    }

    /// The numbers `renumber` would write, applied to the text.
    fn renumbered(text: &str, line: usize) -> String {
        with(text, |l| {
            let mut lines: Vec<String> = text.lines().map(String::from).collect();
            for r in l.renumber(line, None) {
                let s = &mut lines[r.line];
                let chars: Vec<char> = s.chars().collect();
                *s = chars[..r.cols.start].iter().collect::<String>()
                    + &r.number
                    + &chars[r.cols.end..].iter().collect::<String>();
            }
            lines.join("\n") + "\n"
        })
    }

    #[test]
    fn renumber_counts_up_from_the_first_number() {
        assert_eq!(renumbered("1. a\n1. b\n5. c\n", 0), "1. a\n2. b\n3. c\n");
        assert_eq!(renumbered("3. a\n1. b\n", 1), "3. a\n4. b\n");
        // Each item keeps its own delimiter.
        assert_eq!(renumbered("1) a\n1. b\n", 0), "1) a\n2. b\n");
        // Already in sequence: nothing to do.
        with("1. a\n2. b\n", |l| assert!(l.renumber(0, None).is_empty()));
    }

    /// Only the level asked for: its sub-lists, and lists elsewhere, are left
    /// as written.
    #[test]
    fn renumber_touches_one_level() {
        let t = "1. a\n   1. x\n   1. y\n1. b\n\n# h\n\n1. p\n1. q\n";
        assert_eq!(
            renumbered(t, 0),
            "1. a\n   1. x\n   1. y\n2. b\n\n# h\n\n1. p\n1. q\n"
        );
        assert_eq!(
            renumbered(t, 2),
            "1. a\n   1. x\n   2. y\n1. b\n\n# h\n\n1. p\n1. q\n"
        );
    }

    #[test]
    fn renumber_handles_a_change_of_width() {
        let t: String = (0..10).map(|i| format!("1. i{i}\n")).collect();
        let want: String = (1..=10).map(|i| format!("{i}. i{}\n", i - 1)).collect();
        assert_eq!(renumbered(&t, 0), want);
    }

    #[test]
    fn renumber_from_a_given_start() {
        with("4. a\n4. b\n", |l| {
            let r = l.renumber(0, Some(1));
            assert_eq!(r.iter().map(|r| r.number.as_str()).collect::<Vec<_>>(), ["1", "2"]);
        });
    }

    #[test]
    fn bullet_lists_are_never_renumbered() {
        with("- a\n- b\n", |l| assert!(l.renumber(0, None).is_empty()));
        with("prose\n", |l| assert!(l.renumber(0, None).is_empty()));
    }

    /// Two lists separated by a heading never see each other.
    #[test]
    fn lists_do_not_cross_a_heading() {
        let t = "- a\n\n# h\n\n- b\n";
        with(t, |l| {
            assert_eq!(l.next_sibling_bounds(0), None);
            assert_eq!(l.prev_sibling_bounds(4), None);
        });
    }
}