paper 0.4.0

A terminal-based editor with goals to maximize simplicity and efficiency.
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
//! Implements the functionality of interpreting an [`Input`] into [`Operation`]s.
#![allow(clippy::pattern_type_mismatch)] // False positive.
use {
    crate::{
        io::{Dimensions, File, Input, UserAction},
        orient,
    },
    core::fmt::{self, Debug},
    crossterm::event::KeyCode,
    enum_map::{enum_map, Enum, EnumMap},
    lsp_types::{MessageType, ShowMessageRequestParams},
    parse_display::Display as ParseDisplay,
};

/// Signifies actions that can be performed by the application.
#[derive(Debug, PartialEq)]
pub(crate) enum Operation {
    /// Updates the display to `size`.
    Resize {
        /// The new [`Dimensions`].
        dimensions: Dimensions,
    },
    /// Resets the application.
    Reset,
    /// Confirms that the action is desired.
    Confirm(ConfirmAction),
    /// Quits the application.
    Quit,
    /// Open input box for a command.
    StartCommand(Command),
    /// Input to input box.
    Collect(char),
    /// Executes the current command.
    Execute,
    /// Creates a document from the file.
    CreateDoc(File),
    /// Scrolls the document.
    Scroll(orient::ScreenDirection),
}

/// Signifies actions that require a confirmation prior to their execution.
#[derive(Debug, PartialEq)]
pub(crate) enum ConfirmAction {
    /// Quit the application.
    Quit,
}

impl fmt::Display for ConfirmAction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "You have input that you want to quit the application.\nPlease confirm this action by pressing `y`. To cancel this action, press any other key.")
    }
}

impl From<ConfirmAction> for ShowMessageRequestParams {
    #[inline]
    #[must_use]
    fn from(value: ConfirmAction) -> Self {
        Self {
            typ: MessageType::Info,
            message: value.to_string(),
            actions: None,
        }
    }
}

/// Signifies a command that a user can give to the application.
#[derive(Debug, ParseDisplay, PartialEq)]
pub(crate) enum Command {
    /// Opens a given file.
    #[display("Open <file>")]
    Open,
}

/// An operation performed on a document.
#[derive(Debug, PartialEq)]
pub(crate) enum DocOp {
    /// Saves the document.
    Save,
}

impl fmt::Display for DocOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Save => "save",
            }
        )
    }
}

/// Manages interpretation for the application.
///
/// How an [`Input`] maps to [`Operation`]s is determined by the [`Mode`] of the [`Interpreter`]. Each mode defines a struct to implement [`ModeInterpreter`].
#[derive(Debug)]
pub(crate) struct Interpreter {
    /// Signifies the current [`Mode`] of the [`Interpreter`].
    mode: Mode,
    /// Map of [`ModeInterpreter`]s.
    map: EnumMap<Mode, &'static dyn ModeInterpreter>,
}

impl Interpreter {
    /// Returns the [`Operation`] that maps to `input` given the current [`Mode`].
    pub(crate) fn translate(&mut self, input: Input) -> Option<Operation> {
        let mut output = Output::new();

        match input {
            Input::File(file) => {
                output.add_op(Operation::CreateDoc(file));
            }
            Input::Lsp(_statement) => {}
            Input::User(user_input) => {
                #[allow(clippy::indexing_slicing)] // EnumMap guarantees that index is in bounds.
                let mode_interpreter = self.map[self.mode];

                output = mode_interpreter.decode(user_input);
            }
        }

        if let Some(mode) = output.new_mode {
            self.mode = mode;
        }

        output.operation
    }
}

impl Default for Interpreter {
    fn default() -> Self {
        /// The [`ModeInterpreter`] for [`Mode::View`].
        static VIEW_INTERPRETER: ViewInterpreter = ViewInterpreter::new();
        /// The [`ModeInterpreter`] for [`Mode::Confirm`].
        static CONFIRM_INTERPRETER: ConfirmInterpreter = ConfirmInterpreter::new();
        /// The [`ModeInterpreter`] for [`Mode::Collect`].
        static COLLECT_INTERPRETER: CollectInterpreter = CollectInterpreter::new();

        // Required to establish value type in enum_map.
        let view_interpreter: &dyn ModeInterpreter = &VIEW_INTERPRETER;

        Self {
            map: enum_map! {
                Mode::View => view_interpreter,
                Mode::Confirm => &CONFIRM_INTERPRETER,
                Mode::Collect => &COLLECT_INTERPRETER,
            },
            mode: Mode::default(),
        }
    }
}

/// Signifies the mode of the application.
#[derive(Copy, Clone, Debug, Enum, Eq, ParseDisplay, PartialEq, Hash)]
#[display(style = "CamelCase")]
enum Mode {
    /// Displays the current file.
    View,
    /// Confirms the user's action
    Confirm,
    /// Collects input from the user.
    Collect,
}

