-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
vimState.ts
340 lines (290 loc) · 10.4 KB
/
vimState.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
import * as vscode from 'vscode';
import { SUPPORT_IME_SWITCHER, SUPPORT_NVIM } from 'platform/constants';
import { Position } from 'vscode';
import { IMovement } from '../actions/baseMotion';
import { IEasyMotion } from '../actions/plugins/easymotion/types';
import { SurroundState } from '../actions/plugins/surround';
import { ExCommandLine, SearchCommandLine } from '../cmd_line/commandLine';
import { Cursor } from '../common/motion/cursor';
import { configuration } from '../configuration/configuration';
import { DotCommandStatus, Mode, NormalCommandState } from '../mode/mode';
import { ModeData } from '../mode/modeData';
import { Logger } from '../util/logger';
import { SearchDirection } from '../vimscript/pattern';
import { HistoryTracker } from './../history/historyTracker';
import { RegisterMode } from './../register/register';
import { ReplaceState } from './../state/replaceState';
import { globalState } from './globalState';
import { RecordedState } from './recordedState';
interface IInputMethodSwitcher {
switchInputMethod(prevMode: Mode, newMode: Mode): Promise<void>;
}
interface IBaseMovement {
execActionWithCount(
position: Position,
vimState: VimState,
count: number,
): Promise<Position | IMovement>;
}
interface INVim {
run(vimState: VimState, command: string): Promise<{ statusBarText: string; error: boolean }>;
dispose(): void;
}
/**
* The VimState class holds permanent state that carries over from action
* to action.
*
* Actions defined in actions.ts are only allowed to mutate a VimState in order to
* indicate what they want to do.
*
* Each ModeHandler holds a VimState, so there is one for each open editor.
*/
export class VimState implements vscode.Disposable {
/**
* The column the cursor wants to be at, or Number.POSITIVE_INFINITY if it should always
* be the rightmost column.
*
* Example: If you go to the end of a 20 character column, this value
* will be 20, even if you press j and the next column is only 5 characters.
* This is because if the third column is 25 characters, the cursor will go
* back to the 20th column.
*/
public desiredColumn = 0;
public historyTracker: HistoryTracker;
public easyMotion: IEasyMotion;
public readonly documentUri: vscode.Uri;
public editor: vscode.TextEditor;
public get document(): vscode.TextDocument {
return this.editor.document;
}
/**
* Are multiple cursors currently present?
*/
public get isMultiCursor(): boolean {
return this._cursors.length > 1;
}
/**
* Is the multicursor something like visual block "multicursor", where
* natively in vim there would only be one cursor whose changes were applied
* to all lines after edit.
*/
public isFakeMultiCursor = false;
/**
* Tracks movements that can be repeated with ; (e.g. t, T, f, and F).
*/
public lastSemicolonRepeatableMovement: IBaseMovement | undefined = undefined;
/**
* Tracks movements that can be repeated with , (e.g. t, T, f, and F).
*/
public lastCommaRepeatableMovement: IBaseMovement | undefined = undefined;
// TODO: move into ModeHandler
public lastMovementFailed: boolean = false;
/**
* Keep track of whether the last command that ran is able to be repeated
* with the dot command.
*/
public lastCommandDotRepeatable: boolean = true;
public dotCommandStatus: DotCommandStatus = DotCommandStatus.Waiting;
public isReplayingMacro: boolean = false;
public normalCommandState: NormalCommandState = NormalCommandState.Waiting;
/**
* The last visual selection before running the dot command
*/
public dotCommandPreviousVisualSelection: vscode.Selection | undefined = undefined;
public surround: SurroundState | undefined = undefined;
/**
* Used for `<C-o>` in insert mode, which allows you run one normal mode
* command, then go back to insert mode.
*/
public returnToInsertAfterCommand = false;
public actionCount = 0;
/**
* Every time we invoke a VSCode command which might trigger a view update.
* We should postpone its view updating phase to avoid conflicting with our internal view updating mechanism.
* This array is used to cache every VSCode view updating event and they will be triggered once we run the inhouse `viewUpdate`.
*/
public postponedCodeViewChanges: ViewChange[] = [];
/**
* The cursor position (start, stop) when this action finishes.
*/
public get cursorStartPosition(): Position {
return this.cursors[0].start;
}
public set cursorStartPosition(value: Position) {
if (!value.isValid(this.editor)) {
Logger.warn(`invalid cursor start position. ${value.toString()}.`);
}
this.cursors[0] = this.cursors[0].withNewStart(value);
}
public get cursorStopPosition(): Position {
return this.cursors[0].stop;
}
public set cursorStopPosition(value: Position) {
if (!value.isValid(this.editor)) {
Logger.warn(`invalid cursor stop position. ${value.toString()}.`);
}
this.cursors[0] = this.cursors[0].withNewStop(value);
}
/**
* The position of every cursor. Will never be empty.
*/
private _cursors: Cursor[] = [new Cursor(new Position(0, 0), new Position(0, 0))];
public get cursors(): Cursor[] {
return this._cursors;
}
public set cursors(value: Cursor[]) {
if (value.length === 0) {
Logger.warn('Tried to set VimState.cursors to an empty array');
return;
}
const map = new Map<string, Cursor>();
for (const cursor of value) {
if (!cursor.isValid(this.editor)) {
Logger.warn(`invalid cursor position. ${cursor.toString()}.`);
}
// use a map to ensure no two cursors are at the same location.
map.set(cursor.toString(), cursor);
}
this._cursors = [...map.values()];
}
/**
* Initial state of cursors prior to any action being performed
*/
private _cursorsInitialState!: Cursor[];
public get cursorsInitialState(): Cursor[] {
return this._cursorsInitialState;
}
public set cursorsInitialState(cursors: Cursor[]) {
this._cursorsInitialState = [...cursors];
}
/**
* Stores last visual mode as well as what was selected for `gv`
*/
public lastVisualSelection:
| {
mode: Mode.Visual | Mode.VisualLine | Mode.VisualBlock;
start: Position;
end: Position;
}
| undefined = undefined;
/**
* The current mode and its associated state.
*/
public modeData: ModeData = { mode: Mode.Normal };
public get currentMode(): Mode {
return this.modeData.mode;
}
private inputMethodSwitcher?: IInputMethodSwitcher;
/**
* The mode Vim is currently including pseudo-modes like OperatorPendingMode
* This is to be used only by the Remappers when getting the remappings so don't
* use it anywhere else.
*/
public get currentModeIncludingPseudoModes(): Mode {
return this.recordedState.getOperatorState(this.currentMode) === 'pending'
? Mode.OperatorPendingMode
: this.currentMode;
}
public async setModeData(modeData: ModeData): Promise<void> {
if (modeData === undefined) {
// TODO: remove this once we're sure this is no longer an issue (#6500, #6464)
throw new Error('Tried setting modeData to undefined');
}
await this.inputMethodSwitcher?.switchInputMethod(this.currentMode, modeData.mode);
if (this.returnToInsertAfterCommand && modeData.mode === Mode.Insert) {
this.returnToInsertAfterCommand = false;
}
if (modeData.mode === Mode.SearchInProgressMode) {
globalState.searchState = modeData.commandLine.getSearchState();
}
if (configuration.smartRelativeLine) {
this.editor.options.lineNumbers =
modeData.mode === Mode.Insert
? vscode.TextEditorLineNumbersStyle.On
: vscode.TextEditorLineNumbersStyle.Relative;
}
this.modeData = modeData;
}
public async setCurrentMode(mode: Mode): Promise<void> {
if (mode === undefined) {
// TODO: remove this once we're sure this is no longer an issue (#6500, #6464)
throw new Error('Tried setting currentMode to undefined');
}
await this.setModeData(
mode === Mode.Replace
? {
mode,
replaceState: new ReplaceState(
this.cursors.map((cursor) => cursor.stop),
this.recordedState.count,
),
}
: mode === Mode.CommandlineInProgress
? {
mode,
commandLine: new ExCommandLine('', this.modeData.mode),
}
: mode === Mode.SearchInProgressMode
? {
mode,
commandLine: new SearchCommandLine(this, '', SearchDirection.Forward),
firstVisibleLineBeforeSearch: this.editor.visibleRanges[0].start.line,
}
: mode === Mode.Insert
? {
mode,
highSurrogate: undefined,
}
: { mode },
);
}
/**
* The currently active `RegisterMode`.
*
* When setting, `undefined` means "default for current `Mode`".
*/
public set currentRegisterMode(registerMode: RegisterMode | undefined) {
this._currentRegisterMode = registerMode;
}
public get currentRegisterMode(): RegisterMode {
if (this._currentRegisterMode) {
return this._currentRegisterMode;
}
switch (this.currentMode) {
case Mode.VisualLine:
return RegisterMode.LineWise;
case Mode.VisualBlock:
return RegisterMode.BlockWise;
default:
return RegisterMode.CharacterWise;
}
}
private _currentRegisterMode: RegisterMode | undefined;
public recordedState = new RecordedState();
/** The macro currently being recorded, if one exists. */
public macro: RecordedState | undefined;
public nvim?: INVim;
public constructor(editor: vscode.TextEditor, easyMotion: IEasyMotion) {
this.editor = editor;
this.documentUri = editor?.document.uri ?? vscode.Uri.file(''); // TODO: this is needed for some badly written tests
this.historyTracker = new HistoryTracker(this);
this.easyMotion = easyMotion;
}
async load() {
if (SUPPORT_NVIM) {
const m = await import('../neovim/neovim');
this.nvim = new m.NeovimWrapper();
}
if (SUPPORT_IME_SWITCHER) {
const ime = await import('../actions/plugins/imswitcher');
this.inputMethodSwitcher = new ime.InputMethodSwitcher();
}
}
dispose() {
this.nvim?.dispose();
}
}
export interface ViewChange {
command: string;
args: any;
}