vim-navigation 0.2.1

Reusable Vim-compatible motion and modal text-input state
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
//! Borrowed multi-line text model and semantic Vim scans.
//!
//! The model normalizes only observation: it treats an empty input slice as a
//! virtual empty line and clamps positions without allocating or changing the
//! caller's text. Word, sentence, paragraph, structural, comment,
//! preprocessor, and diff movement live here because they scan across logical
//! lines rather than terminal cells.

use std::cmp::Ordering;

use super::Cursor;
use super::line::{
    byte_at_display, clamp_boundary, first_non_blank, is_diff_change_line, is_pair_character,
    last_column, next_column,
};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct Position {
    pub(super) line: usize,
    pub(super) column: usize,
}

impl From<Position> for Cursor {
    fn from(value: Position) -> Self {
        Self::new(value.line, value.column)
    }
}

#[derive(Clone, Copy)]
pub(super) enum WordMotion {
    StartForward,
    EndForward,
    StartBackward,
    EndBackward,
}

#[derive(Clone, Copy)]
pub(super) enum WordStyle {
    Word,
    BigWord,
}

#[derive(Clone, Copy, Eq, PartialEq)]
pub(super) enum ScanDirection {
    Forward,
    Backward,
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum SentenceStart {
    Punctuation,
    Paragraph,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PreprocessorDirective {
    If,
    Else,
    EndIf,
}

pub(super) struct TextBuffer<'a> {
    lines: &'a [&'a str],
}

