alma 0.1.1

A Bevy-native modal text editor with Vim-style navigation.
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
//! Pure Vim operator targets.
//!
//! This module owns target shape and range validation for destructive and
//! register-producing operations. It does not mutate text or registers.

use std::{
    fmt::{Display, Formatter},
    ops::Range,
};

use crate::text_stream::{TextByteStream, TextRange, TextStreamError, ValidatedTextRange};

use super::{
    Counted, Motion, OperatorTargetSource, VimSelection, VisualMode,
    motion::{self, ColumnMotion, LineAddress},
};

/// Target kind produced for an operator.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TargetKind {
    /// Characterwise target.
    Characterwise,
    /// Whole-line target.
    Linewise,
    /// Reserved for future blockwise visual mode.
    Blockwise,
}

/// A resolved operator target.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct OperatorTarget {
    /// Target kind.
    kind: TargetKind,
    /// Validated byte range.
    range: ValidatedOperatorRange,
}

impl OperatorTarget {
    /// Creates a characterwise target.
    ///
    /// # Errors
    ///
    /// Returns [`TargetResolutionError`] when `range` is inverted, out of
    /// bounds, or not aligned to UTF-8 boundaries for `stream`.
    pub fn characterwise(
        stream: &TextByteStream,
        range: Range<usize>,
    ) -> Result<Self, TargetResolutionError> {
        Self::new(stream, TargetKind::Characterwise, range)
    }

    /// Creates a linewise target.
    ///
    /// # Errors
    ///
    /// Returns [`TargetResolutionError`] when `range` is inverted, out of
    /// bounds, or not aligned to UTF-8 boundaries for `stream`.
    pub fn linewise(
        stream: &TextByteStream,
        range: Range<usize>,
    ) -> Result<Self, TargetResolutionError> {
        Self::new(stream, TargetKind::Linewise, range)
    }

    /// Resolves the current visual selection into an operator target.
    ///
    /// # Errors
    ///
    /// Returns [`TargetResolutionError`] if the derived selection range is not a
    /// valid UTF-8 byte range for `stream`.
    pub fn from_visual_selection(
        stream: &TextByteStream,
        selection: VimSelection,
        cursor_byte_index: usize,
        visual_mode: VisualMode,
    ) -> Result<Self, TargetResolutionError> {
        let text = stream.as_str();
        match visual_mode {
            VisualMode::Characterwise => Self::characterwise(
                stream,
                selection.characterwise_byte_range(text, cursor_byte_index),
            ),
            VisualMode::Linewise => Self::linewise(
                stream,
                selection.linewise_operator_byte_range(text, cursor_byte_index),
            ),
            VisualMode::Blockwise => Err(TargetResolutionError::UnsupportedTarget),
        }
    }

    /// Resolves an operator target source.
    ///
    /// # Errors
    ///
    /// Returns [`TargetResolutionError`] when `source` is unsupported or
    /// produces an invalid byte range for `stream`.
    pub fn from_source(
        stream: &TextByteStream,
        cursor_byte_index: usize,
        source: OperatorTargetSource,
    ) -> Result<Self, TargetResolutionError> {
        let text = stream.as_str();
        match source {
            OperatorTargetSource::Motion(counted) => Self::from_counted_motion(
                stream,
                motion::clamp_to_cursor_position(text, cursor_byte_index),
                counted,
            ),
            OperatorTargetSource::CurrentLine { count } => Self::current_line_count(
                stream,
                motion::clamp_to_boundary(text, cursor_byte_index),
                count.get(),
            ),
            OperatorTargetSource::TextObject(object) => {
                let range = super::resolve_text_object_range(
                    text,
                    cursor_byte_index,
                    object.item,
                    object.count.get(),
                )?;
                Self::characterwise(stream, range)
            }
            OperatorTargetSource::VisualSelection { selection, mode } => {
                Self::from_visual_selection(stream, selection, cursor_byte_index, mode)
            }
        }
    }

    /// Resolves a normal-mode operator target source.
    ///
    /// # Errors
    ///
    /// Returns [`TargetResolutionError`] when `source` is unsupported or
    /// produces an invalid byte range for `stream`.
    pub fn from_normal_source(
        stream: &TextByteStream,
        cursor_byte_index: usize,
        source: OperatorTargetSource,
    ) -> Result<Self, TargetResolutionError> {
        match source {
            OperatorTargetSource::VisualSelection { .. } => Err(TargetResolutionError::WrongMode),
            source => Self::from_source(stream, cursor_byte_index, source),
        }
    }

