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
//! Pure Vim operation model.
//!
//! Operations sit below key grammar and above editor adapters. They describe
//! what Vim semantics intend without depending on Bevy, ECS messages,
//! filesystem state, or UI rendering.

use super::{
    Count, Counted, InsertEntry, ModeSwitch, Motion, NormalCommand, NormalOperatorTarget, Operator,
    PastePlacement, SearchDirection, TextObject, ViewportPosition,
    operator::{ResolvedTarget, TargetResolutionError},
    search::SearchRepeatDirection,
};
use crate::text_stream::TextByteStream;
use std::fmt::{Display, Formatter};

/// A pure Vim operation resolved from an action or grammar command.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum VimOperation {
    /// Move the cursor by a counted motion.
    MoveCursor(Counted<Motion>),
    /// Apply an operator to a target producer.
    ApplyOperator {
        /// Operator count.
        count: Count,
        /// Operator kind.
        operator: Operator,
        /// Target producer.
        target: OperatorTargetSource,
    },
    /// Switch mode.
    SwitchMode(ModeSwitch),
    /// Enter insert mode through a normal-mode entry command.
    EnterInsert(InsertEntry),
    /// Paste register text.
    Paste {
        /// Paste count.
        count: Count,
        /// Paste side.
        placement: PastePlacement,
    },
    /// Undo one edit transaction.
    Undo,
    /// Redo one edit transaction.
    Redo,
    /// Start the `:` command-line.
    StartCommandLine,
    /// Start a `/` or `?` search prompt.
    StartSearch(SearchDirection),
    /// Repeat the current search.
    RepeatSearch(SearchRepeatDirection),
    /// Repeat the current search in an explicit direction.
    RepeatSearchInDirection(SearchDirection),
    /// Reposition the viewport around the cursor.
    ViewportPosition(ViewportPosition),
    /// Start a prefilled `:` command.
    PrefilledCommandLine(String),
    /// Intentional no-op.
    NoOp,
}

impl From<NormalCommand> for VimOperation {
    fn from(command: NormalCommand) -> Self {
        match command {
            NormalCommand::Motion(motion) => Self::MoveCursor(motion),
            NormalCommand::Operator {
                count,
                operator,
                target,
            } => Self::ApplyOperator {
                count,
                operator,
                target: OperatorTargetSource::from(target),
            },
            NormalCommand::ModeSwitch(mode_switch) => Self::SwitchMode(mode_switch),
            NormalCommand::Insert(entry) => Self::EnterInsert(entry),
            NormalCommand::Paste { count, placement } => Self::Paste { count, placement },
            NormalCommand::Undo => Self::Undo,
            NormalCommand::Redo => Self::Redo,
            NormalCommand::RepeatLastChange => Self::NoOp,
            NormalCommand::ExCommandStart => Self::StartCommandLine,
            NormalCommand::SearchStart(direction) => Self::StartSearch(direction),
            NormalCommand::SearchRepeat(direction) => Self::RepeatSearch(direction),
            NormalCommand::ViewportPosition(position) => Self::ViewportPosition(position),
        }
    }
}

/// A target producer for an operator.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OperatorTargetSource {
    /// Target resolved by applying a motion.
    Motion(Counted<Motion>),
    /// Current physical line.
    CurrentLine {
        /// Number of lines targeted.
        count: Count,
    },
    /// Text object under or after the cursor.
    TextObject(Counted<TextObject>),
    /// Current visual selection.
    VisualSelection {
        /// Selection anchor.
        selection: super::VimSelection,
        /// Active visual mode.
        mode: super::VisualMode,
    },
}

impl From<NormalOperatorTarget> for OperatorTargetSource {
    fn from(target: NormalOperatorTarget) -> Self {
        match target {
            NormalOperatorTarget::Motion(motion) => Self::Motion(motion),
            NormalOperatorTarget::CurrentLine => Self::CurrentLine {
                count: Count::default(),
            },
            NormalOperatorTarget::TextObject(object) => Self::TextObject(object),
        }
    }
}

/// Coherent effects produced by a resolved operation before adapter emission.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum OperationEffect {
    /// Move the cursor.
    MoveCursor(Counted<Motion>),
    /// Switch mode.
    SwitchMode(ModeSwitch),
    /// Enter insert mode through a normal-mode entry command.
    EnterInsert(InsertEntry),
    /// Paste register text.
    Paste {
        /// Paste count.
        count: Count,
        /// Paste side.
        placement: PastePlacement,
    },
    /// Undo one edit transaction.
    Undo,
    /// Redo one edit transaction.
    Redo,
    /// Start command-line input.
    StartCommandLine,
    /// Start command-line input with existing text.
    PrefilledCommandLine(String),
    /// Start search input.
    StartSearch(SearchDirection),
    /// Repeat search.
    RepeatSearch(SearchRepeatDirection),
    /// Repeat search in an explicit direction.
    RepeatSearchInDirection(SearchDirection),
    /// Reposition viewport.
    ViewportPosition(ViewportPosition),
    /// Apply an operator to a resolved target.
    ApplyOperator {
        /// Operator kind.
        operator: Operator,
        /// Target.
        target: ResolvedTarget,
    },
}

