-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathmodeHandler.ts
1826 lines (1614 loc) · 71.4 KB
/
modeHandler.ts
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import _ from 'lodash';
import * as vscode from 'vscode';
import * as process from 'process';
import { Position, Range, Uri } from 'vscode';
import { BaseMovement } from '../actions/baseMotion';
import { BaseOperator } from '../actions/operator';
import { EasyMotion } from '../actions/plugins/easymotion/easymotion';
import { SearchByNCharCommand } from '../actions/plugins/easymotion/easymotion.cmd';
import { IBaseAction } from '../actions/types';
import { Cursor } from '../common/motion/cursor';
import { configuration } from '../configuration/configuration';
import { decoration } from '../configuration/decoration';
import { Notation } from '../configuration/notation';
import { Remappers } from '../configuration/remapper';
import { Jump } from '../jumps/jump';
import { globalState } from '../state/globalState';
import { RemapState } from '../state/remapState';
import { StatusBar } from '../statusBar';
import { IModeHandler, executeTransformations } from '../transformations/execute';
import { Dot, isTextTransformation } from '../transformations/transformations';
import { SearchDecorations, getDecorationsForSearchMatchRanges } from '../util/decorationUtils';
import { Logger } from '../util/logger';
import { SpecialKeys } from '../util/specialKeys';
import { scrollView } from '../util/util';
import { VSCodeContext } from '../util/vscodeContext';
import { BaseAction, BaseCommand, KeypressState, getRelevantAction } from './../actions/base';
import {
ActionOverrideCmdD,
ActionReplaceCharacter,
CommandInsertAtCursor,
CommandNumber,
CommandQuitRecordMacro,
CommandRegister,
DocumentContentChangeAction,
} from './../actions/commands/actions';
import {
CommandBackspaceInInsertMode,
CommandEscInsertMode,
CommandInsertInInsertMode,
CommandInsertPreviousText,
InsertCharAbove,
InsertCharBelow,
} from './../actions/commands/insert';
import { PairMatcher } from './../common/matching/matcher';
import { earlierOf, laterOf } from './../common/motion/position';
import { ForceStopRemappingError, VimError } from './../error';
import { Register, RegisterMode } from './../register/register';
import { RecordedState } from './../state/recordedState';
import { VimState } from './../state/vimState';
import { TextEditor } from './../textEditor';
import {
DotCommandStatus,
Mode,
NormalCommandState,
ReplayMode,
VSCodeVimCursorType,
getCursorStyle,
isStatusBarMode,
isVisualMode,
} from './mode';
import { isLiteralMode, remapKey } from '../configuration/langmap';
interface IModeHandlerMap {
get(editorId: Uri): ModeHandler | undefined;
}
/**
* ModeHandler is the extension's backbone. It listens to events and updates the VimState.
* One of these exists for each editor - see ModeHandlerMap
*
* See: https://github.com/VSCodeVim/Vim/blob/master/.github/CONTRIBUTING.md#the-vim-state-machine
*/
export class ModeHandler implements vscode.Disposable, IModeHandler {
public readonly vimState: VimState;
public readonly remapState: RemapState;
public lastMovementFailed: boolean = false;
public focusChanged = false;
private searchDecorationCacheKey: { searchString: string; documentVersion: number } | undefined;
private readonly disposables: vscode.Disposable[] = [];
private readonly handlerMap: IModeHandlerMap;
private readonly remappers: Remappers;
/**
* Used internally to ignore selection changes that were performed by us.
* 'ignoreIntermediateSelections': set to true when running an action, during this time
* all selections change events will be ignored.
* 'ourSelections': keeps track of our selections that will trigger a selection change event
* so that we can ignore them.
*/
public selectionsChanged = {
/**
* Set to true when running an action, during this time
* all selections change events will be ignored.
*/
ignoreIntermediateSelections: false,
/**
* keeps track of our selections that will trigger a selection change event
* so that we can ignore them.
*/
ourSelections: Array<string>(),
};
/**
* Was the previous mouse click past EOL
*/
private lastClickWasPastEol: boolean = false;
private _currentMode!: Mode;
private get currentMode(): Mode {
return this._currentMode;
}
private async setCurrentMode(mode: Mode): Promise<void> {
if (this.vimState.currentMode !== mode) {
await this.vimState.setCurrentMode(mode);
}
this._currentMode = mode;
}
public static async create(
handlerMap: IModeHandlerMap,
textEditor: vscode.TextEditor,
): Promise<ModeHandler> {
const modeHandler = new ModeHandler(handlerMap, textEditor);
await modeHandler.vimState.load();
await modeHandler.setCurrentMode(configuration.startInInsertMode ? Mode.Insert : Mode.Normal);
modeHandler.syncCursors();
return modeHandler;
}
private constructor(handlerMap: IModeHandlerMap, textEditor: vscode.TextEditor) {
this.handlerMap = handlerMap;
this.remappers = new Remappers();
this.vimState = new VimState(textEditor, new EasyMotion());
this.remapState = new RemapState();
this.disposables.push(this.vimState);
}
/**
* Updates VSCodeVim's internal representation of cursors to match VSCode's selections.
* This loses some information, so it should only be done when necessary.
*/
public syncCursors() {
// TODO: getCursorsAfterSync() is basically this, but stupider
const { selections } = this.vimState.editor;
// TODO: this if block is a workaround for a problem described here https://github.com/VSCodeVim/Vim/pull/8426
if (
selections.length === 1 &&
selections[0].isEqual(new Range(new Position(0, 0), new Position(0, 0)))
) {
return;
}
if (
!this.vimState.cursorStartPosition.isEqual(selections[0].anchor) ||
!this.vimState.cursorStopPosition.isEqual(selections[0].active)
) {
this.vimState.desiredColumn = selections[0].active.character;
}
this.vimState.cursors = selections.map(({ active, anchor }) =>
active.isBefore(anchor) ? new Cursor(anchor.getLeft(), active) : new Cursor(anchor, active),
);
}
/**
* This is easily the worst function in VSCodeVim.
*
* We need to know when VSCode has updated our selection, so that we can sync
* that internally. Unfortunately, VSCode has a habit of calling this
* function at weird times, or or with incomplete information, so we have to
* do a lot of voodoo to make sure we're updating the cursors correctly.
*
* Even worse, we don't even know how to test this stuff.
*
* Anyone who wants to change the behavior of this method should make sure
* all selection related test cases pass. Follow this spec
* https://gist.github.com/rebornix/d21d1cc060c009d4430d3904030bd4c1 to
* perform the manual testing. Besides this testing you should still test
* commands like 'editor.action.smartSelect.grow' and you should test moving
* continuously up/down or left/right with and without remapped movement keys
* because sometimes vscode lags behind and calls this function with information
* that is not up to date with our selections yet and we need to make sure we don't
* change our cursors to previous information (this usally is only an issue in visual
* mode because of our different ways of handling selections and in those cases
* updating our cursors with not up to date info might result in us changing our
* cursor start position).
*/
public async handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent): Promise<void> {
if (
vscode.window.activeTextEditor === undefined ||
e.textEditor.document !== vscode.window.activeTextEditor.document
) {
// we don't care if there is no active editor
// or user selection changed in a paneled window (e.g debug console/terminal)
// This check is made before enqueuing this selection change, but sometimes
// between the enqueueing and the actual calling of this function the editor
// might close or change to other document
return;
}
const selection = e.selections[0];
Logger.debug(
`Selection change: ${selection.anchor.toString()}, ${selection.active}, SelectionsLength: ${
e.selections.length
}`,
);
// If our previous cursors are not included on any of the current selections, then a snippet
// must have been inserted.
const isSnippetSelectionChange = () => {
return e.selections.every((s) => {
return this.vimState.cursors.every((c) => !s.contains(new vscode.Range(c.start, c.stop)));
});
};
if (
(e.selections.length !== this.vimState.cursors.length || this.vimState.isMultiCursor) &&
this.vimState.currentMode !== Mode.VisualBlock
) {
const allowedModes = [Mode.Normal];
if (!isSnippetSelectionChange()) {
allowedModes.push(Mode.Insert, Mode.Replace);
}
// Number of selections changed, make sure we know about all of them still
this.vimState.cursors = e.textEditor.selections.map(
(sel) =>
new Cursor(
// Adjust the cursor positions because cursors & selections don't match exactly
sel.anchor.isAfter(sel.active) ? sel.anchor.getLeft() : sel.anchor,
sel.active,
),
);
if (
e.selections.some((s) => !s.anchor.isEqual(s.active)) &&
allowedModes.includes(this.vimState.currentMode)
) {
// If we got a visual selection and we are on normal, insert or replace mode, enter visual mode.
// We shouldn't go to visual mode on any other mode, because the other visual modes are handled
// very differently than vscode so only our extension will create them. And the other modes
// like the plugin modes shouldn't be changed or else it might mess up the plugins actions.
await this.setCurrentMode(Mode.Visual);
}
return this.updateView({ drawSelection: false, revealRange: false });
}
/**
* We only trigger our view updating process if it's a mouse selection.
* Otherwise we only update our internal cursor positions accordingly.
*/
if (e.kind !== vscode.TextEditorSelectionChangeKind.Mouse) {
if (selection) {
if (e.kind === vscode.TextEditorSelectionChangeKind.Command) {
// This 'Command' kind is triggered when using a command like 'editor.action.smartSelect.grow'
// but it is also triggered when we set the 'editor.selections' on 'updateView'.
const allowedModes = [Mode.Normal, Mode.Visual, Mode.VisualLine];
if (!isSnippetSelectionChange()) {
// if we just inserted a snippet then don't allow insert modes to go to visual mode
allowedModes.push(Mode.Insert, Mode.Replace);
}
if (allowedModes.includes(this.vimState.currentMode)) {
// Since the selections weren't ignored then probably we got change of selection from
// a command, so we need to update our start and stop positions. This is where commands
// like 'editor.action.smartSelect.grow' are handled.
if (this.vimState.currentMode === Mode.Visual) {
Logger.trace('Updating Visual Selection!');
this.vimState.cursorStopPosition = selection.active;
this.vimState.cursorStartPosition = selection.anchor;
this.updateView({ drawSelection: false, revealRange: false });
// Store selection for commands like gv
this.vimState.lastVisualSelection = {
mode: this.vimState.currentMode,
start: this.vimState.cursorStartPosition,
end: this.vimState.cursorStopPosition,
};
return;
} else if (!selection.active.isEqual(selection.anchor)) {
Logger.trace('Creating Visual Selection from command!');
this.vimState.cursorStopPosition = selection.active;
this.vimState.cursorStartPosition = selection.anchor;
await this.setCurrentMode(Mode.Visual);
this.updateView({ drawSelection: false, revealRange: false });
// Store selection for commands like gv
this.vimState.lastVisualSelection = {
mode: Mode.Visual,
start: this.vimState.cursorStartPosition,
end: this.vimState.cursorStopPosition,
};
return;
}
}
}
// Here we are on the selection changed of kind 'Keyboard' or 'undefined' which is triggered
// when pressing movement keys that are not caught on the 'type' override but also when using
// commands like 'cursorMove'.
if (isVisualMode(this.vimState.currentMode)) {
/**
* In Visual Mode, our `cursorPosition` and `cursorStartPosition` can not reflect `active`,
* `start`, `end` and `anchor` information in a selection.
* See `Fake block cursor with text decoration` section of `updateView` method.
* Besides this, sometimes on visual modes our start position is not the same has vscode
* anchor because we need to move vscode anchor one to the right of our start when our start
* is after our stop in order to include the start character on vscodes selection.
*/
return;
}
const cursorEnd = laterOf(
this.vimState.cursorStartPosition,
this.vimState.cursorStopPosition,
);
if (e.textEditor.document.validatePosition(cursorEnd).isBefore(cursorEnd)) {
// The document changed such that our cursor position is now out of bounds, possibly by
// another program. Let's just use VSCode's selection.
// TODO: if this is the case, but we're in visual mode, we never get here (because of branch above)
} else if (
e.kind === vscode.TextEditorSelectionChangeKind.Keyboard &&
this.vimState.cursorStopPosition.isEqual(this.vimState.cursorStartPosition) &&
this.vimState.cursorStopPosition.getRight().isLineEnd() &&
this.vimState.cursorStopPosition.getLineEnd().isEqual(selection.active)
) {
// We get here when we use a 'cursorMove' command (that is considered a selection changed
// kind of 'Keyboard') that ends past the line break. But our cursors are already on last
// character which is what we want. Even though our cursors will be corrected again when
// checking if they are in bounds on 'runAction' there is no need to be changing them back
// and forth so we check for this situation here.
return;
}
// Here we allow other 'cursorMove' commands to update our cursors in case there is another
// extension making cursor changes that we need to catch.
//
// We still need to be careful with this because this here might be changing our cursors
// in ways we don't want to. So with future selection issues this is a good place to start
// looking.
Logger.debug(
`Selections: Changing Cursors from selection handler... ${selection.anchor.toString()}, ${
selection.active
}`,
);
this.vimState.cursorStopPosition = selection.active;
this.vimState.cursorStartPosition = selection.anchor;
this.vimState.desiredColumn = selection.active.character;
this.updateView({ drawSelection: false, revealRange: false });
}
return;
}
if (isStatusBarMode(this.vimState.currentMode)) {
return;
}
let toDraw = false;
if (selection) {
let newPosition = selection.active;
// Only check on a click, not a full selection (to prevent clicking past EOL)
if (newPosition.character >= newPosition.getLineEnd().character && selection.isEmpty) {
if (this.vimState.currentMode !== Mode.Insert) {
this.lastClickWasPastEol = true;
// This prevents you from mouse clicking past the EOL
newPosition = newPosition.withColumn(Math.max(newPosition.getLineEnd().character - 1, 0));
// Switch back to normal mode since it was a click not a selection
await this.setCurrentMode(Mode.Normal);
toDraw = true;
}
} else if (selection.isEmpty) {
this.lastClickWasPastEol = false;
}
this.vimState.cursorStopPosition = newPosition;
this.vimState.cursorStartPosition = newPosition;
this.vimState.desiredColumn = newPosition.character;
// start visual mode?
if (
selection.anchor.line === selection.active.line &&
selection.anchor.character >= newPosition.getLineEnd().character &&
selection.active.character >= newPosition.getLineEnd().character
) {
// This prevents you from selecting EOL
} else if (!selection.anchor.isEqual(selection.active)) {
let selectionStart = new Position(selection.anchor.line, selection.anchor.character);
if (selectionStart.character > selectionStart.getLineEnd().character) {
selectionStart = new Position(selectionStart.line, selectionStart.getLineEnd().character);
}
this.vimState.cursorStartPosition = selectionStart;
if (selectionStart.isAfter(newPosition)) {
this.vimState.cursorStartPosition = this.vimState.cursorStartPosition.getLeft();
}
// If we prevented from clicking past eol but it is part of this selection, include the last char
if (this.lastClickWasPastEol) {
const newStart = new Position(selection.anchor.line, selection.anchor.character + 1);
this.vimState.editor.selection = new vscode.Selection(newStart, selection.active);
this.vimState.cursorStartPosition = selectionStart;
this.lastClickWasPastEol = false;
}
if (
configuration.mouseSelectionGoesIntoVisualMode &&
!isVisualMode(this.vimState.currentMode) &&
this.currentMode !== Mode.Insert
) {
await this.setCurrentMode(Mode.Visual);
// double click mouse selection causes an extra character to be selected so take one less character
}
} else if (this.vimState.currentMode !== Mode.Insert) {
await this.setCurrentMode(Mode.Normal);
}
if (isVisualMode(this.vimState.currentMode)) {
// Store selection for commands like gv
this.vimState.lastVisualSelection = {
mode: this.vimState.currentMode,
start: this.vimState.cursorStartPosition,
end: this.vimState.cursorStopPosition,
};
}
void this.updateView({ drawSelection: toDraw, revealRange: false });
}
}
async handleMultipleKeyEvents(keys: string[], alreadyRemapped: boolean = true): Promise<void> {
for (const key of keys) {
await (alreadyRemapped ? this.handleKeyEventLangmapped(key) : this.handleKeyEvent(key));
}
}
public async handleKeyEvent(keyRaw: string): Promise<void> {
const key =
isLiteralMode(this.currentMode) || this.vimState.isReplayingMacro ? keyRaw : remapKey(keyRaw);
return this.handleKeyEventLangmapped(key);
}
private async handleKeyEventLangmapped(key: string): Promise<void> {
if (this.remapState.forceStopRecursiveRemapping) {
return;
}
const now = Date.now();
const printableKey = Notation.printableKey(key, configuration.leader);
Logger.debug(`Handling key: ${printableKey}`);
if (
(key === SpecialKeys.TimeoutFinished ||
this.vimState.recordedState.bufferedKeys.length > 0) &&
this.vimState.recordedState.bufferedKeysTimeoutObj
) {
// Handle the bufferedKeys or append the new key to the previously bufferedKeys
clearTimeout(this.vimState.recordedState.bufferedKeysTimeoutObj);
this.vimState.recordedState.bufferedKeysTimeoutObj = undefined;
this.vimState.recordedState.commandList = [...this.vimState.recordedState.bufferedKeys];
this.vimState.recordedState.bufferedKeys = [];
}
// rewrite copy
if (configuration.overrideCopy) {
// The conditions when you trigger a "copy" rather than a ctrl-c are
// too sophisticated to be covered by the "when" condition in package.json
if (key === '<D-c>') {
key = '<copy>';
}
if (key === '<C-c>' && process.platform !== 'darwin') {
if (
!configuration.useCtrlKeys ||
this.vimState.currentMode === Mode.Visual ||
this.vimState.currentMode === Mode.VisualBlock ||
this.vimState.currentMode === Mode.VisualLine
) {
key = '<copy>';
}
}
}
// <C-d> triggers "add selection to next find match" by default,
// unless users explicity make <C-d>: true
// TODO: Destroy this silliness
if (key === '<C-d>' && !(configuration.handleKeys['<C-d>'] === true)) {
key = '<D-d>';
}
this.vimState.cursorsInitialState = this.vimState.cursors;
this.vimState.recordedState.commandList.push(key);
const oldMode = this.vimState.currentMode;
const oldFullMode = this.vimState.currentModeIncludingPseudoModes;
const oldStatusBarText = StatusBar.getText();
const oldWaitingForAnotherActionKey = this.vimState.recordedState.waitingForAnotherActionKey;
let handledAsRemap = false;
let handledAsAction = false;
try {
// Handling special case for '0'. From Vim documentation (:help :map-modes)
// Special case: While typing a count for a command in Normal mode, mapping zero
// is disabled. This makes it possible to map zero without making it impossible
// to type a count with a zero.
const preventZeroRemap =
key === '0' &&
this.vimState.recordedState.actionsRun[
this.vimState.recordedState.actionsRun.length - 1
] instanceof CommandNumber;
// Check for remapped keys if:
// 1. We are not currently performing a non-recursive remapping
// 2. We are not typing '0' after starting to type a count
// 3. We are not waiting for another action key
// Example: jj should not remap the second 'j', if jj -> <Esc> in insert mode
// 0 should not be remapped if typed after another number, like 10
// for actions with multiple keys like 'gg' or 'fx' the second character
// shouldn't be mapped
if (
!this.remapState.isCurrentlyPerformingNonRecursiveRemapping &&
!preventZeroRemap &&
!this.vimState.recordedState.waitingForAnotherActionKey
) {
handledAsRemap = await this.remappers.sendKey(
this.vimState.recordedState.commandList,
this,
);
}
this.vimState.recordedState.allowPotentialRemapOnFirstKey = true;
if (!handledAsRemap) {
if (key === SpecialKeys.TimeoutFinished) {
// Remove the <TimeoutFinished> key and get the key before that. If the <TimeoutFinished>
// key was the last key, then 'key' will be undefined and won't be sent to handle action.
this.vimState.recordedState.commandList.pop();
key =
this.vimState.recordedState.commandList[
this.vimState.recordedState.commandList.length - 1
];
}
if (key !== undefined) {
handledAsAction = await this.handleKeyAsAnAction(key);
}
}
} catch (e) {
this.selectionsChanged.ignoreIntermediateSelections = false;
if (e instanceof VimError) {
StatusBar.displayError(this.vimState, e);
this.vimState.recordedState = new RecordedState();
if (this.remapState.isCurrentlyPerformingRemapping) {
// If we are handling a remap and we got a VimError stop handling the remap
// and discard the rest of the keys. We throw an Exception here to stop any other
// remapping handling steps and go straight to the 'finally' step of the remapper.
throw ForceStopRemappingError.fromVimError(e);
}
} else if (e instanceof ForceStopRemappingError) {
// If this is a ForceStopRemappingError rethrow it until it gets to the remapper
throw e;
} else if (e instanceof Error) {
e.message = `Failed to handle key \`${key}\`: ${e.message}`;
throw e;
} else {
throw new Error(`Failed to handle key \`${key}\` due to an unknown error.`);
}
}
this.remapState.lastKeyPressedTimestamp = now;
StatusBar.updateShowCmd(this.vimState);
// We don't want to immediately erase any message that resulted from the action just performed
if (StatusBar.getText() === oldStatusBarText) {
// Clear the status bar of high priority messages if the mode has changed, the view has scrolled
// or it is recording a Macro
const forceClearStatusBar =
(this.vimState.currentMode !== oldMode && this.vimState.currentMode !== Mode.Normal) ||
this.vimState.macro !== undefined;
StatusBar.clear(this.vimState, forceClearStatusBar);
}
// We either already ran an action or we have a potential action to run but
// the key is already stored on 'actionKeys' in that case we don't need it
// anymore on commandList that is only used for the remapper and 'showCmd'
// and both had already been handled at this point.
// If we got here it means that there is no potential remap for the key
// either so we need to clear it from commandList so that it doesn't interfere
// with the next remapper check.
this.vimState.recordedState.resetCommandList();
Logger.trace(`handleKeyEvent('${printableKey}') took ${Date.now() - now}ms`);
// If we are handling a remap and the last movement failed stop handling the remap
// and discard the rest of the keys. We throw an Exception here to stop any other
// remapping handling steps and go straight to the 'finally' step of the remapper.
if (this.remapState.isCurrentlyPerformingRemapping && this.lastMovementFailed) {
this.lastMovementFailed = false;
throw new ForceStopRemappingError('Last movement failed');
}
// Reset lastMovementFailed. Anyone who needed it has probably already handled it.
// And keeping it past this point would make any following remapping force stop.
this.lastMovementFailed = false;
if (!handledAsAction) {
// There was no action run yet but we still want to update the view to be able
// to show the potential remapping keys being pressed, the `"` character when
// waiting on a register key or the `?` character and any following character
// when waiting on digraph keys. The 'oldWaitingForAnotherActionKey' is used
// to call the updateView after we are no longer waiting keys so that any
// existing overlapped key is removed.
if (
((this.vimState.currentMode === Mode.Insert ||
this.vimState.currentMode === Mode.Replace) &&
(this.vimState.recordedState.bufferedKeys.length > 0 ||
this.vimState.recordedState.waitingForAnotherActionKey ||
this.vimState.recordedState.waitingForAnotherActionKey !==
oldWaitingForAnotherActionKey)) ||
this.vimState.currentModeIncludingPseudoModes !== oldFullMode
) {
// TODO: this call to updateView is only used to update the virtualCharacter and halfBlock
// cursor decorations, if in the future we split up the updateView function there should
// be no need to call all of it.
this.updateView({ drawSelection: false, revealRange: false });
}
}
}
private async handleKeyAsAnAction(key: string): Promise<boolean> {
if (vscode.window.activeTextEditor !== this.vimState.editor) {
Logger.warn('Current window is not active');
return false;
}
// Catch any text change not triggered by us (example: tab completion).
this.vimState.historyTracker.addChange();
const recordedState = this.vimState.recordedState;
recordedState.actionKeys.push(key);
void VSCodeContext.set('vim.command', recordedState.commandString);
const action = getRelevantAction(recordedState.actionKeys, this.vimState);
switch (action) {
case KeypressState.NoPossibleMatch:
if (this.vimState.currentMode === Mode.Insert) {
this.vimState.recordedState.actionKeys = [];
} else {
this.vimState.recordedState = new RecordedState();
}
// Since there is no possible action we are no longer waiting any action keys
this.vimState.recordedState.waitingForAnotherActionKey = false;
void VSCodeContext.set('vim.command', '');
return false;
case KeypressState.WaitingOnKeys:
this.vimState.recordedState.waitingForAnotherActionKey = true;
return false;
}
if (
!this.remapState.remapUsedACharacter &&
this.remapState.isCurrentlyPerformingRecursiveRemapping
) {
// Used a character inside a recursive remapping so we reset the mapDepth.
this.remapState.remapUsedACharacter = true;
this.remapState.mapDepth = 0;
}
// Since we got an action we are no longer waiting any action keys
this.vimState.recordedState.waitingForAnotherActionKey = false;
// Store action pressed keys for showCmd
recordedState.actionsRunPressedKeys.push(...recordedState.actionKeys);
let actionToRecord: BaseAction | undefined = action;
if (recordedState.actionsRun.length === 0) {
recordedState.actionsRun.push(action);
} else {
const lastAction = recordedState.actionsRun[recordedState.actionsRun.length - 1];
const actionCanBeMergedWithDocumentChange =
action instanceof CommandInsertInInsertMode ||
action instanceof CommandBackspaceInInsertMode ||
action instanceof CommandInsertPreviousText ||
action instanceof InsertCharAbove ||
action instanceof InsertCharBelow;
if (lastAction instanceof DocumentContentChangeAction) {
if (!(action instanceof CommandEscInsertMode)) {
// TODO: this includes things like <BS>, which it shouldn't
lastAction.keysPressed.push(key);
}
if (actionCanBeMergedWithDocumentChange) {
// delay the macro recording
actionToRecord = undefined;
} else {
// Push document content change to the stack
lastAction.addChanges(
this.vimState.historyTracker.currentContentChanges,
this.vimState.cursorStopPosition,
);
this.vimState.historyTracker.currentContentChanges = [];
recordedState.actionsRun.push(action);
}
} else {
if (actionCanBeMergedWithDocumentChange) {
// This means we are already in Insert Mode but there is still not DocumentContentChangeAction in stack
this.vimState.historyTracker.currentContentChanges = [];
const newContentChange = new DocumentContentChangeAction(
this.vimState.cursorStopPosition,
);
newContentChange.keysPressed.push(key);
recordedState.actionsRun.push(newContentChange);
actionToRecord = newContentChange;
} else {
recordedState.actionsRun.push(action);
}
}
}
if (
this.vimState.macro !== undefined &&
actionToRecord &&
!(actionToRecord instanceof CommandQuitRecordMacro)
) {
this.vimState.macro.actionsRun.push(actionToRecord);
}
await this.runAction(recordedState, action);
if (this.vimState.currentMode === Mode.Insert) {
recordedState.isInsertion = true;
}
// Update view
this.updateView();
if (action.isJump) {
globalState.jumpTracker.recordJump(
Jump.fromStateBefore(this.vimState),
Jump.fromStateNow(this.vimState),
);
}
return true;
}
private async runAction(recordedState: RecordedState, action: IBaseAction): Promise<void> {
this.selectionsChanged.ignoreIntermediateSelections = true;
// We handle the end of selections different to VSCode. In order for VSCode to select
// including the last character we will at the end of 'runAction' shift our stop position
// to the right. So here we shift it back by one so that our actions have our correct
// position instead of the position sent to VSCode.
if (this.vimState.currentMode === Mode.Visual) {
this.vimState.cursors = this.vimState.cursors.map((c) =>
c.start.isBefore(c.stop) ? c.withNewStop(c.stop.getLeftThroughLineBreaks(true)) : c,
);
}
// Make sure all cursors are within the document's bounds before running any action
// It's not 100% clear to me that this is the correct place to do this, but it should solve a lot of issues
this.vimState.cursors = this.vimState.cursors.map(
(c) =>
new Cursor(
this.vimState.document.validatePosition(c.start),
this.vimState.document.validatePosition(c.stop),
),
);
let ranRepeatableAction = false;
let ranAction = false;
if (action instanceof BaseMovement) {
recordedState = await this.executeMovement(action);
ranAction = true;
} else if (action instanceof BaseCommand) {
await action.execCount(this.vimState.cursorStopPosition, this.vimState);
const transformer = this.vimState.recordedState.transformer;
await executeTransformations(this, transformer.transformations);
if (action.isCompleteAction) {
ranAction = true;
}
if (action.createsUndoPoint) {
ranRepeatableAction = true;
}
if (this.vimState.normalCommandState === NormalCommandState.Finished) {
ranRepeatableAction = true;
}
} else if (action instanceof BaseOperator) {
recordedState.operatorCount = recordedState.count;
} else {
throw new Error('Unknown action type');
}
// Update mode (note the ordering allows you to go into search mode,
// then return and have the motion immediately applied to an operator).
const prevMode = this.currentMode;
if (this.vimState.currentMode !== this.currentMode) {
await this.setCurrentMode(this.vimState.currentMode);
// We don't want to mark any searches as a repeatable action
if (
this.vimState.currentMode === Mode.Normal &&
prevMode !== Mode.SearchInProgressMode &&
prevMode !== Mode.EasyMotionInputMode &&
prevMode !== Mode.EasyMotionMode &&
!(
prevMode === Mode.CommandlineInProgress &&
this.vimState.normalCommandState === NormalCommandState.Executing
)
) {
ranRepeatableAction = true;
}
}
// If there's an operator pending and we have a motion or visual selection, run the operator
if (recordedState.getOperatorState(this.vimState.currentMode) === 'ready') {
const operator = this.vimState.recordedState.operator;
if (operator) {
await this.executeOperator();
this.vimState.recordedState.hasRunOperator = true;
ranRepeatableAction = operator.createsUndoPoint;
ranAction = true;
}
}
// And then we have to do it again because an operator could
// have changed it as well. (TODO: do you even decomposition bro)
if (this.vimState.currentMode !== this.currentMode) {
await this.setCurrentMode(this.vimState.currentMode);
if (this.vimState.currentMode === Mode.Normal) {
ranRepeatableAction = true;
}
}
ranRepeatableAction =
(ranRepeatableAction && this.vimState.currentMode === Mode.Normal) ||
this.createUndoPointForBrackets();
// We don't want to record a repeatable action when exiting from these modes
// by pressing <Esc>
if (
(prevMode === Mode.Visual ||
prevMode === Mode.VisualBlock ||
prevMode === Mode.VisualLine ||
prevMode === Mode.CommandlineInProgress) &&
action.keysPressed[0] === '<Esc>'
) {
ranRepeatableAction = false;
}
// Record down previous action and flush temporary state
if (
ranRepeatableAction &&
this.vimState.lastCommandDotRepeatable &&
this.vimState.dotCommandStatus !== DotCommandStatus.Finished
) {
globalState.previousFullAction = _.cloneDeep(this.vimState.recordedState);
if (recordedState.isInsertion) {
Register.setReadonlyRegister('.', recordedState);
}
}
this.vimState.lastCommandDotRepeatable = true;
// Update desiredColumn
const preservesDesiredColumn =
action instanceof BaseOperator && !ranAction ? true : action.preservesDesiredColumn;
if (!preservesDesiredColumn) {
if (action instanceof BaseMovement) {
// We check !operator here because e.g. d$ should NOT set the desired column to EOL.
if (action.setsDesiredColumnToEOL && !recordedState.operator) {
this.vimState.desiredColumn = Number.POSITIVE_INFINITY;
} else {
this.vimState.desiredColumn = this.vimState.cursorStopPosition.character;
}
} else if (this.vimState.currentMode !== Mode.VisualBlock) {
// TODO: explain why not VisualBlock
this.vimState.desiredColumn = this.vimState.cursorStopPosition.character;
}
}
// Like previously stated we handle the end of selections different to VSCode. In order
// for VSCode to select including the last character we shift our stop position to the
// right now that all steps that need that position have already run. On the next action
// we will shift it back again on the start of 'runAction'.
if (this.vimState.currentMode === Mode.Visual) {
this.vimState.cursors = this.vimState.cursors.map((c) =>
c.start.isBeforeOrEqual(c.stop)
? c.withNewStop(
c.stop.isLineEnd() ? c.stop.getRightThroughLineBreaks() : c.stop.getRight(),
)
: c,
);
}
// We've run a complete action sequence - wipe the slate clean with a new RecordedState
if (
ranAction &&
this.vimState.currentMode === Mode.Normal &&
this.vimState.dotCommandStatus !== DotCommandStatus.Executing
) {
this.vimState.recordedState = new RecordedState();
// Return to insert mode after 1 command in this case for <C-o>
if (this.vimState.returnToInsertAfterCommand) {
if (this.vimState.actionCount > 0) {
await this.setCurrentMode(Mode.Insert);
} else {
this.vimState.actionCount++;
}
}
}
if (this.vimState.dotCommandStatus === DotCommandStatus.Finished) {
this.vimState.dotCommandStatus = DotCommandStatus.Waiting;
}
// track undo history
if (!this.focusChanged) {
// important to ensure that focus didn't change, otherwise
// we'll grab the text of the incorrect active window and assume the
// whole document changed!
this.vimState.historyTracker.addChange();
}
// Don't record an undo point for every action of a macro, only at the very end
if (
ranRepeatableAction &&
!this.vimState.isReplayingMacro &&
this.vimState.normalCommandState !== NormalCommandState.Executing &&
this.vimState.dotCommandStatus !== DotCommandStatus.Executing &&
!this.remapState.isCurrentlyPerformingRemapping
) {
this.vimState.historyTracker.finishCurrentStep();
}
if (this.vimState.normalCommandState === NormalCommandState.Finished) {
this.vimState.normalCommandState = NormalCommandState.Waiting;
}
recordedState.actionKeys = [];
this.vimState.currentRegisterMode = undefined;
// If we're in Normal mode, collapse each cursor down to one character
if (this.currentMode === Mode.Normal) {
this.vimState.cursors = this.vimState.cursors.map(
(cursor) => new Cursor(cursor.stop, cursor.stop),
);
}
// Ensure cursors are within bounds
if (
!this.vimState.document.isClosed &&
this.vimState.editor === vscode.window.activeTextEditor
) {
const documentEndPosition = TextEditor.getDocumentEnd(this.vimState.document);
const documentLineCount = this.vimState.document.lineCount;
this.vimState.cursors = this.vimState.cursors.map((cursor: Cursor) => {
// Adjust start/stop
if (cursor.start.line >= documentLineCount) {
cursor = cursor.withNewStart(documentEndPosition);
}
if (cursor.stop.line >= documentLineCount) {
cursor = cursor.withNewStop(documentEndPosition);
}
// Adjust column. When getting from insert into normal mode with <C-o>,
// the cursor position should remain even if it is behind the last
// character in the line
if (
!this.vimState.returnToInsertAfterCommand &&
(this.vimState.currentMode === Mode.Normal || isVisualMode(this.vimState.currentMode))
) {
const currentLineLength = TextEditor.getLineLength(cursor.stop.line);
const currentStartLineLength = TextEditor.getLineLength(cursor.start.line);
// When in visual mode you can move the cursor past the last character in order
// to select that character. We use this offset to allow for that, otherwise
// we would consider the position invalid and change it to the left of the last