    /// Resolves the current physical line as a linewise target.
    ///
    /// # Errors
    ///
    /// Returns [`TargetResolutionError`] if the derived line range is invalid
    /// for `stream`.
    pub fn current_line(
        stream: &TextByteStream,
        cursor_byte_index: usize,
    ) -> Result<Self, TargetResolutionError> {
        Self::current_line_count(stream, cursor_byte_index, 1)
    }

    /// Resolves one or more physical lines as a linewise target.
    fn current_line_count(
        stream: &TextByteStream,
        cursor_byte_index: usize,
        count: usize,
    ) -> Result<Self, TargetResolutionError> {
        let text = stream.as_str();
        let cursor = motion::clamp_to_boundary(text, cursor_byte_index);
        let start = line_start(text, cursor);
        let end = (1..count).fold(line_end_including_newline(text, cursor), |end, _line| {
            if end >= text.len() {
                end
            } else {
                line_end_including_newline(text, end)
            }
        });
        Self::linewise(stream, start..end)
    }

    /// Target kind.
    #[must_use]
    pub const fn kind(self) -> TargetKind {
        self.kind
    }

    /// Validated byte range.
    #[must_use]
    pub const fn range(self) -> ValidatedOperatorRange {
        self.range
    }

    /// Creates a validated target.
    fn new(
        stream: &TextByteStream,
        kind: TargetKind,
        range: Range<usize>,
    ) -> Result<Self, TargetResolutionError> {
        Ok(Self {
            kind,
            range: ValidatedOperatorRange::new(stream, range)?,
        })
    }

    /// Resolves a counted normal-mode motion into an operator target.
    fn from_counted_motion(
        stream: &TextByteStream,
        cursor_byte_index: usize,
        counted: Counted<Motion>,
    ) -> Result<Self, TargetResolutionError> {
        let text = stream.as_str();
        if is_linewise_motion(counted.item) {
            return Self::linewise_motion(stream, cursor_byte_index, counted);
        }

        let destination = apply_counted_motion_for_target(text, cursor_byte_index, counted);
        let range = characterwise_motion_range(text, cursor_byte_index, destination, counted.item);
        Self::characterwise(stream, range)
    }

    /// Resolves a linewise motion into a linewise operator target.
    fn linewise_motion(
        stream: &TextByteStream,
        cursor_byte_index: usize,
        counted: Counted<Motion>,
    ) -> Result<Self, TargetResolutionError> {
        let text = stream.as_str();
        let destination = apply_counted_motion_for_target(text, cursor_byte_index, counted);
        let start = line_start(text, cursor_byte_index.min(destination));
        let end = line_end_including_newline(text, cursor_byte_index.max(destination));
        Self::linewise(stream, start..end)
    }
}

/// Applies a counted motion for target resolution.
fn apply_counted_motion_for_target(
    text: &str,
    cursor_byte_index: usize,
    counted: Counted<Motion>,
) -> usize {
    match counted.item {
        Motion::LineAddress(_) => motion::apply_motion(text, cursor_byte_index, counted.item),
        Motion::Column(ColumnMotion::ScreenColumn) => {
            motion::apply_screen_column_motion(text, cursor_byte_index, counted.count.get())
        }
        motion_item => (0..counted.count.get()).fold(cursor_byte_index, |index, _step| {
            motion::apply_motion(text, index, motion_item)
        }),
    }
}

/// Returns the characterwise half-open range for a motion.
fn characterwise_motion_range(
    text: &str,
    cursor_byte_index: usize,
    destination: usize,
    motion: Motion,
) -> Range<usize> {
    if destination < cursor_byte_index {
        return destination..cursor_byte_index;
    }

    let end = if matches!(motion, Motion::Column(ColumnMotion::LineEnd)) {
        text[destination..]
            .chars()
            .next()
            .map_or(destination, |character| destination + character.len_utf8())
    } else {
        destination
    };

    cursor_byte_index..end
}

/// Returns whether a motion produces a linewise operator target.
const fn is_linewise_motion(motion: Motion) -> bool {
    matches!(
        motion,
        Motion::Down
            | Motion::Up
            | Motion::LineAddress(
                LineAddress::FirstNonBlank | LineAddress::LastNonBlank | LineAddress::Number(_)
            )
    )
}

/// Returns the byte index at the start of the line containing `index`.
fn line_start(text: &str, index: usize) -> usize {
    let index = motion::clamp_to_boundary(text, index);
    text[..index]
        .rfind('\n')
        .map_or(0, |newline_index| newline_index + '\n'.len_utf8())
}