/// Operation result before conversion to adapter effects.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct OperationOutcome {
    /// Ordered effects produced by one operation.
    effects: Vec<OperationEffect>,
}

impl OperationOutcome {
    /// Builds an outcome from ordered effects.
    #[must_use]
    pub const fn new(effects: Vec<OperationEffect>) -> Self {
        Self { effects }
    }

    /// Returns the ordered effects.
    #[must_use]
    pub fn effects(&self) -> &[OperationEffect] {
        &self.effects
    }

    /// Consumes this outcome and returns ordered effects.
    #[must_use]
    pub fn into_effects(self) -> Vec<OperationEffect> {
        self.effects
    }
}

/// Operation-level errors.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum OperationError {
    /// The operation needs target resolution that has not been implemented.
    TargetResolution(#[source] TargetResolutionError),
}

impl Display for OperationError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TargetResolution(_) => formatter.write_str("operation target resolution failed"),
        }
    }
}

impl VimOperation {
    /// Resolves an operation against a concrete text stream and cursor state.
    ///
    /// # Errors
    ///
    /// Returns [`OperationError::TargetResolution`] when an operator target
    /// cannot be resolved into a valid byte range.
    pub fn resolve(
        self,
        stream: &TextByteStream,
        cursor_byte_index: usize,
    ) -> Result<OperationOutcome, OperationError> {
        match self {
            Self::ApplyOperator {
                count,
                operator,
                target,
            } => {
                let target = target.with_operator_count(count);
                let target = super::OperatorTarget::from_source(stream, cursor_byte_index, target)
                    .map_err(OperationError::TargetResolution)?;
                Ok(OperationOutcome::new(vec![
                    OperationEffect::ApplyOperator { operator, target },
                ]))
            }
            operation => operation.resolve_without_target(),
        }
    }

    /// Converts an operation that needs no target resolution into an outcome.
    ///
    /// # Errors
    ///
    /// Returns [`OperationError::TargetResolution`] when the operation needs an
    /// operator target that has not been resolved yet.
    pub fn resolve_without_target(self) -> Result<OperationOutcome, OperationError> {
        let effect = match self {
            Self::MoveCursor(motion) => OperationEffect::MoveCursor(motion),
            Self::SwitchMode(mode_switch) => OperationEffect::SwitchMode(mode_switch),
            Self::EnterInsert(entry) => OperationEffect::EnterInsert(entry),
            Self::Paste { count, placement } => OperationEffect::Paste { count, placement },
            Self::Undo => OperationEffect::Undo,
            Self::Redo => OperationEffect::Redo,
            Self::StartCommandLine => OperationEffect::StartCommandLine,
            Self::StartSearch(direction) => OperationEffect::StartSearch(direction),
            Self::RepeatSearch(direction) => OperationEffect::RepeatSearch(direction),
            Self::RepeatSearchInDirection(direction) => {
                OperationEffect::RepeatSearchInDirection(direction)
            }
            Self::ViewportPosition(position) => OperationEffect::ViewportPosition(position),
            Self::PrefilledCommandLine(command) => OperationEffect::PrefilledCommandLine(command),
            Self::NoOp => return Ok(OperationOutcome::default()),
            Self::ApplyOperator { .. } => {
                return Err(OperationError::TargetResolution(
                    TargetResolutionError::UnsupportedTarget,
                ));
            }
        };

        Ok(OperationOutcome::new(vec![effect]))
    }
}

impl OperatorTargetSource {
    /// Combines an operator count with this target source.
    #[must_use]
    fn with_operator_count(self, count: Count) -> Self {
        match self {
            Self::Motion(mut counted) => {
                counted.count = multiply_counts(count, counted.count);
                Self::Motion(counted)
            }
            Self::CurrentLine { .. } => Self::CurrentLine { count },
            Self::TextObject(mut counted) => {
                counted.count = multiply_counts(count, counted.count);
                Self::TextObject(counted)
            }
            Self::VisualSelection { .. } => self,
        }
    }
}

/// Multiplies two non-zero Vim counts, saturating on overflow.
fn multiply_counts(left: Count, right: Count) -> Count {
    std::num::NonZeroUsize::new(left.get().saturating_mul(right.get()))
        .map_or_else(Count::default, Count::new)
}

#[cfg(test)]
mod tests {
    use super::{OperationEffect, OperationError, VimOperation};
    use crate::text_stream::TextByteStream;
    use crate::vim::{
        Count, Counted, InsertEntry, ModeSwitch, Motion, NormalCommand, NormalOperatorTarget,
        Operator, OperatorTargetSource, PastePlacement, TargetKind, TargetResolutionError,
        TextObject, TextObjectKind, TextObjectScope, ViewportPosition,
    };

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

