forked from VSCodeVim/Vim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extension.ts
513 lines (438 loc) · 16.6 KB
/
extension.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
/**
* Extension.ts is a lightweight wrapper around ModeHandler. It converts key
* events to their string names and passes them on to ModeHandler via
* handleKeyEvent().
*/
import './src/actions/include-all';
import * as vscode from 'vscode';
import { CompositionState } from './src/state/compositionState';
import { EditorIdentity } from './src/editorIdentity';
import { Globals } from './src/globals';
import { Jump } from './src/jumps/jump';
import { ModeHandler } from './src/mode/modeHandler';
import { ModeHandlerMap } from './src/mode/modeHandlerMap';
import { ModeName } from './src/mode/mode';
import { Notation } from './src/configuration/notation';
import { Logger } from './src/util/logger';
import { Position } from './src/common/motion/position';
import { StatusBar } from './src/statusBar';
import { VsCodeContext } from './src/util/vscode-context';
import { commandLine } from './src/cmd_line/commandLine';
import { configuration } from './src/configuration/configuration';
import { globalState } from './src/state/globalState';
import { taskQueue } from './src/taskQueue';
import { Register } from './src/register/register';
let extensionContext: vscode.ExtensionContext;
let previousActiveEditorId: EditorIdentity | null = null;
let lastClosedModeHandler: ModeHandler | null = null;
interface ICodeKeybinding {
after?: string[];
commands?: { command: string; args: any[] }[];
}
export async function getAndUpdateModeHandler(forceSyncAndUpdate = false): Promise<ModeHandler> {
const activeTextEditor = vscode.window.activeTextEditor;
const activeEditorId = new EditorIdentity(activeTextEditor);
let [curHandler, isNew] = await ModeHandlerMap.getOrCreate(activeEditorId.toString());
if (isNew) {
extensionContext.subscriptions.push(curHandler);
}
curHandler.vimState.editor = activeTextEditor!;
if (
forceSyncAndUpdate ||
!previousActiveEditorId ||
!previousActiveEditorId.isEqual(activeEditorId)
) {
curHandler.syncCursors();
await curHandler.updateView(curHandler.vimState, { drawSelection: false, revealRange: false });
}
previousActiveEditorId = activeEditorId;
if (curHandler.vimState.focusChanged) {
curHandler.vimState.focusChanged = false;
if (previousActiveEditorId) {
const prevHandler = ModeHandlerMap.get(previousActiveEditorId.toString());
prevHandler!.vimState.focusChanged = true;
}
}
return curHandler;
}
async function loadConfiguration() {
const logger = Logger.get('Configuration');
const validatorResults = await configuration.load();
logger.debug(`${validatorResults.numErrors} errors found with vim configuration`);
if (validatorResults.numErrors > 0) {
for (let validatorResult of validatorResults.get()) {
switch (validatorResult.level) {
case 'error':
logger.error(validatorResult.message);
break;
case 'warning':
logger.warn(validatorResult.message);
break;
}
}
}
}
export async function activate(context: vscode.ExtensionContext) {
// before we do anything else,
// we need to load the configuration first
await loadConfiguration();
const logger = Logger.get('Extension Startup');
logger.debug('Start');
extensionContext = context;
extensionContext.subscriptions.push(StatusBar);
// Set the storage path to be used by history files
Globals.extensionStoragePath = context.globalStoragePath;
if (vscode.window.activeTextEditor) {
const filepathComponents = vscode.window.activeTextEditor.document.fileName.split(/\\|\//);
Register.putByKey(filepathComponents[filepathComponents.length - 1], '%', undefined, true);
}
// load state
await Promise.all([commandLine.load(), globalState.load()]);
// workspace events
registerEventListener(
context,
vscode.workspace.onDidChangeConfiguration,
async () => {
await loadConfiguration();
},
false
);
registerEventListener(context, vscode.workspace.onDidChangeTextDocument, async event => {
const textWasDeleted = changeEvent =>
changeEvent.contentChanges.length === 1 &&
changeEvent.contentChanges[0].text === '' &&
changeEvent.contentChanges[0].range.start.line !==
changeEvent.contentChanges[0].range.end.line;
const textWasAdded = changeEvent =>
changeEvent.contentChanges.length === 1 &&
(changeEvent.contentChanges[0].text === '\n' ||
changeEvent.contentChanges[0].text === '\r\n') &&
changeEvent.contentChanges[0].range.start.line ===
changeEvent.contentChanges[0].range.end.line;
if (textWasDeleted(event)) {
globalState.jumpTracker.handleTextDeleted(event.document, event.contentChanges[0].range);
} else if (textWasAdded(event)) {
globalState.jumpTracker.handleTextAdded(
event.document,
event.contentChanges[0].range,
event.contentChanges[0].text
);
}
// Change from vscode editor should set document.isDirty to true but they initially don't!
// There is a timing issue in vscode codebase between when the isDirty flag is set and
// when registered callbacks are fired. https://github.com/Microsoft/vscode/issues/11339
const contentChangeHandler = (modeHandler: ModeHandler) => {
if (modeHandler.vimState.currentMode === ModeName.Insert) {
if (modeHandler.vimState.historyTracker.currentContentChanges === undefined) {
modeHandler.vimState.historyTracker.currentContentChanges = [];
}
modeHandler.vimState.historyTracker.currentContentChanges = modeHandler.vimState.historyTracker.currentContentChanges.concat(
event.contentChanges
);
}
};
if (Globals.isTesting && Globals.mockModeHandler) {
contentChangeHandler(Globals.mockModeHandler as ModeHandler);
} else {
ModeHandlerMap.getAll()
.filter(modeHandler => modeHandler.vimState.identity.fileName === event.document.fileName)
.forEach(modeHandler => {
contentChangeHandler(modeHandler);
});
}
setTimeout(() => {
if (!event.document.isDirty && !event.document.isUntitled && event.contentChanges.length) {
handleContentChangedFromDisk(event.document);
}
}, 0);
});
registerEventListener(
context,
vscode.workspace.onDidCloseTextDocument,
async closedDocument => {
const documents = vscode.workspace.textDocuments;
// Delete modehandler once all tabs of this document have been closed
for (let editorIdentity of ModeHandlerMap.getKeys()) {
const modeHandler = ModeHandlerMap.get(editorIdentity);
let shouldDelete = false;
if (modeHandler == null || modeHandler.vimState.editor === undefined) {
shouldDelete = true;
} else {
const document = modeHandler.vimState.editor.document;
if (!documents.includes(document)) {
shouldDelete = true;
if (closedDocument === document) {
lastClosedModeHandler = modeHandler;
}
}
}
if (shouldDelete) {
ModeHandlerMap.delete(editorIdentity);
}
}
},
false
);
// window events
registerEventListener(
context,
vscode.window.onDidChangeActiveTextEditor,
async () => {
const mhPrevious: ModeHandler | null = previousActiveEditorId
? ModeHandlerMap.get(previousActiveEditorId.toString())
: null;
// Track the closed editor so we can use it the next time an open event occurs.
// When vscode changes away from a temporary file, onDidChangeActiveTextEditor first twice.
// First it fires when leaving the closed editor. Then onDidCloseTextDocument first, and we delete
// the old ModeHandler. Then a new editor opens.
//
// This also applies to files that are merely closed, which allows you to jump back to that file similarly
// once a new file is opened.
lastClosedModeHandler = mhPrevious || lastClosedModeHandler;
if (vscode.window.activeTextEditor === undefined) {
Register.putByKey('', '%', undefined, true);
return;
}
const filepathComponents = vscode.window.activeTextEditor.document.fileName.split(/\\|\//);
Register.putByKey(filepathComponents[filepathComponents.length - 1], '%', undefined, true);
taskQueue.enqueueTask(async () => {
if (vscode.window.activeTextEditor !== undefined) {
const mh: ModeHandler = await getAndUpdateModeHandler(true);
await VsCodeContext.Set('vim.mode', ModeName[mh.vimState.currentMode]);
await mh.updateView(mh.vimState, { drawSelection: false, revealRange: false });
globalState.jumpTracker.handleFileJump(
lastClosedModeHandler ? Jump.fromStateNow(lastClosedModeHandler.vimState) : null,
Jump.fromStateNow(mh.vimState)
);
}
});
},
true,
true
);
registerEventListener(
context,
vscode.window.onDidChangeTextEditorSelection,
async (e: vscode.TextEditorSelectionChangeEvent) => {
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)
return;
}
const mh = await getAndUpdateModeHandler();
// We may receive changes from other panels when, having selections in them containing the same file
// and changing text before the selection in current panel.
if (e.textEditor !== mh.vimState.editor) {
return;
}
if (mh.vimState.focusChanged) {
mh.vimState.focusChanged = false;
return;
}
if (mh.currentMode.name === ModeName.EasyMotionMode) {
return;
}
taskQueue.enqueueTask(
() => mh.handleSelectionChange(e),
undefined,
/**
* We don't want these to become backlogged! If they do, we'll update
* the selection to an incorrect value and see a jittering cursor.
*/
true
);
},
true,
true
);
const compositionState = new CompositionState();
// override vscode commands
overrideCommand(context, 'type', async args => {
taskQueue.enqueueTask(async () => {
const mh = await getAndUpdateModeHandler();
if (compositionState.isInComposition) {
compositionState.composingText += args.text;
} else {
await mh.handleKeyEvent(args.text);
}
});
});
overrideCommand(context, 'replacePreviousChar', async args => {
taskQueue.enqueueTask(async () => {
const mh = await getAndUpdateModeHandler();
if (compositionState.isInComposition) {
compositionState.composingText =
compositionState.composingText.substr(
0,
compositionState.composingText.length - args.replaceCharCnt
) + args.text;
} else {
await vscode.commands.executeCommand('default:replacePreviousChar', {
text: args.text,
replaceCharCnt: args.replaceCharCnt,
});
mh.vimState.cursorStopPosition = Position.FromVSCodePosition(
mh.vimState.editor.selection.start
);
mh.vimState.cursorStartPosition = Position.FromVSCodePosition(
mh.vimState.editor.selection.start
);
}
});
});
overrideCommand(context, 'compositionStart', async () => {
taskQueue.enqueueTask(async () => {
const mh = await getAndUpdateModeHandler();
if (mh.vimState.currentMode !== ModeName.Insert) {
compositionState.isInComposition = true;
}
});
});
overrideCommand(context, 'compositionEnd', async () => {
taskQueue.enqueueTask(async () => {
const mh = await getAndUpdateModeHandler();
if (mh.vimState.currentMode !== ModeName.Insert) {
let text = compositionState.composingText;
compositionState.reset();
mh.handleMultipleKeyEvents(text.split(''));
}
});
});
// register extension commands
registerCommand(context, 'vim.showQuickpickCmdLine', async () => {
const mh = await getAndUpdateModeHandler();
await commandLine.PromptAndRun('', mh.vimState);
mh.updateView(mh.vimState);
});
registerCommand(context, 'vim.remap', async (args: ICodeKeybinding) => {
taskQueue.enqueueTask(async () => {
const mh = await getAndUpdateModeHandler();
if (args.after) {
for (const key of args.after) {
await mh.handleKeyEvent(Notation.NormalizeKey(key, configuration.leader));
}
return;
}
if (args.commands) {
for (const command of args.commands) {
// Check if this is a vim command by looking for :
if (command.command.slice(0, 1) === ':') {
await commandLine.Run(command.command.slice(1, command.command.length), mh.vimState);
mh.updateView(mh.vimState);
} else {
vscode.commands.executeCommand(command.command, command.args);
}
}
}
});
});
registerCommand(context, 'toggleVim', async () => {
configuration.disableExtension = !configuration.disableExtension;
toggleExtension(configuration.disableExtension, compositionState);
});
for (const boundKey of configuration.boundKeyCombinations) {
registerCommand(context, boundKey.command, () => handleKeyEvent(`${boundKey.key}`));
}
// Initialize mode handler for current active Text Editor at startup.
if (vscode.window.activeTextEditor) {
let mh = await getAndUpdateModeHandler();
// This is called last because getAndUpdateModeHandler() will change cursor
mh.updateView(mh.vimState, { drawSelection: false, revealRange: false });
}
// Disable automatic keyboard navigation in lists, so it doesn't interfere
// with our list navigation keybindings
await VsCodeContext.Set('listAutomaticKeyboardNavigation', false);
await toggleExtension(configuration.disableExtension, compositionState);
logger.debug('Finish.');
}
/**
* Toggles the VSCodeVim extension between Enabled mode and Disabled mode. This
* function is activated by calling the 'toggleVim' command from the Command Palette.
*
* @param isDisabled if true, sets VSCodeVim to Disabled mode; else sets to enabled mode
*/
async function toggleExtension(isDisabled: boolean, compositionState: CompositionState) {
await VsCodeContext.Set('vim.active', !isDisabled);
if (!vscode.window.activeTextEditor) {
// This was happening in unit tests.
// If activate was called and no editor window is open, we can't properly initialize.
return;
}
let mh = await getAndUpdateModeHandler();
if (isDisabled) {
await mh.handleKeyEvent('<ExtensionDisable>');
compositionState.reset();
ModeHandlerMap.clear();
} else {
await mh.handleKeyEvent('<ExtensionEnable>');
}
}
function overrideCommand(
context: vscode.ExtensionContext,
command: string,
callback: (...args: any[]) => any
) {
const disposable = vscode.commands.registerCommand(command, async args => {
if (configuration.disableExtension) {
return vscode.commands.executeCommand('default:' + command, args);
}
if (!vscode.window.activeTextEditor) {
return;
}
if (
vscode.window.activeTextEditor.document &&
vscode.window.activeTextEditor.document.uri.toString() === 'debug:input'
) {
return vscode.commands.executeCommand('default:' + command, args);
}
return callback(args);
});
context.subscriptions.push(disposable);
}
function registerCommand(
context: vscode.ExtensionContext,
command: string,
callback: (...args: any[]) => any
) {
const disposable = vscode.commands.registerCommand(command, async args => {
if (!vscode.window.activeTextEditor) {
return;
}
callback(args);
});
context.subscriptions.push(disposable);
}
function registerEventListener<T>(
context: vscode.ExtensionContext,
event: vscode.Event<T>,
listener: (e: T) => any,
exitOnExtensionDisable = true,
exitOnTests = false
) {
const disposable = event(async e => {
if (exitOnExtensionDisable && configuration.disableExtension) {
return;
}
if (exitOnTests && Globals.isTesting) {
return;
}
listener(e);
});
context.subscriptions.push(disposable);
}
async function handleKeyEvent(key: string): Promise<void> {
const mh = await getAndUpdateModeHandler();
taskQueue.enqueueTask(async () => {
await mh.handleKeyEvent(key);
});
}
function handleContentChangedFromDisk(document: vscode.TextDocument): void {
ModeHandlerMap.getAll()
.filter(modeHandler => modeHandler.vimState.identity.fileName === document.fileName)
.forEach(modeHandler => {
modeHandler.vimState.historyTracker.clear();
});
}