/// Returns the byte index after the line ending for the line containing `index`, or EOF.
fn line_end_including_newline(text: &str, index: usize) -> usize {
    let index = motion::clamp_to_boundary(text, index);
    let content_end = text[index..]
        .find('\n')
        .map_or(text.len(), |newline_offset| index + newline_offset);
    text[content_end..]
        .chars()
        .next()
        .filter(|character| *character == '\n')
        .map_or(content_end, |newline| content_end + newline.len_utf8())
}

/// A resolved target alias for callers that distinguish producer from result.
pub type ResolvedTarget = OperatorTarget;

/// A byte range validated for operator use.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ValidatedOperatorRange {
    /// Stream-scoped validated range.
    range: ValidatedTextRange,
}

impl ValidatedOperatorRange {
    /// Creates an ordered, in-bounds, UTF-8-aligned half-open byte range.
    ///
    /// # Errors
    ///
    /// Returns [`TargetResolutionError`] when `range` is inverted, exceeds
    /// `text`, or starts/ends inside a UTF-8 scalar.
    pub fn new(
        stream: &TextByteStream,
        range: Range<usize>,
    ) -> Result<Self, TargetResolutionError> {
        let range = stream
            .validate_range(TextRange::from(range))
            .map_err(|error| TargetResolutionError::from_text_stream_error(&error))?;
        Ok(Self { range })
    }

    /// Start byte index.
    #[must_use]
    pub const fn start(self) -> usize {
        self.range.start()
    }

    /// Exclusive end byte index.
    #[must_use]
    pub const fn end(self) -> usize {
        self.range.end()
    }

    /// Half-open range.
    #[must_use]
    pub const fn as_range(self) -> Range<usize> {
        self.range.as_range()
    }

    /// Returns the stream-scoped validated text range.
    #[must_use]
    pub const fn validated_text_range(self) -> ValidatedTextRange {
        self.range
    }

    /// Byte length.
    #[must_use]
    pub const fn len(self) -> usize {
        self.end() - self.start()
    }

    /// Returns whether the target is empty.
    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.start() == self.end()
    }
}

/// Target-resolution errors.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum TargetResolutionError {
    /// Start was greater than end.
    InvertedRange {
        /// Start byte index.
        start: usize,
        /// End byte index.
        end: usize,
    },
    /// Range exceeded the text length.
    OutOfBounds {
        /// Requested exclusive end.
        end: usize,
        /// Text length.
        text_len: usize,
    },
    /// Index did not fall on a UTF-8 boundary.
    InvalidBoundary {
        /// Invalid byte index.
        index: usize,
    },
    /// The target producer is not supported yet.
    UnsupportedTarget,
    /// The target producer belongs to a different editor mode.
    WrongMode,
    /// No matching text object exists in the text snapshot.
    NoTextObject,
    /// A previously validated range no longer matches the stream snapshot.
    StaleRange,
}

impl TargetResolutionError {
    /// Converts text-stream validation into the operator target vocabulary.
    const fn from_text_stream_error(error: &TextStreamError) -> Self {
        match error {
            TextStreamError::InvalidUtf8 { .. } => Self::InvalidBoundary { index: 0 },
            TextStreamError::OutOfBounds { index, len } => Self::OutOfBounds {
                end: *index,
                text_len: *len,
            },
            TextStreamError::NotCharBoundary { index } => Self::InvalidBoundary { index: *index },
            TextStreamError::InvalidRange { start, end } => Self::InvertedRange {
                start: *start,
                end: *end,
            },
            TextStreamError::StaleValidatedRange { .. }
            | TextStreamError::WrongTextStream { .. } => Self::StaleRange,
        }
    }
}

