forked from rhysd/tui-textarea
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvim.rs
657 lines (616 loc) · 25.5 KB
/
vim.rs
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
use crossterm::event::{DisableMouseCapture, EnableMouseCapture};
use crossterm::terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use ratatui::backend::CrosstermBackend;
use ratatui::style::{Color, Modifier, Style};
use ratatui::widgets::{Block, Borders};
use ratatui::Terminal;
use std::env;
use std::fmt;
use std::fs;
use std::io;
use std::io::BufRead;
use tui_textarea::{CursorMove, Input, Key, Scrolling, TextArea};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
Normal,
Insert,
Replace(bool), // Bool for "once only?"
Visual,
Operator(char),
}
impl Mode {
fn block<'a>(&self) -> Block<'a> {
let help = match self {
Self::Normal => "type q to quit, type i to enter insert mode",
Self::Replace(_) | Self::Insert => "type Esc to back to normal mode",
Self::Visual => "type y to yank, type d to delete, type Esc to back to normal mode",
Self::Operator(_) => "move cursor to apply operator",
};
let title = format!("{} MODE ({})", self, help);
Block::default().borders(Borders::ALL).title(title)
}
fn cursor_style(&self) -> Style {
let color = match self {
Self::Normal => Color::Reset,
Self::Insert => Color::LightBlue,
Self::Visual => Color::LightYellow,
Self::Replace(_) => Color::LightRed,
Self::Operator(_) => Color::LightGreen,
};
Style::default().fg(color).add_modifier(Modifier::REVERSED)
}
}
impl fmt::Display for Mode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self {
Self::Normal => write!(f, "NORMAL"),
Self::Insert => write!(f, "INSERT"),
Self::Visual => write!(f, "VISUAL"),
Self::Replace(_) => write!(f, "REPLACE"),
Self::Operator(c) => write!(f, "OPERATOR({})", c),
}
}
}
// How the Vim emulation state transitions
enum Transition {
Nop,
Mode(Mode),
Pending(Input),
Quit,
}
// State of Vim emulation
struct Vim {
mode: Mode,
pending: Input, // Pending input to handle a sequence with two keys like gg
}
impl Vim {
fn new(mode: Mode) -> Self {
Self {
mode,
pending: Input::default(),
}
}
fn with_pending(self, pending: Input) -> Self {
Self {
mode: self.mode,
pending,
}
}
// True if the textarea cursor is at the end of its given line
fn is_before_line_end(textarea: &TextArea<'_>) -> bool {
let (cursor_line, cursor_char) = textarea.cursor();
let lines = textarea.lines();
let line = &lines[cursor_line];
let line_length = line.chars().count(); // FIXME: Not acceptable-- O(N)
cursor_char < line_length
}
fn transition(&self, input: Input, textarea: &mut TextArea<'_>) -> Transition {
if input.key == Key::Null {
return Transition::Nop;
}
match self.mode {
Mode::Normal | Mode::Visual | Mode::Operator(_) => {
match input {
Input {
key: Key::Char('h'),
..
}
| Input { key: Key::Left, .. } => textarea.move_cursor(CursorMove::Back),
Input {
key: Key::Char('j'),
..
}
| Input { key: Key::Down, .. } => textarea.move_cursor(CursorMove::Down),
Input {
key: Key::Char('k'),
..
}
| Input { key: Key::Up, .. } => textarea.move_cursor(CursorMove::Up),
Input {
key: Key::Char('l'),
..
}
| Input {
key: Key::Right, ..
} => textarea.move_cursor(CursorMove::Forward),
Input {
key: Key::Char('w'),
..
} => textarea.move_cursor(CursorMove::WordForward),
Input {
key: Key::Char('e'),
ctrl: false,
..
} => {
textarea.move_cursor(CursorMove::WordEnd);
if matches!(self.mode, Mode::Operator(_)) {
textarea.move_cursor(CursorMove::Forward); // Include the text under the cursor
}
}
Input {
key: Key::Char('b'),
ctrl: false,
..
} => textarea.move_cursor(CursorMove::WordBack),
Input {
key: Key::Char('^'),
..
} => textarea.move_cursor(CursorMove::Head),
Input {
key: Key::Char('$'),
..
} => textarea.move_cursor(CursorMove::End),
Input {
// Note: Not sorted with j
key: Key::Char('J'),
..
} => {
let mut cursor = textarea.cursor();
let mut line_count = 1;
if let Some(((from_line, from_idx), (to_line, _))) =
textarea.selection_range()
{
// J with a selection joins all lines selected
// If only one line is selected, it acts like normal J,
// except on failure the cursor moves to selection start.
line_count = (to_line - from_line).max(1);
cursor = (from_line, from_idx);
textarea.cancel_selection(); // fixme restore
textarea
.move_cursor(CursorMove::Jump(from_line as u16, from_idx as u16));
}
for _ in 0..line_count {
textarea.move_cursor(CursorMove::End);
let success = textarea.delete_line_by_end();
if success {
// A line existed
textarea.insert_char(' ');
} else {
// In regular vim, joining on the final line is a noop
let (c1, c2) = cursor;
textarea.move_cursor(CursorMove::Jump(c1 as u16, c2 as u16));
// TODO: beep
}
}
}
Input {
key: Key::Char('D'),
..
} => {
textarea.delete_line_by_end();
return Transition::Mode(Mode::Normal);
}
Input {
key: Key::Char('C'),
..
} => {
textarea.delete_line_by_end();
textarea.cancel_selection();
return Transition::Mode(Mode::Insert);
}
Input {
key: Key::Char('p'),
..
} => {
textarea.paste();
return Transition::Mode(Mode::Normal);
}
Input {
key: Key::Char('u'),
ctrl: false,
..
} => {
textarea.undo();
return Transition::Mode(Mode::Normal);
}
Input {
key: Key::Char('r'),
ctrl: true,
..
} => {
textarea.redo();
return Transition::Mode(Mode::Normal);
}
Input {
key: Key::Char('x'),
..
} => {
// FIXME: This check shouldn't be necessary, but the vim example is able to cursor over a terminating newline currently, which real vim can't in normal mode
// FIXME: Repeatedly mashing x at the end of a line should delete the entire line right to left
if Vim::is_before_line_end(textarea) {
textarea.delete_next_char();
}
return Transition::Mode(Mode::Normal);
}
Input {
key: Key::Char('i'),
..
} => {
textarea.cancel_selection();
return Transition::Mode(Mode::Insert);
}
Input {
key: Key::Char('a'),
..
} => {
textarea.cancel_selection();
if Vim::is_before_line_end(textarea) {
textarea.move_cursor(CursorMove::Forward);
}
return Transition::Mode(Mode::Insert);
}
Input {
key: Key::Char('A'),
..
} => {
textarea.cancel_selection();
textarea.move_cursor(CursorMove::End);
return Transition::Mode(Mode::Insert);
}
Input {
key: Key::Char('S'),
..
} => {
let mut line_count = 1;
if let Some(((from_line, from_idx), (to_line, _))) =
textarea.selection_range()
{
// S with a selection clears all lines selected
line_count = (to_line - from_line).max(1);
textarea.cancel_selection(); // fixme restore
textarea
.move_cursor(CursorMove::Jump(from_line as u16, from_idx as u16));
}
textarea.move_cursor(CursorMove::Head);
for line_idx in 0..line_count {
let (cursor_line, _) = textarea.cursor();
let lines = textarea.lines();
let line = &lines[cursor_line];
if !line.is_empty() {
// delete_line_by_end has a special behavior where if you are at the end,
// it joins the line with the next. Prevent accidentally triggering this on an empty line.
textarea.delete_line_by_end();
}
if line_idx < line_count - 1 {
// We are now guaranteed at the end of the line.
// Join to next line.
textarea.delete_line_by_end();
}
}
return Transition::Mode(Mode::Insert);
}
Input {
key: Key::Char('o'),
..
} => {
textarea.move_cursor(CursorMove::End);
textarea.insert_newline();
return Transition::Mode(Mode::Insert);
}
Input {
key: Key::Char('O'),
..
} => {
textarea.move_cursor(CursorMove::Head);
textarea.insert_newline();
textarea.move_cursor(CursorMove::Up);
return Transition::Mode(Mode::Insert);
}
Input {
key: Key::Char('I'),
..
} => {
textarea.cancel_selection();
textarea.move_cursor(CursorMove::Head);
return Transition::Mode(Mode::Insert);
}
Input {
key: Key::Char('r'),
..
} => {
// Notice selection is not cancelled-- it will be used by replace mode
return Transition::Mode(Mode::Replace(true));
}
Input {
key: Key::Char('R'),
..
} => {
if textarea.selection_range().is_some() {
// R with a selection does the same thing as S-- it enters Insert NOT Replace mode.
return self.transition(
Input {
key: Key::Char('S'),
ctrl: false,
alt: false,
shift: true,
},
textarea,
);
} else {
return Transition::Mode(Mode::Replace(false));
}
}
Input {
key: Key::Char('q'),
..
} => return Transition::Quit,
Input {
key: Key::Char('e'),
ctrl: true,
..
} => textarea.scroll((1, 0)),
Input {
key: Key::Char('y'),
ctrl: true,
..
} => textarea.scroll((-1, 0)),
Input {
key: Key::Char('d'),
ctrl: true,
..
} => textarea.scroll(Scrolling::HalfPageDown),
Input {
key: Key::Char('u'),
ctrl: true,
..
} => textarea.scroll(Scrolling::HalfPageUp),
Input {
key: Key::Char('f'),
ctrl: true,
..
} => textarea.scroll(Scrolling::PageDown),
Input {
key: Key::Char('b'),
ctrl: true,
..
} => textarea.scroll(Scrolling::PageUp),
Input {
key: Key::Char('v'),
ctrl: false,
..
} if self.mode == Mode::Normal => {
textarea.start_selection();
return Transition::Mode(Mode::Visual);
}
Input {
key: Key::Char('V'),
ctrl: false,
..
} if self.mode == Mode::Normal => {
textarea.move_cursor(CursorMove::Head);
textarea.start_selection();
textarea.move_cursor(CursorMove::End);
return Transition::Mode(Mode::Visual);
}
Input { key: Key::Esc, .. }
| Input {
key: Key::Char('['),
ctrl: true,
..
}
| Input {
key: Key::Char('v'),
ctrl: false,
..
} if self.mode == Mode::Visual => {
textarea.cancel_selection();
return Transition::Mode(Mode::Normal);
}
Input {
key: Key::Char('g'),
ctrl: false,
..
} if matches!(
self.pending,
Input {
key: Key::Char('g'),
ctrl: false,
..
}
) =>
{
textarea.move_cursor(CursorMove::Top)
}
Input {
key: Key::Char('G'),
ctrl: false,
..
} => textarea.move_cursor(CursorMove::Bottom),
Input {
key: Key::Char(c),
ctrl: false,
..
} if self.mode == Mode::Operator(c) => {
// Handle yy, dd, cc. (This is not strictly the same behavior as Vim)
textarea.move_cursor(CursorMove::Head);
textarea.start_selection();
let cursor = textarea.cursor();
textarea.move_cursor(CursorMove::Down);
if cursor == textarea.cursor() {
textarea.move_cursor(CursorMove::End); // At the last line, move to end of the line instead
}
}
Input {
key: Key::Char(op @ ('y' | 'd' | 'c')),
ctrl: false,
..
} if self.mode == Mode::Normal => {
textarea.start_selection();
return Transition::Mode(Mode::Operator(op));
}
Input {
key: Key::Char('y'),
ctrl: false,
..
} if self.mode == Mode::Visual => {
textarea.move_cursor(CursorMove::Forward); // Vim's text selection is inclusive
textarea.copy();
return Transition::Mode(Mode::Normal);
}
Input {
key: Key::Char('d'),
ctrl: false,
..
} if self.mode == Mode::Visual => {
textarea.move_cursor(CursorMove::Forward); // Vim's text selection is inclusive
textarea.cut();
return Transition::Mode(Mode::Normal);
}
Input {
key: Key::Char('c'),
ctrl: false,
..
} if self.mode == Mode::Visual => {
textarea.move_cursor(CursorMove::Forward); // Vim's text selection is inclusive
textarea.cut();
return Transition::Mode(Mode::Insert);
}
input => return Transition::Pending(input),
}
// Handle the pending operator
match self.mode {
Mode::Operator('y') => {
textarea.copy();
Transition::Mode(Mode::Normal)
}
Mode::Operator('d') => {
textarea.cut();
Transition::Mode(Mode::Normal)
}
Mode::Operator('c') => {
textarea.cut();
Transition::Mode(Mode::Insert)
}
_ => Transition::Nop,
}
}
Mode::Insert => match input {
Input { key: Key::Esc, .. }
| Input {
key: Key::Char('['),
ctrl: true,
..
}
| Input {
key: Key::Char('c'),
ctrl: true,
..
} => Transition::Mode(Mode::Normal),
input => {
textarea.input(input); // Use default key mappings in insert mode
Transition::Mode(Mode::Insert)
}
},
Mode::Replace(once) => match input {
Input { key: Key::Esc, .. }
| Input {
key: Key::Char('['),
ctrl: true,
..
}
| Input {
key: Key::Char('c'),
ctrl: true,
..
} => {
if textarea.selection_range().is_some() {
// The user made a selection, hit lowercase 'r', then aborted.
// (It shouldn't be possible to get here in non-"once" mode.)
Transition::Mode(Mode::Visual)
} else {
Transition::Mode(Mode::Normal)
}
}
Input { key, .. } => {
if !matches!(key, Key::Down | Key::Up | Key::Left | Key::Right)
&& !(once && (key == Key::Backspace || key == Key::Delete))
{
// Allowed with R, not r
if let Some(((from_line, from_idx), (to_line, to_idx))) =
textarea.selection_range()
{
// Bizarro 'r' with a selection: Replace every non-newline character at once?!
let mut next_start_idx = from_idx;
for line_idx in from_line..=to_line {
let lines = textarea.lines();
let line = &lines[line_idx];
let line_len = line.len();
textarea.move_cursor(CursorMove::Jump(
line_idx as u16,
next_start_idx as u16,
));
// "min" is to handle the odd case where the cursor is on the newline (not possible in real vim)
let end_idx = if line_idx == to_line {
line_len.min(to_idx + 1)
} else {
line_len
};
for _ in next_start_idx..end_idx {
textarea.delete_next_char();
textarea.input(input.clone());
}
next_start_idx = 0;
}
textarea
.move_cursor(CursorMove::Jump(from_line as u16, from_idx as u16));
} else {
// Normal 'r'
if Vim::is_before_line_end(textarea) {
textarea.delete_next_char(); // FIXME: Will eat newlines and join into next line, should act like insert at end of line
}
textarea.input(input); // Use default key mappings in insert mode
}
} // TODO: else beep
if once {
Transition::Mode(Mode::Normal)
} else {
Transition::Mode(Mode::Replace(false))
}
}
},
}
}
}
fn main() -> io::Result<()> {
let stdout = io::stdout();
let mut stdout = stdout.lock();
enable_raw_mode()?;
crossterm::execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut term = Terminal::new(backend)?;
let mut textarea = if let Some(path) = env::args().nth(1) {
let file = fs::File::open(path)?;
io::BufReader::new(file)
.lines()
.collect::<io::Result<_>>()?
} else {
TextArea::default()
};
textarea.set_block(Mode::Normal.block());
textarea.set_cursor_style(Mode::Normal.cursor_style());
let mut vim = Vim::new(Mode::Normal);
loop {
term.draw(|f| f.render_widget(&textarea, f.area()))?;
vim = match vim.transition(crossterm::event::read()?.into(), &mut textarea) {
Transition::Mode(mode) if vim.mode != mode => {
textarea.set_block(mode.block());
textarea.set_cursor_style(mode.cursor_style());
Vim::new(mode)
}
Transition::Nop | Transition::Mode(_) => vim,
Transition::Pending(input) => vim.with_pending(input),
Transition::Quit => break,
}
}
disable_raw_mode()?;
crossterm::execute!(
term.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
term.show_cursor()?;
println!("Lines: {:?}", textarea.lines());
Ok(())
}