-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathmodeHandler.ts
1645 lines (1418 loc) · 62.1 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 * as vscode from 'vscode';
import { Actions, BaseAction, KeypressState } from './../actions/base';
import { BaseMovement } from '../actions/baseMotion';
import { CommandInsertInInsertMode, CommandInsertPreviousText } from './../actions/commands/insert';
import { Jump } from '../jumps/jump';
import { Logger } from '../util/logger';
import { Mode, VSCodeVimCursorType, isVisualMode, getCursorStyle, isStatusBarMode } from './mode';
import { PairMatcher } from './../common/matching/matcher';
import { Position, PositionDiff } from './../common/motion/position';
import { Range } from './../common/motion/range';
import { RecordedState } from './../state/recordedState';
import { Register, RegisterMode } from './../register/register';
import { Remappers } from '../configuration/remapper';
import { StatusBar } from '../statusBar';
import { TextEditor } from './../textEditor';
import { VimError, ErrorCode } from './../error';
import { VimState } from './../state/vimState';
import { VsCodeContext } from '../util/vscode-context';
import { commandLine } from '../cmd_line/commandLine';
import { configuration } from '../configuration/configuration';
import { decoration } from '../configuration/decoration';
import { scrollView } from '../util/util';
import {
BaseCommand,
CommandQuitRecordMacro,
DocumentContentChangeAction,
ActionOverrideCmdD,
CommandRegister,
CommandVisualMode,
} from './../actions/commands/actions';
import {
areAnyTransformationsOverlapping,
isTextTransformation,
TextTransformations,
areAllSameTransformation,
isMultiCursorTextTransformation,
InsertTextVSCodeTransformation,
} from './../transformations/transformations';
import { globalState } from '../state/globalState';
import { reportSearch } from '../util/statusBarTextUtils';
import { Notation } from '../configuration/notation';
import { ModeHandlerMap } from './modeHandlerMap';
import { EditorIdentity } from '../editorIdentity';
import { BaseOperator } from '../actions/operator';
/**
* 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 {
private _disposables: vscode.Disposable[] = [];
private _remappers: Remappers;
private readonly _logger = Logger.get('ModeHandler');
// TODO: clarify the difference between ModeHandler.currentMode and VimState.currentMode
private _currentMode: Mode;
public vimState: VimState;
get currentMode(): Mode {
return this._currentMode;
}
private async setCurrentMode(modeName: Mode): Promise<void> {
await this.vimState.setCurrentMode(modeName);
this._currentMode = modeName;
}
public static async create(textEditor = vscode.window.activeTextEditor!): Promise<ModeHandler> {
const modeHandler = new ModeHandler(textEditor);
await modeHandler.vimState.load();
await modeHandler.setCurrentMode(configuration.startInInsertMode ? Mode.Insert : Mode.Normal);
modeHandler.syncCursors();
return modeHandler;
}
private constructor(textEditor: vscode.TextEditor) {
this._remappers = new Remappers();
this.vimState = new VimState(textEditor);
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
setImmediate(() => {
if (this.vimState.editor) {
const { selections } = this.vimState.editor;
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 Range(
Position.FromVSCodePosition(anchor).getLeft(),
Position.FromVSCodePosition(active)
)
: new Range(Position.FromVSCodePosition(anchor), Position.FromVSCodePosition(active))
);
}
}, 0);
}
/**
* 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;
}
let selection = e.selections[0];
this._logger.debug(
`Selections: Handling Selection Change! Selection: ${Position.FromVSCodePosition(
selection.anchor
).toString()}, ${Position.FromVSCodePosition(selection.active)}, SelectionsLength: ${
e.selections.length
}`
);
if (
(e.selections.length !== this.vimState.cursors.length || this.vimState.isMultiCursor) &&
this.vimState.currentMode !== Mode.VisualBlock
) {
// Number of selections changed, make sure we know about all of them still
this.vimState.cursors = e.textEditor.selections.map(
(sel) =>
new Range(
// Adjust the cursor positions because cursors & selections don't match exactly
sel.anchor.isAfter(sel.active)
? Position.FromVSCodePosition(sel.anchor).getLeft()
: Position.FromVSCodePosition(sel.anchor),
Position.FromVSCodePosition(sel.active)
)
);
if (
e.textEditor.selections.some((s) => !s.anchor.isEqual(s.active)) &&
[Mode.Normal, Mode.Insert, Mode.Replace].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.
this._logger.debug('Selections: Creating Multi Cursor Visual Selection!');
if (e.kind === vscode.TextEditorSelectionChangeKind.Keyboard) {
this.vimState.cursors = e.textEditor.selections.map(
(sel) =>
new Range(
Position.FromVSCodePosition(sel.anchor),
sel.anchor.isBefore(sel.active)
? // This is another case where we are changing our cursor so that the selection looks right
Position.FromVSCodePosition(sel.active).getRight()
: Position.FromVSCodePosition(sel.active)
)
);
}
await this.setCurrentMode(Mode.Visual);
// Here we need our updateView to draw the selection because we want vscode to include the initial
// character, and by doing it through out updateView we make sure that any resultant selection
// change event will be ignored.
await this.updateView(this.vimState);
return;
}
return this.updateView(this.vimState);
}
/**
* 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 (
[Mode.Normal, Mode.Visual, Mode.Insert, Mode.Replace].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) {
this._logger.debug('Selections: Updating Visual Selection!');
const active = Position.FromVSCodePosition(selection.active);
const anchor = Position.FromVSCodePosition(selection.anchor);
this.vimState.cursorStopPosition = active;
this.vimState.cursorStartPosition = anchor;
if (e.kind === vscode.TextEditorSelectionChangeKind.Keyboard) {
if (selection.anchor.isAfter(selection.active)) {
this.vimState.cursorStartPosition = anchor.getLeft();
}
}
await this.updateView(this.vimState, { drawSelection: false, revealRange: false });
return;
} else if (!selection.active.isEqual(selection.anchor)) {
this._logger.debug('Selections: Creating Visual Selection from command!');
const active = Position.FromVSCodePosition(selection.active);
const anchor = Position.FromVSCodePosition(selection.anchor);
this.vimState.cursorStopPosition = active;
this.vimState.cursorStartPosition = anchor;
if (e.kind === vscode.TextEditorSelectionChangeKind.Keyboard) {
if (selection.anchor.isBefore(selection.active)) {
// This is another case where we are changing our cursor so that the selection looks right
this.vimState.cursorStopPosition = active.getRight();
}
}
await this.setCurrentMode(Mode.Visual);
// Here we need our updateView to draw the selection because we want vscode to include the initial
// character, and by doing it through out updateView we make sure that any resultant selection
// change event will be ignored.
await this.updateView(this.vimState);
return;
}
}
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;
}
// 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.
if (
this.vimState.cursorStopPosition.isEqual(this.vimState.cursorStartPosition) &&
this.vimState.cursorStopPosition.getRight().isLineEnd() &&
this.vimState.cursorStopPosition.getLineEnd().isEqual(selection.active)
) {
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.
this._logger.debug(
`Selections: Changing Cursors from selection handler... ${Position.FromVSCodePosition(
selection.anchor
).toString()}, ${Position.FromVSCodePosition(selection.active)}`
);
this.vimState.cursorStopPosition = Position.FromVSCodePosition(selection.active);
this.vimState.cursorStartPosition = Position.FromVSCodePosition(selection.anchor);
await this.updateView(this.vimState, { drawSelection: false, revealRange: false });
}
return;
}
if (e.selections.length === 1) {
this.vimState.isMultiCursor = false;
}
if (isStatusBarMode(this.vimState.currentMode)) {
return;
}
let toDraw = false;
if (selection) {
let newPosition = Position.FromVSCodePosition(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.vimState.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.vimState.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 - 1 &&
selection.active.character >= newPosition.getLineEnd().character - 1
) {
// 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.vimState.lastClickWasPastEol) {
const newStart = new Position(selection.anchor.line, selection.anchor.character + 1);
this.vimState.editor.selection = new vscode.Selection(newStart, selection.end);
this.vimState.cursorStartPosition = selectionStart;
this.vimState.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);
}
return this.updateView(this.vimState, { drawSelection: toDraw, revealRange: false });
}
}
async handleMultipleKeyEvents(keys: string[]): Promise<void> {
for (const key of keys) {
await this.handleKeyEvent(key);
}
}
public async handleKeyEvent(key: string): Promise<void> {
const now = Number(new Date());
const printableKey = Notation.printableKey(key);
this._logger.debug(`handling key=${printableKey}.`);
// 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
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 oldVisibleRange = this.vimState.editor.visibleRanges[0];
const oldStatusBarText = StatusBar.getText();
try {
const isWithinTimeout = now - this.vimState.lastKeyPressedTimestamp < configuration.timeout;
if (!isWithinTimeout) {
// sufficient time has elapsed since the prior keypress,
// only consider the last keypress for remapping
this.vimState.recordedState.commandList = [
this.vimState.recordedState.commandList[
this.vimState.recordedState.commandList.length - 1
],
];
}
let handled = false;
const isOperatorCombination = this.vimState.recordedState.operator;
// Check for remapped keys if:
// 1. We are not currently performing a non-recursive remapping
// 2. We are not in normal mode performing on an operator
// Example: ciwjj should be remapped if jj -> <Esc> in insert mode
// dd should not remap the second "d", if d -> "_d in normal mode
if (
!this.vimState.isCurrentlyPerformingRemapping &&
(!isOperatorCombination || this.vimState.currentMode !== Mode.Normal)
) {
handled = await this._remappers.sendKey(
this.vimState.recordedState.commandList,
this,
this.vimState
);
}
if (handled) {
this.vimState.recordedState.resetCommandList();
} else {
this.vimState = await this.handleKeyEventHelper(key, this.vimState);
}
} catch (e) {
this.vimState.selectionsChanged.ignoreIntermediateSelections = false;
if (e instanceof VimError) {
StatusBar.displayError(this.vimState, e);
} else {
throw new Error(`Failed to handle key=${key}. ${e.message}`);
}
}
this.vimState.lastKeyPressedTimestamp = now;
// 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.editor.visibleRanges[0] !== oldVisibleRange ||
this.vimState.isRecordingMacro;
StatusBar.clear(this.vimState, forceClearStatusBar);
}
this._logger.debug(`handleKeyEvent('${printableKey}') took ${Number(new Date()) - now}ms`);
}
private async handleKeyEventHelper(key: string, vimState: VimState): Promise<VimState> {
if (vscode.window.activeTextEditor !== this.vimState.editor) {
this._logger.warn('Current window is not active');
return this.vimState;
}
// Catch any text change not triggered by us (example: tab completion).
vimState.historyTracker.addChange(this.vimState.cursorsInitialState.map((c) => c.stop));
vimState.keyHistory.push(key);
let recordedState = vimState.recordedState;
recordedState.actionKeys.push(key);
let result = Actions.getRelevantAction(recordedState.actionKeys, vimState);
switch (result) {
case KeypressState.NoPossibleMatch:
if (!this._remappers.isPotentialRemap) {
vimState.recordedState = new RecordedState();
}
StatusBar.updateShowCmd(this.vimState);
return vimState;
case KeypressState.WaitingOnKeys:
StatusBar.updateShowCmd(this.vimState);
return vimState;
}
let action = result as BaseAction;
let actionToRecord: BaseAction | undefined = action;
if (recordedState.actionsRun.length === 0) {
recordedState.actionsRun.push(action);
} else {
let lastAction = recordedState.actionsRun[recordedState.actionsRun.length - 1];
if (lastAction instanceof DocumentContentChangeAction) {
lastAction.keysPressed.push(key);
if (
action instanceof CommandInsertInInsertMode ||
action instanceof CommandInsertPreviousText
) {
// delay the macro recording
actionToRecord = undefined;
} else {
// Push document content change to the stack
lastAction.addChanges(vimState.historyTracker.currentContentChanges);
vimState.historyTracker.currentContentChanges = [];
recordedState.actionsRun.push(action);
}
} else {
if (
action instanceof CommandInsertInInsertMode ||
action instanceof CommandInsertPreviousText
) {
// This means we are already in Insert Mode but there is still not DocumentContentChangeAction in stack
vimState.historyTracker.currentContentChanges = [];
let newContentChange = new DocumentContentChangeAction();
newContentChange.keysPressed.push(key);
recordedState.actionsRun.push(newContentChange);
actionToRecord = newContentChange;
} else {
recordedState.actionsRun.push(action);
}
}
}
if (
vimState.isRecordingMacro &&
actionToRecord &&
!(actionToRecord instanceof CommandQuitRecordMacro)
) {
vimState.recordedMacro.actionsRun.push(actionToRecord);
}
vimState = await this.runAction(vimState, recordedState, action);
if (vimState.currentMode === Mode.Insert) {
recordedState.isInsertion = true;
}
// Update view
await this.updateView(vimState);
if (action.isJump) {
globalState.jumpTracker.recordJump(
Jump.fromStateBefore(vimState),
Jump.fromStateNow(vimState)
);
}
if (!this._remappers.isPotentialRemap && recordedState.isInsertion) {
vimState.recordedState.resetCommandList();
}
return vimState;
}
private async runAction(
vimState: VimState,
recordedState: RecordedState,
action: BaseAction
): Promise<VimState> {
let ranRepeatableAction = false;
let ranAction = false;
vimState.selectionsChanged.ignoreIntermediateSelections = true;
// If arrow keys or mouse was used prior to entering characters while in insert mode, create an undo point
// this needs to happen before any changes are made
/*
TODO: This causes . to crash vscodevim for some reason.
if (!vimState.isMultiCursor) {
let prevPos = vimState.historyTracker.getLastHistoryEndPosition();
if (prevPos !== undefined && !vimState.isRunningDotCommand) {
if (vimState.cursorPositionJustBeforeAnythingHappened[0].line !== prevPos[0].line ||
vimState.cursorPositionJustBeforeAnythingHappened[0].character !== prevPos[0].character) {
globalState.previousFullAction = recordedState;
vimState.historyTracker.finishCurrentStep();
}
}
}
*/
// 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 (vimState.currentMode === Mode.Visual) {
vimState.cursors = vimState.cursors.map((c) =>
c.start.isBefore(c.stop) ? c.withNewStop(c.stop.getLeftThroughLineBreaks(true)) : c
);
}
if (action instanceof BaseMovement) {
({ vimState, recordedState } = await this.executeMovement(vimState, action));
ranAction = true;
}
if (action instanceof BaseCommand) {
vimState = await action.execCount(vimState.cursorStopPosition, vimState);
vimState = await this.executeCommand(vimState);
if (action.isCompleteAction) {
ranAction = true;
}
if (action.canBeRepeatedWithDot) {
ranRepeatableAction = true;
}
}
if (action instanceof DocumentContentChangeAction) {
vimState = await action.exec(vimState.cursorStopPosition, vimState);
}
if (action instanceof BaseOperator) {
recordedState.operatorCount = recordedState.count;
}
// 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 (vimState.currentMode !== this.currentMode) {
await this.setCurrentMode(vimState.currentMode);
// We don't want to mark any searches as a repeatable action
if (
vimState.currentMode === Mode.Normal &&
prevMode !== Mode.SearchInProgressMode &&
prevMode !== Mode.CommandlineInProgress &&
prevMode !== Mode.EasyMotionInputMode &&
prevMode !== Mode.EasyMotionMode
) {
ranRepeatableAction = true;
}
}
// Set context for overriding cmd-V, this is only done in search entry and
// commandline modes
if (isStatusBarMode(vimState.currentMode) !== isStatusBarMode(prevMode)) {
await VsCodeContext.Set('vim.overrideCmdV', isStatusBarMode(vimState.currentMode));
}
if (recordedState.operatorReadyToExecute(vimState.currentMode)) {
if (vimState.recordedState.operator) {
vimState = await this.executeOperator(vimState);
vimState.recordedState.hasRunOperator = true;
ranRepeatableAction = vimState.recordedState.operator!.canBeRepeatedWithDot;
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 (vimState.currentMode !== this.currentMode) {
await this.setCurrentMode(vimState.currentMode);
if (vimState.currentMode === Mode.Normal) {
ranRepeatableAction = true;
}
}
if (
(ranAction && !(action instanceof CommandRegister) && vimState.currentMode !== Mode.Insert) ||
action instanceof CommandVisualMode
) {
vimState.recordedState.resetCommandList();
}
ranRepeatableAction =
(ranRepeatableAction && vimState.currentMode === Mode.Normal) ||
this.createUndoPointForBrackets(vimState);
ranAction = ranAction && vimState.currentMode === Mode.Normal;
// Record down previous action and flush temporary state
if (ranRepeatableAction) {
globalState.previousFullAction = vimState.recordedState;
if (recordedState.isInsertion) {
Register.putByKey(recordedState, '.', undefined, true);
}
}
// Update desiredColumn
if (!action.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) {
vimState.desiredColumn = Number.POSITIVE_INFINITY;
} else {
vimState.desiredColumn = vimState.cursorStopPosition.character;
}
} else if (vimState.currentMode !== Mode.VisualBlock) {
// TODO: explain why not VisualBlock
vimState.desiredColumn = 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 (vimState.currentMode === Mode.Visual) {
vimState.cursors = vimState.cursors.map((c) =>
c.start.isBefore(c.stop)
? c.withNewStop(
c.stop.isLineEnd() ? c.stop.getRightThroughLineBreaks() : c.stop.getRight()
)
: c
);
}
if (ranAction) {
vimState.recordedState = new RecordedState();
// Return to insert mode after 1 command in this case for <C-o>
if (vimState.returnToInsertAfterCommand) {
if (vimState.actionCount > 0) {
await this.setCurrentMode(Mode.Insert);
} else {
vimState.actionCount++;
}
}
}
// track undo history
if (!this.vimState.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!
if (this.vimState.alteredHistory) {
this.vimState.alteredHistory = false;
vimState.historyTracker.ignoreChange();
} else {
vimState.historyTracker.addChange(this.vimState.cursorsInitialState.map((c) => c.stop));
}
}
// Don't record an undo point for every action of a macro, only at the very end
if (ranRepeatableAction && !vimState.isReplayingMacro) {
vimState.historyTracker.finishCurrentStep();
}
recordedState.actionKeys = [];
vimState.currentRegisterMode = RegisterMode.AscertainFromCurrentMode;
if (this.currentMode === Mode.Normal) {
vimState.cursorStartPosition = vimState.cursorStopPosition;
}
// Ensure cursors are within bounds
if (!vimState.editor.document.isClosed && vimState.editor === vscode.window.activeTextEditor) {
vimState.cursors = vimState.cursors.map((cursor: Range) => {
// adjust start/stop
const documentEndPosition = TextEditor.getDocumentEnd(vimState.editor);
const documentLineCount = TextEditor.getLineCount(vimState.editor);
if (cursor.start.line >= documentLineCount) {
cursor = cursor.withNewStart(documentEndPosition);
}
if (cursor.stop.line >= documentLineCount) {
cursor = cursor.withNewStop(documentEndPosition);
}
// adjust column
if (vimState.currentMode === Mode.Normal) {
const currentLineLength = TextEditor.getLineLength(cursor.stop.line);
if (currentLineLength > 0) {
const lineEndPosition = cursor.start.getLineEnd().getLeftThroughLineBreaks(true);
if (cursor.start.character >= currentLineLength) {
cursor = cursor.withNewStart(lineEndPosition);
}
if (cursor.stop.character >= currentLineLength) {
cursor = cursor.withNewStop(lineEndPosition);
}
}
}
return cursor;
});
}
// Update the current history step to have the latest cursor position
vimState.historyTracker.setLastHistoryEndPosition(vimState.cursors.map((c) => c.stop));
if (isVisualMode(this.vimState.currentMode) && !this.vimState.isRunningDotCommand) {
// Store selection for commands like gv
this.vimState.lastVisualSelection = {
mode: this.vimState.currentMode,
start: this.vimState.cursorStartPosition,
end: this.vimState.cursorStopPosition,
};
}
vimState.selectionsChanged.ignoreIntermediateSelections = false;
return vimState;
}
private async executeMovement(
vimState: VimState,
movement: BaseMovement
): Promise<{ vimState: VimState; recordedState: RecordedState }> {
vimState.lastMovementFailed = false;
let recordedState = vimState.recordedState;
for (let i = 0; i < vimState.cursors.length; i++) {
/**
* Essentially what we're doing here is pretending like the
* current VimState only has one cursor (the cursor that we just
* iterated to).
*
* We set the cursor position to be equal to the iterated one,
* and then set it back immediately after we're done.
*
* The slightly more complicated logic here allows us to write
* Action definitions without having to think about multiple
* cursors in almost all cases.
*/
const oldCursorPositionStart = vimState.cursorStartPosition;
const oldCursorPositionStop = vimState.cursorStopPosition;
vimState.cursorStartPosition = vimState.cursors[i].start;
let cursorPosition = vimState.cursors[i].stop;
vimState.cursorStopPosition = cursorPosition;
const result = await movement.execActionWithCount(
cursorPosition,
vimState,
recordedState.count
);
// We also need to update the specific cursor, in case the cursor position was modified inside
// the handling functions (e.g. 'it')
vimState.cursors[i] = new Range(vimState.cursorStartPosition, vimState.cursorStopPosition);
vimState.cursorStartPosition = oldCursorPositionStart;
vimState.cursorStopPosition = oldCursorPositionStop;
if (result instanceof Position) {
vimState.cursors[i] = vimState.cursors[i].withNewStop(result);
if (!isVisualMode(this.currentMode) && !vimState.recordedState.operator) {
vimState.cursors[i] = vimState.cursors[i].withNewStart(result);
}
} else {
if (result.failed) {
vimState.recordedState = new RecordedState();
vimState.lastMovementFailed = true;
}
vimState.cursors[i] = new Range(result.start, result.stop);
if (result.registerMode) {
vimState.currentRegisterMode = result.registerMode;
}
}
}
vimState.recordedState.count = 0;
// Keep the cursor within bounds
if (vimState.currentMode !== Mode.Normal || recordedState.operator) {
let stop = vimState.cursorStopPosition;
// Vim does this weird thing where it allows you to select and delete
// the newline character, which it places 1 past the last character
// in the line. This is why we use > instead of >=.
if (stop.character > TextEditor.getLineLength(stop.line)) {
vimState.cursorStopPosition = stop.getLineEnd();
}
}
return { vimState, recordedState };
}
private async executeOperator(vimState: VimState): Promise<VimState> {
let recordedState = vimState.recordedState;
const operator = recordedState.operator!;
// TODO - if actions were more pure, this would be unnecessary.
const startingMode = vimState.currentMode;
const startingRegisterMode = vimState.currentRegisterMode;
const resultingCursors: Range[] = [];
for (let [i, { start, stop }] of vimState.cursors.entries()) {
operator.multicursorIndex = i;
if (start.isAfter(stop)) {
[start, stop] = [stop, start];
}
if (!isVisualMode(startingMode) && startingRegisterMode !== RegisterMode.LineWise) {
stop = stop.getLeftThroughLineBreaks(true);
}
if (this.currentMode === Mode.VisualLine) {
start = start.getLineBegin();
stop = stop.getLineEnd();
vimState.currentRegisterMode = RegisterMode.LineWise;
}
await vimState.setCurrentMode(startingMode);
// We run the repeat version of an operator if the last 2 operators are the same.
if (
recordedState.operators.length > 1 &&
recordedState.operators.reverse()[0].constructor ===
recordedState.operators.reverse()[1].constructor
) {
vimState = await operator.runRepeat(vimState, start, recordedState.count);
} else {
vimState = await operator.run(vimState, start, stop);
}
for (const transformation of vimState.recordedState.transformations) {
if (isTextTransformation(transformation) && transformation.cursorIndex === undefined) {
transformation.cursorIndex = operator.multicursorIndex;
}
}
let resultingRange = new Range(vimState.cursorStartPosition, vimState.cursorStopPosition);
resultingCursors.push(resultingRange);
}
if (vimState.recordedState.transformations.length > 0) {
vimState = await this.executeCommand(vimState);
} else {
// Keep track of all cursors (in the case of multi-cursor).
vimState.cursors = resultingCursors;
vimState.editor.selections = vimState.cursors.map(
(cursor) => new vscode.Selection(cursor.start, cursor.stop)
);
}
return vimState;
}
private async executeCommand(vimState: VimState): Promise<VimState> {
const transformations = vimState.recordedState.transformations;
if (transformations.length === 0) {
return vimState;
}
const textTransformations: TextTransformations[] = transformations.filter((x) =>
isTextTransformation(x)
) as any;
const multicursorTextTransformations: InsertTextVSCodeTransformation[] = transformations.filter(
(x) => isMultiCursorTextTransformation(x)
) as any;
const otherTransformations = transformations.filter(
(x) => !isTextTransformation(x) && !isMultiCursorTextTransformation(x)
);
let accumulatedPositionDifferences: { [key: number]: PositionDiff[] } = {};
const doTextEditorEdit = (command: TextTransformations, edit: vscode.TextEditorEdit) => {
switch (command.type) {
case 'insertText':
edit.insert(command.position, command.text);
break;
case 'replaceText':
edit.replace(new vscode.Selection(command.end, command.start), command.text);
break;
case 'deleteText':
let matchRange = PairMatcher.immediateMatchingBracket(command.position);
if (matchRange) {
edit.delete(matchRange);
}
edit.delete(
new vscode.Range(command.position, command.position.getLeftThroughLineBreaks())
);
break;
case 'deleteRange':
edit.delete(new vscode.Selection(command.range.start, command.range.stop));