vimlet 0.2.0

A headless Vim editing engine for Rust
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
//! Resolve Vim motions and text objects over a borrowed [`TextSource`].

use crate::{ByteOffset, DocumentView, Shape, TextRange, TextSource};

mod block;
mod objects;

/// A search for a single character on the current logical line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CharacterMotion {
    /// Land on the next occurrence (`f`).
    Find,
    /// Stop immediately before the next occurrence (`t`).
    Till,
    /// Land on the previous occurrence (`F`).
    FindBackward,
    /// Stop immediately after the previous occurrence (`T`).
    TillBackward,
}

/// How much of a text object's surroundings the selection includes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextObjectScope {
    /// Select the object's contents (`i` prefix).
    Inner,
    /// Include the object's delimiters or adjacent whitespace (`a` prefix).
    Around,
}

/// The unit to select around the current cursor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextObjectKind {
    /// Select a word using Vimlet's word-character classes (`w`).
    Word,
    /// Select a run of non-whitespace characters (`W`).
    BigWord,
    /// Select a sentence (`s`).
    Sentence,
    /// Select a paragraph as a linewise range (`p`).
    Paragraph,
    /// Select text between a matching pair of delimiters, allowing nesting.
    Delimited {
        /// Opening delimiter.
        open: char,
        /// Matching closing delimiter.
        close: char,
    },
    /// Select text between two occurrences of the supplied quote character.
    Quote(char),
}

impl TextObjectKind {
    /// Decode the key after an inner or around prefix. Unknown keys return `None`.
    pub fn from_key(key: char) -> Option<Self> {
        Some(match key {
            'w' => Self::Word,
            'W' => Self::BigWord,
            's' => Self::Sentence,
            'p' => Self::Paragraph,
            '(' | ')' | 'b' => Self::Delimited {
                open: '(',
                close: ')',
            },
            '<' | '>' => Self::Delimited {
                open: '<',
                close: '>',
            },
            '[' | ']' => Self::Delimited {
                open: '[',
                close: ']',
            },
            '{' | '}' | 'B' => Self::Delimited {
                open: '{',
                close: '}',
            },
            '"' | '\'' | '`' => Self::Quote(key),
            _ => return None,
        })
    }
}

/// Destination within the next or previous Vim word.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WordDestination {
    /// Move forward to the start of a word (`w` or `W`).
    NextStart,
    /// Move forward to the end of a word (`e` or `E`).
    NextEnd,
    /// Move backward to the start of a word (`b` or `B`).
    PreviousStart,
    /// Move backward to the end of a word (`ge` or `gE`).
    PreviousEnd,
}

/// Classification used by word motions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WordClass {
    /// Distinguish letters, digits and underscores from punctuation.
    Word,
    /// Treat each run of non-whitespace characters as a single WORD.
    BigWord,
}

/// A cursor movement that can also supply the target for an operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Motion {
    /// Move one grapheme or opaque span left on the current line (`h`).
    Left,
    /// Move one grapheme or opaque span right on the current line (`l`).
    Right,
    /// Move up a logical line using the host's display columns (`k`).
    Up,
    /// Move down a logical line using the host's display columns (`j`).
    Down,
    /// Move down the counted logical lines to the first nonblank (Visual Enter).
    /// Return no target when already on the final line; otherwise clamp to that line.
    NextLineFirstNonBlank,
    /// Move to byte zero of the current line (`0`).
    LineStart,
    /// Move to the first non-whitespace grapheme on the line (`^`).
    FirstNonBlank,
    /// Move to the final grapheme on the line (`$`).
    LineEnd,
    /// Move to a word boundary using the supplied classification.
    Word {
        /// Which end of the word to target and in which direction.
        destination: WordDestination,
        /// How the resolver groups characters into words.
        class: WordClass,
    },
    /// Move to the first line, or the one-based line given by the count (`gg`).
    FirstLine,
    /// Move to the final line, or the one-based line given by the count (`G`).
    LastLine,
    /// Use the count as a percentage of the document's logical lines.
    Percent,
    /// Move to a paragraph boundary (`{` or `}`).
    Paragraph {
        /// Search preceding boundaries when true.
        backward: bool,
    },
    /// Move to a sentence boundary (`(` or `)`).
    Sentence {
        /// Search preceding boundaries when true.
        backward: bool,
    },
    /// Find a character on the current line.
    Character {
        /// Search direction and whether to land on the character or adjacent to it.
        kind: CharacterMotion,
        /// Unicode scalar to find.
        character: char,
    },
    /// Repeat a character search, advancing past the preceding till-match when needed.
    RepeatCharacter {
        /// Search direction and landing rule after applying the repeat key.
        kind: CharacterMotion,
        /// Character remembered from the original search.
        character: char,
    },
    /// Move to the partner of a delimiter at or after the cursor (`%`).
    MatchDelimiter,
}

