Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for KuCalc : devops.
Download
50665 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 null;
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
// TODO: lots of possible exceptions that can be thrown here. Try da(
1536
// outside of a () block.
1537
1538
// TODO: adding <> >< to this map doesn't work, presumably because
1539
// they're operators
1540
var mirroredPairs = {'(': ')', ')': '(',
1541
'{': '}', '}': '{',
1542
'[': ']', ']': '['};
1543
var selfPaired = {'\'': true, '"': true};
1544
1545
var character = motionArgs.selectedCharacter;
1546
1547
// Inclusive is the difference between a and i
1548
// TODO: Instead of using the additional text object map to perform text
1549
// object operations, merge the map into the defaultKeyMap and use
1550
// motionArgs to define behavior. Define separate entries for 'aw',
1551
// 'iw', 'a[', 'i[', etc.
1552
var inclusive = !motionArgs.textObjectInner;
1553
1554
var tmp;
1555
if (mirroredPairs[character]) {
1556
tmp = selectCompanionObject(cm, mirroredPairs[character], inclusive);
1557
} else if (selfPaired[character]) {
1558
tmp = findBeginningAndEnd(cm, character, inclusive);
1559
} else if (character === 'W') {
1560
tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
1561
true /** bigWord */);
1562
} else if (character === 'w') {
1563
tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
1564
false /** bigWord */);
1565
} else {
1566
// No text object defined for this, don't move.
1567
return null;
1568
}
1569
1570
return [tmp.start, tmp.end];
1571
},
1572
1573
repeatLastCharacterSearch: function(cm, motionArgs) {
1574
var lastSearch = vimGlobalState.lastChararacterSearch;
1575
var repeat = motionArgs.repeat;
1576
var forward = motionArgs.forward === lastSearch.forward;
1577
var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
1578
cm.moveH(-increment, 'char');
1579
motionArgs.inclusive = forward ? true : false;
1580
var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
1581
if (!curEnd) {
1582
cm.moveH(increment, 'char');
1583
return cm.getCursor();
1584
}
1585
curEnd.ch += increment;
1586
return curEnd;
1587
}
1588
};
1589
1590
var operators = {
1591
change: function(cm, operatorArgs, _vim, curStart, curEnd) {
1592
vimGlobalState.registerController.pushText(
1593
operatorArgs.registerName, 'change', cm.getRange(curStart, curEnd),
1594
operatorArgs.linewise);
1595
if (operatorArgs.linewise) {
1596
// Push the next line back down, if there is a next line.
1597
var replacement = curEnd.line > cm.lastLine() ? '' : '\n';
1598
cm.replaceRange(replacement, curStart, curEnd);
1599
cm.indentLine(curStart.line, 'smart');
1600
// null ch so setCursor moves to end of line.
1601
curStart.ch = null;
1602
} else {
1603
// Exclude trailing whitespace if the range is not all whitespace.
1604
var text = cm.getRange(curStart, curEnd);
1605
if (!isWhiteSpaceString(text)) {
1606
var match = (/\s+$/).exec(text);
1607
if (match) {
1608
curEnd = offsetCursor(curEnd, 0, - match[0].length);
1609
}
1610
}
1611
cm.replaceRange('', curStart, curEnd);
1612
}
1613
actions.enterInsertMode(cm, {}, cm.state.vim);
1614
cm.setCursor(curStart);
1615
},
1616
// delete is a javascript keyword.
1617
'delete': function(cm, operatorArgs, _vim, curStart, curEnd) {
1618
// If the ending line is past the last line, inclusive, instead of
1619
// including the trailing \n, include the \n before the starting line
1620
if (operatorArgs.linewise &&
1621
curEnd.line > cm.lastLine() && curStart.line > cm.firstLine()) {
1622
curStart.line--;
1623
curStart.ch = lineLength(cm, curStart.line);
1624
}
1625
vimGlobalState.registerController.pushText(
1626
operatorArgs.registerName, 'delete', cm.getRange(curStart, curEnd),
1627
operatorArgs.linewise);
1628
cm.replaceRange('', curStart, curEnd);
1629
if (operatorArgs.linewise) {
1630
cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
1631
} else {
1632
cm.setCursor(curStart);
1633
}
1634
},
1635
indent: function(cm, operatorArgs, vim, curStart, curEnd) {
1636
var startLine = curStart.line;
1637
var endLine = curEnd.line;
1638
// In visual mode, n> shifts the selection right n times, instead of
1639
// shifting n lines right once.
1640
var repeat = (vim.visualMode) ? operatorArgs.repeat : 1;
1641
if (operatorArgs.linewise) {
1642
// The only way to delete a newline is to delete until the start of
1643
// the next line, so in linewise mode evalInput will include the next
1644
// line. We don't want this in indent, so we go back a line.
1645
endLine--;
1646
}
1647
for (var i = startLine; i <= endLine; i++) {
1648
for (var j = 0; j < repeat; j++) {
1649
cm.indentLine(i, operatorArgs.indentRight);
1650
}
1651
}
1652
cm.setCursor(curStart);
1653
cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
1654
},
1655
swapcase: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
1656
var toSwap = cm.getRange(curStart, curEnd);
1657
var swapped = '';
1658
for (var i = 0; i < toSwap.length; i++) {
1659
var character = toSwap.charAt(i);
1660
swapped += isUpperCase(character) ? character.toLowerCase() :
1661
character.toUpperCase();
1662
}
1663
cm.replaceRange(swapped, curStart, curEnd);
1664
if (!operatorArgs.shouldMoveCursor) {
1665
cm.setCursor(curOriginal);
1666
}
1667
},
1668
yank: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
1669
vimGlobalState.registerController.pushText(
1670
operatorArgs.registerName, 'yank',
1671
cm.getRange(curStart, curEnd), operatorArgs.linewise);
1672
cm.setCursor(curOriginal);
1673
}
1674
};
1675
1676
var actions = {
1677
jumpListWalk: function(cm, actionArgs, vim) {
1678
if (vim.visualMode) {
1679
return;
1680
}
1681
var repeat = actionArgs.repeat;
1682
var forward = actionArgs.forward;
1683
var jumpList = vimGlobalState.jumpList;
1684
1685
var mark = jumpList.move(cm, forward ? repeat : -repeat);
1686
var markPos = mark ? mark.find() : undefined;
1687
markPos = markPos ? markPos : cm.getCursor();
1688
cm.setCursor(markPos);
1689
},
1690
scroll: function(cm, actionArgs, vim) {
1691
if (vim.visualMode) {
1692
return;
1693
}
1694
var repeat = actionArgs.repeat || 1;
1695
var lineHeight = cm.defaultTextHeight();
1696
var top = cm.getScrollInfo().top;
1697
var delta = lineHeight * repeat;
1698
var newPos = actionArgs.forward ? top + delta : top - delta;
1699
var cursor = cm.getCursor();
1700
var cursorCoords = cm.charCoords(cursor, 'local');
1701
if (actionArgs.forward) {
1702
if (newPos > cursorCoords.top) {
1703
cursor.line += (newPos - cursorCoords.top) / lineHeight;
1704
cursor.line = Math.ceil(cursor.line);
1705
cm.setCursor(cursor);
1706
cursorCoords = cm.charCoords(cursor, 'local');
1707
cm.scrollTo(null, cursorCoords.top);
1708
} else {
1709
// Cursor stays within bounds. Just reposition the scroll window.
1710
cm.scrollTo(null, newPos);
1711
}
1712
} else {
1713
var newBottom = newPos + cm.getScrollInfo().clientHeight;
1714
if (newBottom < cursorCoords.bottom) {
1715
cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
1716
cursor.line = Math.floor(cursor.line);
1717
cm.setCursor(cursor);
1718
cursorCoords = cm.charCoords(cursor, 'local');
1719
cm.scrollTo(
1720
null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
1721
} else {
1722
// Cursor stays within bounds. Just reposition the scroll window.
1723
cm.scrollTo(null, newPos);
1724
}
1725
}
1726
},
1727
scrollToCursor: function(cm, actionArgs) {
1728
var lineNum = cm.getCursor().line;
1729
var charCoords = cm.charCoords({line: lineNum, ch: 0}, 'local');
1730
var height = cm.getScrollInfo().clientHeight;
1731
var y = charCoords.top;
1732
var lineHeight = charCoords.bottom - y;
1733
switch (actionArgs.position) {
1734
case 'center': y = y - (height / 2) + lineHeight;
1735
break;
1736
case 'bottom': y = y - height + lineHeight*1.4;
1737
break;
1738
case 'top': y = y + lineHeight*0.4;
1739
break;
1740
}
1741
cm.scrollTo(null, y);
1742
},
1743
replayMacro: function(cm, actionArgs) {
1744
var registerName = actionArgs.selectedCharacter;
1745
var repeat = actionArgs.repeat;
1746
var macroModeState = vimGlobalState.macroModeState;
1747
if (registerName == '@') {
1748
registerName = macroModeState.latestRegister;
1749
}
1750
var keyBuffer = parseRegisterToKeyBuffer(macroModeState, registerName);
1751
while(repeat--){
1752
executeMacroKeyBuffer(cm, macroModeState, keyBuffer);
1753
}
1754
},
1755
exitMacroRecordMode: function() {
1756
var macroModeState = vimGlobalState.macroModeState;
1757
macroModeState.toggle();
1758
parseKeyBufferToRegister(macroModeState.latestRegister,
1759
macroModeState.macroKeyBuffer);
1760
},
1761
enterMacroRecordMode: function(cm, actionArgs) {
1762
var macroModeState = vimGlobalState.macroModeState;
1763
var registerName = actionArgs.selectedCharacter;
1764
macroModeState.toggle(cm, registerName);
1765
emptyMacroKeyBuffer(macroModeState);
1766
},
1767
enterInsertMode: function(cm, actionArgs, vim) {
1768
if (cm.getOption('readOnly')) { return; }
1769
vim.insertMode = true;
1770
vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
1771
var insertAt = (actionArgs) ? actionArgs.insertAt : null;
1772
if (insertAt == 'eol') {
1773
var cursor = cm.getCursor();
1774
cursor = { line: cursor.line, ch: lineLength(cm, cursor.line) };
1775
cm.setCursor(cursor);
1776
} else if (insertAt == 'charAfter') {
1777
cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
1778
} else if (insertAt == 'firstNonBlank') {
1779
cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
1780
}
1781
cm.setOption('keyMap', 'vim-insert');
1782
cm.setOption('disableInput', false);
1783
if (actionArgs && actionArgs.replace) {
1784
// Handle Replace-mode as a special case of insert mode.
1785
cm.toggleOverwrite(true);
1786
cm.setOption('keyMap', 'vim-replace');
1787
CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
1788
} else {
1789
cm.setOption('keyMap', 'vim-insert');
1790
CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
1791
}
1792
if (!vimGlobalState.macroModeState.inReplay) {
1793
// Only record if not replaying.
1794
cm.on('change', onChange);
1795
cm.on('cursorActivity', onCursorActivity);
1796
CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
1797
}
1798
},
1799
toggleVisualMode: function(cm, actionArgs, vim) {
1800
var repeat = actionArgs.repeat;
1801
var curStart = cm.getCursor();
1802
var curEnd;
1803
// TODO: The repeat should actually select number of characters/lines
1804
// equal to the repeat times the size of the previous visual
1805
// operation.
1806
if (!vim.visualMode) {
1807
cm.on('mousedown', exitVisualMode);
1808
vim.visualMode = true;
1809
vim.visualLine = !!actionArgs.linewise;
1810
if (vim.visualLine) {
1811
curStart.ch = 0;
1812
curEnd = clipCursorToContent(cm, {
1813
line: curStart.line + repeat - 1,
1814
ch: lineLength(cm, curStart.line)
1815
}, true /** includeLineBreak */);
1816
} else {
1817
curEnd = clipCursorToContent(cm, {
1818
line: curStart.line,
1819
ch: curStart.ch + repeat
1820
}, true /** includeLineBreak */);
1821
}
1822
// Make the initial selection.
1823
if (!actionArgs.repeatIsExplicit && !vim.visualLine) {
1824
// This is a strange case. Here the implicit repeat is 1. The
1825
// following commands lets the cursor hover over the 1 character
1826
// selection.
1827
cm.setCursor(curEnd);
1828
cm.setSelection(curEnd, curStart);
1829
} else {
1830
cm.setSelection(curStart, curEnd);
1831
}
1832
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : ""});
1833
} else {
1834
curStart = cm.getCursor('anchor');
1835
curEnd = cm.getCursor('head');
1836
if (!vim.visualLine && actionArgs.linewise) {
1837
// Shift-V pressed in characterwise visual mode. Switch to linewise
1838
// visual mode instead of exiting visual mode.
1839
vim.visualLine = true;
1840
curStart.ch = cursorIsBefore(curStart, curEnd) ? 0 :
1841
lineLength(cm, curStart.line);
1842
curEnd.ch = cursorIsBefore(curStart, curEnd) ?
1843
lineLength(cm, curEnd.line) : 0;
1844
cm.setSelection(curStart, curEnd);
1845
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: "linewise"});
1846
} else if (vim.visualLine && !actionArgs.linewise) {
1847
// v pressed in linewise visual mode. Switch to characterwise visual
1848
// mode instead of exiting visual mode.
1849
vim.visualLine = false;
1850
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
1851
} else {
1852
exitVisualMode(cm);
1853
}
1854
}
1855
updateMark(cm, vim, '<', cursorIsBefore(curStart, curEnd) ? curStart
1856
: curEnd);
1857
updateMark(cm, vim, '>', cursorIsBefore(curStart, curEnd) ? curEnd
1858
: curStart);
1859
},
1860
joinLines: function(cm, actionArgs, vim) {
1861
var curStart, curEnd;
1862
if (vim.visualMode) {
1863
curStart = cm.getCursor('anchor');
1864
curEnd = cm.getCursor('head');
1865
curEnd.ch = lineLength(cm, curEnd.line) - 1;
1866
} else {
1867
// Repeat is the number of lines to join. Minimum 2 lines.
1868
var repeat = Math.max(actionArgs.repeat, 2);
1869
curStart = cm.getCursor();
1870
curEnd = clipCursorToContent(cm, { line: curStart.line + repeat - 1,
1871
ch: Infinity });
1872
}
1873
var finalCh = 0;
1874
cm.operation(function() {
1875
for (var i = curStart.line; i < curEnd.line; i++) {
1876
finalCh = lineLength(cm, curStart.line);
1877
var tmp = { line: curStart.line + 1,
1878
ch: lineLength(cm, curStart.line + 1) };
1879
var text = cm.getRange(curStart, tmp);
1880
text = text.replace(/\n\s*/g, ' ');
1881
cm.replaceRange(text, curStart, tmp);
1882
}
1883
var curFinalPos = { line: curStart.line, ch: finalCh };
1884
cm.setCursor(curFinalPos);
1885
});
1886
},
1887
newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
1888
vim.insertMode = true;
1889
var insertAt = cm.getCursor();
1890
if (insertAt.line === cm.firstLine() && !actionArgs.after) {
1891
// Special case for inserting newline before start of document.
1892
cm.replaceRange('\n', { line: cm.firstLine(), ch: 0 });
1893
cm.setCursor(cm.firstLine(), 0);
1894
} else {
1895
insertAt.line = (actionArgs.after) ? insertAt.line :
1896
insertAt.line - 1;
1897
insertAt.ch = lineLength(cm, insertAt.line);
1898
cm.setCursor(insertAt);
1899
var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
1900
CodeMirror.commands.newlineAndIndent;
1901
newlineFn(cm);
1902
}
1903
this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
1904
},
1905
paste: function(cm, actionArgs) {
1906
var cur = cm.getCursor();
1907
var register = vimGlobalState.registerController.getRegister(
1908
actionArgs.registerName);
1909
if (!register.text) {
1910
return;
1911
}
1912
for (var text = '', i = 0; i < actionArgs.repeat; i++) {
1913
text += register.text;
1914
}
1915
var linewise = register.linewise;
1916
if (linewise) {
1917
if (actionArgs.after) {
1918
// Move the newline at the end to the start instead, and paste just
1919
// before the newline character of the line we are on right now.
1920
text = '\n' + text.slice(0, text.length - 1);
1921
cur.ch = lineLength(cm, cur.line);
1922
} else {
1923
cur.ch = 0;
1924
}
1925
} else {
1926
cur.ch += actionArgs.after ? 1 : 0;
1927
}
1928
cm.replaceRange(text, cur);
1929
// Now fine tune the cursor to where we want it.
1930
var curPosFinal;
1931
var idx;
1932
if (linewise && actionArgs.after) {
1933
curPosFinal = { line: cur.line + 1,
1934
ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)) };
1935
} else if (linewise && !actionArgs.after) {
1936
curPosFinal = { line: cur.line,
1937
ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)) };
1938
} else if (!linewise && actionArgs.after) {
1939
idx = cm.indexFromPos(cur);
1940
curPosFinal = cm.posFromIndex(idx + text.length - 1);
1941
} else {
1942
idx = cm.indexFromPos(cur);
1943
curPosFinal = cm.posFromIndex(idx + text.length);
1944
}
1945
cm.setCursor(curPosFinal);
1946
},
1947
undo: function(cm, actionArgs) {
1948
cm.operation(function() {
1949
repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
1950
cm.setCursor(cm.getCursor('anchor'));
1951
});
1952
},
1953
redo: function(cm, actionArgs) {
1954
repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
1955
},
1956
setRegister: function(_cm, actionArgs, vim) {
1957
vim.inputState.registerName = actionArgs.selectedCharacter;
1958
},
1959
setMark: function(cm, actionArgs, vim) {
1960
var markName = actionArgs.selectedCharacter;
1961
updateMark(cm, vim, markName, cm.getCursor());
1962
},
1963
replace: function(cm, actionArgs, vim) {
1964
var replaceWith = actionArgs.selectedCharacter;
1965
var curStart = cm.getCursor();
1966
var replaceTo;
1967
var curEnd;
1968
if(vim.visualMode){
1969
curStart=cm.getCursor('start');
1970
curEnd=cm.getCursor('end');
1971
// workaround to catch the character under the cursor
1972
// existing workaround doesn't cover actions
1973
curEnd=cm.clipPos({line: curEnd.line, ch: curEnd.ch+1});
1974
}else{
1975
var line = cm.getLine(curStart.line);
1976
replaceTo = curStart.ch + actionArgs.repeat;
1977
if (replaceTo > line.length) {
1978
replaceTo=line.length;
1979
}
1980
curEnd = { line: curStart.line, ch: replaceTo };
1981
}
1982
if(replaceWith=='\n'){
1983
if(!vim.visualMode) cm.replaceRange('', curStart, curEnd);
1984
// special case, where vim help says to replace by just one line-break
1985
(CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
1986
}else {
1987
var replaceWithStr=cm.getRange(curStart, curEnd);
1988
//replace all characters in range by selected, but keep linebreaks
1989
replaceWithStr=replaceWithStr.replace(/[^\n]/g,replaceWith);
1990
cm.replaceRange(replaceWithStr, curStart, curEnd);
1991
if(vim.visualMode){
1992
cm.setCursor(curStart);
1993
exitVisualMode(cm);
1994
}else{
1995
cm.setCursor(offsetCursor(curEnd, 0, -1));
1996
}
1997
}
1998
},
1999
incrementNumberToken: function(cm, actionArgs) {
2000
var cur = cm.getCursor();
2001
var lineStr = cm.getLine(cur.line);
2002
var re = /-?\d+/g;
2003
var match;
2004
var start;
2005
var end;
2006
var numberStr;
2007
var token;
2008
while ((match = re.exec(lineStr)) !== null) {
2009
token = match[0];
2010
start = match.index;
2011
end = start + token.length;
2012
if(cur.ch < end)break;
2013
}
2014
if(!actionArgs.backtrack && (end <= cur.ch))return;
2015
if (token) {
2016
var increment = actionArgs.increase ? 1 : -1;
2017
var number = parseInt(token) + (increment * actionArgs.repeat);
2018
var from = {ch:start, line:cur.line};
2019
var to = {ch:end, line:cur.line};
2020
numberStr = number.toString();
2021
cm.replaceRange(numberStr, from, to);
2022
} else {
2023
return;
2024
}
2025
cm.setCursor({line: cur.line, ch: start + numberStr.length - 1});
2026
},
2027
repeatLastEdit: function(cm, actionArgs, vim) {
2028
var lastEditInputState = vim.lastEditInputState;
2029
if (!lastEditInputState) { return; }
2030
var repeat = actionArgs.repeat;
2031
if (repeat && actionArgs.repeatIsExplicit) {
2032
vim.lastEditInputState.repeatOverride = repeat;
2033
} else {
2034
repeat = vim.lastEditInputState.repeatOverride || repeat;
2035
}
2036
repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
2037
}
2038
};
2039
2040
/*
2041
* Below are miscellaneous utility functions used by vim.js
2042
*/
2043
2044
/**
2045
* Clips cursor to ensure that line is within the buffer's range
2046
* If includeLineBreak is true, then allow cur.ch == lineLength.
2047
*/
2048
function clipCursorToContent(cm, cur, includeLineBreak) {
2049
var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
2050
var maxCh = lineLength(cm, line) - 1;
2051
maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
2052
var ch = Math.min(Math.max(0, cur.ch), maxCh);
2053
return { line: line, ch: ch };
2054
}
2055
function copyArgs(args) {
2056
var ret = {};
2057
for (var prop in args) {
2058
if (args.hasOwnProperty(prop)) {
2059
ret[prop] = args[prop];
2060
}
2061
}
2062
return ret;
2063
}
2064
function offsetCursor(cur, offsetLine, offsetCh) {
2065
return { line: cur.line + offsetLine, ch: cur.ch + offsetCh };
2066
}
2067
function matchKeysPartial(pressed, mapped) {
2068
for (var i = 0; i < pressed.length; i++) {
2069
// 'character' means any character. For mark, register commads, etc.
2070
if (pressed[i] != mapped[i] && mapped[i] != 'character') {
2071
return false;
2072
}
2073
}
2074
return true;
2075
}
2076
function repeatFn(cm, fn, repeat) {
2077
return function() {
2078
for (var i = 0; i < repeat; i++) {
2079
fn(cm);
2080
}
2081
};
2082
}
2083
function copyCursor(cur) {
2084
return { line: cur.line, ch: cur.ch };
2085
}
2086
function cursorEqual(cur1, cur2) {
2087
return cur1.ch == cur2.ch && cur1.line == cur2.line;
2088
}
2089
function cursorIsBefore(cur1, cur2) {
2090
if (cur1.line < cur2.line) {
2091
return true;
2092
}
2093
if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
2094
return true;
2095
}
2096
return false;
2097
}
2098
function cusrorIsBetween(cur1, cur2, cur3) {
2099
// returns true if cur2 is between cur1 and cur3.
2100
var cur1before2 = cursorIsBefore(cur1, cur2);
2101
var cur2before3 = cursorIsBefore(cur2, cur3);
2102
return cur1before2 && cur2before3;
2103
}
2104
function lineLength(cm, lineNum) {
2105
return cm.getLine(lineNum).length;
2106
}
2107
function reverse(s){
2108
return s.split('').reverse().join('');
2109
}
2110
function trim(s) {
2111
if (s.trim) {
2112
return s.trim();
2113
}
2114
return s.replace(/^\s+|\s+$/g, '');
2115
}
2116
function escapeRegex(s) {
2117
return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
2118
}
2119
2120
function exitVisualMode(cm) {
2121
cm.off('mousedown', exitVisualMode);
2122
var vim = cm.state.vim;
2123
vim.visualMode = false;
2124
vim.visualLine = false;
2125
var selectionStart = cm.getCursor('anchor');
2126
var selectionEnd = cm.getCursor('head');
2127
if (!cursorEqual(selectionStart, selectionEnd)) {
2128
// Clear the selection and set the cursor only if the selection has not
2129
// already been cleared. Otherwise we risk moving the cursor somewhere
2130
// it's not supposed to be.
2131
cm.setCursor(clipCursorToContent(cm, selectionEnd));
2132
}
2133
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
2134
}
2135
2136
// Remove any trailing newlines from the selection. For
2137
// example, with the caret at the start of the last word on the line,
2138
// 'dw' should word, but not the newline, while 'w' should advance the
2139
// caret to the first character of the next line.
2140
function clipToLine(cm, curStart, curEnd) {
2141
var selection = cm.getRange(curStart, curEnd);
2142
// Only clip if the selection ends with trailing newline + whitespace
2143
if (/\n\s*$/.test(selection)) {
2144
var lines = selection.split('\n');
2145
// We know this is all whitepsace.
2146
lines.pop();
2147
2148
// Cases:
2149
// 1. Last word is an empty line - do not clip the trailing '\n'
2150
// 2. Last word is not an empty line - clip the trailing '\n'
2151
var line;
2152
// Find the line containing the last word, and clip all whitespace up
2153
// to it.
2154
for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
2155
curEnd.line--;
2156
curEnd.ch = 0;
2157
}
2158
// If the last word is not an empty line, clip an additional newline
2159
if (line) {
2160
curEnd.line--;
2161
curEnd.ch = lineLength(cm, curEnd.line);
2162
} else {
2163
curEnd.ch = 0;
2164
}
2165
}
2166
}
2167
2168
// Expand the selection to line ends.
2169
function expandSelectionToLine(_cm, curStart, curEnd) {
2170
curStart.ch = 0;
2171
curEnd.ch = 0;
2172
curEnd.line++;
2173
}
2174
2175
function findFirstNonWhiteSpaceCharacter(text) {
2176
if (!text) {
2177
return 0;
2178
}
2179
var firstNonWS = text.search(/\S/);
2180
return firstNonWS == -1 ? text.length : firstNonWS;
2181
}
2182
2183
function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
2184
var cur = cm.getCursor();
2185
var line = cm.getLine(cur.line);
2186
var idx = cur.ch;
2187
2188
// Seek to first word or non-whitespace character, depending on if
2189
// noSymbol is true.
2190
var textAfterIdx = line.substring(idx);
2191
var firstMatchedChar;
2192
if (noSymbol) {
2193
firstMatchedChar = textAfterIdx.search(/\w/);
2194
} else {
2195
firstMatchedChar = textAfterIdx.search(/\S/);
2196
}
2197
if (firstMatchedChar == -1) {
2198
return null;
2199
}
2200
idx += firstMatchedChar;
2201
textAfterIdx = line.substring(idx);
2202
var textBeforeIdx = line.substring(0, idx);
2203
2204
var matchRegex;
2205
// Greedy matchers for the "word" we are trying to expand.
2206
if (bigWord) {
2207
matchRegex = /^\S+/;
2208
} else {
2209
if ((/\w/).test(line.charAt(idx))) {
2210
matchRegex = /^\w+/;
2211
} else {
2212
matchRegex = /^[^\w\s]+/;
2213
}
2214
}
2215
2216
var wordAfterRegex = matchRegex.exec(textAfterIdx);
2217
var wordStart = idx;
2218
var wordEnd = idx + wordAfterRegex[0].length;
2219
// TODO: Find a better way to do this. It will be slow on very long lines.
2220
var revTextBeforeIdx = reverse(textBeforeIdx);
2221
var wordBeforeRegex = matchRegex.exec(revTextBeforeIdx);
2222
if (wordBeforeRegex) {
2223
wordStart -= wordBeforeRegex[0].length;
2224
}
2225
2226
if (inclusive) {
2227
// If present, trim all whitespace after word.
2228
// Otherwise, trim all whitespace before word.
2229
var textAfterWordEnd = line.substring(wordEnd);
2230
var whitespacesAfterWord = textAfterWordEnd.match(/^\s*/)[0].length;
2231
if (whitespacesAfterWord > 0) {
2232
wordEnd += whitespacesAfterWord;
2233
} else {
2234
var revTrim = revTextBeforeIdx.length - wordStart;
2235
var textBeforeWordStart = revTextBeforeIdx.substring(revTrim);
2236
var whitespacesBeforeWord = textBeforeWordStart.match(/^\s*/)[0].length;
2237
wordStart -= whitespacesBeforeWord;
2238
}
2239
}
2240
2241
return { start: { line: cur.line, ch: wordStart },
2242
end: { line: cur.line, ch: wordEnd }};
2243
}
2244
2245
function recordJumpPosition(cm, oldCur, newCur) {
2246
if(!cursorEqual(oldCur, newCur)) {
2247
vimGlobalState.jumpList.add(cm, oldCur, newCur);
2248
}
2249
}
2250
2251
function recordLastCharacterSearch(increment, args) {
2252
vimGlobalState.lastChararacterSearch.increment = increment;
2253
vimGlobalState.lastChararacterSearch.forward = args.forward;
2254
vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter;
2255
}
2256
2257
var symbolToMode = {
2258
'(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
2259
'[': 'section', ']': 'section',
2260
'*': 'comment', '/': 'comment',
2261
'm': 'method', 'M': 'method',
2262
'#': 'preprocess'
2263
};
2264
var findSymbolModes = {
2265
bracket: {
2266
isComplete: function(state) {
2267
if (state.nextCh === state.symb) {
2268
state.depth++;
2269
if(state.depth >= 1)return true;
2270
} else if (state.nextCh === state.reverseSymb) {
2271
state.depth--;
2272
}
2273
return false;
2274
}
2275
},
2276
section: {
2277
init: function(state) {
2278
state.curMoveThrough = true;
2279
state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
2280
},
2281
isComplete: function(state) {
2282
return state.index === 0 && state.nextCh === state.symb;
2283
}
2284
},
2285
comment: {
2286
isComplete: function(state) {
2287
var found = state.lastCh === '*' && state.nextCh === '/';
2288
state.lastCh = state.nextCh;
2289
return found;
2290
}
2291
},
2292
// TODO: The original Vim implementation only operates on level 1 and 2.
2293
// The current implementation doesn't check for code block level and
2294
// therefore it operates on any levels.
2295
method: {
2296
init: function(state) {
2297
state.symb = (state.symb === 'm' ? '{' : '}');
2298
state.reverseSymb = state.symb === '{' ? '}' : '{';
2299
},
2300
isComplete: function(state) {
2301
if(state.nextCh === state.symb)return true;
2302
return false;
2303
}
2304
},
2305
preprocess: {
2306
init: function(state) {
2307
state.index = 0;
2308
},
2309
isComplete: function(state) {
2310
if (state.nextCh === '#') {
2311
var token = state.lineText.match(/#(\w+)/)[1];
2312
if (token === 'endif') {
2313
if (state.forward && state.depth === 0) {
2314
return true;
2315
}
2316
state.depth++;
2317
} else if (token === 'if') {
2318
if (!state.forward && state.depth === 0) {
2319
return true;
2320
}
2321
state.depth--;
2322
}
2323
if(token === 'else' && state.depth === 0)return true;
2324
}
2325
return false;
2326
}
2327
}
2328
};
2329
function findSymbol(cm, repeat, forward, symb) {
2330
var cur = cm.getCursor();
2331
var increment = forward ? 1 : -1;
2332
var endLine = forward ? cm.lineCount() : -1;
2333
var curCh = cur.ch;
2334
var line = cur.line;
2335
var lineText = cm.getLine(line);
2336
var state = {
2337
lineText: lineText,
2338
nextCh: lineText.charAt(curCh),
2339
lastCh: null,
2340
index: curCh,
2341
symb: symb,
2342
reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
2343
forward: forward,
2344
depth: 0,
2345
curMoveThrough: false
2346
};
2347
var mode = symbolToMode[symb];
2348
if(!mode)return cur;
2349
var init = findSymbolModes[mode].init;
2350
var isComplete = findSymbolModes[mode].isComplete;
2351
if(init)init(state);
2352
while (line !== endLine && repeat) {
2353
state.index += increment;
2354
state.nextCh = state.lineText.charAt(state.index);
2355
if (!state.nextCh) {
2356
line += increment;
2357
state.lineText = cm.getLine(line) || '';
2358
if (increment > 0) {
2359
state.index = 0;
2360
} else {
2361
var lineLen = state.lineText.length;
2362
state.index = (lineLen > 0) ? (lineLen-1) : 0;
2363
}
2364
state.nextCh = state.lineText.charAt(state.index);
2365
}
2366
if (isComplete(state)) {
2367
cur.line = line;
2368
cur.ch = state.index;
2369
repeat--;
2370
}
2371
}
2372
if (state.nextCh || state.curMoveThrough) {
2373
return { line: line, ch: state.index };
2374
}
2375
return cur;
2376
}
2377
2378
/*
2379
* Returns the boundaries of the next word. If the cursor in the middle of
2380
* the word, then returns the boundaries of the current word, starting at
2381
* the cursor. If the cursor is at the start/end of a word, and we are going
2382
* forward/backward, respectively, find the boundaries of the next word.
2383
*
2384
* @param {CodeMirror} cm CodeMirror object.
2385
* @param {Cursor} cur The cursor position.
2386
* @param {boolean} forward True to search forward. False to search
2387
* backward.
2388
* @param {boolean} bigWord True if punctuation count as part of the word.
2389
* False if only [a-zA-Z0-9] characters count as part of the word.
2390
* @param {boolean} emptyLineIsWord True if empty lines should be treated
2391
* as words.
2392
* @return {Object{from:number, to:number, line: number}} The boundaries of
2393
* the word, or null if there are no more words.
2394
*/
2395
function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
2396
var lineNum = cur.line;
2397
var pos = cur.ch;
2398
var line = cm.getLine(lineNum);
2399
var dir = forward ? 1 : -1;
2400
var regexps = bigWord ? bigWordRegexp : wordRegexp;
2401
2402
if (emptyLineIsWord && line == '') {
2403
lineNum += dir;
2404
line = cm.getLine(lineNum);
2405
if (!isLine(cm, lineNum)) {
2406
return null;
2407
}
2408
pos = (forward) ? 0 : line.length;
2409
}
2410
2411
while (true) {
2412
if (emptyLineIsWord && line == '') {
2413
return { from: 0, to: 0, line: lineNum };
2414
}
2415
var stop = (dir > 0) ? line.length : -1;
2416
var wordStart = stop, wordEnd = stop;
2417
// Find bounds of next word.
2418
while (pos != stop) {
2419
var foundWord = false;
2420
for (var i = 0; i < regexps.length && !foundWord; ++i) {
2421
if (regexps[i].test(line.charAt(pos))) {
2422
wordStart = pos;
2423
// Advance to end of word.
2424
while (pos != stop && regexps[i].test(line.charAt(pos))) {
2425
pos += dir;
2426
}
2427
wordEnd = pos;
2428
foundWord = wordStart != wordEnd;
2429
if (wordStart == cur.ch && lineNum == cur.line &&
2430
wordEnd == wordStart + dir) {
2431
// We started at the end of a word. Find the next one.
2432
continue;
2433
} else {
2434
return {
2435
from: Math.min(wordStart, wordEnd + 1),
2436
to: Math.max(wordStart, wordEnd),
2437
line: lineNum };
2438
}
2439
}
2440
}
2441
if (!foundWord) {
2442
pos += dir;
2443
}
2444
}
2445
// Advance to next/prev line.
2446
lineNum += dir;
2447
if (!isLine(cm, lineNum)) {
2448
return null;
2449
}
2450
line = cm.getLine(lineNum);
2451
pos = (dir > 0) ? 0 : line.length;
2452
}
2453
// Should never get here.
2454
throw new Error('The impossible happened.');
2455
}
2456
2457
/**
2458
* @param {CodeMirror} cm CodeMirror object.
2459
* @param {int} repeat Number of words to move past.
2460
* @param {boolean} forward True to search forward. False to search
2461
* backward.
2462
* @param {boolean} wordEnd True to move to end of word. False to move to
2463
* beginning of word.
2464
* @param {boolean} bigWord True if punctuation count as part of the word.
2465
* False if only alphabet characters count as part of the word.
2466
* @return {Cursor} The position the cursor should move to.
2467
*/
2468
function moveToWord(cm, repeat, forward, wordEnd, bigWord) {
2469
var cur = cm.getCursor();
2470
var curStart = copyCursor(cur);
2471
var words = [];
2472
if (forward && !wordEnd || !forward && wordEnd) {
2473
repeat++;
2474
}
2475
// For 'e', empty lines are not considered words, go figure.
2476
var emptyLineIsWord = !(forward && wordEnd);
2477
for (var i = 0; i < repeat; i++) {
2478
var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
2479
if (!word) {
2480
var eodCh = lineLength(cm, cm.lastLine());
2481
words.push(forward
2482
? {line: cm.lastLine(), from: eodCh, to: eodCh}
2483
: {line: 0, from: 0, to: 0});
2484
break;
2485
}
2486
words.push(word);
2487
cur = {line: word.line, ch: forward ? (word.to - 1) : word.from};
2488
}
2489
var shortCircuit = words.length != repeat;
2490
var firstWord = words[0];
2491
var lastWord = words.pop();
2492
if (forward && !wordEnd) {
2493
// w
2494
if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
2495
// We did not start in the middle of a word. Discard the extra word at the end.
2496
lastWord = words.pop();
2497
}
2498
return {line: lastWord.line, ch: lastWord.from};
2499
} else if (forward && wordEnd) {
2500
return {line: lastWord.line, ch: lastWord.to - 1};
2501
} else if (!forward && wordEnd) {
2502
// ge
2503
if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
2504
// We did not start in the middle of a word. Discard the extra word at the end.
2505
lastWord = words.pop();
2506
}
2507
return {line: lastWord.line, ch: lastWord.to};
2508
} else {
2509
// b
2510
return {line: lastWord.line, ch: lastWord.from};
2511
}
2512
}
2513
2514
function moveToCharacter(cm, repeat, forward, character) {
2515
var cur = cm.getCursor();
2516
var start = cur.ch;
2517
var idx;
2518
for (var i = 0; i < repeat; i ++) {
2519
var line = cm.getLine(cur.line);
2520
idx = charIdxInLine(start, line, character, forward, true);
2521
if (idx == -1) {
2522
return null;
2523
}
2524
start = idx;
2525
}
2526
return { line: cm.getCursor().line, ch: idx };
2527
}
2528
2529
function moveToColumn(cm, repeat) {
2530
// repeat is always >= 1, so repeat - 1 always corresponds
2531
// to the column we want to go to.
2532
var line = cm.getCursor().line;
2533
return clipCursorToContent(cm, { line: line, ch: repeat - 1 });
2534
}
2535
2536
function updateMark(cm, vim, markName, pos) {
2537
if (!inArray(markName, validMarks)) {
2538
return;
2539
}
2540
if (vim.marks[markName]) {
2541
vim.marks[markName].clear();
2542
}
2543
vim.marks[markName] = cm.setBookmark(pos);
2544
}
2545
2546
function charIdxInLine(start, line, character, forward, includeChar) {
2547
// Search for char in line.
2548
// motion_options: {forward, includeChar}
2549
// If includeChar = true, include it too.
2550
// If forward = true, search forward, else search backwards.
2551
// If char is not found on this line, do nothing
2552
var idx;
2553
if (forward) {
2554
idx = line.indexOf(character, start + 1);
2555
if (idx != -1 && !includeChar) {
2556
idx -= 1;
2557
}
2558
} else {
2559
idx = line.lastIndexOf(character, start - 1);
2560
if (idx != -1 && !includeChar) {
2561
idx += 1;
2562
}
2563
}
2564
return idx;
2565
}
2566
2567
function getContextLevel(ctx) {
2568
return (ctx === 'string' || ctx === 'comment') ? 1 : 0;
2569
}
2570
2571
function findMatchedSymbol(cm, cur, symb) {
2572
var line = cur.line;
2573
var ch = cur.ch;
2574
symb = symb ? symb : cm.getLine(line).charAt(ch);
2575
2576
var symbContext = cm.getTokenAt({line:line, ch:ch+1}).type;
2577
var symbCtxLevel = getContextLevel(symbContext);
2578
2579
var reverseSymb = ({
2580
'(': ')', ')': '(',
2581
'[': ']', ']': '[',
2582
'{': '}', '}': '{'})[symb];
2583
2584
// Couldn't find a matching symbol, abort
2585
if (!reverseSymb) {
2586
return cur;
2587
}
2588
2589
// set our increment to move forward (+1) or backwards (-1)
2590
// depending on which bracket we're matching
2591
var increment = ({'(': 1, '{': 1, '[': 1})[symb] || -1;
2592
var endLine = increment === 1 ? cm.lineCount() : -1;
2593
var depth = 1, nextCh = symb, index = ch, lineText = cm.getLine(line);
2594
// Simple search for closing paren--just count openings and closings till
2595
// we find our match
2596
// TODO: use info from CodeMirror to ignore closing brackets in comments
2597
// and quotes, etc.
2598
while (line !== endLine && depth > 0) {
2599
index += increment;
2600
nextCh = lineText.charAt(index);
2601
if (!nextCh) {
2602
line += increment;
2603
lineText = cm.getLine(line) || '';
2604
if (increment > 0) {
2605
index = 0;
2606
} else {
2607
var lineLen = lineText.length;
2608
index = (lineLen > 0) ? (lineLen-1) : 0;
2609
}
2610
nextCh = lineText.charAt(index);
2611
}
2612
var revSymbContext = cm.getTokenAt({line:line, ch:index+1}).type;
2613
var revSymbCtxLevel = getContextLevel(revSymbContext);
2614
if (symbCtxLevel >= revSymbCtxLevel) {
2615
if (nextCh === symb) {
2616
depth++;
2617
} else if (nextCh === reverseSymb) {
2618
depth--;
2619
}
2620
}
2621
}
2622
2623
if (nextCh) {
2624
return { line: line, ch: index };
2625
}
2626
return cur;
2627
}
2628
2629
// TODO: perhaps this finagling of start and end positions belonds
2630
// in codmirror/replaceRange?
2631
function selectCompanionObject(cm, revSymb, inclusive) {
2632
var cur = cm.getCursor();
2633
var end = findMatchedSymbol(cm, cur, revSymb);
2634
var start = findMatchedSymbol(cm, end);
2635
2636
if((start.line == end.line && start.ch > end.ch)
2637
|| (start.line > end.line)) {
2638
var tmp = start;
2639
start = end;
2640
end = tmp;
2641
}
2642
2643
if(inclusive) {
2644
end.ch += 1;
2645
} else {
2646
start.ch += 1;
2647
}
2648
2649
return { start: start, end: end };
2650
}
2651
2652
// Takes in a symbol and a cursor and tries to simulate text objects that
2653
// have identical opening and closing symbols
2654
// TODO support across multiple lines
2655
function findBeginningAndEnd(cm, symb, inclusive) {
2656
var cur = cm.getCursor();
2657
var line = cm.getLine(cur.line);
2658
var chars = line.split('');
2659
var start, end, i, len;
2660
var firstIndex = chars.indexOf(symb);
2661
2662
// the decision tree is to always look backwards for the beginning first,
2663
// but if the cursor is in front of the first instance of the symb,
2664
// then move the cursor forward
2665
if (cur.ch < firstIndex) {
2666
cur.ch = firstIndex;
2667
// Why is this line even here???
2668
// cm.setCursor(cur.line, firstIndex+1);
2669
}
2670
// otherwise if the cursor is currently on the closing symbol
2671
else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
2672
end = cur.ch; // assign end to the current cursor
2673
--cur.ch; // make sure to look backwards
2674
}
2675
2676
// if we're currently on the symbol, we've got a start
2677
if (chars[cur.ch] == symb && !end) {
2678
start = cur.ch + 1; // assign start to ahead of the cursor
2679
} else {
2680
// go backwards to find the start
2681
for (i = cur.ch; i > -1 && !start; i--) {
2682
if (chars[i] == symb) {
2683
start = i + 1;
2684
}
2685
}
2686
}
2687
2688
// look forwards for the end symbol
2689
if (start && !end) {
2690
for (i = start, len = chars.length; i < len && !end; i++) {
2691
if (chars[i] == symb) {
2692
end = i;
2693
}
2694
}
2695
}
2696
2697
// nothing found
2698
if (!start || !end) {
2699
return { start: cur, end: cur };
2700
}
2701
2702
// include the symbols
2703
if (inclusive) {
2704
--start; ++end;
2705
}
2706
2707
return {
2708
start: { line: cur.line, ch: start },
2709
end: { line: cur.line, ch: end }
2710
};
2711
}
2712
2713
// Search functions
2714
function SearchState() {}
2715
SearchState.prototype = {
2716
getQuery: function() {
2717
return vimGlobalState.query;
2718
},
2719
setQuery: function(query) {
2720
vimGlobalState.query = query;
2721
},
2722
getOverlay: function() {
2723
return this.searchOverlay;
2724
},
2725
setOverlay: function(overlay) {
2726
this.searchOverlay = overlay;
2727
},
2728
isReversed: function() {
2729
return vimGlobalState.isReversed;
2730
},
2731
setReversed: function(reversed) {
2732
vimGlobalState.isReversed = reversed;
2733
}
2734
};
2735
function getSearchState(cm) {
2736
var vim = cm.state.vim;
2737
return vim.searchState_ || (vim.searchState_ = new SearchState());
2738
}
2739
function dialog(cm, template, shortText, onClose, options) {
2740
if (cm.openDialog) {
2741
cm.openDialog(template, onClose, { bottom: true, value: options.value,
2742
onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp });
2743
}
2744
else {
2745
onClose(prompt(shortText, ''));
2746
}
2747
}
2748
2749
function findUnescapedSlashes(str) {
2750
var escapeNextChar = false;
2751
var slashes = [];
2752
for (var i = 0; i < str.length; i++) {
2753
var c = str.charAt(i);
2754
if (!escapeNextChar && c == '/') {
2755
slashes.push(i);
2756
}
2757
escapeNextChar = !escapeNextChar && (c == '\\');
2758
}
2759
return slashes;
2760
}
2761
2762
// Translates a search string from ex (vim) syntax into javascript form.
2763
function fixRegex(str) {
2764
// When these match, add a '\' if unescaped or remove one if escaped.
2765
var specials = ['|', '(', ')', '{'];
2766
// Remove, but never add, a '\' for these.
2767
var unescape = ['}'];
2768
var escapeNextChar = false;
2769
var out = [];
2770
for (var i = -1; i < str.length; i++) {
2771
var c = str.charAt(i) || '';
2772
var n = str.charAt(i+1) || '';
2773
var specialComesNext = (specials.indexOf(n) != -1);
2774
if (escapeNextChar) {
2775
if (c !== '\\' || !specialComesNext) {
2776
out.push(c);
2777
}
2778
escapeNextChar = false;
2779
} else {
2780
if (c === '\\') {
2781
escapeNextChar = true;
2782
// Treat the unescape list as special for removing, but not adding '\'.
2783
if (unescape.indexOf(n) != -1) {
2784
specialComesNext = true;
2785
}
2786
// Not passing this test means removing a '\'.
2787
if (!specialComesNext || n === '\\') {
2788
out.push(c);
2789
}
2790
} else {
2791
out.push(c);
2792
if (specialComesNext && n !== '\\') {
2793
out.push('\\');
2794
}
2795
}
2796
}
2797
}
2798
return out.join('');
2799
}
2800
2801
// Translates the replace part of a search and replace from ex (vim) syntax into
2802
// javascript form. Similar to fixRegex, but additionally fixes back references
2803
// (translates '\[0..9]' to '$[0..9]') and follows different rules for escaping '$'.
2804
function fixRegexReplace(str) {
2805
var escapeNextChar = false;
2806
var out = [];
2807
for (var i = -1; i < str.length; i++) {
2808
var c = str.charAt(i) || '';
2809
var n = str.charAt(i+1) || '';
2810
if (escapeNextChar) {
2811
out.push(c);
2812
escapeNextChar = false;
2813
} else {
2814
if (c === '\\') {
2815
escapeNextChar = true;
2816
if ((isNumber(n) || n === '$')) {
2817
out.push('$');
2818
} else if (n !== '/' && n !== '\\') {
2819
out.push('\\');
2820
}
2821
} else {
2822
if (c === '$') {
2823
out.push('$');
2824
}
2825
out.push(c);
2826
if (n === '/') {
2827
out.push('\\');
2828
}
2829
}
2830
}
2831
}
2832
return out.join('');
2833
}
2834
2835
/**
2836
* Extract the regular expression from the query and return a Regexp object.
2837
* Returns null if the query is blank.
2838
* If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
2839
* If smartCase is passed in, and the query contains upper case letters,
2840
* then ignoreCase is overridden, and the 'i' flag will not be set.
2841
* If the query contains the /i in the flag part of the regular expression,
2842
* then both ignoreCase and smartCase are ignored, and 'i' will be passed
2843
* through to the Regex object.
2844
*/
2845
function parseQuery(query, ignoreCase, smartCase) {
2846
// Check if the query is already a regex.
2847
if (query instanceof RegExp) { return query; }
2848
// First try to extract regex + flags from the input. If no flags found,
2849
// extract just the regex. IE does not accept flags directly defined in
2850
// the regex string in the form /regex/flags
2851
var slashes = findUnescapedSlashes(query);
2852
var regexPart;
2853
var forceIgnoreCase;
2854
if (!slashes.length) {
2855
// Query looks like 'regexp'
2856
regexPart = query;
2857
} else {
2858
// Query looks like 'regexp/...'
2859
regexPart = query.substring(0, slashes[0]);
2860
var flagsPart = query.substring(slashes[0]);
2861
forceIgnoreCase = (flagsPart.indexOf('i') != -1);
2862
}
2863
if (!regexPart) {
2864
return null;
2865
}
2866
regexPart = fixRegex(regexPart);
2867
if (smartCase) {
2868
ignoreCase = (/^[^A-Z]*$/).test(regexPart);
2869
}
2870
var regexp = new RegExp(regexPart,
2871
(ignoreCase || forceIgnoreCase) ? 'i' : undefined);
2872
return regexp;
2873
}
2874
function showConfirm(cm, text) {
2875
if (cm.openNotification) {
2876
cm.openNotification('<span style="color: red">' + text + '</span>',
2877
{bottom: true, duration: 5000});
2878
} else {
2879
alert(text);
2880
}
2881
}
2882
function makePrompt(prefix, desc) {
2883
var raw = '';
2884
if (prefix) {
2885
raw += '<span style="font-family: monospace">' + prefix + '</span>';
2886
}
2887
raw += '<input type="text"/> ' +
2888
'<span style="color: #888">';
2889
if (desc) {
2890
raw += '<span style="color: #888">';
2891
raw += desc;
2892
raw += '</span>';
2893
}
2894
return raw;
2895
}
2896
var searchPromptDesc = '(Javascript regexp)';
2897
function showPrompt(cm, options) {
2898
var shortText = (options.prefix || '') + ' ' + (options.desc || '');
2899
var prompt = makePrompt(options.prefix, options.desc);
2900
dialog(cm, prompt, shortText, options.onClose, options);
2901
}
2902
function regexEqual(r1, r2) {
2903
if (r1 instanceof RegExp && r2 instanceof RegExp) {
2904
var props = ['global', 'multiline', 'ignoreCase', 'source'];
2905
for (var i = 0; i < props.length; i++) {
2906
var prop = props[i];
2907
if (r1[prop] !== r2[prop]) {
2908
return false;
2909
}
2910
}
2911
return true;
2912
}
2913
return false;
2914
}
2915
// Returns true if the query is valid.
2916
function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
2917
if (!rawQuery) {
2918
return;
2919
}
2920
var state = getSearchState(cm);
2921
var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
2922
if (!query) {
2923
return;
2924
}
2925
highlightSearchMatches(cm, query);
2926
if (regexEqual(query, state.getQuery())) {
2927
return query;
2928
}
2929
state.setQuery(query);
2930
return query;
2931
}
2932
function searchOverlay(query) {
2933
if (query.source.charAt(0) == '^') {
2934
var matchSol = true;
2935
}
2936
return {
2937
token: function(stream) {
2938
if (matchSol && !stream.sol()) {
2939
stream.skipToEnd();
2940
return;
2941
}
2942
var match = stream.match(query, false);
2943
if (match) {
2944
if (match[0].length == 0) {
2945
// Matched empty string, skip to next.
2946
stream.next();
2947
return 'searching';
2948
}
2949
if (!stream.sol()) {
2950
// Backtrack 1 to match \b
2951
stream.backUp(1);
2952
if (!query.exec(stream.next() + match[0])) {
2953
stream.next();
2954
return null;
2955
}
2956
}
2957
stream.match(query);
2958
return 'searching';
2959
}
2960
while (!stream.eol()) {
2961
stream.next();
2962
if (stream.match(query, false)) break;
2963
}
2964
},
2965
query: query
2966
};
2967
}
2968
function highlightSearchMatches(cm, query) {
2969
var overlay = getSearchState(cm).getOverlay();
2970
if (!overlay || query != overlay.query) {
2971
if (overlay) {
2972
cm.removeOverlay(overlay);
2973
}
2974
overlay = searchOverlay(query);
2975
cm.addOverlay(overlay);
2976
getSearchState(cm).setOverlay(overlay);
2977
}
2978
}
2979
function findNext(cm, prev, query, repeat) {
2980
if (repeat === undefined) { repeat = 1; }
2981
return cm.operation(function() {
2982
var pos = cm.getCursor();
2983
var cursor = cm.getSearchCursor(query, pos);
2984
for (var i = 0; i < repeat; i++) {
2985
var found = cursor.find(prev);
2986
if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
2987
if (!found) {
2988
// SearchCursor may have returned null because it hit EOF, wrap
2989
// around and try again.
2990
cursor = cm.getSearchCursor(query,
2991
(prev) ? { line: cm.lastLine() } : {line: cm.firstLine(), ch: 0} );
2992
if (!cursor.find(prev)) {
2993
return;
2994
}
2995
}
2996
}
2997
return cursor.from();
2998
});
2999
}
3000
function clearSearchHighlight(cm) {
3001
cm.removeOverlay(getSearchState(cm).getOverlay());
3002
getSearchState(cm).setOverlay(null);
3003
}
3004
/**
3005
* Check if pos is in the specified range, INCLUSIVE.
3006
* Range can be specified with 1 or 2 arguments.
3007
* If the first range argument is an array, treat it as an array of line
3008
* numbers. Match pos against any of the lines.
3009
* If the first range argument is a number,
3010
* if there is only 1 range argument, check if pos has the same line
3011
* number
3012
* if there are 2 range arguments, then check if pos is in between the two
3013
* range arguments.
3014
*/
3015
function isInRange(pos, start, end) {
3016
if (typeof pos != 'number') {
3017
// Assume it is a cursor position. Get the line number.
3018
pos = pos.line;
3019
}
3020
if (start instanceof Array) {
3021
return inArray(pos, start);
3022
} else {
3023
if (end) {
3024
return (pos >= start && pos <= end);
3025
} else {
3026
return pos == start;
3027
}
3028
}
3029
}
3030
function getUserVisibleLines(cm) {
3031
var scrollInfo = cm.getScrollInfo();
3032
var occludeToleranceTop = 6;
3033
var occludeToleranceBottom = 10;
3034
var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');
3035
var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;
3036
var to = cm.coordsChar({left:0, top: bottomY}, 'local');
3037
return {top: from.line, bottom: to.line};
3038
}
3039
3040
// Ex command handling
3041
// Care must be taken when adding to the default Ex command map. For any
3042
// pair of commands that have a shared prefix, at least one of their
3043
// shortNames must not match the prefix of the other command.
3044
var defaultExCommandMap = [
3045
{ name: 'map' },
3046
{ name: 'nmap', shortName: 'nm' },
3047
{ name: 'vmap', shortName: 'vm' },
3048
{ name: 'write', shortName: 'w' },
3049
{ name: 'undo', shortName: 'u' },
3050
{ name: 'redo', shortName: 'red' },
3051
{ name: 'sort', shortName: 'sor' },
3052
{ name: 'substitute', shortName: 's' },
3053
{ name: 'nohlsearch', shortName: 'noh' },
3054
{ name: 'delmarks', shortName: 'delm' }
3055
];
3056
Vim.ExCommandDispatcher = function() {
3057
this.buildCommandMap_();
3058
};
3059
Vim.ExCommandDispatcher.prototype = {
3060
processCommand: function(cm, input) {
3061
var vim = cm.state.vim;
3062
if (vim.visualMode) {
3063
exitVisualMode(cm);
3064
}
3065
var inputStream = new CodeMirror.StringStream(input);
3066
var params = {};
3067
params.input = input;
3068
try {
3069
this.parseInput_(cm, inputStream, params);
3070
} catch(e) {
3071
showConfirm(cm, e);
3072
return;
3073
}
3074
var commandName;
3075
if (!params.commandName) {
3076
// If only a line range is defined, move to the line.
3077
if (params.line !== undefined) {
3078
commandName = 'move';
3079
}
3080
} else {
3081
var command = this.matchCommand_(params.commandName);
3082
if (command) {
3083
commandName = command.name;
3084
this.parseCommandArgs_(inputStream, params, command);
3085
if (command.type == 'exToKey') {
3086
// Handle Ex to Key mapping.
3087
for (var i = 0; i < command.toKeys.length; i++) {
3088
CodeMirror.Vim.handleKey(cm, command.toKeys[i]);
3089
}
3090
return;
3091
} else if (command.type == 'exToEx') {
3092
// Handle Ex to Ex mapping.
3093
this.processCommand(cm, command.toInput);
3094
return;
3095
}
3096
}
3097
}
3098
if (!commandName) {
3099
showConfirm(cm, 'Not an editor command ":' + input + '"');
3100
return;
3101
}
3102
try {
3103
exCommands[commandName](cm, params);
3104
} catch(e) {
3105
showConfirm(cm, e);
3106
throw e;
3107
}
3108
},
3109
parseInput_: function(cm, inputStream, result) {
3110
inputStream.eatWhile(':');
3111
// Parse range.
3112
if (inputStream.eat('%')) {
3113
result.line = cm.firstLine();
3114
result.lineEnd = cm.lastLine();
3115
} else {
3116
result.line = this.parseLineSpec_(cm, inputStream);
3117
if (result.line !== undefined && inputStream.eat(',')) {
3118
result.lineEnd = this.parseLineSpec_(cm, inputStream);
3119
}
3120
}
3121
3122
// Parse command name.
3123
var commandMatch = inputStream.match(/^(\w+)/);
3124
if (commandMatch) {
3125
result.commandName = commandMatch[1];
3126
} else {
3127
result.commandName = inputStream.match(/.*/)[0];
3128
}
3129
3130
return result;
3131
},
3132
parseLineSpec_: function(cm, inputStream) {
3133
var numberMatch = inputStream.match(/^(\d+)/);
3134
if (numberMatch) {
3135
return parseInt(numberMatch[1], 10) - 1;
3136
}
3137
switch (inputStream.next()) {
3138
case '.':
3139
return cm.getCursor().line;
3140
case '$':
3141
return cm.lastLine();
3142
case '\'':
3143
var mark = cm.state.vim.marks[inputStream.next()];
3144
if (mark && mark.find()) {
3145
return mark.find().line;
3146
}
3147
throw new Error('Mark not set');
3148
default:
3149
inputStream.backUp(1);
3150
return undefined;
3151
}
3152
},
3153
parseCommandArgs_: function(inputStream, params, command) {
3154
if (inputStream.eol()) {
3155
return;
3156
}
3157
params.argString = inputStream.match(/.*/)[0];
3158
// Parse command-line arguments
3159
var delim = command.argDelimiter || /\s+/;
3160
var args = trim(params.argString).split(delim);
3161
if (args.length && args[0]) {
3162
params.args = args;
3163
}
3164
},
3165
matchCommand_: function(commandName) {
3166
// Return the command in the command map that matches the shortest
3167
// prefix of the passed in command name. The match is guaranteed to be
3168
// unambiguous if the defaultExCommandMap's shortNames are set up
3169
// correctly. (see @code{defaultExCommandMap}).
3170
for (var i = commandName.length; i > 0; i--) {
3171
var prefix = commandName.substring(0, i);
3172
if (this.commandMap_[prefix]) {
3173
var command = this.commandMap_[prefix];
3174
if (command.name.indexOf(commandName) === 0) {
3175
return command;
3176
}
3177
}
3178
}
3179
return null;
3180
},
3181
buildCommandMap_: function() {
3182
this.commandMap_ = {};
3183
for (var i = 0; i < defaultExCommandMap.length; i++) {
3184
var command = defaultExCommandMap[i];
3185
var key = command.shortName || command.name;
3186
this.commandMap_[key] = command;
3187
}
3188
},
3189
map: function(lhs, rhs, ctx) {
3190
if (lhs != ':' && lhs.charAt(0) == ':') {
3191
if (ctx) { throw Error('Mode not supported for ex mappings'); }
3192
var commandName = lhs.substring(1);
3193
if (rhs != ':' && rhs.charAt(0) == ':') {
3194
// Ex to Ex mapping
3195
this.commandMap_[commandName] = {
3196
name: commandName,
3197
type: 'exToEx',
3198
toInput: rhs.substring(1)
3199
};
3200
} else {
3201
// Ex to key mapping
3202
this.commandMap_[commandName] = {
3203
name: commandName,
3204
type: 'exToKey',
3205
toKeys: parseKeyString(rhs)
3206
};
3207
}
3208
} else {
3209
if (rhs != ':' && rhs.charAt(0) == ':') {
3210
// Key to Ex mapping.
3211
var mapping = {
3212
keys: parseKeyString(lhs),
3213
type: 'keyToEx',
3214
exArgs: { input: rhs.substring(1) }};
3215
if (ctx) { mapping.context = ctx; }
3216
defaultKeymap.unshift(mapping);
3217
} else {
3218
// Key to key mapping
3219
var mapping = {
3220
keys: parseKeyString(lhs),
3221
type: 'keyToKey',
3222
toKeys: parseKeyString(rhs)
3223
};
3224
if (ctx) { mapping.context = ctx; }
3225
defaultKeymap.unshift(mapping);
3226
}
3227
}
3228
}
3229
};
3230
3231
// Converts a key string sequence of the form a<C-w>bd<Left> into Vim's
3232
// keymap representation.
3233
function parseKeyString(str) {
3234
var key, match;
3235
var keys = [];
3236
while (str) {
3237
match = (/<\w+-.+?>|<\w+>|./).exec(str);
3238
if(match === null)break;
3239
key = match[0];
3240
str = str.substring(match.index + key.length);
3241
keys.push(key);
3242
}
3243
return keys;
3244
}
3245
3246
var exCommands = {
3247
map: function(cm, params, ctx) {
3248
var mapArgs = params.args;
3249
if (!mapArgs || mapArgs.length < 2) {
3250
if (cm) {
3251
showConfirm(cm, 'Invalid mapping: ' + params.input);
3252
}
3253
return;
3254
}
3255
exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
3256
},
3257
nmap: function(cm, params) { this.map(cm, params, 'normal'); },
3258
vmap: function(cm, params) { this.map(cm, params, 'visual'); },
3259
move: function(cm, params) {
3260
commandDispatcher.processCommand(cm, cm.state.vim, {
3261
type: 'motion',
3262
motion: 'moveToLineOrEdgeOfDocument',
3263
motionArgs: { forward: false, explicitRepeat: true,
3264
linewise: true },
3265
repeatOverride: params.line+1});
3266
},
3267
sort: function(cm, params) {
3268
var reverse, ignoreCase, unique, number;
3269
function parseArgs() {
3270
if (params.argString) {
3271
var args = new CodeMirror.StringStream(params.argString);
3272
if (args.eat('!')) { reverse = true; }
3273
if (args.eol()) { return; }
3274
if (!args.eatSpace()) { return 'Invalid arguments'; }
3275
var opts = args.match(/[a-z]+/);
3276
if (opts) {
3277
opts = opts[0];
3278
ignoreCase = opts.indexOf('i') != -1;
3279
unique = opts.indexOf('u') != -1;
3280
var decimal = opts.indexOf('d') != -1 && 1;
3281
var hex = opts.indexOf('x') != -1 && 1;
3282
var octal = opts.indexOf('o') != -1 && 1;
3283
if (decimal + hex + octal > 1) { return 'Invalid arguments'; }
3284
number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
3285
}
3286
if (args.eatSpace() && args.match(/\/.*\//)) { 'patterns not supported'; }
3287
}
3288
}
3289
var err = parseArgs();
3290
if (err) {
3291
showConfirm(cm, err + ': ' + params.argString);
3292
return;
3293
}
3294
var lineStart = params.line || cm.firstLine();
3295
var lineEnd = params.lineEnd || params.line || cm.lastLine();
3296
if (lineStart == lineEnd) { return; }
3297
var curStart = { line: lineStart, ch: 0 };
3298
var curEnd = { line: lineEnd, ch: lineLength(cm, lineEnd) };
3299
var text = cm.getRange(curStart, curEnd).split('\n');
3300
var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ :
3301
(number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
3302
(number == 'octal') ? /([0-7]+)/ : null;
3303
var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
3304
var numPart = [], textPart = [];
3305
if (number) {
3306
for (var i = 0; i < text.length; i++) {
3307
if (numberRegex.exec(text[i])) {
3308
numPart.push(text[i]);
3309
} else {
3310
textPart.push(text[i]);
3311
}
3312
}
3313
} else {
3314
textPart = text;
3315
}
3316
function compareFn(a, b) {
3317
if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
3318
if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
3319
var anum = number && numberRegex.exec(a);
3320
var bnum = number && numberRegex.exec(b);
3321
if (!anum) { return a < b ? -1 : 1; }
3322
anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
3323
bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
3324
return anum - bnum;
3325
}
3326
numPart.sort(compareFn);
3327
textPart.sort(compareFn);
3328
text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
3329
if (unique) { // Remove duplicate lines
3330
var textOld = text;
3331
var lastLine;
3332
text = [];
3333
for (var i = 0; i < textOld.length; i++) {
3334
if (textOld[i] != lastLine) {
3335
text.push(textOld[i]);
3336
}
3337
lastLine = textOld[i];
3338
}
3339
}
3340
cm.replaceRange(text.join('\n'), curStart, curEnd);
3341
},
3342
substitute: function(cm, params) {
3343
if (!cm.getSearchCursor) {
3344
throw new Error('Search feature not available. Requires searchcursor.js or ' +
3345
'any other getSearchCursor implementation.');
3346
}
3347
var argString = params.argString;
3348
var slashes = findUnescapedSlashes(argString);
3349
if (slashes[0] !== 0) {
3350
showConfirm(cm, 'Substitutions should be of the form ' +
3351
':s/pattern/replace/');
3352
return;
3353
}
3354
var regexPart = argString.substring(slashes[0] + 1, slashes[1]);
3355
var replacePart = '';
3356
var flagsPart;
3357
var count;
3358
var confirm = false; // Whether to confirm each replace.
3359
if (slashes[1]) {
3360
replacePart = argString.substring(slashes[1] + 1, slashes[2]);
3361
replacePart = fixRegexReplace(replacePart);
3362
}
3363
if (slashes[2]) {
3364
// After the 3rd slash, we can have flags followed by a space followed
3365
// by count.
3366
var trailing = argString.substring(slashes[2] + 1).split(' ');
3367
flagsPart = trailing[0];
3368
count = parseInt(trailing[1]);
3369
}
3370
if (flagsPart) {
3371
if (flagsPart.indexOf('c') != -1) {
3372
confirm = true;
3373
flagsPart.replace('c', '');
3374
}
3375
regexPart = regexPart + '/' + flagsPart;
3376
}
3377
if (regexPart) {
3378
// If regex part is empty, then use the previous query. Otherwise use
3379
// the regex part as the new query.
3380
try {
3381
updateSearchQuery(cm, regexPart, true /** ignoreCase */,
3382
true /** smartCase */);
3383
} catch (e) {
3384
showConfirm(cm, 'Invalid regex: ' + regexPart);
3385
return;
3386
}
3387
}
3388
var state = getSearchState(cm);
3389
var query = state.getQuery();
3390
var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
3391
var lineEnd = params.lineEnd || lineStart;
3392
if (count) {
3393
lineStart = lineEnd;
3394
lineEnd = lineStart + count - 1;
3395
}
3396
var startPos = clipCursorToContent(cm, { line: lineStart, ch: 0 });
3397
var cursor = cm.getSearchCursor(query, startPos);
3398
doReplace(cm, confirm, lineStart, lineEnd, cursor, query, replacePart);
3399
},
3400
redo: CodeMirror.commands.redo,
3401
undo: CodeMirror.commands.undo,
3402
write: function(cm) {
3403
if (CodeMirror.commands.save) {
3404
// If a save command is defined, call it.
3405
CodeMirror.commands.save(cm);
3406
} else {
3407
// Saves to text area if no save command is defined.
3408
cm.save();
3409
}
3410
},
3411
nohlsearch: function(cm) {
3412
clearSearchHighlight(cm);
3413
},
3414
delmarks: function(cm, params) {
3415
if (!params.argString || !trim(params.argString)) {
3416
showConfirm(cm, 'Argument required');
3417
return;
3418
}
3419
3420
var state = cm.state.vim;
3421
var stream = new CodeMirror.StringStream(trim(params.argString));
3422
while (!stream.eol()) {
3423
stream.eatSpace();
3424
3425
// Record the streams position at the beginning of the loop for use
3426
// in error messages.
3427
var count = stream.pos;
3428
3429
if (!stream.match(/[a-zA-Z]/, false)) {
3430
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
3431
return;
3432
}
3433
3434
var sym = stream.next();
3435
// Check if this symbol is part of a range
3436
if (stream.match('-', true)) {
3437
// This symbol is part of a range.
3438
3439
// The range must terminate at an alphabetic character.
3440
if (!stream.match(/[a-zA-Z]/, false)) {
3441
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
3442
return;
3443
}
3444
3445
var startMark = sym;
3446
var finishMark = stream.next();
3447
// The range must terminate at an alphabetic character which
3448
// shares the same case as the start of the range.
3449
if (isLowerCase(startMark) && isLowerCase(finishMark) ||
3450
isUpperCase(startMark) && isUpperCase(finishMark)) {
3451
var start = startMark.charCodeAt(0);
3452
var finish = finishMark.charCodeAt(0);
3453
if (start >= finish) {
3454
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
3455
return;
3456
}
3457
3458
// Because marks are always ASCII values, and we have
3459
// determined that they are the same case, we can use
3460
// their char codes to iterate through the defined range.
3461
for (var j = 0; j <= finish - start; j++) {
3462
var mark = String.fromCharCode(start + j);
3463
delete state.marks[mark];
3464
}
3465
} else {
3466
showConfirm(cm, 'Invalid argument: ' + startMark + '-');
3467
return;
3468
}
3469
} else {
3470
// This symbol is a valid mark, and is not part of a range.
3471
delete state.marks[sym];
3472
}
3473
}
3474
}
3475
};
3476
3477
var exCommandDispatcher = new Vim.ExCommandDispatcher();
3478
3479
/**
3480
* @param {CodeMirror} cm CodeMirror instance we are in.
3481
* @param {boolean} confirm Whether to confirm each replace.
3482
* @param {Cursor} lineStart Line to start replacing from.
3483
* @param {Cursor} lineEnd Line to stop replacing at.
3484
* @param {RegExp} query Query for performing matches with.
3485
* @param {string} replaceWith Text to replace matches with. May contain $1,
3486
* $2, etc for replacing captured groups using Javascript replace.
3487
*/
3488
function doReplace(cm, confirm, lineStart, lineEnd, searchCursor, query,
3489
replaceWith) {
3490
// Set up all the functions.
3491
cm.state.vim.exMode = true;
3492
var done = false;
3493
var lastPos = searchCursor.from();
3494
function replaceAll() {
3495
cm.operation(function() {
3496
while (!done) {
3497
replace();
3498
next();
3499
}
3500
stop();
3501
});
3502
}
3503
function replace() {
3504
var text = cm.getRange(searchCursor.from(), searchCursor.to());
3505
var newText = text.replace(query, replaceWith);
3506
searchCursor.replace(newText);
3507
}
3508
function next() {
3509
var found = searchCursor.findNext();
3510
if (!found) {
3511
done = true;
3512
} else if (isInRange(searchCursor.from(), lineStart, lineEnd)) {
3513
cm.scrollIntoView(searchCursor.from(), 30);
3514
cm.setSelection(searchCursor.from(), searchCursor.to());
3515
lastPos = searchCursor.from();
3516
done = false;
3517
} else {
3518
done = true;
3519
}
3520
}
3521
function stop(close) {
3522
if (close) { close(); }
3523
cm.focus();
3524
if (lastPos) {
3525
cm.setCursor(lastPos);
3526
var vim = cm.state.vim;
3527
vim.exMode = false;
3528
vim.lastHPos = vim.lastHSPos = lastPos.ch;
3529
}
3530
}
3531
function onPromptKeyDown(e, _value, close) {
3532
// Swallow all keys.
3533
CodeMirror.e_stop(e);
3534
var keyName = CodeMirror.keyName(e);
3535
switch (keyName) {
3536
case 'Y':
3537
replace(); next(); break;
3538
case 'N':
3539
next(); break;
3540
case 'A':
3541
cm.operation(replaceAll); break;
3542
case 'L':
3543
replace();
3544
// fall through and exit.
3545
case 'Q':
3546
case 'Esc':
3547
case 'Ctrl-C':
3548
case 'Ctrl-[':
3549
stop(close);
3550
break;
3551
}
3552
if (done) { stop(close); }
3553
}
3554
3555
// Actually do replace.
3556
next();
3557
if (done) {
3558
showConfirm(cm, 'No matches for ' + query.source);
3559
return;
3560
}
3561
if (!confirm) {
3562
replaceAll();
3563
return;
3564
}
3565
showPrompt(cm, {
3566
prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',
3567
onKeyDown: onPromptKeyDown
3568
});
3569
}
3570
3571
// Register Vim with CodeMirror
3572
function buildVimKeyMap() {
3573
/**
3574
* Handle the raw key event from CodeMirror. Translate the
3575
* Shift + key modifier to the resulting letter, while preserving other
3576
* modifers.
3577
*/
3578
function cmKeyToVimKey(key, modifier) {
3579
var vimKey = key;
3580
if (isUpperCase(vimKey) && modifier == 'Ctrl') {
3581
vimKey = vimKey.toLowerCase();
3582
}
3583
if (modifier) {
3584
// Vim will parse modifier+key combination as a single key.
3585
vimKey = modifier.charAt(0) + '-' + vimKey;
3586
}
3587
var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey];
3588
vimKey = specialKey ? specialKey : vimKey;
3589
vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey;
3590
return vimKey;
3591
}
3592
3593
// Closure to bind CodeMirror, key, modifier.
3594
function keyMapper(vimKey) {
3595
return function(cm) {
3596
CodeMirror.Vim.handleKey(cm, vimKey);
3597
};
3598
}
3599
3600
var cmToVimKeymap = {
3601
'nofallthrough': true,
3602
'style': 'fat-cursor'
3603
};
3604
function bindKeys(keys, modifier) {
3605
for (var i = 0; i < keys.length; i++) {
3606
var key = keys[i];
3607
if (!modifier && key.length == 1) {
3608
// Wrap all keys without modifiers with '' to identify them by their
3609
// key characters instead of key identifiers.
3610
key = "'" + key + "'";
3611
}
3612
var vimKey = cmKeyToVimKey(keys[i], modifier);
3613
var cmKey = modifier ? modifier + '-' + key : key;
3614
cmToVimKeymap[cmKey] = keyMapper(vimKey);
3615
}
3616
}
3617
bindKeys(upperCaseAlphabet);
3618
bindKeys(lowerCaseAlphabet);
3619
bindKeys(upperCaseAlphabet, 'Ctrl');
3620
bindKeys(specialSymbols);
3621
bindKeys(specialSymbols, 'Ctrl');
3622
bindKeys(numbers);
3623
bindKeys(numbers, 'Ctrl');
3624
bindKeys(specialKeys);
3625
bindKeys(specialKeys, 'Ctrl');
3626
return cmToVimKeymap;
3627
}
3628
CodeMirror.keyMap.vim = buildVimKeyMap();
3629
3630
function exitInsertMode(cm) {
3631
var vim = cm.state.vim;
3632
var inReplay = vimGlobalState.macroModeState.inReplay;
3633
if (!inReplay) {
3634
cm.off('change', onChange);
3635
cm.off('cursorActivity', onCursorActivity);
3636
CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
3637
}
3638
if (!inReplay && vim.insertModeRepeat > 1) {
3639
// Perform insert mode repeat for commands like 3,a and 3,o.
3640
repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
3641
true /** repeatForInsert */);
3642
vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
3643
}
3644
delete vim.insertModeRepeat;
3645
cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1, true);
3646
vim.insertMode = false;
3647
cm.setOption('keyMap', 'vim');
3648
cm.setOption('disableInput', true);
3649
cm.toggleOverwrite(false); // exit replace mode if we were in it.
3650
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
3651
}
3652
3653
CodeMirror.keyMap['vim-insert'] = {
3654
// TODO: override navigation keys so that Esc will cancel automatic
3655
// indentation from o, O, i_<CR>
3656
'Esc': exitInsertMode,
3657
'Ctrl-[': exitInsertMode,
3658
'Ctrl-C': exitInsertMode,
3659
'Ctrl-N': 'autocomplete',
3660
'Ctrl-P': 'autocomplete',
3661
'Enter': function(cm) {
3662
var fn = CodeMirror.commands.newlineAndIndentContinueComment ||
3663
CodeMirror.commands.newlineAndIndent;
3664
fn(cm);
3665
},
3666
fallthrough: ['default']
3667
};
3668
3669
CodeMirror.keyMap['vim-replace'] = {
3670
'Backspace': 'goCharLeft',
3671
fallthrough: ['vim-insert']
3672
};
3673
3674
function parseRegisterToKeyBuffer(macroModeState, registerName) {
3675
var match, key;
3676
var register = vimGlobalState.registerController.getRegister(registerName);
3677
var text = register.toString();
3678
var macroKeyBuffer = macroModeState.macroKeyBuffer;
3679
emptyMacroKeyBuffer(macroModeState);
3680
do {
3681
match = (/<\w+-.+?>|<\w+>|./).exec(text);
3682
if(match === null)break;
3683
key = match[0];
3684
text = text.substring(match.index + key.length);
3685
macroKeyBuffer.push(key);
3686
} while (text);
3687
return macroKeyBuffer;
3688
}
3689
3690
function parseKeyBufferToRegister(registerName, keyBuffer) {
3691
var text = keyBuffer.join('');
3692
vimGlobalState.registerController.setRegisterText(registerName, text);
3693
}
3694
3695
function emptyMacroKeyBuffer(macroModeState) {
3696
if(macroModeState.isMacroPlaying)return;
3697
var macroKeyBuffer = macroModeState.macroKeyBuffer;
3698
macroKeyBuffer.length = 0;
3699
}
3700
3701
function executeMacroKeyBuffer(cm, macroModeState, keyBuffer) {
3702
macroModeState.isMacroPlaying = true;
3703
for (var i = 0, len = keyBuffer.length; i < len; i++) {
3704
CodeMirror.Vim.handleKey(cm, keyBuffer[i]);
3705
};
3706
macroModeState.isMacroPlaying = false;
3707
}
3708
3709
function logKey(macroModeState, key) {
3710
if(macroModeState.isMacroPlaying)return;
3711
var macroKeyBuffer = macroModeState.macroKeyBuffer;
3712
macroKeyBuffer.push(key);
3713
}
3714
3715
/**
3716
* Listens for changes made in insert mode.
3717
* Should only be active in insert mode.
3718
*/
3719
function onChange(_cm, changeObj) {
3720
var macroModeState = vimGlobalState.macroModeState;
3721
var lastChange = macroModeState.lastInsertModeChanges;
3722
while (changeObj) {
3723
lastChange.expectCursorActivityForChange = true;
3724
if (changeObj.origin == '+input' || changeObj.origin == 'paste'
3725
|| changeObj.origin === undefined /* only in testing */) {
3726
var text = changeObj.text.join('\n');
3727
lastChange.changes.push(text);
3728
}
3729
// Change objects may be chained with next.
3730
changeObj = changeObj.next;
3731
}
3732
}
3733
3734
/**
3735
* Listens for any kind of cursor activity on CodeMirror.
3736
* - For tracking cursor activity in insert mode.
3737
* - Should only be active in insert mode.
3738
*/
3739
function onCursorActivity() {
3740
var macroModeState = vimGlobalState.macroModeState;
3741
var lastChange = macroModeState.lastInsertModeChanges;
3742
if (lastChange.expectCursorActivityForChange) {
3743
lastChange.expectCursorActivityForChange = false;
3744
} else {
3745
// Cursor moved outside the context of an edit. Reset the change.
3746
lastChange.changes = [];
3747
}
3748
}
3749
3750
/** Wrapper for special keys pressed in insert mode */
3751
function InsertModeKey(keyName) {
3752
this.keyName = keyName;
3753
}
3754
3755
/**
3756
* Handles raw key down events from the text area.
3757
* - Should only be active in insert mode.
3758
* - For recording deletes in insert mode.
3759
*/
3760
function onKeyEventTargetKeyDown(e) {
3761
var macroModeState = vimGlobalState.macroModeState;
3762
var lastChange = macroModeState.lastInsertModeChanges;
3763
var keyName = CodeMirror.keyName(e);
3764
function onKeyFound() {
3765
lastChange.changes.push(new InsertModeKey(keyName));
3766
return true;
3767
}
3768
if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
3769
CodeMirror.lookupKey(keyName, ['vim-insert'], onKeyFound);
3770
}
3771
}
3772
3773
/**
3774
* Repeats the last edit, which includes exactly 1 command and at most 1
3775
* insert. Operator and motion commands are read from lastEditInputState,
3776
* while action commands are read from lastEditActionCommand.
3777
*
3778
* If repeatForInsert is true, then the function was called by
3779
* exitInsertMode to repeat the insert mode changes the user just made. The
3780
* corresponding enterInsertMode call was made with a count.
3781
*/
3782
function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
3783
var macroModeState = vimGlobalState.macroModeState;
3784
macroModeState.inReplay = true;
3785
var isAction = !!vim.lastEditActionCommand;
3786
var cachedInputState = vim.inputState;
3787
function repeatCommand() {
3788
if (isAction) {
3789
commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
3790
} else {
3791
commandDispatcher.evalInput(cm, vim);
3792
}
3793
}
3794
function repeatInsert(repeat) {
3795
if (macroModeState.lastInsertModeChanges.changes.length > 0) {
3796
// For some reason, repeat cw in desktop VIM will does not repeat
3797
// insert mode changes. Will conform to that behavior.
3798
repeat = !vim.lastEditActionCommand ? 1 : repeat;
3799
repeatLastInsertModeChanges(cm, repeat, macroModeState);
3800
}
3801
}
3802
vim.inputState = vim.lastEditInputState;
3803
if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
3804
// o and O repeat have to be interlaced with insert repeats so that the
3805
// insertions appear on separate lines instead of the last line.
3806
for (var i = 0; i < repeat; i++) {
3807
repeatCommand();
3808
repeatInsert(1);
3809
}
3810
} else {
3811
if (!repeatForInsert) {
3812
// Hack to get the cursor to end up at the right place. If I is
3813
// repeated in insert mode repeat, cursor will be 1 insert
3814
// change set left of where it should be.
3815
repeatCommand();
3816
}
3817
repeatInsert(repeat);
3818
}
3819
vim.inputState = cachedInputState;
3820
if (vim.insertMode && !repeatForInsert) {
3821
// Don't exit insert mode twice. If repeatForInsert is set, then we
3822
// were called by an exitInsertMode call lower on the stack.
3823
exitInsertMode(cm);
3824
}
3825
macroModeState.inReplay = false;
3826
};
3827
3828
function repeatLastInsertModeChanges(cm, repeat, macroModeState) {
3829
var lastChange = macroModeState.lastInsertModeChanges;
3830
function keyHandler(binding) {
3831
if (typeof binding == 'string') {
3832
CodeMirror.commands[binding](cm);
3833
} else {
3834
binding(cm);
3835
}
3836
return true;
3837
}
3838
for (var i = 0; i < repeat; i++) {
3839
for (var j = 0; j < lastChange.changes.length; j++) {
3840
var change = lastChange.changes[j];
3841
if (change instanceof InsertModeKey) {
3842
CodeMirror.lookupKey(change.keyName, ['vim-insert'], keyHandler);
3843
} else {
3844
var cur = cm.getCursor();
3845
cm.replaceRange(change, cur, cur);
3846
}
3847
}
3848
}
3849
}
3850
3851
resetVimGlobalState();
3852
return vimApi;
3853
};
3854
// Initialize Vim and make it available as an API.
3855
CodeMirror.Vim = Vim();
3856
}
3857
)();
3858
3859