Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
malwaredllc
GitHub Repository: malwaredllc/byob
Path: blob/master/web-gui/buildyourownbotnet/assets/js/codemirror/keymap/vim.js
1293 views
1
/**
2
* Supported keybindings:
3
*
4
* Motion:
5
* h, j, k, l
6
* gj, gk
7
* e, E, w, W, b, B, ge, gE
8
* f<character>, F<character>, t<character>, T<character>
9
* $, ^, 0, -, +, _
10
* gg, G
11
* %
12
* '<character>, `<character>
13
*
14
* Operator:
15
* d, y, c
16
* dd, yy, cc
17
* g~, g~g~
18
* >, <, >>, <<
19
*
20
* Operator-Motion:
21
* x, X, D, Y, C, ~
22
*
23
* Action:
24
* a, i, s, A, I, S, o, O
25
* zz, z., z<CR>, zt, zb, z-
26
* J
27
* u, Ctrl-r
28
* m<character>
29
* r<character>
30
*
31
* Modes:
32
* ESC - leave insert mode, visual mode, and clear input state.
33
* Ctrl-[, Ctrl-c - same as ESC.
34
*
35
* Registers: unamed, -, a-z, A-Z, 0-9
36
* (Does not respect the special case for number registers when delete
37
* operator is made with these commands: %, (, ), , /, ?, n, N, {, } )
38
* TODO: Implement the remaining registers.
39
* Marks: a-z, A-Z, and 0-9
40
* TODO: Implement the remaining special marks. They have more complex
41
* behavior.
42
*
43
* Events:
44
* 'vim-mode-change' - raised on the editor anytime the current mode changes,
45
* Event object: {mode: "visual", subMode: "linewise"}
46
*
47
* Code structure:
48
* 1. Default keymap
49
* 2. Variable declarations and short basic helpers
50
* 3. Instance (External API) implementation
51
* 4. Internal state tracking objects (input state, counter) implementation
52
* and instanstiation
53
* 5. Key handler (the main command dispatcher) implementation
54
* 6. Motion, operator, and action implementations
55
* 7. Helper functions for the key handler, motions, operators, and actions
56
* 8. Set up Vim to work as a keymap for CodeMirror.
57
*/
58
59
(function() {
60
'use strict';
61
62
var defaultKeymap = [
63
// Key to key mapping. This goes first to make it possible to override
64
// existing mappings.
65
{ keys: ['<Left>'], type: 'keyToKey', toKeys: ['h'] },
66
{ keys: ['<Right>'], type: 'keyToKey', toKeys: ['l'] },
67
{ keys: ['<Up>'], type: 'keyToKey', toKeys: ['k'] },
68
{ keys: ['<Down>'], type: 'keyToKey', toKeys: ['j'] },
69
{ keys: ['<Space>'], type: 'keyToKey', toKeys: ['l'] },
70
{ keys: ['<BS>'], type: 'keyToKey', toKeys: ['h'] },
71
{ keys: ['<C-Space>'], type: 'keyToKey', toKeys: ['W'] },
72
{ keys: ['<C-BS>'], type: 'keyToKey', toKeys: ['B'] },
73
{ keys: ['<S-Space>'], type: 'keyToKey', toKeys: ['w'] },
74
{ keys: ['<S-BS>'], type: 'keyToKey', toKeys: ['b'] },
75
{ keys: ['<C-n>'], type: 'keyToKey', toKeys: ['j'] },
76
{ keys: ['<C-p>'], type: 'keyToKey', toKeys: ['k'] },
77
{ keys: ['C-['], type: 'keyToKey', toKeys: ['<Esc>'] },
78
{ keys: ['<C-c>'], type: 'keyToKey', toKeys: ['<Esc>'] },
79
{ keys: ['s'], type: 'keyToKey', toKeys: ['c', 'l'], context: 'normal' },
80
{ keys: ['s'], type: 'keyToKey', toKeys: ['x', 'i'], context: 'visual'},
81
{ keys: ['S'], type: 'keyToKey', toKeys: ['c', 'c'], context: 'normal' },
82
{ keys: ['S'], type: 'keyToKey', toKeys: ['d', 'c', 'c'], context: 'visual' },
83
{ keys: ['<Home>'], type: 'keyToKey', toKeys: ['0'] },
84
{ keys: ['<End>'], type: 'keyToKey', toKeys: ['$'] },
85
{ keys: ['<PageUp>'], type: 'keyToKey', toKeys: ['<C-b>'] },
86
{ keys: ['<PageDown>'], type: 'keyToKey', toKeys: ['<C-f>'] },
87
{ keys: ['<CR>'], type: 'keyToKey', toKeys: ['j', '^'], context: 'normal' },
88
// Motions
89
{ keys: ['H'], type: 'motion',
90
motion: 'moveToTopLine',
91
motionArgs: { linewise: true, toJumplist: true }},
92
{ keys: ['M'], type: 'motion',
93
motion: 'moveToMiddleLine',
94
motionArgs: { linewise: true, toJumplist: true }},
95
{ keys: ['L'], type: 'motion',
96
motion: 'moveToBottomLine',
97
motionArgs: { linewise: true, toJumplist: true }},
98
{ keys: ['h'], type: 'motion',
99
motion: 'moveByCharacters',
100
motionArgs: { forward: false }},
101
{ keys: ['l'], type: 'motion',
102
motion: 'moveByCharacters',
103
motionArgs: { forward: true }},
104
{ keys: ['j'], type: 'motion',
105
motion: 'moveByLines',
106
motionArgs: { forward: true, linewise: true }},
107
{ keys: ['k'], type: 'motion',
108
motion: 'moveByLines',
109
motionArgs: { forward: false, linewise: true }},
110
{ keys: ['g','j'], type: 'motion',
111
motion: 'moveByDisplayLines',
112
motionArgs: { forward: true }},
113
{ keys: ['g','k'], type: 'motion',
114
motion: 'moveByDisplayLines',
115
motionArgs: { forward: false }},
116
{ keys: ['w'], type: 'motion',
117
motion: 'moveByWords',
118
motionArgs: { forward: true, wordEnd: false }},
119
{ keys: ['W'], type: 'motion',
120
motion: 'moveByWords',
121
motionArgs: { forward: true, wordEnd: false, bigWord: true }},
122
{ keys: ['e'], type: 'motion',
123
motion: 'moveByWords',
124
motionArgs: { forward: true, wordEnd: true, inclusive: true }},
125
{ keys: ['E'], type: 'motion',
126
motion: 'moveByWords',
127
motionArgs: { forward: true, wordEnd: true, bigWord: true,
128
inclusive: true }},
129
{ keys: ['b'], type: 'motion',
130
motion: 'moveByWords',
131
motionArgs: { forward: false, wordEnd: false }},
132
{ keys: ['B'], type: 'motion',
133
motion: 'moveByWords',
134
motionArgs: { forward: false, wordEnd: false, bigWord: true }},
135
{ keys: ['g', 'e'], type: 'motion',
136
motion: 'moveByWords',
137
motionArgs: { forward: false, wordEnd: true, inclusive: true }},
138
{ keys: ['g', 'E'], type: 'motion',
139
motion: 'moveByWords',
140
motionArgs: { forward: false, wordEnd: true, bigWord: true,
141
inclusive: true }},
142
{ keys: ['{'], type: 'motion', motion: 'moveByParagraph',
143
motionArgs: { forward: false, toJumplist: true }},
144
{ keys: ['}'], type: 'motion', motion: 'moveByParagraph',
145
motionArgs: { forward: true, toJumplist: true }},
146
{ keys: ['<C-f>'], type: 'motion',
147
motion: 'moveByPage', motionArgs: { forward: true }},
148
{ keys: ['<C-b>'], type: 'motion',
149
motion: 'moveByPage', motionArgs: { forward: false }},
150
{ keys: ['<C-d>'], type: 'motion',
151
motion: 'moveByScroll',
152
motionArgs: { forward: true, explicitRepeat: true }},
153
{ keys: ['<C-u>'], type: 'motion',
154
motion: 'moveByScroll',
155
motionArgs: { forward: false, explicitRepeat: true }},
156
{ keys: ['g', 'g'], type: 'motion',
157
motion: 'moveToLineOrEdgeOfDocument',
158
motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
159
{ keys: ['G'], type: 'motion',
160
motion: 'moveToLineOrEdgeOfDocument',
161
motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
162
{ keys: ['0'], type: 'motion', motion: 'moveToStartOfLine' },
163
{ keys: ['^'], type: 'motion',
164
motion: 'moveToFirstNonWhiteSpaceCharacter' },
165
{ keys: ['+'], type: 'motion',
166
motion: 'moveByLines',
167
motionArgs: { forward: true, toFirstChar:true }},
168
{ keys: ['-'], type: 'motion',
169
motion: 'moveByLines',
170
motionArgs: { forward: false, toFirstChar:true }},
171
{ keys: ['_'], type: 'motion',
172
motion: 'moveByLines',
173
motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
174
{ keys: ['$'], type: 'motion',
175
motion: 'moveToEol',
176
motionArgs: { inclusive: true }},
177
{ keys: ['%'], type: 'motion',
178
motion: 'moveToMatchedSymbol',
179
motionArgs: { inclusive: true, toJumplist: true }},
180
{ keys: ['f', 'character'], type: 'motion',
181
motion: 'moveToCharacter',
182
motionArgs: { forward: true , inclusive: true }},
183
{ keys: ['F', 'character'], type: 'motion',
184
motion: 'moveToCharacter',
185
motionArgs: { forward: false }},
186
{ keys: ['t', 'character'], type: 'motion',
187
motion: 'moveTillCharacter',
188
motionArgs: { forward: true, inclusive: true }},
189
{ keys: ['T', 'character'], type: 'motion',
190
motion: 'moveTillCharacter',
191
motionArgs: { forward: false }},
192
{ keys: [';'], type: 'motion', motion: 'repeatLastCharacterSearch',
193
motionArgs: { forward: true }},
194
{ keys: [','], type: 'motion', motion: 'repeatLastCharacterSearch',
195
motionArgs: { forward: false }},
196
{ keys: ['\'', 'character'], type: 'motion', motion: 'goToMark',
197
motionArgs: {toJumplist: true}},
198
{ keys: ['`', 'character'], type: 'motion', motion: 'goToMark',
199
motionArgs: {toJumplist: true}},
200
{ keys: [']', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
201
{ keys: ['[', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
202
{ keys: [']', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
203
{ keys: ['[', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
204
{ keys: [']', 'character'], type: 'motion',
205
motion: 'moveToSymbol',
206
motionArgs: { forward: true, toJumplist: true}},
207
{ keys: ['[', 'character'], type: 'motion',
208
motion: 'moveToSymbol',
209
motionArgs: { forward: false, toJumplist: true}},
210
{ keys: ['|'], type: 'motion',
211
motion: 'moveToColumn',
212
motionArgs: { }},
213
// Operators
214
{ keys: ['d'], type: 'operator', operator: 'delete' },
215
{ keys: ['y'], type: 'operator', operator: 'yank' },
216
{ keys: ['c'], type: 'operator', operator: 'change' },
217
{ keys: ['>'], type: 'operator', operator: 'indent',
218
operatorArgs: { indentRight: true }},
219
{ keys: ['<'], type: 'operator', operator: 'indent',
220
operatorArgs: { indentRight: false }},
221
{ keys: ['g', '~'], type: 'operator', operator: 'swapcase' },
222
{ keys: ['n'], type: 'motion', motion: 'findNext',
223
motionArgs: { forward: true, toJumplist: true }},
224
{ keys: ['N'], type: 'motion', motion: 'findNext',
225
motionArgs: { forward: false, toJumplist: true }},
226
// Operator-Motion dual commands
227
{ keys: ['x'], type: 'operatorMotion', operator: 'delete',
228
motion: 'moveByCharacters', motionArgs: { forward: true },
229
operatorMotionArgs: { visualLine: false }},
230
{ keys: ['X'], type: 'operatorMotion', operator: 'delete',
231
motion: 'moveByCharacters', motionArgs: { forward: false },
232
operatorMotionArgs: { visualLine: true }},
233
{ keys: ['D'], type: 'operatorMotion', operator: 'delete',
234
motion: 'moveToEol', motionArgs: { inclusive: true },
235
operatorMotionArgs: { visualLine: true }},
236
{ keys: ['Y'], type: 'operatorMotion', operator: 'yank',
237
motion: 'moveToEol', motionArgs: { inclusive: true },
238
operatorMotionArgs: { visualLine: true }},
239
{ keys: ['C'], type: 'operatorMotion',
240
operator: 'change',
241
motion: 'moveToEol', motionArgs: { inclusive: true },
242
operatorMotionArgs: { visualLine: true }},
243
{ keys: ['~'], type: 'operatorMotion',
244
operator: 'swapcase', operatorArgs: { shouldMoveCursor: true },
245
motion: 'moveByCharacters', motionArgs: { forward: true }},
246
// Actions
247
{ keys: ['<C-i>'], type: 'action', action: 'jumpListWalk',
248
actionArgs: { forward: true }},
249
{ keys: ['<C-o>'], type: 'action', action: 'jumpListWalk',
250
actionArgs: { forward: false }},
251
{ keys: ['<C-e>'], type: 'action',
252
action: 'scroll',
253
actionArgs: { forward: true, linewise: true }},
254
{ keys: ['<C-y>'], type: 'action',
255
action: 'scroll',
256
actionArgs: { forward: false, linewise: true }},
257
{ keys: ['a'], type: 'action', action: 'enterInsertMode', isEdit: true,
258
actionArgs: { insertAt: 'charAfter' }},
259
{ keys: ['A'], type: 'action', action: 'enterInsertMode', isEdit: true,
260
actionArgs: { insertAt: 'eol' }},
261
{ keys: ['i'], type: 'action', action: 'enterInsertMode', isEdit: true,
262
actionArgs: { insertAt: 'inplace' }},
263
{ keys: ['I'], type: 'action', action: 'enterInsertMode', isEdit: true,
264
actionArgs: { insertAt: 'firstNonBlank' }},
265
{ keys: ['o'], type: 'action', action: 'newLineAndEnterInsertMode',
266
isEdit: true, interlaceInsertRepeat: true,
267
actionArgs: { after: true }},
268
{ keys: ['O'], type: 'action', action: 'newLineAndEnterInsertMode',
269
isEdit: true, interlaceInsertRepeat: true,
270
actionArgs: { after: false }},
271
{ keys: ['v'], type: 'action', action: 'toggleVisualMode' },
272
{ keys: ['V'], type: 'action', action: 'toggleVisualMode',
273
actionArgs: { linewise: true }},
274
{ keys: ['J'], type: 'action', action: 'joinLines', isEdit: true },
275
{ keys: ['p'], type: 'action', action: 'paste', isEdit: true,
276
actionArgs: { after: true, isEdit: true }},
277
{ keys: ['P'], type: 'action', action: 'paste', isEdit: true,
278
actionArgs: { after: false, isEdit: true }},
279
{ keys: ['r', 'character'], type: 'action', action: 'replace', isEdit: true },
280
{ keys: ['@', 'character'], type: 'action', action: 'replayMacro' },
281
{ keys: ['q', 'character'], type: 'action', action: 'enterMacroRecordMode' },
282
// Handle Replace-mode as a special case of insert mode.
283
{ keys: ['R'], type: 'action', action: 'enterInsertMode', isEdit: true,
284
actionArgs: { replace: true }},
285
{ keys: ['u'], type: 'action', action: 'undo' },
286
{ keys: ['<C-r>'], type: 'action', action: 'redo' },
287
{ keys: ['m', 'character'], type: 'action', action: 'setMark' },
288
{ keys: ['"', 'character'], type: 'action', action: 'setRegister' },
289
{ keys: ['z', 'z'], type: 'action', action: 'scrollToCursor',
290
actionArgs: { position: 'center' }},
291
{ keys: ['z', '.'], type: 'action', action: 'scrollToCursor',
292
actionArgs: { position: 'center' },
293
motion: 'moveToFirstNonWhiteSpaceCharacter' },
294
{ keys: ['z', 't'], type: 'action', action: 'scrollToCursor',
295
actionArgs: { position: 'top' }},
296
{ keys: ['z', '<CR>'], type: 'action', action: 'scrollToCursor',
297
actionArgs: { position: 'top' },
298
motion: 'moveToFirstNonWhiteSpaceCharacter' },
299
{ keys: ['z', '-'], type: 'action', action: 'scrollToCursor',
300
actionArgs: { position: 'bottom' }},
301
{ keys: ['z', 'b'], type: 'action', action: 'scrollToCursor',
302
actionArgs: { position: 'bottom' },
303
motion: 'moveToFirstNonWhiteSpaceCharacter' },
304
{ keys: ['.'], type: 'action', action: 'repeatLastEdit' },
305
{ keys: ['<C-a>'], type: 'action', action: 'incrementNumberToken',
306
isEdit: true,
307
actionArgs: {increase: true, backtrack: false}},
308
{ keys: ['<C-x>'], type: 'action', action: 'incrementNumberToken',
309
isEdit: true,
310
actionArgs: {increase: false, backtrack: false}},
311
// Text object motions
312
{ keys: ['a', 'character'], type: 'motion',
313
motion: 'textObjectManipulation' },
314
{ keys: ['i', 'character'], type: 'motion',
315
motion: 'textObjectManipulation',
316
motionArgs: { textObjectInner: true }},
317
// Search
318
{ keys: ['/'], type: 'search',
319
searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
320
{ keys: ['?'], type: 'search',
321
searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
322
{ keys: ['*'], type: 'search',
323
searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
324
{ keys: ['#'], type: 'search',
325
searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
326
// Ex command
327
{ keys: [':'], type: 'ex' }
328
];
329
330
var Vim = function() {
331
CodeMirror.defineOption('vimMode', false, function(cm, val) {
332
if (val) {
333
cm.setOption('keyMap', 'vim');
334
cm.setOption('disableInput', true);
335
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
336
cm.on('beforeSelectionChange', beforeSelectionChange);
337
maybeInitVimState(cm);
338
CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
339
} else if (cm.state.vim) {
340
cm.setOption('keyMap', 'default');
341
cm.setOption('disableInput', false);
342
cm.off('beforeSelectionChange', beforeSelectionChange);
343
CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
344
cm.state.vim = null;
345
}
346
});
347
function beforeSelectionChange(cm, cur) {
348
var vim = cm.state.vim;
349
if (vim.insertMode || vim.exMode) return;
350
351
var head = cur.head;
352
if (head.ch && head.ch == cm.doc.getLine(head.line).length) {
353
head.ch--;
354
}
355
}
356
function getOnPasteFn(cm) {
357
var vim = cm.state.vim;
358
if (!vim.onPasteFn) {
359
vim.onPasteFn = function() {
360
if (!vim.insertMode) {
361
cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
362
actions.enterInsertMode(cm, {}, vim);
363
}
364
};
365
}
366
return vim.onPasteFn;
367
}
368
369
var numberRegex = /[\d]/;
370
var wordRegexp = [(/\w/), (/[^\w\s]/)], bigWordRegexp = [(/\S/)];
371
function makeKeyRange(start, size) {
372
var keys = [];
373
for (var i = start; i < start + size; i++) {
374
keys.push(String.fromCharCode(i));
375
}
376
return keys;
377
}
378
var upperCaseAlphabet = makeKeyRange(65, 26);
379
var lowerCaseAlphabet = makeKeyRange(97, 26);
380
var numbers = makeKeyRange(48, 10);
381
var specialSymbols = '~`!@#$%^&*()_-+=[{}]\\|/?.,<>:;"\''.split('');
382
var specialKeys = ['Left', 'Right', 'Up', 'Down', 'Space', 'Backspace',
383
'Esc', 'Home', 'End', 'PageUp', 'PageDown', 'Enter'];
384
var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
385
var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"']);
386
387
function isLine(cm, line) {
388
return line >= cm.firstLine() && line <= cm.lastLine();
389
}
390
function isLowerCase(k) {
391
return (/^[a-z]$/).test(k);
392
}
393
function isMatchableSymbol(k) {
394
return '()[]{}'.indexOf(k) != -1;
395
}
396
function isNumber(k) {
397
return numberRegex.test(k);
398
}
399
function isUpperCase(k) {
400
return (/^[A-Z]$/).test(k);
401
}
402
function isWhiteSpaceString(k) {
403
return (/^\s*$/).test(k);
404
}
405
function inArray(val, arr) {
406
for (var i = 0; i < arr.length; i++) {
407
if (arr[i] == val) {
408
return true;
409
}
410
}
411
return false;
412
}
413
414
var createCircularJumpList = function() {
415
var size = 100;
416
var pointer = -1;
417
var head = 0;
418
var tail = 0;
419
var buffer = new Array(size);
420
function add(cm, oldCur, newCur) {
421
var current = pointer % size;
422
var curMark = buffer[current];
423
function useNextSlot(cursor) {
424
var next = ++pointer % size;
425
var trashMark = buffer[next];
426
if (trashMark) {
427
trashMark.clear();
428
}
429
buffer[next] = cm.setBookmark(cursor);
430
}
431
if (curMark) {
432
var markPos = curMark.find();
433
// avoid recording redundant cursor position
434
if (markPos && !cursorEqual(markPos, oldCur)) {
435
useNextSlot(oldCur);
436
}
437
} else {
438
useNextSlot(oldCur);
439
}
440
useNextSlot(newCur);
441
head = pointer;
442
tail = pointer - size + 1;
443
if (tail < 0) {
444
tail = 0;
445
}
446
}
447
function move(cm, offset) {
448
pointer += offset;
449
if (pointer > head) {
450
pointer = head;
451
} else if (pointer < tail) {
452
pointer = tail;
453
}
454
var mark = buffer[(size + pointer) % size];
455
// skip marks that are temporarily removed from text buffer
456
if (mark && !mark.find()) {
457
var inc = offset > 0 ? 1 : -1;
458
var newCur;
459
var oldCur = cm.getCursor();
460
do {
461
pointer += inc;
462
mark = buffer[(size + pointer) % size];
463
// skip marks that are the same as current position
464
if (mark &&
465
(newCur = mark.find()) &&
466
!cursorEqual(oldCur, newCur)) {
467
break;
468
}
469
} while (pointer < head && pointer > tail);
470
}
471
return mark;
472
}
473
return {
474
cachedCursor: undefined, //used for # and * jumps
475
add: add,
476
move: move
477
};
478
};
479
480
var createMacroState = function() {
481
return {
482
macroKeyBuffer: [],
483
latestRegister: undefined,
484
inReplay: false,
485
lastInsertModeChanges: {
486
changes: [], // Change list
487
expectCursorActivityForChange: false // Set to true on change, false on cursorActivity.
488
},
489
enteredMacroMode: undefined,
490
isMacroPlaying: false,
491
toggle: function(cm, registerName) {
492
if (this.enteredMacroMode) { //onExit
493
this.enteredMacroMode(); // close dialog
494
this.enteredMacroMode = undefined;
495
} else { //onEnter
496
this.latestRegister = registerName;
497
this.enteredMacroMode = cm.openDialog(
498
'(recording)['+registerName+']', null, {bottom:true});
499
}
500
}
501
};
502
};
503
504
505
function maybeInitVimState(cm) {
506
if (!cm.state.vim) {
507
// Store instance state in the CodeMirror object.
508
cm.state.vim = {
509
inputState: new InputState(),
510
// Vim's input state that triggered the last edit, used to repeat
511
// motions and operators with '.'.
512
lastEditInputState: undefined,
513
// Vim's action command before the last edit, used to repeat actions
514
// with '.' and insert mode repeat.
515
lastEditActionCommand: undefined,
516
// When using jk for navigation, if you move from a longer line to a
517
// shorter line, the cursor may clip to the end of the shorter line.
518
// If j is pressed again and cursor goes to the next line, the
519
// cursor should go back to its horizontal position on the longer
520
// line if it can. This is to keep track of the horizontal position.
521
lastHPos: -1,
522
// Doing the same with screen-position for gj/gk
523
lastHSPos: -1,
524
// The last motion command run. Cleared if a non-motion command gets
525
// executed in between.
526
lastMotion: null,
527
marks: {},
528
insertMode: false,
529
// Repeat count for changes made in insert mode, triggered by key
530
// sequences like 3,i. Only exists when insertMode is true.
531
insertModeRepeat: undefined,
532
visualMode: false,
533
// If we are in visual line mode. No effect if visualMode is false.
534
visualLine: false
535
};
536
}
537
return cm.state.vim;
538
}
539
var vimGlobalState;
540
function resetVimGlobalState() {
541
vimGlobalState = {
542
// The current search query.
543
searchQuery: null,
544
// Whether we are searching backwards.
545
searchIsReversed: false,
546
jumpList: createCircularJumpList(),
547
macroModeState: createMacroState(),
548
// Recording latest f, t, F or T motion command.
549
lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''},
550
registerController: new RegisterController({})
551
};
552
}
553
554
var vimApi= {
555
buildKeyMap: function() {
556
// TODO: Convert keymap into dictionary format for fast lookup.
557
},
558
// Testing hook, though it might be useful to expose the register
559
// controller anyways.
560
getRegisterController: function() {
561
return vimGlobalState.registerController;
562
},
563
// Testing hook.
564
resetVimGlobalState_: resetVimGlobalState,
565
566
// Testing hook.
567
getVimGlobalState_: function() {
568
return vimGlobalState;
569
},
570
571
// Testing hook.
572
maybeInitVimState_: maybeInitVimState,
573
574
InsertModeKey: InsertModeKey,
575
map: function(lhs, rhs, ctx) {
576
// Add user defined key bindings.
577
exCommandDispatcher.map(lhs, rhs, ctx);
578
},
579
defineEx: function(name, prefix, func){
580
if (name.indexOf(prefix) !== 0) {
581
throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
582
}
583
exCommands[name]=func;
584
exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
585
},
586
// This is the outermost function called by CodeMirror, after keys have
587
// been mapped to their Vim equivalents.
588
handleKey: function(cm, key) {
589
var command;
590
var vim = maybeInitVimState(cm);
591
var macroModeState = vimGlobalState.macroModeState;
592
if (macroModeState.enteredMacroMode) {
593
if (key == 'q') {
594
actions.exitMacroRecordMode();
595
vim.inputState = new InputState();
596
return;
597
}
598
}
599
if (key == '<Esc>') {
600
// Clear input state and get back to normal mode.
601
vim.inputState = new InputState();
602
if (vim.visualMode) {
603
exitVisualMode(cm);
604
}
605
return;
606
}
607
// Enter visual mode when the mouse selects text.
608
if (!vim.visualMode &&
609
!cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) {
610
vim.visualMode = true;
611
vim.visualLine = false;
612
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
613
cm.on('mousedown', exitVisualMode);
614
}
615
if (key != '0' || (key == '0' && vim.inputState.getRepeat() === 0)) {
616
// Have to special case 0 since it's both a motion and a number.
617
command = commandDispatcher.matchCommand(key, defaultKeymap, vim);
618
}
619
if (!command) {
620
if (isNumber(key)) {
621
// Increment count unless count is 0 and key is 0.
622
vim.inputState.pushRepeatDigit(key);
623
}
624
return;
625
}
626
if (command.type == 'keyToKey') {
627
// TODO: prevent infinite recursion.
628
for (var i = 0; i < command.toKeys.length; i++) {
629
this.handleKey(cm, command.toKeys[i]);
630
}
631
} else {
632
if (macroModeState.enteredMacroMode) {
633
logKey(macroModeState, key);
634
}
635
commandDispatcher.processCommand(cm, vim, command);
636
}
637
},
638
handleEx: function(cm, input) {
639
exCommandDispatcher.processCommand(cm, input);
640
}
641
};
642
643
// Represents the current input state.
644
function InputState() {
645
this.prefixRepeat = [];
646
this.motionRepeat = [];
647
648
this.operator = null;
649
this.operatorArgs = null;
650
this.motion = null;
651
this.motionArgs = null;
652
this.keyBuffer = []; // For matching multi-key commands.
653
this.registerName = null; // Defaults to the unamed register.
654
}
655
InputState.prototype.pushRepeatDigit = function(n) {
656
if (!this.operator) {
657
this.prefixRepeat = this.prefixRepeat.concat(n);
658
} else {
659
this.motionRepeat = this.motionRepeat.concat(n);
660
}
661
};
662
InputState.prototype.getRepeat = function() {
663
var repeat = 0;
664
if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
665
repeat = 1;
666
if (this.prefixRepeat.length > 0) {
667
repeat *= parseInt(this.prefixRepeat.join(''), 10);
668
}
669
if (this.motionRepeat.length > 0) {
670
repeat *= parseInt(this.motionRepeat.join(''), 10);
671
}
672
}
673
return repeat;
674
};
675
676
/*
677
* Register stores information about copy and paste registers. Besides
678
* text, a register must store whether it is linewise (i.e., when it is
679
* pasted, should it insert itself into a new line, or should the text be
680
* inserted at the cursor position.)
681
*/
682
function Register(text, linewise) {
683
this.clear();
684
if (text) {
685
this.set(text, linewise);
686
}
687
}
688
Register.prototype = {
689
set: function(text, linewise) {
690
this.text = text;
691
this.linewise = !!linewise;
692
},
693
append: function(text, linewise) {
694
// if this register has ever been set to linewise, use linewise.
695
if (linewise || this.linewise) {
696
this.text += '\n' + text;
697
this.linewise = true;
698
} else {
699
this.text += text;
700
}
701
},
702
clear: function() {
703
this.text = '';
704
this.linewise = false;
705
},
706
toString: function() { return this.text; }
707
};
708
709
/*
710
* vim registers allow you to keep many independent copy and paste buffers.
711
* See http://usevim.com/2012/04/13/registers/ for an introduction.
712
*
713
* RegisterController keeps the state of all the registers. An initial
714
* state may be passed in. The unnamed register '"' will always be
715
* overridden.
716
*/
717
function RegisterController(registers) {
718
this.registers = registers;
719
this.unamedRegister = registers['"'] = new Register();
720
}
721
RegisterController.prototype = {
722
pushText: function(registerName, operator, text, linewise) {
723
if (linewise && text.charAt(0) == '\n') {
724
text = text.slice(1) + '\n';
725
}
726
if(linewise && text.charAt(text.length - 1) !== '\n'){
727
text += '\n';
728
}
729
// Lowercase and uppercase registers refer to the same register.
730
// Uppercase just means append.
731
var register = this.isValidRegister(registerName) ?
732
this.getRegister(registerName) : null;
733
// if no register/an invalid register was specified, things go to the
734
// default registers
735
if (!register) {
736
switch (operator) {
737
case 'yank':
738
// The 0 register contains the text from the most recent yank.
739
this.registers['0'] = new Register(text, linewise);
740
break;
741
case 'delete':
742
case 'change':
743
if (text.indexOf('\n') == -1) {
744
// Delete less than 1 line. Update the small delete register.
745
this.registers['-'] = new Register(text, linewise);
746
} else {
747
// Shift down the contents of the numbered registers and put the
748
// deleted text into register 1.
749
this.shiftNumericRegisters_();
750
this.registers['1'] = new Register(text, linewise);
751
}
752
break;
753
}
754
// Make sure the unnamed register is set to what just happened
755
this.unamedRegister.set(text, linewise);
756
return;
757
}
758
759
// If we've gotten to this point, we've actually specified a register
760
var append = isUpperCase(registerName);
761
if (append) {
762
register.append(text, linewise);
763
// The unamed register always has the same value as the last used
764
// register.
765
this.unamedRegister.append(text, linewise);
766
} else {
767
register.set(text, linewise);
768
this.unamedRegister.set(text, linewise);
769
}
770
},
771
setRegisterText: function(name, text, linewise) {
772
this.getRegister(name).set(text, linewise);
773
},
774
// Gets the register named @name. If one of @name doesn't already exist,
775
// create it. If @name is invalid, return the unamedRegister.
776
getRegister: function(name) {
777
if (!this.isValidRegister(name)) {
778
return this.unamedRegister;
779
}
780
name = name.toLowerCase();
781
if (!this.registers[name]) {
782
this.registers[name] = new Register();
783
}
784
return this.registers[name];
785
},
786
isValidRegister: function(name) {
787
return name && inArray(name, validRegisters);
788
},
789
shiftNumericRegisters_: function() {
790
for (var i = 9; i >= 2; i--) {
791
this.registers[i] = this.getRegister('' + (i - 1));
792
}
793
}
794
};
795
796
var commandDispatcher = {
797
matchCommand: function(key, keyMap, vim) {
798
var inputState = vim.inputState;
799
var keys = inputState.keyBuffer.concat(key);
800
var matchedCommands = [];
801
var selectedCharacter;
802
for (var i = 0; i < keyMap.length; i++) {
803
var command = keyMap[i];
804
if (matchKeysPartial(keys, command.keys)) {
805
if (inputState.operator && command.type == 'action') {
806
// Ignore matched action commands after an operator. Operators
807
// only operate on motions. This check is really for text
808
// objects since aW, a[ etcs conflicts with a.
809
continue;
810
}
811
// Match commands that take <character> as an argument.
812
if (command.keys[keys.length - 1] == 'character') {
813
selectedCharacter = keys[keys.length - 1];
814
if(selectedCharacter.length>1){
815
switch(selectedCharacter){
816
case '<CR>':
817
selectedCharacter='\n';
818
break;
819
case '<Space>':
820
selectedCharacter=' ';
821
break;
822
default:
823
continue;
824
}
825
}
826
}
827
// Add the command to the list of matched commands. Choose the best
828
// command later.
829
matchedCommands.push(command);
830
}
831
}
832
833
// Returns the command if it is a full match, or null if not.
834
function getFullyMatchedCommandOrNull(command) {
835
if (keys.length < command.keys.length) {
836
// Matches part of a multi-key command. Buffer and wait for next
837
// stroke.
838
inputState.keyBuffer.push(key);
839
return null;
840
} else {
841
if (command.keys[keys.length - 1] == 'character') {
842
inputState.selectedCharacter = selectedCharacter;
843
}
844
// Clear the buffer since a full match was found.
845
inputState.keyBuffer = [];
846
return command;
847
}
848
}
849
850
if (!matchedCommands.length) {
851
// Clear the buffer since there were no matches.
852
inputState.keyBuffer = [];
853
return null;
854
} else if (matchedCommands.length == 1) {
855
return getFullyMatchedCommandOrNull(matchedCommands[0]);
856
} else {
857
// Find the best match in the list of matchedCommands.
858
var context = vim.visualMode ? 'visual' : 'normal';
859
var bestMatch; // Default to first in the list.
860
for (var i = 0; i < matchedCommands.length; i++) {
861
var current = matchedCommands[i];
862
if (current.context == context) {
863
bestMatch = current;
864
break;
865
} else if (!bestMatch && !current.context) {
866
// Only set an imperfect match to best match if no best match is
867
// set and the imperfect match is not restricted to another
868
// context.
869
bestMatch = current;
870
}
871
}
872
return getFullyMatchedCommandOrNull(bestMatch);
873
}
874
},
875
processCommand: function(cm, vim, command) {
876
vim.inputState.repeatOverride = command.repeatOverride;
877
switch (command.type) {
878
case 'motion':
879
this.processMotion(cm, vim, command);
880
break;
881
case 'operator':
882
this.processOperator(cm, vim, command);
883
break;
884
case 'operatorMotion':
885
this.processOperatorMotion(cm, vim, command);
886
break;
887
case 'action':
888
this.processAction(cm, vim, command);
889
break;
890
case 'search':
891
this.processSearch(cm, vim, command);
892
break;
893
case 'ex':
894
case 'keyToEx':
895
this.processEx(cm, vim, command);
896
break;
897
default:
898
break;
899
}
900
},
901
processMotion: function(cm, vim, command) {
902
vim.inputState.motion = command.motion;
903
vim.inputState.motionArgs = copyArgs(command.motionArgs);
904
this.evalInput(cm, vim);
905
},
906
processOperator: function(cm, vim, command) {
907
var inputState = vim.inputState;
908
if (inputState.operator) {
909
if (inputState.operator == command.operator) {
910
// Typing an operator twice like 'dd' makes the operator operate
911
// linewise
912
inputState.motion = 'expandToLine';
913
inputState.motionArgs = { linewise: true };
914
this.evalInput(cm, vim);
915
return;
916
} else {
917
// 2 different operators in a row doesn't make sense.
918
vim.inputState = new InputState();
919
}
920
}
921
inputState.operator = command.operator;
922
inputState.operatorArgs = copyArgs(command.operatorArgs);
923
if (vim.visualMode) {
924
// Operating on a selection in visual mode. We don't need a motion.
925
this.evalInput(cm, vim);
926
}
927
},
928
processOperatorMotion: function(cm, vim, command) {
929
var visualMode = vim.visualMode;
930
var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
931
if (operatorMotionArgs) {
932
// Operator motions may have special behavior in visual mode.
933
if (visualMode && operatorMotionArgs.visualLine) {
934
vim.visualLine = true;
935
}
936
}
937
this.processOperator(cm, vim, command);
938
if (!visualMode) {
939
this.processMotion(cm, vim, command);
940
}
941
},
942
processAction: function(cm, vim, command) {
943
var inputState = vim.inputState;
944
var repeat = inputState.getRepeat();
945
var repeatIsExplicit = !!repeat;
946
var actionArgs = copyArgs(command.actionArgs) || {};
947
if (inputState.selectedCharacter) {
948
actionArgs.selectedCharacter = inputState.selectedCharacter;
949
}
950
// Actions may or may not have motions and operators. Do these first.
951
if (command.operator) {
952
this.processOperator(cm, vim, command);
953
}
954
if (command.motion) {
955
this.processMotion(cm, vim, command);
956
}
957
if (command.motion || command.operator) {
958
this.evalInput(cm, vim);
959
}
960
actionArgs.repeat = repeat || 1;
961
actionArgs.repeatIsExplicit = repeatIsExplicit;
962
actionArgs.registerName = inputState.registerName;
963
vim.inputState = new InputState();
964
vim.lastMotion = null;
965
if (command.isEdit) {
966
this.recordLastEdit(vim, inputState, command);
967
}
968
actions[command.action](cm, actionArgs, vim);
969
},
970
processSearch: function(cm, vim, command) {
971
if (!cm.getSearchCursor) {
972
// Search depends on SearchCursor.
973
return;
974
}
975
var forward = command.searchArgs.forward;
976
getSearchState(cm).setReversed(!forward);
977
var promptPrefix = (forward) ? '/' : '?';
978
var originalQuery = getSearchState(cm).getQuery();
979
var originalScrollPos = cm.getScrollInfo();
980
function handleQuery(query, ignoreCase, smartCase) {
981
try {
982
updateSearchQuery(cm, query, ignoreCase, smartCase);
983
} catch (e) {
984
showConfirm(cm, 'Invalid regex: ' + query);
985
return;
986
}
987
commandDispatcher.processMotion(cm, vim, {
988
type: 'motion',
989
motion: 'findNext',
990
motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
991
});
992
}
993
function onPromptClose(query) {
994
cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
995
handleQuery(query, true /** ignoreCase */, true /** smartCase */);
996
}
997
function onPromptKeyUp(_e, query) {
998
var parsedQuery;
999
try {
1000
parsedQuery = updateSearchQuery(cm, query,
1001
true /** ignoreCase */, true /** smartCase */);
1002
} catch (e) {
1003
// Swallow bad regexes for incremental search.
1004
}
1005
if (parsedQuery) {
1006
cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
1007
} else {
1008
clearSearchHighlight(cm);
1009
cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
1010
}
1011
}
1012
function onPromptKeyDown(e, _query, close) {
1013
var keyName = CodeMirror.keyName(e);
1014
if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
1015
updateSearchQuery(cm, originalQuery);
1016
clearSearchHighlight(cm);
1017
cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
1018
1019
CodeMirror.e_stop(e);
1020
close();
1021
cm.focus();
1022
}
1023
}
1024
switch (command.searchArgs.querySrc) {
1025
case 'prompt':
1026
showPrompt(cm, {
1027
onClose: onPromptClose,
1028
prefix: promptPrefix,
1029
desc: searchPromptDesc,
1030
onKeyUp: onPromptKeyUp,
1031
onKeyDown: onPromptKeyDown
1032
});
1033
break;
1034
case 'wordUnderCursor':
1035
var word = expandWordUnderCursor(cm, false /** inclusive */,
1036
true /** forward */, false /** bigWord */,
1037
true /** noSymbol */);
1038
var isKeyword = true;
1039
if (!word) {
1040
word = expandWordUnderCursor(cm, false /** inclusive */,
1041
true /** forward */, false /** bigWord */,
1042
false /** noSymbol */);
1043
isKeyword = false;
1044
}
1045
if (!word) {
1046
return;
1047
}
1048
var query = cm.getLine(word.start.line).substring(word.start.ch,
1049
word.end.ch);
1050
if (isKeyword) {
1051
query = '\\b' + query + '\\b';
1052
} else {
1053
query = escapeRegex(query);
1054
}
1055
1056
// cachedCursor is used to save the old position of the cursor
1057
// when * or # causes vim to seek for the nearest word and shift
1058
// the cursor before entering the motion.
1059
vimGlobalState.jumpList.cachedCursor = cm.getCursor();
1060
cm.setCursor(word.start);
1061
1062
handleQuery(query, true /** ignoreCase */, false /** smartCase */);
1063
break;
1064
}
1065
},
1066
processEx: function(cm, vim, command) {
1067
function onPromptClose(input) {
1068
// Give the prompt some time to close so that if processCommand shows
1069
// an error, the elements don't overlap.
1070
exCommandDispatcher.processCommand(cm, input);
1071
}
1072
function onPromptKeyDown(e, _input, close) {
1073
var keyName = CodeMirror.keyName(e);
1074
if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
1075
CodeMirror.e_stop(e);
1076
close();
1077
cm.focus();
1078
}
1079
}
1080
if (command.type == 'keyToEx') {
1081
// Handle user defined Ex to Ex mappings
1082
exCommandDispatcher.processCommand(cm, command.exArgs.input);
1083
} else {
1084
if (vim.visualMode) {
1085
showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
1086
onKeyDown: onPromptKeyDown});
1087
} else {
1088
showPrompt(cm, { onClose: onPromptClose, prefix: ':',
1089
onKeyDown: onPromptKeyDown});
1090
}
1091
}
1092
},
1093
evalInput: function(cm, vim) {
1094
// If the motion comand is set, execute both the operator and motion.
1095
// Otherwise return.
1096
var inputState = vim.inputState;
1097
var motion = inputState.motion;
1098
var motionArgs = inputState.motionArgs || {};
1099
var operator = inputState.operator;
1100
var operatorArgs = inputState.operatorArgs || {};
1101
var registerName = inputState.registerName;
1102
var selectionEnd = cm.getCursor('head');
1103
var selectionStart = cm.getCursor('anchor');
1104
// The difference between cur and selection cursors are that cur is
1105
// being operated on and ignores that there is a selection.
1106
var curStart = copyCursor(selectionEnd);
1107
var curOriginal = copyCursor(curStart);
1108
var curEnd;
1109
var repeat;
1110
if (operator) {
1111
this.recordLastEdit(vim, inputState);
1112
}
1113
if (inputState.repeatOverride !== undefined) {
1114
// If repeatOverride is specified, that takes precedence over the
1115
// input state's repeat. Used by Ex mode and can be user defined.
1116
repeat = inputState.repeatOverride;
1117
} else {
1118
repeat = inputState.getRepeat();
1119
}
1120
if (repeat > 0 && motionArgs.explicitRepeat) {
1121
motionArgs.repeatIsExplicit = true;
1122
} else if (motionArgs.noRepeat ||
1123
(!motionArgs.explicitRepeat && repeat === 0)) {
1124
repeat = 1;
1125
motionArgs.repeatIsExplicit = false;
1126
}
1127
if (inputState.selectedCharacter) {
1128
// If there is a character input, stick it in all of the arg arrays.
1129
motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
1130
inputState.selectedCharacter;
1131
}
1132
motionArgs.repeat = repeat;
1133
vim.inputState = new InputState();
1134
if (motion) {
1135
var motionResult = motions[motion](cm, motionArgs, vim);
1136
vim.lastMotion = motions[motion];
1137
if (!motionResult) {
1138
return;
1139
}
1140
if (motionArgs.toJumplist) {
1141
var jumpList = vimGlobalState.jumpList;
1142
// if the current motion is # or *, use cachedCursor
1143
var cachedCursor = jumpList.cachedCursor;
1144
if (cachedCursor) {
1145
recordJumpPosition(cm, cachedCursor, motionResult);
1146
delete jumpList.cachedCursor;
1147
} else {
1148
recordJumpPosition(cm, curOriginal, motionResult);
1149
}
1150
}
1151
if (motionResult instanceof Array) {
1152
curStart = motionResult[0];
1153
curEnd = motionResult[1];
1154
} else {
1155
curEnd = motionResult;
1156
}
1157
// TODO: Handle null returns from motion commands better.
1158
if (!curEnd) {
1159
curEnd = { ch: curStart.ch, line: curStart.line };
1160
}
1161
if (vim.visualMode) {
1162
// Check if the selection crossed over itself. Will need to shift
1163
// the start point if that happened.
1164
if (cursorIsBefore(selectionStart, selectionEnd) &&
1165
(cursorEqual(selectionStart, curEnd) ||
1166
cursorIsBefore(curEnd, selectionStart))) {
1167
// The end of the selection has moved from after the start to
1168
// before the start. We will shift the start right by 1.
1169
selectionStart.ch += 1;
1170
} else if (cursorIsBefore(selectionEnd, selectionStart) &&
1171
(cursorEqual(selectionStart, curEnd) ||
1172
cursorIsBefore(selectionStart, curEnd))) {
1173
// The opposite happened. We will shift the start left by 1.
1174
selectionStart.ch -= 1;
1175
}
1176
selectionEnd = curEnd;
1177
if (vim.visualLine) {
1178
if (cursorIsBefore(selectionStart, selectionEnd)) {
1179
selectionStart.ch = 0;
1180
1181
var lastLine = cm.lastLine();
1182
if (selectionEnd.line > lastLine) {
1183
selectionEnd.line = lastLine;
1184
}
1185
selectionEnd.ch = lineLength(cm, selectionEnd.line);
1186
} else {
1187
selectionEnd.ch = 0;
1188
selectionStart.ch = lineLength(cm, selectionStart.line);
1189
}
1190
}
1191
cm.setSelection(selectionStart, selectionEnd);
1192
updateMark(cm, vim, '<',
1193
cursorIsBefore(selectionStart, selectionEnd) ? selectionStart
1194
: selectionEnd);
1195
updateMark(cm, vim, '>',
1196
cursorIsBefore(selectionStart, selectionEnd) ? selectionEnd
1197
: selectionStart);
1198
} else if (!operator) {
1199
curEnd = clipCursorToContent(cm, curEnd);
1200
cm.setCursor(curEnd.line, curEnd.ch);
1201
}
1202
}
1203
1204
if (operator) {
1205
var inverted = false;
1206
vim.lastMotion = null;
1207
operatorArgs.repeat = repeat; // Indent in visual mode needs this.
1208
if (vim.visualMode) {
1209
curStart = selectionStart;
1210
curEnd = selectionEnd;
1211
motionArgs.inclusive = true;
1212
}
1213
// Swap start and end if motion was backward.
1214
if (cursorIsBefore(curEnd, curStart)) {
1215
var tmp = curStart;
1216
curStart = curEnd;
1217
curEnd = tmp;
1218
inverted = true;
1219
}
1220
if (motionArgs.inclusive && !(vim.visualMode && inverted)) {
1221
// Move the selection end one to the right to include the last
1222
// character.
1223
curEnd.ch++;
1224
}
1225
var linewise = motionArgs.linewise ||
1226
(vim.visualMode && vim.visualLine);
1227
if (linewise) {
1228
// Expand selection to entire line.
1229
expandSelectionToLine(cm, curStart, curEnd);
1230
} else if (motionArgs.forward) {
1231
// Clip to trailing newlines only if the motion goes forward.
1232
clipToLine(cm, curStart, curEnd);
1233
}
1234
operatorArgs.registerName = registerName;
1235
// Keep track of linewise as it affects how paste and change behave.
1236
operatorArgs.linewise = linewise;
1237
operators[operator](cm, operatorArgs, vim, curStart,
1238
curEnd, curOriginal);
1239
if (vim.visualMode) {
1240
exitVisualMode(cm);
1241
}
1242
}
1243
},
1244
recordLastEdit: function(vim, inputState, actionCommand) {
1245
var macroModeState = vimGlobalState.macroModeState;
1246
if (macroModeState.inReplay) { return; }
1247
vim.lastEditInputState = inputState;
1248
vim.lastEditActionCommand = actionCommand;
1249
macroModeState.lastInsertModeChanges.changes = [];
1250
macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
1251
}
1252
};
1253
1254
/**
1255
* typedef {Object{line:number,ch:number}} Cursor An object containing the
1256
* position of the cursor.
1257
*/
1258
// All of the functions below return Cursor objects.
1259
var motions = {
1260
moveToTopLine: function(cm, motionArgs) {
1261
var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
1262
return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
1263
},
1264
moveToMiddleLine: function(cm) {
1265
var range = getUserVisibleLines(cm);
1266
var line = Math.floor((range.top + range.bottom) * 0.5);
1267
return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
1268
},
1269
moveToBottomLine: function(cm, motionArgs) {
1270
var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
1271
return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
1272
},
1273
expandToLine: function(cm, motionArgs) {
1274
// Expands forward to end of line, and then to next line if repeat is
1275
// >1. Does not handle backward motion!
1276
var cur = cm.getCursor();
1277
return { line: cur.line + motionArgs.repeat - 1, ch: Infinity };
1278
},
1279
findNext: function(cm, motionArgs) {
1280
var state = getSearchState(cm);
1281
var query = state.getQuery();
1282
if (!query) {
1283
return;
1284
}
1285
var prev = !motionArgs.forward;
1286
// If search is initiated with ? instead of /, negate direction.
1287
prev = (state.isReversed()) ? !prev : prev;
1288
highlightSearchMatches(cm, query);
1289
return findNext(cm, prev/** prev */, query, motionArgs.repeat);
1290
},
1291
goToMark: function(_cm, motionArgs, vim) {
1292
var mark = vim.marks[motionArgs.selectedCharacter];
1293
if (mark) {
1294
return mark.find();
1295
}
1296
return null;
1297
},
1298
jumpToMark: function(cm, motionArgs, vim) {
1299
var best = cm.getCursor();
1300
for (var i = 0; i < motionArgs.repeat; i++) {
1301
var cursor = best;
1302
for (var key in vim.marks) {
1303
if (!isLowerCase(key)) {
1304
continue;
1305
}
1306
var mark = vim.marks[key].find();
1307
var isWrongDirection = (motionArgs.forward) ?
1308
cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
1309
1310
if (isWrongDirection) {
1311
continue;
1312
}
1313
if (motionArgs.linewise && (mark.line == cursor.line)) {
1314
continue;
1315
}
1316
1317
var equal = cursorEqual(cursor, best);
1318
var between = (motionArgs.forward) ?
1319
cusrorIsBetween(cursor, mark, best) :
1320
cusrorIsBetween(best, mark, cursor);
1321
1322
if (equal || between) {
1323
best = mark;
1324
}
1325
}
1326
}
1327
1328
if (motionArgs.linewise) {
1329
// Vim places the cursor on the first non-whitespace character of
1330
// the line if there is one, else it places the cursor at the end
1331
// of the line, regardless of whether a mark was found.
1332
best.ch = findFirstNonWhiteSpaceCharacter(cm.getLine(best.line));
1333
}
1334
return best;
1335
},
1336
moveByCharacters: function(cm, motionArgs) {
1337
var cur = cm.getCursor();
1338
var repeat = motionArgs.repeat;
1339
var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
1340
return { line: cur.line, ch: ch };
1341
},
1342
moveByLines: function(cm, motionArgs, vim) {
1343
var cur = cm.getCursor();
1344
var endCh = cur.ch;
1345
// Depending what our last motion was, we may want to do different
1346
// things. If our last motion was moving vertically, we want to
1347
// preserve the HPos from our last horizontal move. If our last motion
1348
// was going to the end of a line, moving vertically we should go to
1349
// the end of the line, etc.
1350
switch (vim.lastMotion) {
1351
case this.moveByLines:
1352
case this.moveByDisplayLines:
1353
case this.moveByScroll:
1354
case this.moveToColumn:
1355
case this.moveToEol:
1356
endCh = vim.lastHPos;
1357
break;
1358
default:
1359
vim.lastHPos = endCh;
1360
}
1361
var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
1362
var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
1363
var first = cm.firstLine();
1364
var last = cm.lastLine();
1365
// Vim cancels linewise motions that start on an edge and move beyond
1366
// that edge. It does not cancel motions that do not start on an edge.
1367
if ((line < first && cur.line == first) ||
1368
(line > last && cur.line == last)) {
1369
return;
1370
}
1371
if(motionArgs.toFirstChar){
1372
endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
1373
vim.lastHPos = endCh;
1374
}
1375
vim.lastHSPos = cm.charCoords({line:line, ch:endCh},'div').left;
1376
return { line: line, ch: endCh };
1377
},
1378
moveByDisplayLines: function(cm, motionArgs, vim) {
1379
var cur = cm.getCursor();
1380
switch (vim.lastMotion) {
1381
case this.moveByDisplayLines:
1382
case this.moveByScroll:
1383
case this.moveByLines:
1384
case this.moveToColumn:
1385
case this.moveToEol:
1386
break;
1387
default:
1388
vim.lastHSPos = cm.charCoords(cur,'div').left;
1389
}
1390
var repeat = motionArgs.repeat;
1391
var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
1392
if (res.hitSide) {
1393
if (motionArgs.forward) {
1394
var lastCharCoords = cm.charCoords(res, 'div');
1395
var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
1396
var res = cm.coordsChar(goalCoords, 'div');
1397
} else {
1398
var resCoords = cm.charCoords({ line: cm.firstLine(), ch: 0}, 'div');
1399
resCoords.left = vim.lastHSPos;
1400
res = cm.coordsChar(resCoords, 'div');
1401
}
1402
}
1403
vim.lastHPos = res.ch;
1404
return res;
1405
},
1406
moveByPage: function(cm, motionArgs) {
1407
// CodeMirror only exposes functions that move the cursor page down, so
1408
// doing this bad hack to move the cursor and move it back. evalInput
1409
// will move the cursor to where it should be in the end.
1410
var curStart = cm.getCursor();
1411
var repeat = motionArgs.repeat;
1412
cm.moveV((motionArgs.forward ? repeat : -repeat), 'page');
1413
var curEnd = cm.getCursor();
1414
cm.setCursor(curStart);
1415
return curEnd;
1416
},
1417
moveByParagraph: function(cm, motionArgs) {
1418
var line = cm.getCursor().line;
1419
var repeat = motionArgs.repeat;
1420
var inc = motionArgs.forward ? 1 : -1;
1421
for (var i = 0; i < repeat; i++) {
1422
if ((!motionArgs.forward && line === cm.firstLine() ) ||
1423
(motionArgs.forward && line == cm.lastLine())) {
1424
break;
1425
}
1426
line += inc;
1427
while (line !== cm.firstLine() && line != cm.lastLine() && cm.getLine(line)) {
1428
line += inc;
1429
}
1430
}
1431
return { line: line, ch: 0 };
1432
},
1433
moveByScroll: function(cm, motionArgs, vim) {
1434
var scrollbox = cm.getScrollInfo();
1435
var curEnd = null;
1436
var repeat = motionArgs.repeat;
1437
if (!repeat) {
1438
repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
1439
}
1440
var orig = cm.charCoords(cm.getCursor(), 'local');
1441
motionArgs.repeat = repeat;
1442
var curEnd = motions.moveByDisplayLines(cm, motionArgs, vim);
1443
if (!curEnd) {
1444
return null;
1445
}
1446
var dest = cm.charCoords(curEnd, 'local');
1447
cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
1448
return curEnd;
1449
},
1450
moveByWords: function(cm, motionArgs) {
1451
return moveToWord(cm, motionArgs.repeat, !!motionArgs.forward,
1452
!!motionArgs.wordEnd, !!motionArgs.bigWord);
1453
},
1454
moveTillCharacter: function(cm, motionArgs) {
1455
var repeat = motionArgs.repeat;
1456
var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
1457
motionArgs.selectedCharacter);
1458
var increment = motionArgs.forward ? -1 : 1;
1459
recordLastCharacterSearch(increment, motionArgs);
1460
if(!curEnd)return cm.getCursor();
1461
curEnd.ch += increment;
1462
return curEnd;
1463
},
1464
moveToCharacter: function(cm, motionArgs) {
1465
var repeat = motionArgs.repeat;
1466
recordLastCharacterSearch(0, motionArgs);
1467
return moveToCharacter(cm, repeat, motionArgs.forward,
1468
motionArgs.selectedCharacter) || cm.getCursor();
1469
},
1470
moveToSymbol: function(cm, motionArgs) {
1471
var repeat = motionArgs.repeat;
1472
return findSymbol(cm, repeat, motionArgs.forward,
1473
motionArgs.selectedCharacter) || cm.getCursor();
1474
},
1475
moveToColumn: function(cm, motionArgs, vim) {
1476
var repeat = motionArgs.repeat;
1477
// repeat is equivalent to which column we want to move to!
1478
vim.lastHPos = repeat - 1;
1479
vim.lastHSPos = cm.charCoords(cm.getCursor(),'div').left;
1480
return moveToColumn(cm, repeat);
1481
},
1482
moveToEol: function(cm, motionArgs, vim) {
1483
var cur = cm.getCursor();
1484
vim.lastHPos = Infinity;
1485
var retval={ line: cur.line + motionArgs.repeat - 1, ch: Infinity };
1486
var end=cm.clipPos(retval);
1487
end.ch--;
1488
vim.lastHSPos = cm.charCoords(end,'div').left;
1489
return retval;
1490
},
1491
moveToFirstNonWhiteSpaceCharacter: function(cm) {
1492
// Go to the start of the line where the text begins, or the end for
1493
// whitespace-only lines
1494
var cursor = cm.getCursor();
1495
return { line: cursor.line,
1496
ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)) };
1497
},
1498
moveToMatchedSymbol: function(cm) {
1499
var cursor = cm.getCursor();
1500
var line = cursor.line;
1501
var ch = cursor.ch;
1502
var lineText = cm.getLine(line);
1503
var symbol;
1504
var startContext = cm.getTokenAt(cursor).type;
1505
var startCtxLevel = getContextLevel(startContext);
1506
do {
1507
symbol = lineText.charAt(ch++);
1508
if (symbol && isMatchableSymbol(symbol)) {
1509
var endContext = cm.getTokenAt({line:line, ch:ch}).type;
1510
var endCtxLevel = getContextLevel(endContext);
1511
if (startCtxLevel >= endCtxLevel) {
1512
break;
1513
}
1514
}
1515
} while (symbol);
1516
if (symbol) {
1517
return findMatchedSymbol(cm, {line:line, ch:ch-1}, symbol);
1518
} else {
1519
return cursor;
1520
}
1521
},
1522
moveToStartOfLine: function(cm) {
1523
var cursor = cm.getCursor();
1524
return { line: cursor.line, ch: 0 };
1525
},
1526
moveToLineOrEdgeOfDocument: function(cm, motionArgs) {
1527
var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
1528
if (motionArgs.repeatIsExplicit) {
1529
lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
1530
}
1531
return { line: lineNum,
1532
ch: findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)) };
1533
},
1534
textObjectManipulation: function(cm, motionArgs) {
1535
var character = motionArgs.selectedCharacter;
1536
// Inclusive is the difference between a and i
1537
// TODO: Instead of using the additional text object map to perform text
1538
// object operations, merge the map into the defaultKeyMap and use
1539
// motionArgs to define behavior. Define separate entries for 'aw',
1540
// 'iw', 'a[', 'i[', etc.
1541
var inclusive = !motionArgs.textObjectInner;
1542
if (!textObjects[character]) {
1543
// No text object defined for this, don't move.
1544
return null;
1545
}
1546
var tmp = textObjects[character](cm, inclusive);
1547
var start = tmp.start;
1548
var end = tmp.end;
1549
return [start, end];
1550
},
1551
repeatLastCharacterSearch: function(cm, motionArgs) {
1552
var lastSearch = vimGlobalState.lastChararacterSearch;
1553
var repeat = motionArgs.repeat;
1554
var forward = motionArgs.forward === lastSearch.forward;
1555
var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
1556
cm.moveH(-increment, 'char');
1557
motionArgs.inclusive = forward ? true : false;
1558
var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
1559
if (!curEnd) {
1560
cm.moveH(increment, 'char');
1561
return cm.getCursor();
1562
}
1563
curEnd.ch += increment;
1564
return curEnd;
1565
}
1566
};
1567
1568
var operators = {
1569
change: function(cm, operatorArgs, _vim, curStart, curEnd) {
1570
vimGlobalState.registerController.pushText(
1571
operatorArgs.registerName, 'change', cm.getRange(curStart, curEnd),
1572
operatorArgs.linewise);
1573
if (operatorArgs.linewise) {
1574
// Push the next line back down, if there is a next line.
1575
var replacement = curEnd.line > cm.lastLine() ? '' : '\n';
1576
cm.replaceRange(replacement, curStart, curEnd);
1577
cm.indentLine(curStart.line, 'smart');
1578
// null ch so setCursor moves to end of line.
1579
curStart.ch = null;
1580
} else {
1581
// Exclude trailing whitespace if the range is not all whitespace.
1582
var text = cm.getRange(curStart, curEnd);
1583
if (!isWhiteSpaceString(text)) {
1584
var match = (/\s+$/).exec(text);
1585
if (match) {
1586
curEnd = offsetCursor(curEnd, 0, - match[0].length);
1587
}
1588
}
1589
cm.replaceRange('', curStart, curEnd);
1590
}
1591
actions.enterInsertMode(cm, {}, cm.state.vim);
1592
cm.setCursor(curStart);
1593
},
1594
// delete is a javascript keyword.
1595
'delete': function(cm, operatorArgs, _vim, curStart, curEnd) {
1596
// If the ending line is past the last line, inclusive, instead of
1597
// including the trailing \n, include the \n before the starting line
1598
if (operatorArgs.linewise &&
1599
curEnd.line > cm.lastLine() && curStart.line > cm.firstLine()) {
1600
curStart.line--;
1601
curStart.ch = lineLength(cm, curStart.line);
1602
}
1603
vimGlobalState.registerController.pushText(
1604
operatorArgs.registerName, 'delete', cm.getRange(curStart, curEnd),
1605
operatorArgs.linewise);
1606
cm.replaceRange('', curStart, curEnd);
1607
if (operatorArgs.linewise) {
1608
cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
1609
} else {
1610
cm.setCursor(curStart);
1611
}
1612
},
1613
indent: function(cm, operatorArgs, vim, curStart, curEnd) {
1614
var startLine = curStart.line;
1615
var endLine = curEnd.line;
1616
// In visual mode, n> shifts the selection right n times, instead of
1617
// shifting n lines right once.
1618
var repeat = (vim.visualMode) ? operatorArgs.repeat : 1;
1619
if (operatorArgs.linewise) {
1620
// The only way to delete a newline is to delete until the start of
1621
// the next line, so in linewise mode evalInput will include the next
1622
// line. We don't want this in indent, so we go back a line.
1623
endLine--;
1624
}
1625
for (var i = startLine; i <= endLine; i++) {
1626
for (var j = 0; j < repeat; j++) {
1627
cm.indentLine(i, operatorArgs.indentRight);
1628
}
1629
}
1630
cm.setCursor(curStart);
1631
cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
1632
},
1633
swapcase: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
1634
var toSwap = cm.getRange(curStart, curEnd);
1635
var swapped = '';
1636
for (var i = 0; i < toSwap.length; i++) {
1637
var character = toSwap.charAt(i);
1638
swapped += isUpperCase(character) ? character.toLowerCase() :
1639
character.toUpperCase();
1640
}
1641
cm.replaceRange(swapped, curStart, curEnd);
1642
if (!operatorArgs.shouldMoveCursor) {
1643
cm.setCursor(curOriginal);
1644
}
1645
},
1646
yank: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
1647
vimGlobalState.registerController.pushText(
1648
operatorArgs.registerName, 'yank',
1649
cm.getRange(curStart, curEnd), operatorArgs.linewise);
1650
cm.setCursor(curOriginal);
1651
}
1652
};
1653
1654
var actions = {
1655
jumpListWalk: function(cm, actionArgs, vim) {
1656
if (vim.visualMode) {
1657
return;
1658
}
1659
var repeat = actionArgs.repeat;
1660
var forward = actionArgs.forward;
1661
var jumpList = vimGlobalState.jumpList;
1662
1663
var mark = jumpList.move(cm, forward ? repeat : -repeat);
1664
var markPos = mark ? mark.find() : undefined;
1665
markPos = markPos ? markPos : cm.getCursor();
1666
cm.setCursor(markPos);
1667
},
1668
scroll: function(cm, actionArgs, vim) {
1669
if (vim.visualMode) {
1670
return;
1671
}
1672
var repeat = actionArgs.repeat || 1;
1673
var lineHeight = cm.defaultTextHeight();
1674
var top = cm.getScrollInfo().top;
1675
var delta = lineHeight * repeat;
1676
var newPos = actionArgs.forward ? top + delta : top - delta;
1677
var cursor = cm.getCursor();
1678
var cursorCoords = cm.charCoords(cursor, 'local');
1679
if (actionArgs.forward) {
1680
if (newPos > cursorCoords.top) {
1681
cursor.line += (newPos - cursorCoords.top) / lineHeight;
1682
cursor.line = Math.ceil(cursor.line);
1683
cm.setCursor(cursor);
1684
cursorCoords = cm.charCoords(cursor, 'local');
1685
cm.scrollTo(null, cursorCoords.top);
1686
} else {
1687
// Cursor stays within bounds. Just reposition the scroll window.
1688
cm.scrollTo(null, newPos);
1689
}
1690
} else {
1691
var newBottom = newPos + cm.getScrollInfo().clientHeight;
1692
if (newBottom < cursorCoords.bottom) {
1693
cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
1694
cursor.line = Math.floor(cursor.line);
1695
cm.setCursor(cursor);
1696
cursorCoords = cm.charCoords(cursor, 'local');
1697
cm.scrollTo(
1698
null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
1699
} else {
1700
// Cursor stays within bounds. Just reposition the scroll window.
1701
cm.scrollTo(null, newPos);
1702
}
1703
}
1704
},
1705
scrollToCursor: function(cm, actionArgs) {
1706
var lineNum = cm.getCursor().line;
1707
var charCoords = cm.charCoords({line: lineNum, ch: 0}, 'local');
1708
var height = cm.getScrollInfo().clientHeight;
1709
var y = charCoords.top;
1710
var lineHeight = charCoords.bottom - y;
1711
switch (actionArgs.position) {
1712
case 'center': y = y - (height / 2) + lineHeight;
1713
break;
1714
case 'bottom': y = y - height + lineHeight*1.4;
1715
break;
1716
case 'top': y = y + lineHeight*0.4;
1717
break;
1718
}
1719
cm.scrollTo(null, y);
1720
},
1721
replayMacro: function(cm, actionArgs) {
1722
var registerName = actionArgs.selectedCharacter;
1723
var repeat = actionArgs.repeat;
1724
var macroModeState = vimGlobalState.macroModeState;
1725
if (registerName == '@') {
1726
registerName = macroModeState.latestRegister;
1727
}
1728
var keyBuffer = parseRegisterToKeyBuffer(macroModeState, registerName);
1729
while(repeat--){
1730
executeMacroKeyBuffer(cm, macroModeState, keyBuffer);
1731
}
1732
},
1733
exitMacroRecordMode: function() {
1734
var macroModeState = vimGlobalState.macroModeState;
1735
macroModeState.toggle();
1736
parseKeyBufferToRegister(macroModeState.latestRegister,
1737
macroModeState.macroKeyBuffer);
1738
},
1739
enterMacroRecordMode: function(cm, actionArgs) {
1740
var macroModeState = vimGlobalState.macroModeState;
1741
var registerName = actionArgs.selectedCharacter;
1742
macroModeState.toggle(cm, registerName);
1743
emptyMacroKeyBuffer(macroModeState);
1744
},
1745
enterInsertMode: function(cm, actionArgs, vim) {
1746
if (cm.getOption('readOnly')) { return; }
1747
vim.insertMode = true;
1748
vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
1749
var insertAt = (actionArgs) ? actionArgs.insertAt : null;
1750
if (insertAt == 'eol') {
1751
var cursor = cm.getCursor();
1752
cursor = { line: cursor.line, ch: lineLength(cm, cursor.line) };
1753
cm.setCursor(cursor);
1754
} else if (insertAt == 'charAfter') {
1755
cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
1756
} else if (insertAt == 'firstNonBlank') {
1757
cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
1758
}
1759
cm.setOption('keyMap', 'vim-insert');
1760
cm.setOption('disableInput', false);
1761
if (actionArgs && actionArgs.replace) {
1762
// Handle Replace-mode as a special case of insert mode.
1763
cm.toggleOverwrite(true);
1764
cm.setOption('keyMap', 'vim-replace');
1765
CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
1766
} else {
1767
cm.setOption('keyMap', 'vim-insert');
1768
CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
1769
}
1770
if (!vimGlobalState.macroModeState.inReplay) {
1771
// Only record if not replaying.
1772
cm.on('change', onChange);
1773
cm.on('cursorActivity', onCursorActivity);
1774
CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
1775
}
1776
},
1777
toggleVisualMode: function(cm, actionArgs, vim) {
1778
var repeat = actionArgs.repeat;
1779
var curStart = cm.getCursor();
1780
var curEnd;
1781
// TODO: The repeat should actually select number of characters/lines
1782
// equal to the repeat times the size of the previous visual
1783
// operation.
1784
if (!vim.visualMode) {
1785
cm.on('mousedown', exitVisualMode);
1786
vim.visualMode = true;
1787
vim.visualLine = !!actionArgs.linewise;
1788
if (vim.visualLine) {
1789
curStart.ch = 0;
1790
curEnd = clipCursorToContent(cm, {
1791
line: curStart.line + repeat - 1,
1792
ch: lineLength(cm, curStart.line)
1793
}, true /** includeLineBreak */);
1794
} else {
1795
curEnd = clipCursorToContent(cm, {
1796
line: curStart.line,
1797
ch: curStart.ch + repeat
1798
}, true /** includeLineBreak */);
1799
}
1800
// Make the initial selection.
1801
if (!actionArgs.repeatIsExplicit && !vim.visualLine) {
1802
// This is a strange case. Here the implicit repeat is 1. The
1803
// following commands lets the cursor hover over the 1 character
1804
// selection.
1805
cm.setCursor(curEnd);
1806
cm.setSelection(curEnd, curStart);
1807
} else {
1808
cm.setSelection(curStart, curEnd);
1809
}
1810
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : ""});
1811
} else {
1812
curStart = cm.getCursor('anchor');
1813
curEnd = cm.getCursor('head');
1814
if (!vim.visualLine && actionArgs.linewise) {
1815
// Shift-V pressed in characterwise visual mode. Switch to linewise
1816
// visual mode instead of exiting visual mode.
1817
vim.visualLine = true;
1818
curStart.ch = cursorIsBefore(curStart, curEnd) ? 0 :
1819
lineLength(cm, curStart.line);
1820
curEnd.ch = cursorIsBefore(curStart, curEnd) ?
1821
lineLength(cm, curEnd.line) : 0;
1822
cm.setSelection(curStart, curEnd);
1823
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: "linewise"});
1824
} else if (vim.visualLine && !actionArgs.linewise) {
1825
// v pressed in linewise visual mode. Switch to characterwise visual
1826
// mode instead of exiting visual mode.
1827
vim.visualLine = false;
1828
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
1829
} else {
1830
exitVisualMode(cm);
1831
}
1832
}
1833
updateMark(cm, vim, '<', cursorIsBefore(curStart, curEnd) ? curStart
1834
: curEnd);
1835
updateMark(cm, vim, '>', cursorIsBefore(curStart, curEnd) ? curEnd
1836
: curStart);
1837
},
1838
joinLines: function(cm, actionArgs, vim) {
1839
var curStart, curEnd;
1840
if (vim.visualMode) {
1841
curStart = cm.getCursor('anchor');
1842
curEnd = cm.getCursor('head');
1843
curEnd.ch = lineLength(cm, curEnd.line) - 1;
1844
} else {
1845
// Repeat is the number of lines to join. Minimum 2 lines.
1846
var repeat = Math.max(actionArgs.repeat, 2);
1847
curStart = cm.getCursor();
1848
curEnd = clipCursorToContent(cm, { line: curStart.line + repeat - 1,
1849
ch: Infinity });
1850
}
1851
var finalCh = 0;
1852
cm.operation(function() {
1853
for (var i = curStart.line; i < curEnd.line; i++) {
1854
finalCh = lineLength(cm, curStart.line);
1855
var tmp = { line: curStart.line + 1,
1856
ch: lineLength(cm, curStart.line + 1) };
1857
var text = cm.getRange(curStart, tmp);
1858
text = text.replace(/\n\s*/g, ' ');
1859
cm.replaceRange(text, curStart, tmp);
1860
}
1861
var curFinalPos = { line: curStart.line, ch: finalCh };
1862
cm.setCursor(curFinalPos);
1863
});
1864
},
1865
newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
1866
vim.insertMode = true;
1867
var insertAt = cm.getCursor();
1868
if (insertAt.line === cm.firstLine() && !actionArgs.after) {
1869
// Special case for inserting newline before start of document.
1870
cm.replaceRange('\n', { line: cm.firstLine(), ch: 0 });
1871
cm.setCursor(cm.firstLine(), 0);
1872
} else {
1873
insertAt.line = (actionArgs.after) ? insertAt.line :
1874
insertAt.line - 1;
1875
insertAt.ch = lineLength(cm, insertAt.line);
1876
cm.setCursor(insertAt);
1877
var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
1878
CodeMirror.commands.newlineAndIndent;
1879
newlineFn(cm);
1880
}
1881
this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
1882
},
1883
paste: function(cm, actionArgs) {
1884
var cur = cm.getCursor();
1885
var register = vimGlobalState.registerController.getRegister(
1886
actionArgs.registerName);
1887
if (!register.text) {
1888
return;
1889
}
1890
for (var text = '', i = 0; i < actionArgs.repeat; i++) {
1891
text += register.text;
1892
}
1893
var linewise = register.linewise;
1894
if (linewise) {
1895
if (actionArgs.after) {
1896
// Move the newline at the end to the start instead, and paste just
1897
// before the newline character of the line we are on right now.
1898
text = '\n' + text.slice(0, text.length - 1);
1899
cur.ch = lineLength(cm, cur.line);
1900
} else {
1901
cur.ch = 0;
1902
}
1903
} else {
1904
cur.ch += actionArgs.after ? 1 : 0;
1905
}
1906
cm.replaceRange(text, cur);
1907
// Now fine tune the cursor to where we want it.
1908
var curPosFinal;
1909
var idx;
1910
if (linewise && actionArgs.after) {
1911
curPosFinal = { line: cur.line + 1,
1912
ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)) };
1913
} else if (linewise && !actionArgs.after) {
1914
curPosFinal = { line: cur.line,
1915
ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)) };
1916
} else if (!linewise && actionArgs.after) {
1917
idx = cm.indexFromPos(cur);
1918
curPosFinal = cm.posFromIndex(idx + text.length - 1);
1919
} else {
1920
idx = cm.indexFromPos(cur);
1921
curPosFinal = cm.posFromIndex(idx + text.length);
1922
}
1923
cm.setCursor(curPosFinal);
1924
},
1925
undo: function(cm, actionArgs) {
1926
cm.operation(function() {
1927
repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
1928
cm.setCursor(cm.getCursor('anchor'));
1929
});
1930
},
1931
redo: function(cm, actionArgs) {
1932
repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
1933
},
1934
setRegister: function(_cm, actionArgs, vim) {
1935
vim.inputState.registerName = actionArgs.selectedCharacter;
1936
},
1937
setMark: function(cm, actionArgs, vim) {
1938
var markName = actionArgs.selectedCharacter;
1939
updateMark(cm, vim, markName, cm.getCursor());
1940
},
1941
replace: function(cm, actionArgs, vim) {
1942
var replaceWith = actionArgs.selectedCharacter;
1943
var curStart = cm.getCursor();
1944
var replaceTo;
1945
var curEnd;
1946
if(vim.visualMode){
1947
curStart=cm.getCursor('start');
1948
curEnd=cm.getCursor('end');
1949
// workaround to catch the character under the cursor
1950
// existing workaround doesn't cover actions
1951
curEnd=cm.clipPos({line: curEnd.line, ch: curEnd.ch+1});
1952
}else{
1953
var line = cm.getLine(curStart.line);
1954
replaceTo = curStart.ch + actionArgs.repeat;
1955
if (replaceTo > line.length) {
1956
replaceTo=line.length;
1957
}
1958
curEnd = { line: curStart.line, ch: replaceTo };
1959
}
1960
if(replaceWith=='\n'){
1961
if(!vim.visualMode) cm.replaceRange('', curStart, curEnd);
1962
// special case, where vim help says to replace by just one line-break
1963
(CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
1964
}else {
1965
var replaceWithStr=cm.getRange(curStart, curEnd);
1966
//replace all characters in range by selected, but keep linebreaks
1967
replaceWithStr=replaceWithStr.replace(/[^\n]/g,replaceWith);
1968
cm.replaceRange(replaceWithStr, curStart, curEnd);
1969
if(vim.visualMode){
1970
cm.setCursor(curStart);
1971
exitVisualMode(cm);
1972
}else{
1973
cm.setCursor(offsetCursor(curEnd, 0, -1));
1974
}
1975
}
1976
},
1977
incrementNumberToken: function(cm, actionArgs) {
1978
var cur = cm.getCursor();
1979
var lineStr = cm.getLine(cur.line);
1980
var re = /-?\d+/g;
1981
var match;
1982
var start;
1983
var end;
1984
var numberStr;
1985
var token;
1986
while ((match = re.exec(lineStr)) !== null) {
1987
token = match[0];
1988
start = match.index;
1989
end = start + token.length;
1990
if(cur.ch < end)break;
1991
}
1992
if(!actionArgs.backtrack && (end <= cur.ch))return;
1993
if (token) {
1994
var increment = actionArgs.increase ? 1 : -1;
1995
var number = parseInt(token) + (increment * actionArgs.repeat);
1996
var from = {ch:start, line:cur.line};
1997
var to = {ch:end, line:cur.line};
1998
numberStr = number.toString();
1999
cm.replaceRange(numberStr, from, to);
2000
} else {
2001
return;
2002
}
2003
cm.setCursor({line: cur.line, ch: start + numberStr.length - 1});
2004
},
2005
repeatLastEdit: function(cm, actionArgs, vim) {
2006
var lastEditInputState = vim.lastEditInputState;
2007
if (!lastEditInputState) { return; }
2008
var repeat = actionArgs.repeat;
2009
if (repeat && actionArgs.repeatIsExplicit) {
2010
vim.lastEditInputState.repeatOverride = repeat;
2011
} else {
2012
repeat = vim.lastEditInputState.repeatOverride || repeat;
2013
}
2014
repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
2015
}
2016
};
2017
2018
var textObjects = {
2019
// TODO: lots of possible exceptions that can be thrown here. Try da(
2020
// outside of a () block.
2021
// TODO: implement text objects for the reverse like }. Should just be
2022
// an additional mapping after moving to the defaultKeyMap.
2023
'w': function(cm, inclusive) {
2024
return expandWordUnderCursor(cm, inclusive, true /** forward */,
2025
false /** bigWord */);
2026
},
2027
'W': function(cm, inclusive) {
2028
return expandWordUnderCursor(cm, inclusive,
2029
true /** forward */, true /** bigWord */);
2030
},
2031
'{': function(cm, inclusive) {
2032
return selectCompanionObject(cm, '}', inclusive);
2033
},
2034
'(': function(cm, inclusive) {
2035
return selectCompanionObject(cm, ')', inclusive);
2036
},
2037
'[': function(cm, inclusive) {
2038
return selectCompanionObject(cm, ']', inclusive);
2039
},
2040
'\'': function(cm, inclusive) {
2041
return findBeginningAndEnd(cm, "'", inclusive);
2042
},
2043
'"': function(cm, inclusive) {
2044
return findBeginningAndEnd(cm, '"', inclusive);
2045
}
2046
};
2047
2048
/*
2049
* Below are miscellaneous utility functions used by vim.js
2050
*/
2051
2052
/**
2053
* Clips cursor to ensure that line is within the buffer's range
2054
* If includeLineBreak is true, then allow cur.ch == lineLength.
2055
*/
2056
function clipCursorToContent(cm, cur, includeLineBreak) {
2057
var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
2058
var maxCh = lineLength(cm, line) - 1;
2059
maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
2060
var ch = Math.min(Math.max(0, cur.ch), maxCh);
2061
return { line: line, ch: ch };
2062
}
2063
function copyArgs(args) {
2064
var ret = {};
2065
for (var prop in args) {
2066
if (args.hasOwnProperty(prop)) {
2067
ret[prop] = args[prop];
2068
}
2069
}
2070
return ret;
2071
}
2072
function offsetCursor(cur, offsetLine, offsetCh) {
2073
return { line: cur.line + offsetLine, ch: cur.ch + offsetCh };
2074
}
2075
function matchKeysPartial(pressed, mapped) {
2076
for (var i = 0; i < pressed.length; i++) {
2077
// 'character' means any character. For mark, register commads, etc.
2078
if (pressed[i] != mapped[i] && mapped[i] != 'character') {
2079
return false;
2080
}
2081
}
2082
return true;
2083
}
2084
function repeatFn(cm, fn, repeat) {
2085
return function() {
2086
for (var i = 0; i < repeat; i++) {
2087
fn(cm);
2088
}
2089
};
2090
}
2091
function copyCursor(cur) {
2092
return { line: cur.line, ch: cur.ch };
2093
}
2094
function cursorEqual(cur1, cur2) {
2095
return cur1.ch == cur2.ch && cur1.line == cur2.line;
2096
}
2097
function cursorIsBefore(cur1, cur2) {
2098
if (cur1.line < cur2.line) {
2099
return true;
2100
}
2101
if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
2102
return true;
2103
}
2104
return false;
2105
}
2106
function cusrorIsBetween(cur1, cur2, cur3) {
2107
// returns true if cur2 is between cur1 and cur3.
2108
var cur1before2 = cursorIsBefore(cur1, cur2);
2109
var cur2before3 = cursorIsBefore(cur2, cur3);
2110
return cur1before2 && cur2before3;
2111
}
2112
function lineLength(cm, lineNum) {
2113
return cm.getLine(lineNum).length;
2114
}
2115
function reverse(s){
2116
return s.split('').reverse().join('');
2117
}
2118
function trim(s) {
2119
if (s.trim) {
2120
return s.trim();
2121
}
2122
return s.replace(/^\s+|\s+$/g, '');
2123
}
2124
function escapeRegex(s) {
2125
return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
2126
}
2127
2128
function exitVisualMode(cm) {
2129
cm.off('mousedown', exitVisualMode);
2130
var vim = cm.state.vim;
2131
vim.visualMode = false;
2132
vim.visualLine = false;
2133
var selectionStart = cm.getCursor('anchor');
2134
var selectionEnd = cm.getCursor('head');
2135
if (!cursorEqual(selectionStart, selectionEnd)) {
2136
// Clear the selection and set the cursor only if the selection has not
2137
// already been cleared. Otherwise we risk moving the cursor somewhere
2138
// it's not supposed to be.
2139
cm.setCursor(clipCursorToContent(cm, selectionEnd));
2140
}
2141
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
2142
}
2143
2144
// Remove any trailing newlines from the selection. For
2145
// example, with the caret at the start of the last word on the line,
2146
// 'dw' should word, but not the newline, while 'w' should advance the
2147
// caret to the first character of the next line.
2148
function clipToLine(cm, curStart, curEnd) {
2149
var selection = cm.getRange(curStart, curEnd);
2150
// Only clip if the selection ends with trailing newline + whitespace
2151
if (/\n\s*$/.test(selection)) {
2152
var lines = selection.split('\n');
2153
// We know this is all whitepsace.
2154
lines.pop();
2155
2156
// Cases:
2157
// 1. Last word is an empty line - do not clip the trailing '\n'
2158
// 2. Last word is not an empty line - clip the trailing '\n'
2159
var line;
2160
// Find the line containing the last word, and clip all whitespace up
2161
// to it.
2162
for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
2163
curEnd.line--;
2164
curEnd.ch = 0;
2165
}
2166
// If the last word is not an empty line, clip an additional newline
2167
if (line) {
2168
curEnd.line--;
2169
curEnd.ch = lineLength(cm, curEnd.line);
2170
} else {
2171
curEnd.ch = 0;
2172
}
2173
}
2174
}
2175
2176
// Expand the selection to line ends.
2177
function expandSelectionToLine(_cm, curStart, curEnd) {
2178
curStart.ch = 0;
2179
curEnd.ch = 0;
2180
curEnd.line++;
2181
}
2182
2183
function findFirstNonWhiteSpaceCharacter(text) {
2184
if (!text) {
2185
return 0;
2186
}
2187
var firstNonWS = text.search(/\S/);
2188
return firstNonWS == -1 ? text.length : firstNonWS;
2189
}
2190
2191
function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
2192
var cur = cm.getCursor();
2193
var line = cm.getLine(cur.line);
2194
var idx = cur.ch;
2195
2196
// Seek to first word or non-whitespace character, depending on if
2197
// noSymbol is true.
2198
var textAfterIdx = line.substring(idx);
2199
var firstMatchedChar;
2200
if (noSymbol) {
2201
firstMatchedChar = textAfterIdx.search(/\w/);
2202
} else {
2203
firstMatchedChar = textAfterIdx.search(/\S/);
2204
}
2205
if (firstMatchedChar == -1) {
2206
return null;
2207
}
2208
idx += firstMatchedChar;
2209
textAfterIdx = line.substring(idx);
2210
var textBeforeIdx = line.substring(0, idx);
2211
2212
var matchRegex;
2213
// Greedy matchers for the "word" we are trying to expand.
2214
if (bigWord) {
2215
matchRegex = /^\S+/;
2216
} else {
2217
if ((/\w/).test(line.charAt(idx))) {
2218
matchRegex = /^\w+/;
2219
} else {
2220
matchRegex = /^[^\w\s]+/;
2221
}
2222
}
2223
2224
var wordAfterRegex = matchRegex.exec(textAfterIdx);
2225
var wordStart = idx;
2226
var wordEnd = idx + wordAfterRegex[0].length;
2227
// TODO: Find a better way to do this. It will be slow on very long lines.
2228
var revTextBeforeIdx = reverse(textBeforeIdx);
2229
var wordBeforeRegex = matchRegex.exec(revTextBeforeIdx);
2230
if (wordBeforeRegex) {
2231
wordStart -= wordBeforeRegex[0].length;
2232
}
2233
2234
if (inclusive) {
2235
// If present, trim all whitespace after word.
2236
// Otherwise, trim all whitespace before word.
2237
var textAfterWordEnd = line.substring(wordEnd);
2238
var whitespacesAfterWord = textAfterWordEnd.match(/^\s*/)[0].length;
2239
if (whitespacesAfterWord > 0) {
2240
wordEnd += whitespacesAfterWord;
2241
} else {
2242
var revTrim = revTextBeforeIdx.length - wordStart;
2243
var textBeforeWordStart = revTextBeforeIdx.substring(revTrim);
2244
var whitespacesBeforeWord = textBeforeWordStart.match(/^\s*/)[0].length;
2245
wordStart -= whitespacesBeforeWord;
2246
}
2247
}
2248
2249
return { start: { line: cur.line, ch: wordStart },
2250
end: { line: cur.line, ch: wordEnd }};
2251
}
2252
2253
function recordJumpPosition(cm, oldCur, newCur) {
2254
if(!cursorEqual(oldCur, newCur)) {
2255
vimGlobalState.jumpList.add(cm, oldCur, newCur);
2256
}
2257
}
2258
2259
function recordLastCharacterSearch(increment, args) {
2260
vimGlobalState.lastChararacterSearch.increment = increment;
2261
vimGlobalState.lastChararacterSearch.forward = args.forward;
2262
vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter;
2263
}
2264
2265
var symbolToMode = {
2266
'(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
2267
'[': 'section', ']': 'section',
2268
'*': 'comment', '/': 'comment',
2269
'm': 'method', 'M': 'method',
2270
'#': 'preprocess'
2271
};
2272
var findSymbolModes = {
2273
bracket: {
2274
isComplete: function(state) {
2275
if (state.nextCh === state.symb) {
2276
state.depth++;
2277
if(state.depth >= 1)return true;
2278
} else if (state.nextCh === state.reverseSymb) {
2279
state.depth--;
2280
}
2281
return false;
2282
}
2283
},
2284
section: {
2285
init: function(state) {
2286
state.curMoveThrough = true;
2287
state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
2288
},
2289
isComplete: function(state) {
2290
return state.index === 0 && state.nextCh === state.symb;
2291
}
2292
},
2293
comment: {
2294
isComplete: function(state) {
2295
var found = state.lastCh === '*' && state.nextCh === '/';
2296
state.lastCh = state.nextCh;
2297
return found;
2298
}
2299
},
2300
// TODO: The original Vim implementation only operates on level 1 and 2.
2301
// The current implementation doesn't check for code block level and
2302
// therefore it operates on any levels.
2303
method: {
2304
init: function(state) {
2305
state.symb = (state.symb === 'm' ? '{' : '}');
2306
state.reverseSymb = state.symb === '{' ? '}' : '{';
2307
},
2308
isComplete: function(state) {
2309
if(state.nextCh === state.symb)return true;
2310
return false;
2311
}
2312
},
2313
preprocess: {
2314
init: function(state) {
2315
state.index = 0;
2316
},
2317
isComplete: function(state) {
2318
if (state.nextCh === '#') {
2319
var token = state.lineText.match(/#(\w+)/)[1];
2320
if (token === 'endif') {
2321
if (state.forward && state.depth === 0) {
2322
return true;
2323
}
2324
state.depth++;
2325
} else if (token === 'if') {
2326
if (!state.forward && state.depth === 0) {
2327
return true;
2328
}
2329
state.depth--;
2330
}
2331
if(token === 'else' && state.depth === 0)return true;
2332
}
2333
return false;
2334
}
2335
}
2336
};
2337
function findSymbol(cm, repeat, forward, symb) {
2338
var cur = cm.getCursor();
2339
var increment = forward ? 1 : -1;
2340
var endLine = forward ? cm.lineCount() : -1;
2341
var curCh = cur.ch;
2342
var line = cur.line;
2343
var lineText = cm.getLine(line);
2344
var state = {
2345
lineText: lineText,
2346
nextCh: lineText.charAt(curCh),
2347
lastCh: null,
2348
index: curCh,
2349
symb: symb,
2350
reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
2351
forward: forward,
2352
depth: 0,
2353
curMoveThrough: false
2354
};
2355
var mode = symbolToMode[symb];
2356
if(!mode)return cur;
2357
var init = findSymbolModes[mode].init;
2358
var isComplete = findSymbolModes[mode].isComplete;
2359
if(init)init(state);
2360
while (line !== endLine && repeat) {
2361
state.index += increment;
2362
state.nextCh = state.lineText.charAt(state.index);
2363
if (!state.nextCh) {
2364
line += increment;
2365
state.lineText = cm.getLine(line) || '';
2366
if (increment > 0) {
2367
state.index = 0;
2368
} else {
2369
var lineLen = state.lineText.length;
2370
state.index = (lineLen > 0) ? (lineLen-1) : 0;
2371
}
2372
state.nextCh = state.lineText.charAt(state.index);
2373
}
2374
if (isComplete(state)) {
2375
cur.line = line;
2376
cur.ch = state.index;
2377
repeat--;
2378
}
2379
}
2380
if (state.nextCh || state.curMoveThrough) {
2381
return { line: line, ch: state.index };
2382
}
2383
return cur;
2384
}
2385
2386
/*
2387
* Returns the boundaries of the next word. If the cursor in the middle of
2388
* the word, then returns the boundaries of the current word, starting at
2389
* the cursor. If the cursor is at the start/end of a word, and we are going
2390
* forward/backward, respectively, find the boundaries of the next word.
2391
*
2392
* @param {CodeMirror} cm CodeMirror object.
2393
* @param {Cursor} cur The cursor position.
2394
* @param {boolean} forward True to search forward. False to search
2395
* backward.
2396
* @param {boolean} bigWord True if punctuation count as part of the word.
2397
* False if only [a-zA-Z0-9] characters count as part of the word.
2398
* @param {boolean} emptyLineIsWord True if empty lines should be treated
2399
* as words.
2400
* @return {Object{from:number, to:number, line: number}} The boundaries of
2401
* the word, or null if there are no more words.
2402
*/
2403
function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
2404
var lineNum = cur.line;
2405
var pos = cur.ch;
2406
var line = cm.getLine(lineNum);
2407
var dir = forward ? 1 : -1;
2408
var regexps = bigWord ? bigWordRegexp : wordRegexp;
2409
2410
if (emptyLineIsWord && line == '') {
2411
lineNum += dir;
2412
line = cm.getLine(lineNum);
2413
if (!isLine(cm, lineNum)) {
2414
return null;
2415
}
2416
pos = (forward) ? 0 : line.length;
2417
}
2418
2419
while (true) {
2420
if (emptyLineIsWord && line == '') {
2421
return { from: 0, to: 0, line: lineNum };
2422
}
2423
var stop = (dir > 0) ? line.length : -1;
2424
var wordStart = stop, wordEnd = stop;
2425
// Find bounds of next word.
2426
while (pos != stop) {
2427
var foundWord = false;
2428
for (var i = 0; i < regexps.length && !foundWord; ++i) {
2429
if (regexps[i].test(line.charAt(pos))) {
2430
wordStart = pos;
2431
// Advance to end of word.
2432
while (pos != stop && regexps[i].test(line.charAt(pos))) {
2433
pos += dir;
2434
}
2435
wordEnd = pos;
2436
foundWord = wordStart != wordEnd;
2437
if (wordStart == cur.ch && lineNum == cur.line &&
2438
wordEnd == wordStart + dir) {
2439
// We started at the end of a word. Find the next one.
2440
continue;
2441
} else {
2442
return {
2443
from: Math.min(wordStart, wordEnd + 1),
2444
to: Math.max(wordStart, wordEnd),
2445
line: lineNum };
2446
}
2447
}
2448
}
2449
if (!foundWord) {
2450
pos += dir;
2451
}
2452
}
2453
// Advance to next/prev line.
2454
lineNum += dir;
2455
if (!isLine(cm, lineNum)) {
2456
return null;
2457
}
2458
line = cm.getLine(lineNum);
2459
pos = (dir > 0) ? 0 : line.length;
2460
}
2461
// Should never get here.
2462
throw new Error('The impossible happened.');
2463
}
2464
2465
/**
2466
* @param {CodeMirror} cm CodeMirror object.
2467
* @param {int} repeat Number of words to move past.
2468
* @param {boolean} forward True to search forward. False to search
2469
* backward.
2470
* @param {boolean} wordEnd True to move to end of word. False to move to
2471
* beginning of word.
2472
* @param {boolean} bigWord True if punctuation count as part of the word.
2473
* False if only alphabet characters count as part of the word.
2474
* @return {Cursor} The position the cursor should move to.
2475
*/
2476
function moveToWord(cm, repeat, forward, wordEnd, bigWord) {
2477
var cur = cm.getCursor();
2478
var curStart = copyCursor(cur);
2479
var words = [];
2480
if (forward && !wordEnd || !forward && wordEnd) {
2481
repeat++;
2482
}
2483
// For 'e', empty lines are not considered words, go figure.
2484
var emptyLineIsWord = !(forward && wordEnd);
2485
for (var i = 0; i < repeat; i++) {
2486
var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
2487
if (!word) {
2488
var eodCh = lineLength(cm, cm.lastLine());
2489
words.push(forward
2490
? {line: cm.lastLine(), from: eodCh, to: eodCh}
2491
: {line: 0, from: 0, to: 0});
2492
break;
2493
}
2494
words.push(word);
2495
cur = {line: word.line, ch: forward ? (word.to - 1) : word.from};
2496
}
2497
var shortCircuit = words.length != repeat;
2498
var firstWord = words[0];
2499
var lastWord = words.pop();
2500
if (forward && !wordEnd) {
2501
// w
2502
if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
2503
// We did not start in the middle of a word. Discard the extra word at the end.
2504
lastWord = words.pop();
2505
}
2506
return {line: lastWord.line, ch: lastWord.from};
2507
} else if (forward && wordEnd) {
2508
return {line: lastWord.line, ch: lastWord.to - 1};
2509
} else if (!forward && wordEnd) {
2510
// ge
2511
if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
2512
// We did not start in the middle of a word. Discard the extra word at the end.
2513
lastWord = words.pop();
2514
}
2515
return {line: lastWord.line, ch: lastWord.to};
2516
} else {
2517
// b
2518
return {line: lastWord.line, ch: lastWord.from};
2519
}
2520
}
2521
2522
function moveToCharacter(cm, repeat, forward, character) {
2523
var cur = cm.getCursor();
2524
var start = cur.ch;
2525
var idx;
2526
for (var i = 0; i < repeat; i ++) {
2527
var line = cm.getLine(cur.line);
2528
idx = charIdxInLine(start, line, character, forward, true);
2529
if (idx == -1) {
2530
return null;
2531
}
2532
start = idx;
2533
}
2534
return { line: cm.getCursor().line, ch: idx };
2535
}
2536
2537
function moveToColumn(cm, repeat) {
2538
// repeat is always >= 1, so repeat - 1 always corresponds
2539
// to the column we want to go to.
2540
var line = cm.getCursor().line;
2541
return clipCursorToContent(cm, { line: line, ch: repeat - 1 });
2542
}
2543
2544
function updateMark(cm, vim, markName, pos) {
2545
if (!inArray(markName, validMarks)) {
2546
return;
2547
}
2548
if (vim.marks[markName]) {
2549
vim.marks[markName].clear();
2550
}
2551
vim.marks[markName] = cm.setBookmark(pos);
2552
}
2553
2554
function charIdxInLine(start, line, character, forward, includeChar) {
2555
// Search for char in line.
2556
// motion_options: {forward, includeChar}
2557
// If includeChar = true, include it too.
2558
// If forward = true, search forward, else search backwards.
2559
// If char is not found on this line, do nothing
2560
var idx;
2561
if (forward) {
2562
idx = line.indexOf(character, start + 1);
2563
if (idx != -1 && !includeChar) {
2564
idx -= 1;
2565
}
2566
} else {
2567
idx = line.lastIndexOf(character, start - 1);
2568
if (idx != -1 && !includeChar) {
2569
idx += 1;
2570
}
2571
}
2572
return idx;
2573
}
2574
2575
function getContextLevel(ctx) {
2576
return (ctx === 'string' || ctx === 'comment') ? 1 : 0;
2577
}
2578
2579
function findMatchedSymbol(cm, cur, symb) {
2580
var line = cur.line;
2581
var ch = cur.ch;
2582
symb = symb ? symb : cm.getLine(line).charAt(ch);
2583
2584
var symbContext = cm.getTokenAt({line:line, ch:ch+1}).type;
2585
var symbCtxLevel = getContextLevel(symbContext);
2586
2587
var reverseSymb = ({
2588
'(': ')', ')': '(',
2589
'[': ']', ']': '[',
2590
'{': '}', '}': '{'})[symb];
2591
2592
// Couldn't find a matching symbol, abort
2593
if (!reverseSymb) {
2594
return cur;
2595
}
2596
2597
// set our increment to move forward (+1) or backwards (-1)
2598
// depending on which bracket we're matching
2599
var increment = ({'(': 1, '{': 1, '[': 1})[symb] || -1;
2600
var endLine = increment === 1 ? cm.lineCount() : -1;
2601
var depth = 1, nextCh = symb, index = ch, lineText = cm.getLine(line);
2602
// Simple search for closing paren--just count openings and closings till
2603
// we find our match
2604
// TODO: use info from CodeMirror to ignore closing brackets in comments
2605
// and quotes, etc.
2606
while (line !== endLine && depth > 0) {
2607
index += increment;
2608
nextCh = lineText.charAt(index);
2609
if (!nextCh) {
2610
line += increment;
2611
lineText = cm.getLine(line) || '';
2612
if (increment > 0) {
2613
index = 0;
2614
} else {
2615
var lineLen = lineText.length;
2616
index = (lineLen > 0) ? (lineLen-1) : 0;
2617
}
2618
nextCh = lineText.charAt(index);
2619
}
2620
var revSymbContext = cm.getTokenAt({line:line, ch:index+1}).type;
2621
var revSymbCtxLevel = getContextLevel(revSymbContext);
2622
if (symbCtxLevel >= revSymbCtxLevel) {
2623
if (nextCh === symb) {
2624
depth++;
2625
} else if (nextCh === reverseSymb) {
2626
depth--;
2627
}
2628
}
2629
}
2630
2631
if (nextCh) {
2632
return { line: line, ch: index };
2633
}
2634
return cur;
2635
}
2636
2637
function selectCompanionObject(cm, revSymb, inclusive) {
2638
var cur = cm.getCursor();
2639
2640
var end = findMatchedSymbol(cm, cur, revSymb);
2641
var start = findMatchedSymbol(cm, end);
2642
start.ch += inclusive ? 1 : 0;
2643
end.ch += inclusive ? 0 : 1;
2644
2645
return { start: start, end: end };
2646
}
2647
2648
// Takes in a symbol and a cursor and tries to simulate text objects that
2649
// have identical opening and closing symbols
2650
// TODO support across multiple lines
2651
function findBeginningAndEnd(cm, symb, inclusive) {
2652
var cur = cm.getCursor();
2653
var line = cm.getLine(cur.line);
2654
var chars = line.split('');
2655
var start, end, i, len;
2656
var firstIndex = chars.indexOf(symb);
2657
2658
// the decision tree is to always look backwards for the beginning first,
2659
// but if the cursor is in front of the first instance of the symb,
2660
// then move the cursor forward
2661
if (cur.ch < firstIndex) {
2662
cur.ch = firstIndex;
2663
// Why is this line even here???
2664
// cm.setCursor(cur.line, firstIndex+1);
2665
}
2666
// otherwise if the cursor is currently on the closing symbol
2667
else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
2668
end = cur.ch; // assign end to the current cursor
2669
--cur.ch; // make sure to look backwards
2670
}
2671
2672
// if we're currently on the symbol, we've got a start
2673
if (chars[cur.ch] == symb && !end) {
2674
start = cur.ch + 1; // assign start to ahead of the cursor
2675
} else {
2676
// go backwards to find the start
2677
for (i = cur.ch; i > -1 && !start; i--) {
2678
if (chars[i] == symb) {
2679
start = i + 1;
2680
}
2681
}
2682
}
2683
2684
// look forwards for the end symbol
2685
if (start && !end) {
2686
for (i = start, len = chars.length; i < len && !end; i++) {
2687
if (chars[i] == symb) {
2688
end = i;
2689
}
2690
}
2691
}
2692
2693
// nothing found
2694
if (!start || !end) {
2695
return { start: cur, end: cur };
2696
}
2697
2698
// include the symbols
2699
if (inclusive) {
2700
--start; ++end;
2701
}
2702
2703
return {
2704
start: { line: cur.line, ch: start },
2705
end: { line: cur.line, ch: end }
2706
};
2707
}
2708
2709
// Search functions
2710
function SearchState() {}
2711
SearchState.prototype = {
2712
getQuery: function() {
2713
return vimGlobalState.query;
2714
},
2715
setQuery: function(query) {
2716
vimGlobalState.query = query;
2717
},
2718
getOverlay: function() {
2719
return this.searchOverlay;
2720
},
2721
setOverlay: function(overlay) {
2722
this.searchOverlay = overlay;
2723
},
2724
isReversed: function() {
2725
return vimGlobalState.isReversed;
2726
},
2727
setReversed: function(reversed) {
2728
vimGlobalState.isReversed = reversed;
2729
}
2730
};
2731
function getSearchState(cm) {
2732
var vim = cm.state.vim;
2733
return vim.searchState_ || (vim.searchState_ = new SearchState());
2734
}
2735
function dialog(cm, template, shortText, onClose, options) {
2736
if (cm.openDialog) {
2737
cm.openDialog(template, onClose, { bottom: true, value: options.value,
2738
onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp });
2739
}
2740
else {
2741
onClose(prompt(shortText, ''));
2742
}
2743
}
2744
2745
function findUnescapedSlashes(str) {
2746
var escapeNextChar = false;
2747
var slashes = [];
2748
for (var i = 0; i < str.length; i++) {
2749
var c = str.charAt(i);
2750
if (!escapeNextChar && c == '/') {
2751
slashes.push(i);
2752
}
2753
escapeNextChar = (c == '\\');
2754
}
2755
return slashes;
2756
}
2757
/**
2758
* Extract the regular expression from the query and return a Regexp object.
2759
* Returns null if the query is blank.
2760
* If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
2761
* If smartCase is passed in, and the query contains upper case letters,
2762
* then ignoreCase is overridden, and the 'i' flag will not be set.
2763
* If the query contains the /i in the flag part of the regular expression,
2764
* then both ignoreCase and smartCase are ignored, and 'i' will be passed
2765
* through to the Regex object.
2766
*/
2767
function parseQuery(query, ignoreCase, smartCase) {
2768
// Check if the query is already a regex.
2769
if (query instanceof RegExp) { return query; }
2770
// First try to extract regex + flags from the input. If no flags found,
2771
// extract just the regex. IE does not accept flags directly defined in
2772
// the regex string in the form /regex/flags
2773
var slashes = findUnescapedSlashes(query);
2774
var regexPart;
2775
var forceIgnoreCase;
2776
if (!slashes.length) {
2777
// Query looks like 'regexp'
2778
regexPart = query;
2779
} else {
2780
// Query looks like 'regexp/...'
2781
regexPart = query.substring(0, slashes[0]);
2782
var flagsPart = query.substring(slashes[0]);
2783
forceIgnoreCase = (flagsPart.indexOf('i') != -1);
2784
}
2785
if (!regexPart) {
2786
return null;
2787
}
2788
if (smartCase) {
2789
ignoreCase = (/^[^A-Z]*$/).test(regexPart);
2790
}
2791
var regexp = new RegExp(regexPart,
2792
(ignoreCase || forceIgnoreCase) ? 'i' : undefined);
2793
return regexp;
2794
}
2795
function showConfirm(cm, text) {
2796
if (cm.openNotification) {
2797
cm.openNotification('<span style="color: red">' + text + '</span>',
2798
{bottom: true, duration: 5000});
2799
} else {
2800
alert(text);
2801
}
2802
}
2803
function makePrompt(prefix, desc) {
2804
var raw = '';
2805
if (prefix) {
2806
raw += '<span style="font-family: monospace">' + prefix + '</span>';
2807
}
2808
raw += '<input type="text"/> ' +
2809
'<span style="color: #888">';
2810
if (desc) {
2811
raw += '<span style="color: #888">';
2812
raw += desc;
2813
raw += '</span>';
2814
}
2815
return raw;
2816
}
2817
var searchPromptDesc = '(Javascript regexp)';
2818
function showPrompt(cm, options) {
2819
var shortText = (options.prefix || '') + ' ' + (options.desc || '');
2820
var prompt = makePrompt(options.prefix, options.desc);
2821
dialog(cm, prompt, shortText, options.onClose, options);
2822
}
2823
function regexEqual(r1, r2) {
2824
if (r1 instanceof RegExp && r2 instanceof RegExp) {
2825
var props = ['global', 'multiline', 'ignoreCase', 'source'];
2826
for (var i = 0; i < props.length; i++) {
2827
var prop = props[i];
2828
if (r1[prop] !== r2[prop]) {
2829
return false;
2830
}
2831
}
2832
return true;
2833
}
2834
return false;
2835
}
2836
// Returns true if the query is valid.
2837
function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
2838
if (!rawQuery) {
2839
return;
2840
}
2841
var state = getSearchState(cm);
2842
var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
2843
if (!query) {
2844
return;
2845
}
2846
highlightSearchMatches(cm, query);
2847
if (regexEqual(query, state.getQuery())) {
2848
return query;
2849
}
2850
state.setQuery(query);
2851
return query;
2852
}
2853
function searchOverlay(query) {
2854
if (query.source.charAt(0) == '^') {
2855
var matchSol = true;
2856
}
2857
return {
2858
token: function(stream) {
2859
if (matchSol && !stream.sol()) {
2860
stream.skipToEnd();
2861
return;
2862
}
2863
var match = stream.match(query, false);
2864
if (match) {
2865
if (match[0].length == 0) {
2866
// Matched empty string, skip to next.
2867
stream.next();
2868
return 'searching';
2869
}
2870
if (!stream.sol()) {
2871
// Backtrack 1 to match \b
2872
stream.backUp(1);
2873
if (!query.exec(stream.next() + match[0])) {
2874
stream.next();
2875
return null;
2876
}
2877
}
2878
stream.match(query);
2879
return 'searching';
2880
}
2881
while (!stream.eol()) {
2882
stream.next();
2883
if (stream.match(query, false)) break;
2884
}
2885
},
2886
query: query
2887
};
2888
}
2889
function highlightSearchMatches(cm, query) {
2890
var overlay = getSearchState(cm).getOverlay();
2891
if (!overlay || query != overlay.query) {
2892
if (overlay) {
2893
cm.removeOverlay(overlay);
2894
}
2895
overlay = searchOverlay(query);
2896
cm.addOverlay(overlay);
2897
getSearchState(cm).setOverlay(overlay);
2898
}
2899
}
2900
function findNext(cm, prev, query, repeat) {
2901
if (repeat === undefined) { repeat = 1; }
2902
return cm.operation(function() {
2903
var pos = cm.getCursor();
2904
var cursor = cm.getSearchCursor(query, pos);
2905
for (var i = 0; i < repeat; i++) {
2906
var found = cursor.find(prev);
2907
if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
2908
if (!found) {
2909
// SearchCursor may have returned null because it hit EOF, wrap
2910
// around and try again.
2911
cursor = cm.getSearchCursor(query,
2912
(prev) ? { line: cm.lastLine() } : {line: cm.firstLine(), ch: 0} );
2913
if (!cursor.find(prev)) {
2914
return;
2915
}
2916
}
2917
}
2918
return cursor.from();
2919
});
2920
}
2921
function clearSearchHighlight(cm) {
2922
cm.removeOverlay(getSearchState(cm).getOverlay());
2923
getSearchState(cm).setOverlay(null);
2924
}
2925
/**
2926
* Check if pos is in the specified range, INCLUSIVE.
2927
* Range can be specified with 1 or 2 arguments.
2928
* If the first range argument is an array, treat it as an array of line
2929
* numbers. Match pos against any of the lines.
2930
* If the first range argument is a number,
2931
* if there is only 1 range argument, check if pos has the same line
2932
* number
2933
* if there are 2 range arguments, then check if pos is in between the two
2934
* range arguments.
2935
*/
2936
function isInRange(pos, start, end) {
2937
if (typeof pos != 'number') {
2938
// Assume it is a cursor position. Get the line number.
2939
pos = pos.line;
2940
}
2941
if (start instanceof Array) {
2942
return inArray(pos, start);
2943
} else {
2944
if (end) {
2945
return (pos >= start && pos <= end);
2946
} else {
2947
return pos == start;
2948
}
2949
}
2950
}
2951
function getUserVisibleLines(cm) {
2952
var scrollInfo = cm.getScrollInfo();
2953
var occludeToleranceTop = 6;
2954
var occludeToleranceBottom = 10;
2955
var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');
2956
var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;
2957
var to = cm.coordsChar({left:0, top: bottomY}, 'local');
2958
return {top: from.line, bottom: to.line};
2959
}
2960
2961
// Ex command handling
2962
// Care must be taken when adding to the default Ex command map. For any
2963
// pair of commands that have a shared prefix, at least one of their
2964
// shortNames must not match the prefix of the other command.
2965
var defaultExCommandMap = [
2966
{ name: 'map' },
2967
{ name: 'nmap', shortName: 'nm' },
2968
{ name: 'vmap', shortName: 'vm' },
2969
{ name: 'write', shortName: 'w' },
2970
{ name: 'undo', shortName: 'u' },
2971
{ name: 'redo', shortName: 'red' },
2972
{ name: 'sort', shortName: 'sor' },
2973
{ name: 'substitute', shortName: 's' },
2974
{ name: 'nohlsearch', shortName: 'noh' },
2975
{ name: 'delmarks', shortName: 'delm' }
2976
];
2977
Vim.ExCommandDispatcher = function() {
2978
this.buildCommandMap_();
2979
};
2980
Vim.ExCommandDispatcher.prototype = {
2981
processCommand: function(cm, input) {
2982
var vim = cm.state.vim;
2983
if (vim.visualMode) {
2984
exitVisualMode(cm);
2985
}
2986
var inputStream = new CodeMirror.StringStream(input);
2987
var params = {};
2988
params.input = input;
2989
try {
2990
this.parseInput_(cm, inputStream, params);
2991
} catch(e) {
2992
showConfirm(cm, e);
2993
return;
2994
}
2995
var commandName;
2996
if (!params.commandName) {
2997
// If only a line range is defined, move to the line.
2998
if (params.line !== undefined) {
2999
commandName = 'move';
3000
}
3001
} else {
3002
var command = this.matchCommand_(params.commandName);
3003
if (command) {
3004
commandName = command.name;
3005
this.parseCommandArgs_(inputStream, params, command);
3006
if (command.type == 'exToKey') {
3007
// Handle Ex to Key mapping.
3008
for (var i = 0; i < command.toKeys.length; i++) {
3009
CodeMirror.Vim.handleKey(cm, command.toKeys[i]);
3010
}
3011
return;
3012
} else if (command.type == 'exToEx') {
3013
// Handle Ex to Ex mapping.
3014
this.processCommand(cm, command.toInput);
3015
return;
3016
}
3017
}
3018
}
3019
if (!commandName) {
3020
showConfirm(cm, 'Not an editor command ":' + input + '"');
3021
return;
3022
}
3023
try {
3024
exCommands[commandName](cm, params);
3025
} catch(e) {
3026
showConfirm(cm, e);
3027
throw e;
3028
}
3029
},
3030
parseInput_: function(cm, inputStream, result) {
3031
inputStream.eatWhile(':');
3032
// Parse range.
3033
if (inputStream.eat('%')) {
3034
result.line = cm.firstLine();
3035
result.lineEnd = cm.lastLine();
3036
} else {
3037
result.line = this.parseLineSpec_(cm, inputStream);
3038
if (result.line !== undefined && inputStream.eat(',')) {
3039
result.lineEnd = this.parseLineSpec_(cm, inputStream);
3040
}
3041
}
3042
3043
// Parse command name.
3044
var commandMatch = inputStream.match(/^(\w+)/);
3045
if (commandMatch) {
3046
result.commandName = commandMatch[1];
3047
} else {
3048
result.commandName = inputStream.match(/.*/)[0];
3049
}
3050
3051
return result;
3052
},
3053
parseLineSpec_: function(cm, inputStream) {
3054
var numberMatch = inputStream.match(/^(\d+)/);
3055
if (numberMatch) {
3056
return parseInt(numberMatch[1], 10) - 1;
3057
}
3058
switch (inputStream.next()) {
3059
case '.':
3060
return cm.getCursor().line;
3061
case '$':
3062
return cm.lastLine();
3063
case '\'':
3064
var mark = cm.state.vim.marks[inputStream.next()];
3065
if (mark && mark.find()) {
3066
return mark.find().line;
3067
}
3068
throw new Error('Mark not set');
3069
default:
3070
inputStream.backUp(1);
3071
return undefined;
3072
}
3073
},
3074
parseCommandArgs_: function(inputStream, params, command) {
3075
if (inputStream.eol()) {
3076
return;
3077
}
3078
params.argString = inputStream.match(/.*/)[0];
3079
// Parse command-line arguments
3080
var delim = command.argDelimiter || /\s+/;
3081
var args = trim(params.argString).split(delim);
3082
if (args.length && args[0]) {
3083
params.args = args;
3084
}
3085
},
3086
matchCommand_: function(commandName) {
3087
// Return the command in the command map that matches the shortest
3088
// prefix of the passed in command name. The match is guaranteed to be
3089
// unambiguous if the defaultExCommandMap's shortNames are set up
3090
// correctly. (see @code{defaultExCommandMap}).
3091
for (var i = commandName.length; i > 0; i--) {
3092
var prefix = commandName.substring(0, i);
3093
if (this.commandMap_[prefix]) {
3094
var command = this.commandMap_[prefix];
3095
if (command.name.indexOf(commandName) === 0) {
3096
return command;
3097
}
3098
}
3099
}
3100
return null;
3101
},
3102
buildCommandMap_: function() {
3103
this.commandMap_ = {};
3104
for (var i = 0; i < defaultExCommandMap.length; i++) {
3105
var command = defaultExCommandMap[i];
3106
var key = command.shortName || command.name;
3107
this.commandMap_[key] = command;
3108
}
3109
},
3110
map: function(lhs, rhs, ctx) {
3111
if (lhs != ':' && lhs.charAt(0) == ':') {
3112
if (ctx) { throw Error('Mode not supported for ex mappings'); }
3113
var commandName = lhs.substring(1);
3114
if (rhs != ':' && rhs.charAt(0) == ':') {
3115
// Ex to Ex mapping
3116
this.commandMap_[commandName] = {
3117
name: commandName,
3118
type: 'exToEx',
3119
toInput: rhs.substring(1)
3120
};
3121
} else {
3122
// Ex to key mapping
3123
this.commandMap_[commandName] = {
3124
name: commandName,
3125
type: 'exToKey',
3126
toKeys: parseKeyString(rhs)
3127
};
3128
}
3129
} else {
3130
if (rhs != ':' && rhs.charAt(0) == ':') {
3131
// Key to Ex mapping.
3132
var mapping = {
3133
keys: parseKeyString(lhs),
3134
type: 'keyToEx',
3135
exArgs: { input: rhs.substring(1) }};
3136
if (ctx) { mapping.context = ctx; }
3137
defaultKeymap.unshift(mapping);
3138
} else {
3139
// Key to key mapping
3140
var mapping = {
3141
keys: parseKeyString(lhs),
3142
type: 'keyToKey',
3143
toKeys: parseKeyString(rhs)
3144
};
3145
if (ctx) { mapping.context = ctx; }
3146
defaultKeymap.unshift(mapping);
3147
}
3148
}
3149
}
3150
};
3151
3152
// Converts a key string sequence of the form a<C-w>bd<Left> into Vim's
3153
// keymap representation.
3154
function parseKeyString(str) {
3155
var key, match;
3156
var keys = [];
3157
while (str) {
3158
match = (/<\w+-.+?>|<\w+>|./).exec(str);
3159
if(match === null)break;
3160
key = match[0];
3161
str = str.substring(match.index + key.length);
3162
keys.push(key);
3163
}
3164
return keys;
3165
}
3166
3167
var exCommands = {
3168
map: function(cm, params, ctx) {
3169
var mapArgs = params.args;
3170
if (!mapArgs || mapArgs.length < 2) {
3171
if (cm) {
3172
showConfirm(cm, 'Invalid mapping: ' + params.input);
3173
}
3174
return;
3175
}
3176
exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
3177
},
3178
nmap: function(cm, params) { this.map(cm, params, 'normal'); },
3179
vmap: function(cm, params) { this.map(cm, params, 'visual'); },
3180
move: function(cm, params) {
3181
commandDispatcher.processCommand(cm, cm.state.vim, {
3182
type: 'motion',
3183
motion: 'moveToLineOrEdgeOfDocument',
3184
motionArgs: { forward: false, explicitRepeat: true,
3185
linewise: true },
3186
repeatOverride: params.line+1});
3187
},
3188
sort: function(cm, params) {
3189
var reverse, ignoreCase, unique, number;
3190
function parseArgs() {
3191
if (params.argString) {
3192
var args = new CodeMirror.StringStream(params.argString);
3193
if (args.eat('!')) { reverse = true; }
3194
if (args.eol()) { return; }
3195
if (!args.eatSpace()) { return 'Invalid arguments'; }
3196
var opts = args.match(/[a-z]+/);
3197
if (opts) {
3198
opts = opts[0];
3199
ignoreCase = opts.indexOf('i') != -1;
3200
unique = opts.indexOf('u') != -1;
3201
var decimal = opts.indexOf('d') != -1 && 1;
3202
var hex = opts.indexOf('x') != -1 && 1;
3203
var octal = opts.indexOf('o') != -1 && 1;
3204
if (decimal + hex + octal > 1) { return 'Invalid arguments'; }
3205
number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
3206
}
3207
if (args.eatSpace() && args.match(/\/.*\//)) { 'patterns not supported'; }
3208
}
3209
}
3210
var err = parseArgs();
3211
if (err) {
3212
showConfirm(cm, err + ': ' + params.argString);
3213
return;
3214
}
3215
var lineStart = params.line || cm.firstLine();
3216
var lineEnd = params.lineEnd || params.line || cm.lastLine();
3217
if (lineStart == lineEnd) { return; }
3218
var curStart = { line: lineStart, ch: 0 };
3219
var curEnd = { line: lineEnd, ch: lineLength(cm, lineEnd) };
3220
var text = cm.getRange(curStart, curEnd).split('\n');
3221
var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ :
3222
(number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
3223
(number == 'octal') ? /([0-7]+)/ : null;
3224
var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
3225
var numPart = [], textPart = [];
3226
if (number) {
3227
for (var i = 0; i < text.length; i++) {
3228
if (numberRegex.exec(text[i])) {
3229
numPart.push(text[i]);
3230
} else {
3231
textPart.push(text[i]);
3232
}
3233
}
3234
} else {
3235
textPart = text;
3236
}
3237
function compareFn(a, b) {
3238
if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
3239
if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
3240
var anum = number && numberRegex.exec(a);
3241
var bnum = number && numberRegex.exec(b);
3242
if (!anum) { return a < b ? -1 : 1; }
3243
anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
3244
bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
3245
return anum - bnum;
3246
}
3247
numPart.sort(compareFn);
3248
textPart.sort(compareFn);
3249
text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
3250
if (unique) { // Remove duplicate lines
3251
var textOld = text;
3252
var lastLine;
3253
text = [];
3254
for (var i = 0; i < textOld.length; i++) {
3255
if (textOld[i] != lastLine) {
3256
text.push(textOld[i]);
3257
}
3258
lastLine = textOld[i];
3259
}
3260
}
3261
cm.replaceRange(text.join('\n'), curStart, curEnd);
3262
},
3263
substitute: function(cm, params) {
3264
if (!cm.getSearchCursor) {
3265
throw new Error('Search feature not available. Requires searchcursor.js or ' +
3266
'any other getSearchCursor implementation.');
3267
}
3268
var argString = params.argString;
3269
var slashes = findUnescapedSlashes(argString);
3270
if (slashes[0] !== 0) {
3271
showConfirm(cm, 'Substitutions should be of the form ' +
3272
':s/pattern/replace/');
3273
return;
3274
}
3275
var regexPart = argString.substring(slashes[0] + 1, slashes[1]);
3276
var replacePart = '';
3277
var flagsPart;
3278
var count;
3279
var confirm = false; // Whether to confirm each replace.
3280
if (slashes[1]) {
3281
replacePart = argString.substring(slashes[1] + 1, slashes[2]);
3282
}
3283
if (slashes[2]) {
3284
// After the 3rd slash, we can have flags followed by a space followed
3285
// by count.
3286
var trailing = argString.substring(slashes[2] + 1).split(' ');
3287
flagsPart = trailing[0];
3288
count = parseInt(trailing[1]);
3289
}
3290
if (flagsPart) {
3291
if (flagsPart.indexOf('c') != -1) {
3292
confirm = true;
3293
flagsPart.replace('c', '');
3294
}
3295
regexPart = regexPart + '/' + flagsPart;
3296
}
3297
if (regexPart) {
3298
// If regex part is empty, then use the previous query. Otherwise use
3299
// the regex part as the new query.
3300
try {
3301
updateSearchQuery(cm, regexPart, true /** ignoreCase */,
3302
true /** smartCase */);
3303
} catch (e) {
3304
showConfirm(cm, 'Invalid regex: ' + regexPart);
3305
return;
3306
}
3307
}
3308
var state = getSearchState(cm);
3309
var query = state.getQuery();
3310
var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
3311
var lineEnd = params.lineEnd || lineStart;
3312
if (count) {
3313
lineStart = lineEnd;
3314
lineEnd = lineStart + count - 1;
3315
}
3316
var startPos = clipCursorToContent(cm, { line: lineStart, ch: 0 });
3317
var cursor = cm.getSearchCursor(query, startPos);
3318
doReplace(cm, confirm, lineStart, lineEnd, cursor, query, replacePart);
3319
},
3320
redo: CodeMirror.commands.redo,
3321
undo: CodeMirror.commands.undo,
3322
write: function(cm) {
3323
if (CodeMirror.commands.save) {
3324
// If a save command is defined, call it.
3325
CodeMirror.commands.save(cm);
3326
} else {
3327
// Saves to text area if no save command is defined.
3328
cm.save();
3329
}
3330
},
3331
nohlsearch: function(cm) {
3332
clearSearchHighlight(cm);
3333
},
3334
delmarks: function(cm, params) {
3335
if (!params.argString || !trim(params.argString)) {
3336
showConfirm(cm, 'Argument required');
3337
return;
3338
}
3339
3340
var state = cm.state.vim;
3341
var stream = new CodeMirror.StringStream(trim(params.argString));
3342
while (!stream.eol()) {
3343
stream.eatSpace();
3344
3345
// Record the streams position at the beginning of the loop for use
3346
// in error messages.
3347
var count = stream.pos;
3348
3349
if (!stream.match(/[a-zA-Z]/, false)) {
3350
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
3351
return;
3352
}
3353
3354
var sym = stream.next();
3355
// Check if this symbol is part of a range
3356
if (stream.match('-', true)) {
3357
// This symbol is part of a range.
3358
3359
// The range must terminate at an alphabetic character.
3360
if (!stream.match(/[a-zA-Z]/, false)) {
3361
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
3362
return;
3363
}
3364
3365
var startMark = sym;
3366
var finishMark = stream.next();
3367
// The range must terminate at an alphabetic character which
3368
// shares the same case as the start of the range.
3369
if (isLowerCase(startMark) && isLowerCase(finishMark) ||
3370
isUpperCase(startMark) && isUpperCase(finishMark)) {
3371
var start = startMark.charCodeAt(0);
3372
var finish = finishMark.charCodeAt(0);
3373
if (start >= finish) {
3374
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
3375
return;
3376
}
3377
3378
// Because marks are always ASCII values, and we have
3379
// determined that they are the same case, we can use
3380
// their char codes to iterate through the defined range.
3381
for (var j = 0; j <= finish - start; j++) {
3382
var mark = String.fromCharCode(start + j);
3383
delete state.marks[mark];
3384
}
3385
} else {
3386
showConfirm(cm, 'Invalid argument: ' + startMark + '-');
3387
return;
3388
}
3389
} else {
3390
// This symbol is a valid mark, and is not part of a range.
3391
delete state.marks[sym];
3392
}
3393
}
3394
}
3395
};
3396
3397
var exCommandDispatcher = new Vim.ExCommandDispatcher();
3398
3399
/**
3400
* @param {CodeMirror} cm CodeMirror instance we are in.
3401
* @param {boolean} confirm Whether to confirm each replace.
3402
* @param {Cursor} lineStart Line to start replacing from.
3403
* @param {Cursor} lineEnd Line to stop replacing at.
3404
* @param {RegExp} query Query for performing matches with.
3405
* @param {string} replaceWith Text to replace matches with. May contain $1,
3406
* $2, etc for replacing captured groups using Javascript replace.
3407
*/
3408
function doReplace(cm, confirm, lineStart, lineEnd, searchCursor, query,
3409
replaceWith) {
3410
// Set up all the functions.
3411
cm.state.vim.exMode = true;
3412
var done = false;
3413
var lastPos = searchCursor.from();
3414
function replaceAll() {
3415
cm.operation(function() {
3416
while (!done) {
3417
replace();
3418
next();
3419
}
3420
stop();
3421
});
3422
}
3423
function replace() {
3424
var text = cm.getRange(searchCursor.from(), searchCursor.to());
3425
var newText = text.replace(query, replaceWith);
3426
searchCursor.replace(newText);
3427
}
3428
function next() {
3429
var found = searchCursor.findNext();
3430
if (!found) {
3431
done = true;
3432
} else if (isInRange(searchCursor.from(), lineStart, lineEnd)) {
3433
cm.scrollIntoView(searchCursor.from(), 30);
3434
cm.setSelection(searchCursor.from(), searchCursor.to());
3435
lastPos = searchCursor.from();
3436
done = false;
3437
} else {
3438
done = true;
3439
}
3440
}
3441
function stop(close) {
3442
if (close) { close(); }
3443
cm.focus();
3444
if (lastPos) {
3445
cm.setCursor(lastPos);
3446
var vim = cm.state.vim;
3447
vim.exMode = false;
3448
vim.lastHPos = vim.lastHSPos = lastPos.ch;
3449
}
3450
}
3451
function onPromptKeyDown(e, _value, close) {
3452
// Swallow all keys.
3453
CodeMirror.e_stop(e);
3454
var keyName = CodeMirror.keyName(e);
3455
switch (keyName) {
3456
case 'Y':
3457
replace(); next(); break;
3458
case 'N':
3459
next(); break;
3460
case 'A':
3461
cm.operation(replaceAll); break;
3462
case 'L':
3463
replace();
3464
// fall through and exit.
3465
case 'Q':
3466
case 'Esc':
3467
case 'Ctrl-C':
3468
case 'Ctrl-[':
3469
stop(close);
3470
break;
3471
}
3472
if (done) { stop(close); }
3473
}
3474
3475
// Actually do replace.
3476
next();
3477
if (done) {
3478
showConfirm(cm, 'No matches for ' + query.source);
3479
return;
3480
}
3481
if (!confirm) {
3482
replaceAll();
3483
return;
3484
}
3485
showPrompt(cm, {
3486
prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',
3487
onKeyDown: onPromptKeyDown
3488
});
3489
}
3490
3491
// Register Vim with CodeMirror
3492
function buildVimKeyMap() {
3493
/**
3494
* Handle the raw key event from CodeMirror. Translate the
3495
* Shift + key modifier to the resulting letter, while preserving other
3496
* modifers.
3497
*/
3498
// TODO: Figure out a way to catch capslock.
3499
function cmKeyToVimKey(key, modifier) {
3500
var vimKey = key;
3501
if (isUpperCase(vimKey)) {
3502
// Convert to lower case if shift is not the modifier since the key
3503
// we get from CodeMirror is always upper case.
3504
if (modifier == 'Shift') {
3505
modifier = null;
3506
}
3507
else {
3508
vimKey = vimKey.toLowerCase();
3509
}
3510
}
3511
if (modifier) {
3512
// Vim will parse modifier+key combination as a single key.
3513
vimKey = modifier.charAt(0) + '-' + vimKey;
3514
}
3515
var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey];
3516
vimKey = specialKey ? specialKey : vimKey;
3517
vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey;
3518
return vimKey;
3519
}
3520
3521
// Closure to bind CodeMirror, key, modifier.
3522
function keyMapper(vimKey) {
3523
return function(cm) {
3524
CodeMirror.Vim.handleKey(cm, vimKey);
3525
};
3526
}
3527
3528
var cmToVimKeymap = {
3529
'nofallthrough': true,
3530
'style': 'fat-cursor'
3531
};
3532
function bindKeys(keys, modifier) {
3533
for (var i = 0; i < keys.length; i++) {
3534
var key = keys[i];
3535
if (!modifier && inArray(key, specialSymbols)) {
3536
// Wrap special symbols with '' because that's how CodeMirror binds
3537
// them.
3538
key = "'" + key + "'";
3539
}
3540
var vimKey = cmKeyToVimKey(keys[i], modifier);
3541
var cmKey = modifier ? modifier + '-' + key : key;
3542
cmToVimKeymap[cmKey] = keyMapper(vimKey);
3543
}
3544
}
3545
bindKeys(upperCaseAlphabet);
3546
bindKeys(upperCaseAlphabet, 'Shift');
3547
bindKeys(upperCaseAlphabet, 'Ctrl');
3548
bindKeys(specialSymbols);
3549
bindKeys(specialSymbols, 'Ctrl');
3550
bindKeys(numbers);
3551
bindKeys(numbers, 'Ctrl');
3552
bindKeys(specialKeys);
3553
bindKeys(specialKeys, 'Ctrl');
3554
return cmToVimKeymap;
3555
}
3556
CodeMirror.keyMap.vim = buildVimKeyMap();
3557
3558
function exitInsertMode(cm) {
3559
var vim = cm.state.vim;
3560
var inReplay = vimGlobalState.macroModeState.inReplay;
3561
if (!inReplay) {
3562
cm.off('change', onChange);
3563
cm.off('cursorActivity', onCursorActivity);
3564
CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
3565
}
3566
if (!inReplay && vim.insertModeRepeat > 1) {
3567
// Perform insert mode repeat for commands like 3,a and 3,o.
3568
repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
3569
true /** repeatForInsert */);
3570
vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
3571
}
3572
delete vim.insertModeRepeat;
3573
cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1, true);
3574
vim.insertMode = false;
3575
cm.setOption('keyMap', 'vim');
3576
cm.setOption('disableInput', true);
3577
cm.toggleOverwrite(false); // exit replace mode if we were in it.
3578
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
3579
}
3580
3581
CodeMirror.keyMap['vim-insert'] = {
3582
// TODO: override navigation keys so that Esc will cancel automatic
3583
// indentation from o, O, i_<CR>
3584
'Esc': exitInsertMode,
3585
'Ctrl-[': exitInsertMode,
3586
'Ctrl-C': exitInsertMode,
3587
'Ctrl-N': 'autocomplete',
3588
'Ctrl-P': 'autocomplete',
3589
'Enter': function(cm) {
3590
var fn = CodeMirror.commands.newlineAndIndentContinueComment ||
3591
CodeMirror.commands.newlineAndIndent;
3592
fn(cm);
3593
},
3594
fallthrough: ['default']
3595
};
3596
3597
CodeMirror.keyMap['vim-replace'] = {
3598
'Backspace': 'goCharLeft',
3599
fallthrough: ['vim-insert']
3600
};
3601
3602
function parseRegisterToKeyBuffer(macroModeState, registerName) {
3603
var match, key;
3604
var register = vimGlobalState.registerController.getRegister(registerName);
3605
var text = register.toString();
3606
var macroKeyBuffer = macroModeState.macroKeyBuffer;
3607
emptyMacroKeyBuffer(macroModeState);
3608
do {
3609
match = (/<\w+-.+?>|<\w+>|./).exec(text);
3610
if(match === null)break;
3611
key = match[0];
3612
text = text.substring(match.index + key.length);
3613
macroKeyBuffer.push(key);
3614
} while (text);
3615
return macroKeyBuffer;
3616
}
3617
3618
function parseKeyBufferToRegister(registerName, keyBuffer) {
3619
var text = keyBuffer.join('');
3620
vimGlobalState.registerController.setRegisterText(registerName, text);
3621
}
3622
3623
function emptyMacroKeyBuffer(macroModeState) {
3624
if(macroModeState.isMacroPlaying)return;
3625
var macroKeyBuffer = macroModeState.macroKeyBuffer;
3626
macroKeyBuffer.length = 0;
3627
}
3628
3629
function executeMacroKeyBuffer(cm, macroModeState, keyBuffer) {
3630
macroModeState.isMacroPlaying = true;
3631
for (var i = 0, len = keyBuffer.length; i < len; i++) {
3632
CodeMirror.Vim.handleKey(cm, keyBuffer[i]);
3633
};
3634
macroModeState.isMacroPlaying = false;
3635
}
3636
3637
function logKey(macroModeState, key) {
3638
if(macroModeState.isMacroPlaying)return;
3639
var macroKeyBuffer = macroModeState.macroKeyBuffer;
3640
macroKeyBuffer.push(key);
3641
}
3642
3643
/**
3644
* Listens for changes made in insert mode.
3645
* Should only be active in insert mode.
3646
*/
3647
function onChange(_cm, changeObj) {
3648
var macroModeState = vimGlobalState.macroModeState;
3649
var lastChange = macroModeState.lastInsertModeChanges;
3650
while (changeObj) {
3651
lastChange.expectCursorActivityForChange = true;
3652
if (changeObj.origin == '+input' || changeObj.origin == 'paste'
3653
|| changeObj.origin === undefined /* only in testing */) {
3654
var text = changeObj.text.join('\n');
3655
lastChange.changes.push(text);
3656
}
3657
// Change objects may be chained with next.
3658
changeObj = changeObj.next;
3659
}
3660
}
3661
3662
/**
3663
* Listens for any kind of cursor activity on CodeMirror.
3664
* - For tracking cursor activity in insert mode.
3665
* - Should only be active in insert mode.
3666
*/
3667
function onCursorActivity() {
3668
var macroModeState = vimGlobalState.macroModeState;
3669
var lastChange = macroModeState.lastInsertModeChanges;
3670
if (lastChange.expectCursorActivityForChange) {
3671
lastChange.expectCursorActivityForChange = false;
3672
} else {
3673
// Cursor moved outside the context of an edit. Reset the change.
3674
lastChange.changes = [];
3675
}
3676
}
3677
3678
/** Wrapper for special keys pressed in insert mode */
3679
function InsertModeKey(keyName) {
3680
this.keyName = keyName;
3681
}
3682
3683
/**
3684
* Handles raw key down events from the text area.
3685
* - Should only be active in insert mode.
3686
* - For recording deletes in insert mode.
3687
*/
3688
function onKeyEventTargetKeyDown(e) {
3689
var macroModeState = vimGlobalState.macroModeState;
3690
var lastChange = macroModeState.lastInsertModeChanges;
3691
var keyName = CodeMirror.keyName(e);
3692
function onKeyFound() {
3693
lastChange.changes.push(new InsertModeKey(keyName));
3694
return true;
3695
}
3696
if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
3697
CodeMirror.lookupKey(keyName, ['vim-insert'], onKeyFound);
3698
}
3699
}
3700
3701
/**
3702
* Repeats the last edit, which includes exactly 1 command and at most 1
3703
* insert. Operator and motion commands are read from lastEditInputState,
3704
* while action commands are read from lastEditActionCommand.
3705
*
3706
* If repeatForInsert is true, then the function was called by
3707
* exitInsertMode to repeat the insert mode changes the user just made. The
3708
* corresponding enterInsertMode call was made with a count.
3709
*/
3710
function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
3711
var macroModeState = vimGlobalState.macroModeState;
3712
macroModeState.inReplay = true;
3713
var isAction = !!vim.lastEditActionCommand;
3714
var cachedInputState = vim.inputState;
3715
function repeatCommand() {
3716
if (isAction) {
3717
commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
3718
} else {
3719
commandDispatcher.evalInput(cm, vim);
3720
}
3721
}
3722
function repeatInsert(repeat) {
3723
if (macroModeState.lastInsertModeChanges.changes.length > 0) {
3724
// For some reason, repeat cw in desktop VIM will does not repeat
3725
// insert mode changes. Will conform to that behavior.
3726
repeat = !vim.lastEditActionCommand ? 1 : repeat;
3727
repeatLastInsertModeChanges(cm, repeat, macroModeState);
3728
}
3729
}
3730
vim.inputState = vim.lastEditInputState;
3731
if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
3732
// o and O repeat have to be interlaced with insert repeats so that the
3733
// insertions appear on separate lines instead of the last line.
3734
for (var i = 0; i < repeat; i++) {
3735
repeatCommand();
3736
repeatInsert(1);
3737
}
3738
} else {
3739
if (!repeatForInsert) {
3740
// Hack to get the cursor to end up at the right place. If I is
3741
// repeated in insert mode repeat, cursor will be 1 insert
3742
// change set left of where it should be.
3743
repeatCommand();
3744
}
3745
repeatInsert(repeat);
3746
}
3747
vim.inputState = cachedInputState;
3748
if (vim.insertMode && !repeatForInsert) {
3749
// Don't exit insert mode twice. If repeatForInsert is set, then we
3750
// were called by an exitInsertMode call lower on the stack.
3751
exitInsertMode(cm);
3752
}
3753
macroModeState.inReplay = false;
3754
};
3755
3756
function repeatLastInsertModeChanges(cm, repeat, macroModeState) {
3757
var lastChange = macroModeState.lastInsertModeChanges;
3758
function keyHandler(binding) {
3759
if (typeof binding == 'string') {
3760
CodeMirror.commands[binding](cm);
3761
} else {
3762
binding(cm);
3763
}
3764
return true;
3765
}
3766
for (var i = 0; i < repeat; i++) {
3767
for (var j = 0; j < lastChange.changes.length; j++) {
3768
var change = lastChange.changes[j];
3769
if (change instanceof InsertModeKey) {
3770
CodeMirror.lookupKey(change.keyName, ['vim-insert'], keyHandler);
3771
} else {
3772
var cur = cm.getCursor();
3773
cm.replaceRange(change, cur, cur);
3774
}
3775
}
3776
}
3777
}
3778
3779
resetVimGlobalState();
3780
return vimApi;
3781
};
3782
// Initialize Vim and make it available as an API.
3783
CodeMirror.Vim = Vim();
3784
}
3785
)();
3786
3787