/// The destination of a motion and the rules for using it with an operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Target {
    /// Destination in UTF-8 bytes from the start of the document.
    pub position: ByteOffset,
    /// Whether an operator includes the grapheme at the far end of the motion.
    pub inclusive: bool,
    /// Whether an operator acts on the full logical lines between the endpoints.
    pub linewise: bool,
}

/// The byte ranges and selection shape produced by resolving an edit target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedRange {
    /// Half-open UTF-8 byte ranges in document order. A block can span several ranges.
    pub ranges: Vec<TextRange>,
    /// Shape to retain when yanking, deleting or putting the resolved text.
    pub shape: Shape,
}

impl ResolvedRange {
    /// Construct a characterwise range from inclusive start and exclusive end byte offsets.
    pub fn character(start: usize, end: usize) -> Self {
        Self {
            ranges: vec![TextRange::new(start, end)],
            shape: Shape::Character,
        }
    }
}

/// Resolve motions against a borrowed document without changing its text or cursor.
#[derive(Clone, Copy)]
pub struct MotionResolver<'a> {
    pub(crate) text: &'a dyn TextSource,
    pub(crate) cursor: usize,
    pub(crate) opaque: &'a [TextRange],
    geometry: &'a dyn crate::Geometry,
}

impl<'a> MotionResolver<'a> {
    /// Start at a grapheme boundary using the default terminal geometry and no opaque spans.
    pub fn new(text: &'a dyn TextSource, cursor: ByteOffset) -> Self {
        Self {
            text,
            cursor: cursor.0,
            opaque: &[],
            geometry: &crate::DEFAULT_GEOMETRY,
        }
    }

    /// Use the supplied cursor, opaque spans and geometry. The view must be valid.
    pub fn from_view(view: DocumentView<'a>) -> Self {
        Self {
            text: view.text,
            cursor: view.cursor.0,
            opaque: view.opaque,
            geometry: view.geometry,
        }
    }

    pub(crate) fn span(&self, p: usize) -> Option<TextRange> {
        let index = self.opaque.partition_point(|s| s.end.0 <= p);
        self.opaque.get(index).copied().filter(|s| s.start.0 <= p)
    }

    /// Return the byte offset after the grapheme or opaque span at `p`, stopping at EOF.
    pub fn next(&self, p: usize) -> usize {
        self.span(p)
            .map_or_else(|| self.text.next_grapheme(p), |s| s.end.0)
    }

    /// Return the byte offset before `p`, treating each opaque span as a single unit.
    pub fn previous(&self, p: usize) -> usize {
        let previous = self.text.prev_grapheme(p);
        self.span(previous).map_or(previous, |s| s.start.0)
    }

    pub(crate) fn at_line_end(&self, p: usize) -> bool {
        match self.text.byte_at(p) {
            None | Some(b'\n') => true,
            Some(b'\r') => matches!(self.text.byte_at(p + 1), None | Some(b'\n')),
            _ => false,
        }
    }

    pub(crate) fn next_on_line(&self, p: usize) -> usize {
        if self.at_line_end(p) {
            p
        } else if self.span(p).is_some() {
            self.next(p).min(self.text.line_end(p))
        } else {
            self.next(p)
        }
    }

    pub(crate) fn head(&self, p: usize) -> Option<char> {
        if self.span(p).is_some() {
            Some('\u{fffc}')
        } else {
            self.text.char_at(p)
        }
    }