    #[test]
    fn normal_motion_converts_to_operation_effect() {
        let operation = VimOperation::from(NormalCommand::Motion(Counted::once(Motion::Right)));

        assert_eq!(
            operation.resolve_without_target().unwrap().effects(),
            &[OperationEffect::MoveCursor(Counted::once(Motion::Right))]
        );
    }

    #[test]
    fn normal_operator_preserves_operator_and_motion_target() {
        let command = NormalCommand::Operator {
            count: Count::default(),
            operator: Operator::Delete,
            target: NormalOperatorTarget::Motion(Counted::once(Motion::WordForward(
                crate::vim::WordKind::Normal,
            ))),
        };

        assert_eq!(
            VimOperation::from(command),
            VimOperation::ApplyOperator {
                count: Count::default(),
                operator: Operator::Delete,
                target: OperatorTargetSource::Motion(Counted::once(Motion::WordForward(
                    crate::vim::WordKind::Normal
                ))),
            }
        );
    }

    #[test]
    fn unresolved_operator_is_not_silently_ignored() {
        let operation = VimOperation::ApplyOperator {
            count: Count::default(),
            operator: Operator::Yank,
            target: OperatorTargetSource::Motion(Counted::once(Motion::Right)),
        };

        assert_eq!(
            operation.resolve_without_target(),
            Err(OperationError::TargetResolution(
                TargetResolutionError::UnsupportedTarget
            ))
        );
    }

    #[test]
    fn operator_operation_resolves_target_before_effect() {
        let stream = stream("one two");
        let operation = VimOperation::ApplyOperator {
            count: Count::default(),
            operator: Operator::Delete,
            target: OperatorTargetSource::Motion(Counted::once(Motion::WordForward(
                crate::vim::WordKind::Normal,
            ))),
        };

        assert_eq!(
            operation.resolve(&stream, 0).unwrap().effects(),
            &[OperationEffect::ApplyOperator {
                operator: Operator::Delete,
                target: crate::vim::OperatorTarget::characterwise(&stream, 0..4).unwrap(),
            }]
        );
    }

    #[test]
    fn operator_operation_multiplies_operator_and_motion_counts() {
        let operation = VimOperation::ApplyOperator {
            count: std::num::NonZeroUsize::new(2).unwrap().into(),
            operator: Operator::Delete,
            target: OperatorTargetSource::Motion(Counted {
                count: std::num::NonZeroUsize::new(2).unwrap().into(),
                item: Motion::WordForward(crate::vim::WordKind::Normal),
            }),
        };
        let stream = stream("one two three four five");
        let target = match operation.resolve(&stream, 0).unwrap().effects() {
            [OperationEffect::ApplyOperator { target, .. }] => *target,
            _ => panic!("expected one operator effect"),
        };

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

    #[test]
    fn operator_operation_resolves_text_object_targets() {
        let stream = stream("one two");
        let operation = VimOperation::ApplyOperator {
            count: Count::default(),
            operator: Operator::Yank,
            target: OperatorTargetSource::TextObject(Counted::once(TextObject::new(
                TextObjectScope::Inner,
                TextObjectKind::Word,
            ))),
        };

        assert_eq!(
            operation.resolve(&stream, "one ".len()).unwrap().effects(),
            &[OperationEffect::ApplyOperator {
                operator: Operator::Yank,
                target: crate::vim::OperatorTarget::characterwise(
                    &stream,
                    "one ".len().."one two".len()
                )
                .unwrap(),
            }]
        );
    }

    #[test]
    fn command_line_and_viewport_operations_are_first_class() {
        assert_eq!(
            VimOperation::from(NormalCommand::ModeSwitch(ModeSwitch::VisualCharacterwise))
                .resolve_without_target()
                .unwrap()
                .effects(),
            &[OperationEffect::SwitchMode(ModeSwitch::VisualCharacterwise)]
        );
        assert_eq!(
            VimOperation::from(NormalCommand::ViewportPosition(ViewportPosition::Center))
                .resolve_without_target()
                .unwrap()
                .effects(),
            &[OperationEffect::ViewportPosition(ViewportPosition::Center)]
        );
    }

    #[test]
    fn insert_entry_converts_to_operation_effect() {
        assert_eq!(
            VimOperation::from(NormalCommand::Insert(InsertEntry::AfterCursor))
                .resolve_without_target()
                .unwrap()
                .effects(),
            &[OperationEffect::EnterInsert(InsertEntry::AfterCursor)]
        );
    }

    #[test]
    fn paste_command_converts_to_operation_effect() {
        let count = std::num::NonZeroUsize::new(2).unwrap().into();

        assert_eq!(
            VimOperation::from(NormalCommand::Paste {
                count,
                placement: PastePlacement::After,
            })
            .resolve_without_target()
            .unwrap()
            .effects(),
            &[OperationEffect::Paste {
                count,
                placement: PastePlacement::After,
            }]
        );
    }
}