impl Display for TargetResolutionError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvertedRange { .. } => formatter.write_str("operator target range is inverted"),
            Self::OutOfBounds { .. } => {
                formatter.write_str("operator target range is out of bounds")
            }
            Self::InvalidBoundary { .. } => {
                formatter.write_str("operator target is not on a UTF-8 boundary")
            }
            Self::UnsupportedTarget => formatter.write_str("operator target is unsupported"),
            Self::WrongMode => formatter.write_str("operator target belongs to a different mode"),
            Self::NoTextObject => formatter.write_str("text object target was not found"),
            Self::StaleRange => formatter.write_str("operator target range is stale"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{OperatorTarget, TargetKind, TargetResolutionError, ValidatedOperatorRange};
    use crate::text_stream::TextByteStream;
    use crate::vim::{
        Counted, Motion, OperatorTargetSource, TextObject, TextObjectKind, TextObjectScope,
        VimSelection, VisualMode, WordKind,
    };

    fn stream(text: &str) -> TextByteStream {
        TextByteStream::new(text)
    }

    #[test]
    fn validates_characterwise_utf8_target() {
        let stream = stream("aλb");
        let target = OperatorTarget::characterwise(&stream, 1.."aλ".len()).unwrap();

        assert_eq!(target.kind(), TargetKind::Characterwise);
        assert_eq!(target.range().as_range(), 1.."aλ".len());
    }

    #[test]
    fn rejects_invalid_operator_ranges() {
        let stream = stream("aλb");

        assert_eq!(
            ValidatedOperatorRange::new(&stream, std::ops::Range { start: 3, end: 1 }),
            Err(TargetResolutionError::InvertedRange { start: 3, end: 1 })
        );
        assert_eq!(
            ValidatedOperatorRange::new(&stream, 0..9),
            Err(TargetResolutionError::OutOfBounds {
                end: 9,
                text_len: stream.as_str().len(),
            })
        );
        assert_eq!(
            ValidatedOperatorRange::new(&stream, 2..3),
            Err(TargetResolutionError::InvalidBoundary { index: 2 })
        );
    }

    #[test]
    fn visual_characterwise_target_includes_cursor_cell() {
        let text = "abcd";
        let stream = stream(text);
        let selection = VimSelection::new(text, 1);
        let target =
            OperatorTarget::from_visual_selection(&stream, selection, 2, VisualMode::Characterwise)
                .unwrap();

        assert_eq!(target.kind(), TargetKind::Characterwise);
        assert_eq!(target.range().as_range(), 1..3);
    }

    #[test]
    fn visual_linewise_target_includes_trailing_newline_when_present() {
        let text = "one\ntwo\nthree";
        let stream = stream(text);
        let selection = VimSelection::new(text, "one\nt".len());
        let target = OperatorTarget::from_visual_selection(
            &stream,
            selection,
            "one\ntwo".len(),
            VisualMode::Linewise,
        )
        .unwrap();

        assert_eq!(target.kind(), TargetKind::Linewise);
        assert_eq!(target.range().as_range(), 4..8);
    }

    #[test]
    fn visual_blockwise_operator_target_fails_closed_until_block_edits_exist() {
        let text = "one\ntwo";
        let stream = stream(text);
        let selection = VimSelection::new(text, 1);

        assert_eq!(
            OperatorTarget::from_visual_selection(
                &stream,
                selection,
                "one\nt".len(),
                VisualMode::Blockwise
            ),
            Err(TargetResolutionError::UnsupportedTarget)
        );
    }

    #[test]
    fn normal_word_motion_resolves_characterwise_range() {
        let stream = stream("one two three");
        let target = OperatorTarget::from_normal_source(
            &stream,
            0,
            OperatorTargetSource::Motion(Counted::once(Motion::WordForward(WordKind::Normal))),
        )
        .unwrap();

        assert_eq!(target.kind(), TargetKind::Characterwise);
        assert_eq!(target.range().as_range(), 0.."one ".len());
    }

    #[test]
    fn normal_current_line_resolves_linewise_range() {
        let text = "one\ntwo\nthree";
        let stream = stream(text);
        let target = OperatorTarget::from_normal_source(
            &stream,
            "one\nt".len(),
            OperatorTargetSource::CurrentLine {
                count: crate::vim::Count::default(),
            },
        )
        .unwrap();

        assert_eq!(target.kind(), TargetKind::Linewise);
        assert_eq!(target.range().as_range(), 4..8);
    }

    #[test]
    fn vertical_motion_resolves_linewise_range() {
        let stream = stream("one\ntwo\nthree");
        let target = OperatorTarget::from_normal_source(
            &stream,
            0,
            OperatorTargetSource::Motion(Counted::once(Motion::Down)),
        )
        .unwrap();

        assert_eq!(target.kind(), TargetKind::Linewise);
        assert_eq!(target.range().as_range(), 0..8);
    }

    #[test]
    fn normal_text_object_resolves_characterwise_range() {
        let text = "one two\n";
        let stream = stream(text);
        let target = OperatorTarget::from_normal_source(
            &stream,
            "one ".len(),
            OperatorTargetSource::TextObject(Counted::once(TextObject::new(
                TextObjectScope::Inner,
                TextObjectKind::Word,
            ))),
        )
        .unwrap();

        assert_eq!(target.kind(), TargetKind::Characterwise);
        assert_eq!(target.range().as_range(), "one ".len().."one two".len());
    }
}