    pub(crate) fn kind(&self, p: usize, big: bool) -> u8 {
        match self.head(p) {
            None => 0,
            Some(c) if c.is_whitespace() => 0,
            Some(c) if big || c.is_alphanumeric() || c == '_' => 1,
            Some(c) if c.is_ascii_punctuation() => 2,
            _ => 3,
        }
    }

    /// Find the first non-whitespace byte on the line containing `p`, or its end if blank.
    pub fn first_non_blank(&self, p: usize) -> usize {
        let mut p = self.text.line_start(p);
        let end = self.text.line_end(p);
        while p < end && self.head(p).is_some_and(char::is_whitespace) {
            p = self.next(p);
        }
        p
    }

    /// Clamp a Normal-mode cursor without allowing it inside an opaque element.
    pub fn normal_cursor(&self, p: usize) -> usize {
        // Saved Visual endpoints can outlive edits that change a UTF-8 boundary.
        let mut p = p.min(self.text.len_bytes());
        while !self.text.is_char_boundary(p) {
            p -= 1;
        }
        if p > 0 {
            let previous = self.text.prev_grapheme(p);
            if self.text.next_grapheme(previous) > p {
                p = previous;
            }
        }
        let p = self.span(p).map_or(p, |s| s.start.0);
        if p < self.text.len_bytes() && !matches!(self.head(p), Some('\n' | '\r')) {
            return p;
        }
        if p == 0 {
            return 0;
        }
        let previous = self.previous(p);
        if matches!(self.head(previous), Some('\n' | '\r')) {
            p
        } else {
            previous
        }
    }

    /// Return the zero-based display column at byte offset `p` using the host's geometry.
    pub fn column(&self, p: usize) -> usize {
        let mut start = self.text.line_start(p);
        let mut col = 0;
        while start < p {
            let next = self.next(start);
            col += self.geometry.width(&self.text.slice(start, next), col);
            start = next;
        }
        col
    }

    pub(crate) fn column_span(&self, position: usize) -> (usize, usize) {
        let start = self.column(position);
        let text = self.text.slice(position, self.next(position));
        let width = self.geometry.width(&text, start);
        (start, start + width.saturating_sub(1))
    }

    /// Map a display column on the line beginning at `start` to a Normal-mode byte offset.
    pub fn at_column(&self, start: usize, col: usize) -> usize {
        self.normal_cursor(self.at_visual_column(start, col))
    }

    pub(crate) fn at_visual_column(&self, start: usize, col: usize) -> usize {
        let end = self.text.line_end(start);
        let mut p = start;
        let mut column = 0;
        while column < col && p < end {
            let next = self.next(p);
            let width = self.geometry.width(&self.text.slice(p, next), column);
            if column + width > col {
                break;
            }
            column += width;
            p = next;
        }
        p
    }