impl Default for Mode {
    #[inline]
    fn default() -> Self {
        Self::View
    }
}

/// Signifies the data gleaned from user input.
#[derive(Debug, Default, PartialEq)]
struct Output {
    /// The operation to be run.
    operation: Option<Operation>,
    /// The mode to switch to.
    ///
    /// If None, interpreter should not switch modes.
    new_mode: Option<Mode>,
}

impl Output {
    /// Creates a new `Output`.
    fn new() -> Self {
        Self::default()
    }

    /// Adds `operation` to `self`.
    fn add_op(&mut self, operation: Operation) {
        let _ = self.operation.replace(operation);
    }

    /// Sets the mode of `self` to `mode`.
    fn set_mode(&mut self, mode: Mode) {
        self.new_mode = Some(mode);
    }

    /// Modifies to the [`Operation::Reset`].
    fn reset(&mut self) {
        self.add_op(Operation::Reset);
        self.set_mode(Mode::View);
    }
}

/// Defines the functionality to convert [`Input`] to [`Output`].
trait ModeInterpreter: Debug {
    /// Converts `input` to [`Operation`]s.
    fn decode(&self, input: UserAction) -> Output;
}

/// The [`ModeInterpreter`] for [`Mode::View`].
#[derive(Clone, Debug)]
struct ViewInterpreter {}

impl ViewInterpreter {
    /// Creates a `ViewInterpreter`.
    const fn new() -> Self {
        Self {}
    }

    /// Converts `output` appropriate to `key`.
    fn decode_key(key: KeyCode, output: &mut Output) {
        match key {
            KeyCode::Esc => {
                output.add_op(Operation::Reset);
            }
            KeyCode::Char('w') => {
                output.add_op(Operation::Confirm(ConfirmAction::Quit));
                output.set_mode(Mode::Confirm);
            }
            KeyCode::Char('o') => {
                output.add_op(Operation::StartCommand(Command::Open));
                output.set_mode(Mode::Collect);
            }
            KeyCode::Char('j') => {
                output.add_op(Operation::Scroll(orient::ScreenDirection::Down));
            }
            KeyCode::Char('k') => {
                output.add_op(Operation::Scroll(orient::ScreenDirection::Up));
            }
            KeyCode::Backspace
            | KeyCode::Enter
            | KeyCode::Left
            | KeyCode::Right
            | KeyCode::Up
            | KeyCode::Down
            | KeyCode::Home
            | KeyCode::End
            | KeyCode::PageUp
            | KeyCode::PageDown
            | KeyCode::Tab
            | KeyCode::BackTab
            | KeyCode::Delete
            | KeyCode::Insert
            | KeyCode::F(..)
            | KeyCode::Null
            | KeyCode::Char(..) => {}
        }
    }
}

impl ModeInterpreter for ViewInterpreter {
    fn decode(&self, input: UserAction) -> Output {
        let mut output = Output::new();

        match input {
            UserAction::Key { code, .. } => {
                Self::decode_key(code, &mut output);
            }
            UserAction::Resize { dimensions } => {
                output.add_op(Operation::Resize { dimensions });
            }
            UserAction::Mouse => {}
        }

        output
    }
}

/// The [`ModeInterpreter`] for [`Mode::Confirm`].
#[derive(Clone, Debug)]
struct ConfirmInterpreter {}

impl ConfirmInterpreter {
    /// Creates a new `ConfirmInterpreter`.
    const fn new() -> Self {
        Self {}
    }
}

impl ModeInterpreter for ConfirmInterpreter {
    fn decode(&self, input: UserAction) -> Output {
        let mut output = Output::new();

        match input {
            UserAction::Key {
                code: KeyCode::Char('y'),
                ..
            } => {
                output.add_op(Operation::Quit);
            }
            UserAction::Key { .. } | UserAction::Mouse | UserAction::Resize { .. } => {
                output.reset();
            }
        }

        output
    }
}

/// The [`ModeInterpreter`] for [`Mode::Collect`].
#[derive(Clone, Debug)]
struct CollectInterpreter {}

impl CollectInterpreter {
    /// Creates a new `CollectInterpreter`.
    const fn new() -> Self {
        Self {}
    }
}

impl ModeInterpreter for CollectInterpreter {
    fn decode(&self, input: UserAction) -> Output {
        let mut output = Output::new();

        match input {
            UserAction::Key {
                code: KeyCode::Esc, ..
            } => {
                output.reset();
            }
            UserAction::Key {
                code: KeyCode::Enter,
                ..
            } => {
                output.add_op(Operation::Execute);
                output.set_mode(Mode::View);
            }
            UserAction::Key {
                code: KeyCode::Char(c),
                ..
            } => {
                output.add_op(Operation::Collect(c));
            }
            UserAction::Key { .. } | UserAction::Mouse | UserAction::Resize { .. } => {}
        }

        output
    }
}