impl<'a> TextBuffer<'a> {
    pub(super) fn new(lines: &'a [&'a str]) -> Self {
        Self { lines }
    }

    pub(super) fn len(&self) -> usize {
        // A cursor always needs one addressable logical line, even when an
        // adapter supplies no lines for an empty document.
        self.lines.len().max(1)
    }

    pub(super) fn last_line(&self) -> usize {
        self.len().saturating_sub(1)
    }

    pub(super) fn line(&self, index: usize) -> &str {
        self.lines.get(index).copied().unwrap_or("")
    }

    pub(super) fn clamp(&self, position: Cursor) -> Position {
        let line = position.line().min(self.last_line());
        let text = self.line(line);
        let mut column = position.byte_column().min(text.len());
        while !text.is_char_boundary(column) {
            column = column.saturating_sub(1);
        }
        // Normal-mode motion rests on a scalar, never on the insertion point
        // after it. EditableBuffer performs its separate Insert-mode clamping.
        if column == text.len() && !text.is_empty() {
            column = last_column(text);
        }
        Position { line, column }
    }

    pub(super) fn move_lines(&self, cursor: Position, delta: isize) -> Position {
        let line = cursor
            .line
            .saturating_add_signed(delta)
            .min(self.last_line());
        self.move_to_line(cursor, line)
    }

    pub(super) fn move_to_line(&self, cursor: Position, line: usize) -> Position {
        let line = line.min(self.last_line());
        let text = self.line(line);
        let mut column = cursor.column.min(last_column(text));
        while !text.is_char_boundary(column) {
            column = column.saturating_sub(1);
        }
        Position { line, column }
    }

    pub(super) fn move_lines_to_display(
        &self,
        cursor: Position,
        delta: isize,
        display_column: usize,
    ) -> Position {
        let line = cursor
            .line
            .saturating_add_signed(delta)
            .min(self.last_line());
        self.move_to_line_display(cursor, line, display_column)
    }

    pub(super) fn move_to_line_display(
        &self,
        _cursor: Position,
        line: usize,
        display_column: usize,
    ) -> Position {
        let line = line.min(self.last_line());
        let text = self.line(line);
        // The motion engine uses MAX only for Vim's `$` desired-column rule:
        // subsequent vertical motions follow each destination line's end.
        let column = if display_column == usize::MAX {
            last_column(text)
        } else {
            byte_at_display(text, display_column)
        };
        Position {
            line,
            column: column.min(last_column(text)),
        }
    }

    pub(super) fn byte_offset(&self, one_based: usize) -> Position {
        let mut remaining = one_based.saturating_sub(1);
        for line in 0..self.len() {
            let text = self.line(line);
            if remaining <= text.len() {
                return Position {
                    line,
                    column: clamp_boundary(text, remaining).min(last_column(text)),
                };
            }
            if line == self.last_line() {
                return Position {
                    line,
                    column: last_column(text),
                };
            }
            remaining = remaining.saturating_sub(text.len().saturating_add(1));
        }
        Position {
            line: self.last_line(),
            column: last_column(self.line(self.last_line())),
        }
    }

    pub(super) fn word_motion(
        &self,
        cursor: Position,
        mut count: usize,
        motion: WordMotion,
        style: WordStyle,
    ) -> Position {
        let direction = if matches!(motion, WordMotion::StartForward | WordMotion::EndForward) {
            ScanDirection::Forward
        } else {
            ScanDirection::Backward
        };
        // Start inside the current token: its artificial edge at the cursor
        // is excluded below, while its opposite edge remains a valid e/b target.
        for line in self.line_indices(cursor.line, direction) {
            let text = self.line(line);
            if text.is_empty() && !matches!(motion, WordMotion::EndForward) {
                let position = Position { line, column: 0 };
                if position != cursor {
                    count -= 1;
                    if count == 0 {
                        return position;
                    }
                }
                continue;
            }
            let mut chars = line_characters(text, line, cursor, direction).peekable();
            while let Some((edge, character)) = chars.next() {
                let class = CharacterClass::of(character, style);
                if class == CharacterClass::Space {
                    continue;
                }
                let mut opposite = edge;
                while chars
                    .peek()
                    .is_some_and(|(_, c)| CharacterClass::of(*c, style) == class)
                {
                    if let Some((column, _)) = chars.next() {
                        opposite = column;
                    }
                }
                let column =
                    if matches!(motion, WordMotion::StartForward | WordMotion::StartBackward) {
                        edge.min(opposite)
                    } else {
                        edge.max(opposite)
                    };
                let position = Position { line, column };
                if position != cursor {
                    count -= 1;
                    if count == 0 {
                        return position;
                    }
                }
            }
        }
        if direction == ScanDirection::Forward {
            Position {
                line: self.last_line(),
                column: last_column(self.line(self.last_line())),
            }
        } else {
            Position { line: 0, column: 0 }
        }
    }

    pub(super) fn sentence_forward(&self, cursor: Position) -> Position {
        // An empty-line run is one stop, followed by the next paragraph's text.
        if self.line(cursor.line).is_empty() {
            for line in cursor.line.saturating_add(1)..self.len() {
                if !self.line(line).is_empty() {
                    return self.skip_sentence_blanks(Position { line, column: 0 });
                }
            }
        } else {
            for line in cursor.line..self.len() {
                let text = self.line(line);
                if text.is_empty() {
                    return Position { line, column: 0 };
                }
                for (column, _) in line_characters(text, line, cursor, ScanDirection::Forward) {
                    let candidate = Position { line, column };
                    let boundary = self.sentence_start(candidate);
                    // Leading indentation in the current paragraph belongs to
                    // its first sentence; `)` proceeds to the following one.
                    if candidate != cursor
                        && boundary.is_some()
                        && !(line == cursor.line && boundary == Some(SentenceStart::Paragraph))
                    {
                        return candidate;
                    }
                }
            }
        }
        Position {
            line: self.last_line(),
            column: last_column(self.line(self.last_line())),
        }
    }

    pub(super) fn sentence_backward(&self, cursor: Position) -> Position {
        let mut skipping_empty = self.line(cursor.line).is_empty();
        for line in (0..=cursor.line).rev() {
            let text = self.line(line);
            if text.is_empty() {
                if !skipping_empty {
                    return Position { line, column: 0 };
                }
                continue;
            }
            skipping_empty = false;
            for (column, _) in line_characters(text, line, cursor, ScanDirection::Backward) {
                let candidate = Position { line, column };
                if candidate != cursor && self.sentence_start(candidate).is_some() {
                    return candidate;
                }
            }
        }
        Position { line: 0, column: 0 }
    }

    fn skip_sentence_blanks(&self, cursor: Position) -> Position {
        for line in cursor.line..self.len() {
            let text = self.line(line);
            if text.is_empty() {
                return Position { line, column: 0 };
            }
            if let Some((column, _)) = text.char_indices().find(|(_, c)| !c.is_whitespace()) {
                return Position { line, column };
            }
        }
        Position {
            line: self.last_line(),
            column: last_column(self.line(self.last_line())),
        }
    }

    fn sentence_start(&self, position: Position) -> Option<SentenceStart> {
        let text = self.line(position.line);
        if text[position.column..].starts_with(char::is_whitespace) {
            return None;
        }
        // Only the first nonblank after whitespace can start a sentence. Walk
        // the preceding whitespace/closing punctuation, never the whole prefix.
        let mut before = text[..position.column].chars().rev();
        if position.column > 0 && !before.next().is_some_and(char::is_whitespace) {
            return None;
        }
        let mut closing = false;
        for line in (0..=position.line).rev() {
            let prefix = if line == position.line {
                &text[..position.column]
            } else {
                self.line(line)
            };
            if line < position.line && prefix.is_empty() {
                return Some(SentenceStart::Paragraph);
            }
            for c in prefix.chars().rev() {
                if !closing && c.is_whitespace() {
                    continue;
                }
                if matches!(c, ')' | ']' | '\"' | '\'') {
                    closing = true;
                    continue;
                }
                return matches!(c, '.' | '!' | '?').then_some(SentenceStart::Punctuation);
            }
            // A closing delimiter cannot be separated from its punctuation by
            // a line break. Whitespace alone may span ordinary logical lines.
            if closing {
                return None;
            }
        }
        None
    }

    pub(super) fn paragraph_forward(&self, cursor: Position) -> Position {
        let mut line = cursor.line;
        if self.line(line).is_empty() {
            while line < self.len() && self.line(line).is_empty() {
                line = line.saturating_add(1);
            }
        } else {
            line = line.saturating_add(1);
        }
        while line < self.len() && !self.line(line).is_empty() {
            line = line.saturating_add(1);
        }
        if line < self.len() {
            Position { line, column: 0 }
        } else {
            let line = self.last_line();
            Position {
                line,
                column: last_column(self.line(line)),
            }
        }
    }

    pub(super) fn paragraph_backward(&self, cursor: Position) -> Position {
        let mut line = cursor.line;
        if self.line(line).is_empty() {
            while line > 0 && self.line(line.saturating_sub(1)).is_empty() {
                line = line.saturating_sub(1);
            }
            line = line.saturating_sub(1);
        } else if line > 0 && self.line(line.saturating_sub(1)).is_empty() {
            return Position {
                line: line.saturating_sub(1),
                column: 0,
            };
        }
        while line > 0 && !self.line(line.saturating_sub(1)).is_empty() {
            line = line.saturating_sub(1);
        }
        if line > 0 {
            line = line.saturating_sub(1);
        }
        Position { line, column: 0 }
    }

    pub(super) fn section(
        &self,
        cursor: Position,
        direction: ScanDirection,
        target: char,
    ) -> Position {
        let found = if direction == ScanDirection::Forward {
            ((cursor.line + 1)..self.len()).find(|line| self.line(*line).starts_with(target))
        } else {
            (0..cursor.line)
                .rev()
                .find(|line| self.line(*line).starts_with(target))
        };
        let line = found.unwrap_or(if direction == ScanDirection::Forward {
            self.last_line()
        } else {
            0
        });
        Position {
            line,
            column: first_non_blank(self.line(line)),
        }
    }

    pub(super) fn matching_pair(
        &self,
        cursor: Position,
        direction: ScanDirection,
    ) -> Option<Position> {
        let text = self.line(cursor.line);
        let directive = preprocessor_directive(text);
        if direction == ScanDirection::Backward {
            // Preserve the library's g% extension: select the nearest previous
            // delimiter, comment marker, or directive on this line.
            let (column, _) =
                line_characters(text, cursor.line, cursor, direction).find(|(column, c)| {
                    is_pair_character(*c)
                        || text[*column..].starts_with("/*")
                        || text[*column..].starts_with("*/")
                        || directive.is_some_and(|(at, _)| at == *column)
                })?;
            return self.matching_pair(
                Position {
                    line: cursor.line,
                    column,
                },
                ScanDirection::Forward,
            );
        }
        if let Some((column, kind)) = directive
            && cursor.column <= column
        {
            return self.preprocessor_match(cursor.line, kind);
        }
        // Either character of /* or */ selects that marker. Comments elsewhere
        // on the line are not implicit targets of the forward delimiter scan.
        for column in [cursor.column, cursor.column.saturating_sub(1)] {
            let tail = text.get(column..).unwrap_or("");
            let origin = Position {
                line: cursor.line,
                column,
            };
            if tail.starts_with("/*") {
                return self.comment_match(origin, ScanDirection::Forward);
            }
            if tail.starts_with("*/") {
                return self.comment_match(origin, ScanDirection::Backward);
            }
        }
        let found = line_characters(text, cursor.line, cursor, direction)
            .find(|(_, c)| is_pair_character(*c));
        if let Some((column, character)) = found {
            let start = Position {
                line: cursor.line,
                column,
            };
            let (target, delta) = pair_for(character)?;
            let direction = if delta > 0 {
                ScanDirection::Forward
            } else {
                ScanDirection::Backward
            };
            let mut depth = 0usize;
            for (position, c) in self.characters(start, direction).skip(1) {
                if c == character {
                    depth = depth.saturating_add(1);
                } else if c == target {
                    if depth == 0 {
                        return Some(position);
                    }
                    depth -= 1;
                }
            }
            None
        } else {
            directive.and_then(|(_, kind)| self.preprocessor_match(cursor.line, kind))
        }
    }

    fn comment_match(&self, origin: Position, direction: ScanDirection) -> Option<Position> {
        let needle = if direction == ScanDirection::Forward {
            "*/"
        } else {
            "/*"
        };
        for line in self.line_indices(origin.line, direction) {
            let text = self.line(line);
            let column = if direction == ScanDirection::Forward {
                let start = if line == origin.line {
                    origin.column.saturating_add(1)
                } else {
                    0
                };
                text.get(start..)
                    .and_then(|tail| tail.find(needle))
                    .map(|column| start + column + 1)
            } else {
                let end = if line == origin.line {
                    origin.column
                } else {
                    text.len()
                };
                text[..end].rfind(needle)
            };
            if let Some(column) = column {
                return Some(Position { line, column });
            }
        }
        None
    }

    fn preprocessor_match(
        &self,
        origin_line: usize,
        origin: PreprocessorDirective,
    ) -> Option<Position> {
        if origin == PreprocessorDirective::EndIf {
            let mut depth = 0usize;
            for line in (0..origin_line).rev() {
                let Some((column, directive)) = preprocessor_directive(self.line(line)) else {
                    continue;
                };
                match directive {
                    PreprocessorDirective::EndIf => depth = depth.saturating_add(1),
                    PreprocessorDirective::If if depth == 0 => {
                        return Some(Position { line, column });
                    }
                    PreprocessorDirective::If => depth = depth.saturating_sub(1),
                    PreprocessorDirective::Else => {}
                }
            }
            return None;
        }

        let mut depth = 0usize;
        for line in origin_line.saturating_add(1)..self.len() {
            let Some((column, directive)) = preprocessor_directive(self.line(line)) else {
                continue;
            };
            match directive {
                PreprocessorDirective::If => depth = depth.saturating_add(1),
                PreprocessorDirective::EndIf if depth == 0 => {
                    return Some(Position { line, column });
                }
                PreprocessorDirective::EndIf => depth = depth.saturating_sub(1),
                PreprocessorDirective::Else if depth == 0 => {
                    return Some(Position { line, column });
                }
                PreprocessorDirective::Else => {}
            }
        }
        None
    }

    pub(super) fn unmatched_open(&self, cursor: Position, open: char) -> Position {
        let close = match open {
            '(' => ')',
            '{' => '}',
            '[' => ']',
            _ => return cursor,
        };
        let mut depth = 0usize;
        for (position, character) in self
            .characters(cursor, ScanDirection::Backward)
            .filter(|(at, _)| *at != cursor)
        {
            if character == close {
                depth = depth.saturating_add(1);
            } else if character == open {
                if depth == 0 {
                    return position;
                }
                depth = depth.saturating_sub(1);
            }
        }
        cursor
    }

    pub(super) fn unmatched_close(&self, cursor: Position, close: char) -> Position {
        let open = match close {
            ')' => '(',
            '}' => '{',
            ']' => '[',
            _ => return cursor,
        };
        let mut depth = 0usize;
        for (position, character) in self
            .characters(cursor, ScanDirection::Forward)
            .filter(|(at, _)| *at != cursor)
        {
            if character == open {
                depth = depth.saturating_add(1);
            } else if character == close {
                if depth == 0 {
                    return position;
                }
                depth = depth.saturating_sub(1);
            }
        }
        cursor
    }

    pub(super) fn brace(
        &self,
        cursor: Position,
        direction: ScanDirection,
        target: char,
    ) -> Position {
        self.characters(cursor, direction)
            .filter(|(at, _)| *at != cursor)
            .find(|(_, character)| *character == target)
            .map_or(cursor, |(position, _)| position)
    }

    pub(super) fn preprocessor(&self, cursor: Position, direction: ScanDirection) -> Position {
        let mut depth = 0usize;
        if direction == ScanDirection::Forward {
            for line in cursor.line.saturating_add(1)..self.len() {
                let Some((column, directive)) = preprocessor_directive(self.line(line)) else {
                    continue;
                };
                match directive {
                    PreprocessorDirective::If => depth = depth.saturating_add(1),
                    PreprocessorDirective::EndIf if depth == 0 => {
                        return Position { line, column };
                    }
                    PreprocessorDirective::EndIf => depth = depth.saturating_sub(1),
                    PreprocessorDirective::Else if depth == 0 => {
                        return Position { line, column };
                    }
                    PreprocessorDirective::Else => {}
                }
            }
        } else {
            for line in (0..cursor.line).rev() {
                let Some((column, directive)) = preprocessor_directive(self.line(line)) else {
                    continue;
                };
                match directive {
                    PreprocessorDirective::EndIf => depth = depth.saturating_add(1),
                    PreprocessorDirective::If if depth == 0 => {
                        return Position { line, column };
                    }
                    PreprocessorDirective::If => depth = depth.saturating_sub(1),
                    PreprocessorDirective::Else if depth == 0 => {
                        return Position { line, column };
                    }
                    PreprocessorDirective::Else => {}
                }
            }
        }
        cursor
    }

    pub(super) fn comment(&self, cursor: Position, direction: ScanDirection) -> Position {
        let needle = if direction == ScanDirection::Forward {
            "*/"
        } else {
            "/*"
        };
        let mut candidates = Vec::new();
        for line in 0..self.len() {
            let text = self.line(line);
            for (column, _) in text.match_indices(needle) {
                candidates.push(Position { line, column });
            }
        }
        if direction == ScanDirection::Forward {
            candidates
                .into_iter()
                .find(|position| compare(*position, cursor) == Ordering::Greater)
                .map(|mut position| {
                    position.column = next_column(self.line(position.line), position.column);
                    position
                })
                .unwrap_or(cursor)
        } else {
            candidates
                .into_iter()
                .rev()
                .find(|position| compare(*position, cursor) == Ordering::Less)
                .unwrap_or(cursor)
        }
    }

    pub(super) fn diff_change(&self, cursor: Position, direction: ScanDirection) -> Position {
        let mut starts = (0..self.len()).filter(|line| {
            is_diff_change_line(self.line(*line))
                && (*line == 0 || !is_diff_change_line(self.line(line.saturating_sub(1))))
        });
        let found = if direction == ScanDirection::Forward {
            starts.find(|line| *line > cursor.line)
        } else {
            starts.rfind(|line| *line < cursor.line)
        };
        found.map_or(cursor, |line| Position { line, column: 0 })
    }

    fn line_indices(&self, start: usize, direction: ScanDirection) -> impl Iterator<Item = usize> {
        let length = if direction == ScanDirection::Forward {
            self.len() - start
        } else {
            start + 1
        };
        (0..length).map(move |offset| {
            if direction == ScanDirection::Forward {
                start + offset
            } else {
                start - offset
            }
        })
    }

    fn characters(
        &self,
        cursor: Position,
        direction: ScanDirection,
    ) -> impl Iterator<Item = (Position, char)> {
        self.line_indices(cursor.line, direction)
            .flat_map(move |line| {
                line_characters(self.line(line), line, cursor, direction)
                    .map(move |(column, character)| (Position { line, column }, character))
            })
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum CharacterClass {
    Space,
    Keyword,
    Other,
}

impl CharacterClass {
    fn of(character: char, style: WordStyle) -> Self {
        if character.is_whitespace() {
            Self::Space
        } else if matches!(style, WordStyle::BigWord)
            || character.is_alphanumeric()
            || character == '_'
        {
            Self::Keyword
        } else {
            Self::Other
        }
    }
}

fn compare(left: Position, right: Position) -> Ordering {
    (left.line, left.column).cmp(&(right.line, right.column))
}

// Trim only the origin line, then consume scalars in the requested direction.
// This keeps local motions independent of the size of the rest of the snapshot.
fn line_characters(
    text: &str,
    line: usize,
    cursor: Position,
    direction: ScanDirection,
) -> impl Iterator<Item = (usize, char)> {
    let start = if line == cursor.line && direction == ScanDirection::Forward {
        cursor.column
    } else {
        0
    };
    let end = if line == cursor.line && direction == ScanDirection::Backward {
        cursor.column
            + text[cursor.column..]
                .chars()
                .next()
                .map_or(0, char::len_utf8)
    } else {
        text.len()
    };
    let mut chars = text[start..end].char_indices();
    std::iter::from_fn(move || {
        let next = if direction == ScanDirection::Forward {
            chars.next()
        } else {
            chars.next_back()
        };
        next.map(|(column, c)| (column + start, c))
    })
}

fn preprocessor_directive(line: &str) -> Option<(usize, PreprocessorDirective)> {
    let column = first_non_blank(line);
    let directive = line.get(column..)?.strip_prefix('#')?.trim_start();
    let kind = if directive.starts_with("if") {
        PreprocessorDirective::If
    } else if directive.starts_with("else") || directive.starts_with("elif") {
        PreprocessorDirective::Else
    } else if directive.starts_with("endif") {
        PreprocessorDirective::EndIf
    } else {
        return None;
    };
    Some((column, kind))
}

fn pair_for(character: char) -> Option<(char, isize)> {
    match character {
        '(' => Some((')', 1)),
        '[' => Some((']', 1)),
        '{' => Some(('}', 1)),
        ')' => Some(('(', -1)),
        ']' => Some(('[', -1)),
        '}' => Some(('{', -1)),
        _ => None,
    }
}