    /// Resolve a motion from the current cursor. Zero represents an omitted prefix count.
    /// Returns `None` when a vertical motion cannot reach another line or a search has no target.
    pub fn resolve(&self, motion: Motion, count: usize) -> Option<Target> {
        let n = count.max(1);
        let mut p = self.cursor;
        let mut inclusive = false;
        let mut linewise = false;
        match motion {
            Motion::Left => {
                for _ in 0..n {
                    if p == 0 {
                        break;
                    }
                    let previous = self.previous(p);
                    if matches!(self.head(previous), Some('\n' | '\r')) {
                        break;
                    }
                    p = previous;
                }
            }
            Motion::Right => {
                for _ in 0..n {
                    if matches!(self.head(p), None | Some('\n' | '\r')) {
                        break;
                    }
                    let next = self.next(p);
                    if next >= self.text.len_bytes() || matches!(self.head(next), Some('\n' | '\r'))
                    {
                        break;
                    }
                    p = next;
                }
            }
            Motion::Up | Motion::Down | Motion::NextLineFirstNonBlank => {
                let start = self.text.line_start(p);
                let mut line = start;
                for _ in 0..n {
                    if motion == Motion::Up {
                        if line == 0 {
                            break;
                        }
                        line = self.text.line_start(line - 1);
                    } else {
                        let next = self.text.next_line(line);
                        if next <= line || self.text.byte_at(next - 1) != Some(b'\n') {
                            break;
                        }
                        line = next;
                    }
                }
                // Neovim stops a macro only if the motion could not advance even one line.
                if line == start {
                    return None;
                }
                p = if motion == Motion::NextLineFirstNonBlank {
                    self.first_non_blank(line)
                } else {
                    self.at_column(line, self.column(p))
                };
                linewise = true;
            }
            Motion::LineStart => p = self.text.line_start(p),
            Motion::FirstNonBlank => p = self.first_non_blank(p),
            Motion::LineEnd => {
                for _ in 1..n {
                    let next = self.text.next_line(p);
                    if next >= self.text.len_bytes() {
                        break;
                    }
                    p = next;
                }
                p = self.normal_cursor(self.text.line_end(p));
                inclusive = true;
            }
            Motion::Word { destination, class } => {
                let backward = matches!(
                    destination,
                    WordDestination::PreviousStart | WordDestination::PreviousEnd
                );
                let end = matches!(
                    destination,
                    WordDestination::NextEnd | WordDestination::PreviousEnd
                );
                let big = class == WordClass::BigWord;
                p = self.word(n, backward, end, big);
                inclusive = end;
            }
            Motion::FirstLine | Motion::LastLine | Motion::Percent => {
                let last = if self.text.is_empty() {
                    0
                } else {
                    self.text
                        .line_index(self.text.prev_grapheme(self.text.len_bytes()))
                };
                let line = match motion {
                    Motion::FirstLine => count.saturating_sub(1),
                    Motion::LastLine if count == 0 => last,
                    Motion::LastLine => count - 1,
                    _ => ((last + 1) * count.min(100))
                        .div_ceil(100)
                        .saturating_sub(1),
                };
                p = self.first_non_blank(self.text.line_offset(line.min(last)));
                linewise = true;
            }
            Motion::Character { kind, character } => {
                let backward = matches!(
                    kind,
                    CharacterMotion::FindBackward | CharacterMotion::TillBackward
                );
                let mut remaining = n;
                let start = self.text.line_start(p);
                let end = self.text.line_end(p);
                loop {
                    if backward {
                        if p <= start {
                            return None;
                        }
                        p = self.previous(p);
                    } else {
                        p = self.next(p);
                        if p >= end {
                            return None;
                        }
                    }
                    if self.span(p).is_none() && self.head(p) == Some(character) {
                        remaining -= 1;
                        if remaining == 0 {
                            break;
                        }
                    }
                }
                match kind {
                    CharacterMotion::Till => p = self.previous(p),
                    CharacterMotion::TillBackward => p = self.next(p),
                    _ => {}
                }
                inclusive = !backward;
            }
            Motion::RepeatCharacter { kind, character } => {
                let mut resolver = *self;
                let motion = Motion::Character { kind, character };
                if matches!(kind, CharacterMotion::Till | CharacterMotion::TillBackward)
                    && resolver
                        .resolve(motion, 1)
                        .is_some_and(|t| t.position.0 == self.cursor)
                {
                    resolver.cursor = if kind == CharacterMotion::Till {
                        self.next(self.cursor)
                    } else {
                        self.previous(self.cursor)
                    };
                }
                return resolver.resolve(motion, count);
            }
            Motion::MatchDelimiter => {
                p = self.match_delimiter()?;
                inclusive = true;
            }
            Motion::Paragraph { backward } => {
                p = self.paragraph_target(n, backward);
                inclusive = p == self.normal_cursor(self.text.len_bytes()) && !backward;
            }
            Motion::Sentence { backward } => {
                p = self.sentence_target(n, backward);
                inclusive = p == self.normal_cursor(self.text.len_bytes()) && !backward;
            }
        }
        Some(Target {
            position: ByteOffset(p),
            inclusive,
            linewise,
        })
    }