/// Testing of the translate module.
#[cfg(test)]
mod test {
    use {super::*, crossterm::event::KeyModifiers};

    /// Tests decoding user input while the [`Interpreter`] is in [`Mode::View`].
    mod view {
        use super::*;

        fn view_mode() -> Interpreter {
            Interpreter::default()
        }

        /// The `Ctrl-w` key shall confirm the user wants to quit.
        #[test]
        fn quit() {
            let mut int = view_mode();

            assert_eq!(
                int.translate(Input::User(UserAction::Key {
                    code: KeyCode::Char('w'),
                    modifiers: KeyModifiers::CONTROL,
                })),
                Some(Operation::Confirm(ConfirmAction::Quit))
            );
            assert_eq!(int.mode, Mode::Confirm);
        }

        /// The `Ctrl-o` key shall request the name of the document to be opened.
        #[test]
        fn open() {
            let mut int = view_mode();

            assert_eq!(
                int.translate(Input::User(UserAction::Key {
                    code: KeyCode::Char('o'),
                    modifiers: KeyModifiers::CONTROL,
                })),
                Some(Operation::StartCommand(Command::Open))
            );
            assert_eq!(int.mode, Mode::Collect);
        }
    }

    /// Tests decoding user input while in the Confirm mode.
    mod confirm {
        use super::*;

        fn confirm_mode() -> Interpreter {
            let mut int = Interpreter::default();
            int.mode = Mode::Confirm;
            int
        }

        /// The `y` key shall confirm the action.
        #[test]
        fn confirm() {
            let mut int = confirm_mode();

            assert_eq!(
                int.translate(Input::User(UserAction::Key {
                    code: KeyCode::Char('y'),
                    modifiers: KeyModifiers::empty(),
                })),
                Some(Operation::Quit)
            );
        }

        /// Any other key shall cancel the action, resetting the application to View mode.
        #[test]
        fn cancel() {
            let mut int = confirm_mode();

            assert_eq!(
                int.translate(Input::User(UserAction::Key {
                    code: KeyCode::Char('n'),
                    modifiers: KeyModifiers::empty(),
                })),
                Some(Operation::Reset)
            );
            assert_eq!(int.mode, Mode::View);

            int = confirm_mode();

            assert_eq!(
                int.translate(Input::User(UserAction::Key {
                    code: KeyCode::Char('1'),
                    modifiers: KeyModifiers::empty(),
                })),
                Some(Operation::Reset)
            );
            assert_eq!(int.mode, Mode::View);
        }
    }

    /// Tests decoding user input while mode is [`Mode::Collect`].
    #[cfg(test)]
    mod collect {
        use super::*;

        fn collect_mode() -> Interpreter {
            let mut int = Interpreter::default();
            int.mode = Mode::Collect;
            int
        }

        /// The `Esc` key shall return to [`Mode::View`].
        #[test]
        fn reset() {
            let mut int = collect_mode();

            assert_eq!(
                int.translate(Input::User(UserAction::Key {
                    code: KeyCode::Esc,
                    modifiers: KeyModifiers::empty(),
                })),
                Some(Operation::Reset)
            );
            assert_eq!(int.mode, Mode::View);
        }

        /// All char keys shall be collected.
        #[test]
        fn collect() {
            let mut int = collect_mode();

            assert_eq!(
                int.translate(Input::User(UserAction::Key {
                    code: KeyCode::Char('a'),
                    modifiers: KeyModifiers::empty(),
                })),
                Some(Operation::Collect('a'))
            );
            assert_eq!(int.mode, Mode::Collect);

            int = collect_mode();

            assert_eq!(
                int.translate(Input::User(UserAction::Key {
                    code: KeyCode::Char('.'),
                    modifiers: KeyModifiers::empty(),
                })),
                Some(Operation::Collect('.'))
            );
            assert_eq!(int.mode, Mode::Collect);

            int = collect_mode();

            assert_eq!(
                int.translate(Input::User(UserAction::Key {
                    code: KeyCode::Char('1'),
                    modifiers: KeyModifiers::empty(),
                })),
                Some(Operation::Collect('1'))
            );
            assert_eq!(int.mode, Mode::Collect);
        }

        /// The `Enter` key shall execute the command and return to [`Mode::View`].
        #[test]
        fn execute() {
            let mut int = collect_mode();

            assert_eq!(
                int.translate(Input::User(UserAction::Key {
                    code: KeyCode::Enter,
                    modifiers: KeyModifiers::empty(),
                })),
                Some(Operation::Execute)
            );
            assert_eq!(int.mode, Mode::View);
        }
    }
}