    fn word(&self, count: usize, backward: bool, end: bool, big: bool) -> usize {
        let len = self.text.len_bytes();
        let mut p = self.cursor;
        for _ in 0..count {
            if backward {
                if p == 0 {
                    break;
                }
                if end && self.kind(p, big) != 0 {
                    let k = self.kind(p, big);
                    while p > 0 && self.kind(self.previous(p), big) == k {
                        p = self.previous(p);
                    }
                }
                if p == 0 {
                    break;
                }
                p = self.previous(p);
                while p > 0 && self.kind(p, big) == 0 {
                    p = self.previous(p);
                }
                if !end {
                    let k = self.kind(p, big);
                    while p > 0 && self.kind(self.previous(p), big) == k {
                        p = self.previous(p);
                    }
                }
            } else {
                let k = self.kind(p, big);
                if end {
                    let next = self.next(p);
                    if next < len && k != 0 && self.kind(next, big) == k {
                        p = next;
                    } else {
                        p = next;
                        while p < len && self.kind(p, big) == 0 {
                            p = self.next(p);
                        }
                    }
                    if p < len {
                        let k = self.kind(p, big);
                        while self.next(p) < len && self.kind(self.next(p), big) == k {
                            p = self.next(p);
                        }
                    }
                } else {
                    // An empty line is a word boundary. Do not skip over it.
                    if p < len
                        && (p == 0 || self.text.byte_at(p - 1) == Some(b'\n'))
                        && matches!(self.head(p), Some('\n' | '\r') | None)
                    {
                        p = self.next(p);
                    } else {
                        while p < len && self.kind(p, big) == k {
                            p = self.next(p);
                            if k == 0 && (p == 0 || self.text.byte_at(p - 1) == Some(b'\n')) {
                                break;
                            }
                        }
                    }
                    while p < len && self.kind(p, big) == 0 {
                        if (p == 0 || self.text.byte_at(p - 1) == Some(b'\n'))
                            && matches!(self.head(p), Some('\n' | '\r') | None)
                        {
                            break;
                        }
                        p = self.next(p);
                    }
                }
            }
        }
        p.min(len)
    }

    /// Resolve an operator motion, including `cw`, end-of-line `dw`, and
    /// Vim's exclusive-motion-to-column-zero rule.
    pub fn operator_range(
        &self,
        motion: Motion,
        count: usize,
        operator: crate::Operator,
    ) -> Option<ResolvedRange> {
        let cursor = self.normal_cursor(self.cursor);
        if cursor != self.cursor {
            return Self { cursor, ..*self }.operator_range(motion, count, operator);
        }
        let change = operator == crate::Operator::Change;
        if motion == Motion::Right {
            let mut end = self.cursor;
            for _ in 0..count.max(1) {
                if matches!(self.head(end), None | Some('\n' | '\r')) {
                    break;
                }
                end = self.next(end);
            }
            return (end > self.cursor || change)
                .then(|| ResolvedRange::character(self.cursor, end));
        }
        let target = if let Motion::Word {
            destination: WordDestination::NextStart,
            class,
        } = motion
        {
            let big = class == WordClass::BigWord;
            if change && self.kind(self.cursor, big) != 0 {
                // For cw the character under the cursor can already be the first counted word end.
                let next = self.next(self.cursor);
                let at_end = self.kind(next, big) != self.kind(self.cursor, big);
                let remaining = count.max(1) - usize::from(at_end);
                let end = self.word(remaining, false, true, big);
                return Some(ResolvedRange::character(self.cursor, self.next(end)));
            }
            let mut last = *self;
            last.cursor = self.word(count.max(1) - 1, false, false, big);
            let mut end = last.word(1, false, false, big);
            let line_end = self.text.line_end(last.cursor);
            // Only the final step stops at EOL. Starting on an empty line includes its separator.
            if end >= line_end
                && self.text.line_start(last.cursor) > self.cursor
                && self.cursor <= self.first_non_blank(self.cursor)
            {
                return Some(self.lines(self.cursor, last.cursor));
            }
            if end > line_end {
                end = if self.text.line_start(last.cursor) == line_end {
                    self.text.next_line(last.cursor)
                } else {
                    line_end
                };
            }
            if change && end == self.cursor {
                return Some(ResolvedRange::character(end, end));
            }
            Target {
                position: ByteOffset(end),
                inclusive: false,
                linewise: false,
            }
        } else {
            self.resolve(motion, count)?
        };
        if target.linewise {
            return Some(self.lines(self.cursor, target.position.0));
        }
        if change
            && target.position.0 == self.cursor
            && matches!(
                motion,
                Motion::Character {
                    kind: CharacterMotion::TillBackward,
                    ..
                }
            )
        {
            return Some(ResolvedRange::character(self.cursor, self.cursor));
        }
        if !target.inclusive {
            return self.exclusive_range(target.position);
        }
        let start = self.cursor.min(target.position.0);
        let last = self.cursor.max(target.position.0);
        let end = if motion == Motion::LineEnd && last == self.text.line_end(last) {
            last
        } else {
            self.next(last)
        };
        (start < end || change).then(|| ResolvedRange::character(start, end))
    }

    /// Convert a host-resolved exclusive motion into an operator range.
    ///
    /// A motion ending in column zero on another line becomes linewise when it starts
    /// at or before the first nonblank. Otherwise it leaves the final line ending intact.
    pub fn exclusive_range(&self, target: ByteOffset) -> Option<ResolvedRange> {
        let start = self.cursor.min(target.0);
        let mut end = self.cursor.max(target.0);
        if end > start && self.text.line_start(end) == end {
            if start <= self.first_non_blank(start) {
                return Some(ResolvedRange {
                    ranges: vec![TextRange::new(self.text.line_start(start), end)],
                    shape: Shape::Line,
                });
            }
            end = self.text.line_end(end - 1);
        }
        (start < end).then(|| ResolvedRange::character(start, end))
    }

    /// Cover the complete lines containing byte offsets `a` and `b`, including intervening lines.
    pub fn lines(&self, a: usize, b: usize) -> ResolvedRange {
        ResolvedRange {
            ranges: vec![TextRange::new(
                self.text.line_start(a.min(b)),
                self.text.next_line(a.max(b)),
            )],
            shape: Shape::Line,
        }
    }

    /// Extend a range to cover every opaque span it intersects.
    pub fn expand_opaque(&self, range: TextRange) -> TextRange {
        let mut range = range;
        for span in self.opaque {
            if span.start < range.end && range.start < span.end {
                range.start = range.start.min(span.start);
                range.end = range.end.max(span.end);
            }
        }
        range
    }

    fn match_delimiter(&self) -> Option<usize> {
        let mut p = self.cursor;
        let end = self.text.line_end(p);
        while p < end && !self.head(p).is_some_and(|c| "()[]{}".contains(c)) {
            p = self.next(p);
        }
        let c = self.head(p)?;
        let (open, close, backward) = match c {
            '(' => ('(', ')', false),
            ')' => ('(', ')', true),
            '[' => ('[', ']', false),
            ']' => ('[', ']', true),
            '{' => ('{', '}', false),
            '}' => ('{', '}', true),
            _ => return None,
        };
        let mut depth = 1;
        loop {
            if backward {
                if p == 0 {
                    return None;
                }
                p = self.previous(p);
            } else {
                p = self.next(p);
                if p >= self.text.len_bytes() {
                    return None;
                }
            }
            let c = self.head(p)?;
            if c == if backward { close } else { open } {
                depth += 1;
            }
            if c == if backward { open } else { close } {
                depth -= 1;
                if depth == 0 {
                    return Some(p);
                }
            }
        }
    }

    fn paragraph_target(&self, count: usize, backward: bool) -> usize {
        let mut line = self.text.line_start(self.cursor);
        for _ in 0..count {
            let mut skip_empty = self.text.line_end(line) == line;
            loop {
                if backward {
                    if line == 0 {
                        return 0;
                    }
                    line = self.text.line_start(line - 1);
                } else {
                    let next = self.text.next_line(line);
                    if next <= line || next >= self.text.len_bytes() {
                        return self.normal_cursor(self.text.len_bytes());
                    }
                    line = next;
                }
                let empty = self.text.line_end(line) == line;
                if skip_empty && empty {
                    continue;
                }
                skip_empty = false;
                if empty {
                    break;
                }
            }
        }
        line
    }
}