2 * Supported keybindings:
7 * e, E, w, W, b, B, ge, gE
8 * f<character>, F<character>, t<character>, T<character>
12 * '<character>, `<character>
24 * a, i, s, A, I, S, o, O
25 * zz, z., z<CR>, zt, zb, z-
32 * ESC - leave insert mode, visual mode, and clear input state.
33 * Ctrl-[, Ctrl-c - same as ESC.
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
45 * 2. Variable declarations and short basic helpers
46 * 3. Instance (External API) implementation
47 * 4. Internal state tracking objects (input state, counter) implementation
49 * 5. Key handler (the main command dispatcher) implementation
50 * 6. Motion, operator, and action implementations
51 * 7. Helper functions for the key handler, motions, operators, and actions
52 * 8. Set up Vim to work as a keymap for CodeMirror.
59 // Key to key mapping. This goes first to make it possible to override
61 { keys: ['<Left>'], type: 'keyToKey', toKeys: ['h'] },
62 { keys: ['<Right>'], type: 'keyToKey', toKeys: ['l'] },
63 { keys: ['<Up>'], type: 'keyToKey', toKeys: ['k'] },
64 { keys: ['<Down>'], type: 'keyToKey', toKeys: ['j'] },
65 { keys: ['<Space>'], type: 'keyToKey', toKeys: ['l'] },
66 { keys: ['<BS>'], type: 'keyToKey', toKeys: ['h'] },
67 { keys: ['<C-Space>'], type: 'keyToKey', toKeys: ['W'] },
68 { keys: ['<C-BS>'], type: 'keyToKey', toKeys: ['B'] },
69 { keys: ['<S-Space>'], type: 'keyToKey', toKeys: ['w'] },
70 { keys: ['<S-BS>'], type: 'keyToKey', toKeys: ['b'] },
71 { keys: ['<C-n>'], type: 'keyToKey', toKeys: ['j'] },
72 { keys: ['<C-p>'], type: 'keyToKey', toKeys: ['k'] },
73 { keys: ['C-['], type: 'keyToKey', toKeys: ['<Esc>'] },
74 { keys: ['<C-c>'], type: 'keyToKey', toKeys: ['<Esc>'] },
75 { keys: ['s'], type: 'keyToKey', toKeys: ['c', 'l'] },
76 { keys: ['S'], type: 'keyToKey', toKeys: ['c', 'c'] },
77 { keys: ['<Home>'], type: 'keyToKey', toKeys: ['0'] },
78 { keys: ['<End>'], type: 'keyToKey', toKeys: ['$'] },
79 { keys: ['<PageUp>'], type: 'keyToKey', toKeys: ['<C-b>'] },
80 { keys: ['<PageDown>'], type: 'keyToKey', toKeys: ['<C-f>'] },
82 { keys: ['H'], type: 'motion',
83 motion: 'moveToTopLine',
84 motionArgs: { linewise: true, toJumplist: true }},
85 { keys: ['M'], type: 'motion',
86 motion: 'moveToMiddleLine',
87 motionArgs: { linewise: true, toJumplist: true }},
88 { keys: ['L'], type: 'motion',
89 motion: 'moveToBottomLine',
90 motionArgs: { linewise: true, toJumplist: true }},
91 { keys: ['h'], type: 'motion',
92 motion: 'moveByCharacters',
93 motionArgs: { forward: false }},
94 { keys: ['l'], type: 'motion',
95 motion: 'moveByCharacters',
96 motionArgs: { forward: true }},
97 { keys: ['j'], type: 'motion',
98 motion: 'moveByLines',
99 motionArgs: { forward: true, linewise: true }},
100 { keys: ['k'], type: 'motion',
101 motion: 'moveByLines',
102 motionArgs: { forward: false, linewise: true }},
103 { keys: ['g','j'], type: 'motion',
104 motion: 'moveByDisplayLines',
105 motionArgs: { forward: true }},
106 { keys: ['g','k'], type: 'motion',
107 motion: 'moveByDisplayLines',
108 motionArgs: { forward: false }},
109 { keys: ['w'], type: 'motion',
110 motion: 'moveByWords',
111 motionArgs: { forward: true, wordEnd: false }},
112 { keys: ['W'], type: 'motion',
113 motion: 'moveByWords',
114 motionArgs: { forward: true, wordEnd: false, bigWord: true }},
115 { keys: ['e'], type: 'motion',
116 motion: 'moveByWords',
117 motionArgs: { forward: true, wordEnd: true, inclusive: true }},
118 { keys: ['E'], type: 'motion',
119 motion: 'moveByWords',
120 motionArgs: { forward: true, wordEnd: true, bigWord: true,
122 { keys: ['b'], type: 'motion',
123 motion: 'moveByWords',
124 motionArgs: { forward: false, wordEnd: false }},
125 { keys: ['B'], type: 'motion',
126 motion: 'moveByWords',
127 motionArgs: { forward: false, wordEnd: false, bigWord: true }},
128 { keys: ['g', 'e'], type: 'motion',
129 motion: 'moveByWords',
130 motionArgs: { forward: false, wordEnd: true, inclusive: true }},
131 { keys: ['g', 'E'], type: 'motion',
132 motion: 'moveByWords',
133 motionArgs: { forward: false, wordEnd: true, bigWord: true,
135 { keys: ['{'], type: 'motion', motion: 'moveByParagraph',
136 motionArgs: { forward: false, toJumplist: true }},
137 { keys: ['}'], type: 'motion', motion: 'moveByParagraph',
138 motionArgs: { forward: true, toJumplist: true }},
139 { keys: ['<C-f>'], type: 'motion',
140 motion: 'moveByPage', motionArgs: { forward: true }},
141 { keys: ['<C-b>'], type: 'motion',
142 motion: 'moveByPage', motionArgs: { forward: false }},
143 { keys: ['<C-d>'], type: 'motion',
144 motion: 'moveByScroll',
145 motionArgs: { forward: true, explicitRepeat: true }},
146 { keys: ['<C-u>'], type: 'motion',
147 motion: 'moveByScroll',
148 motionArgs: { forward: false, explicitRepeat: true }},
149 { keys: ['g', 'g'], type: 'motion',
150 motion: 'moveToLineOrEdgeOfDocument',
151 motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
152 { keys: ['G'], type: 'motion',
153 motion: 'moveToLineOrEdgeOfDocument',
154 motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
155 { keys: ['0'], type: 'motion', motion: 'moveToStartOfLine' },
156 { keys: ['^'], type: 'motion',
157 motion: 'moveToFirstNonWhiteSpaceCharacter' },
158 { keys: ['+'], type: 'motion',
159 motion: 'moveByLines',
160 motionArgs: { forward: true, toFirstChar:true }},
161 { keys: ['-'], type: 'motion',
162 motion: 'moveByLines',
163 motionArgs: { forward: false, toFirstChar:true }},
164 { keys: ['_'], type: 'motion',
165 motion: 'moveByLines',
166 motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
167 { keys: ['$'], type: 'motion',
169 motionArgs: { inclusive: true }},
170 { keys: ['%'], type: 'motion',
171 motion: 'moveToMatchedSymbol',
172 motionArgs: { inclusive: true, toJumplist: true }},
173 { keys: ['f', 'character'], type: 'motion',
174 motion: 'moveToCharacter',
175 motionArgs: { forward: true , inclusive: true }},
176 { keys: ['F', 'character'], type: 'motion',
177 motion: 'moveToCharacter',
178 motionArgs: { forward: false }},
179 { keys: ['t', 'character'], type: 'motion',
180 motion: 'moveTillCharacter',
181 motionArgs: { forward: true, inclusive: true }},
182 { keys: ['T', 'character'], type: 'motion',
183 motion: 'moveTillCharacter',
184 motionArgs: { forward: false }},
185 { keys: [';'], type: 'motion', motion: 'repeatLastCharacterSearch',
186 motionArgs: { forward: true }},
187 { keys: [','], type: 'motion', motion: 'repeatLastCharacterSearch',
188 motionArgs: { forward: false }},
189 { keys: ['\'', 'character'], type: 'motion', motion: 'goToMark',
190 motionArgs: {toJumplist: true}},
191 { keys: ['`', 'character'], type: 'motion', motion: 'goToMark',
192 motionArgs: {toJumplist: true}},
193 { keys: [']', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
194 { keys: ['[', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
195 { keys: [']', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
196 { keys: ['[', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
197 { keys: [']', 'character'], type: 'motion',
198 motion: 'moveToSymbol',
199 motionArgs: { forward: true, toJumplist: true}},
200 { keys: ['[', 'character'], type: 'motion',
201 motion: 'moveToSymbol',
202 motionArgs: { forward: false, toJumplist: true}},
203 { keys: ['|'], type: 'motion',
204 motion: 'moveToColumn',
207 { keys: ['d'], type: 'operator', operator: 'delete' },
208 { keys: ['y'], type: 'operator', operator: 'yank' },
209 { keys: ['c'], type: 'operator', operator: 'change' },
210 { keys: ['>'], type: 'operator', operator: 'indent',
211 operatorArgs: { indentRight: true }},
212 { keys: ['<'], type: 'operator', operator: 'indent',
213 operatorArgs: { indentRight: false }},
214 { keys: ['g', '~'], type: 'operator', operator: 'swapcase' },
215 { keys: ['n'], type: 'motion', motion: 'findNext',
216 motionArgs: { forward: true, toJumplist: true }},
217 { keys: ['N'], type: 'motion', motion: 'findNext',
218 motionArgs: { forward: false, toJumplist: true }},
219 // Operator-Motion dual commands
220 { keys: ['x'], type: 'operatorMotion', operator: 'delete',
221 motion: 'moveByCharacters', motionArgs: { forward: true },
222 operatorMotionArgs: { visualLine: false }},
223 { keys: ['X'], type: 'operatorMotion', operator: 'delete',
224 motion: 'moveByCharacters', motionArgs: { forward: false },
225 operatorMotionArgs: { visualLine: true }},
226 { keys: ['D'], type: 'operatorMotion', operator: 'delete',
227 motion: 'moveToEol', motionArgs: { inclusive: true },
228 operatorMotionArgs: { visualLine: true }},
229 { keys: ['Y'], type: 'operatorMotion', operator: 'yank',
230 motion: 'moveToEol', motionArgs: { inclusive: true },
231 operatorMotionArgs: { visualLine: true }},
232 { keys: ['C'], type: 'operatorMotion',
234 motion: 'moveToEol', motionArgs: { inclusive: true },
235 operatorMotionArgs: { visualLine: true }},
236 { keys: ['~'], type: 'operatorMotion',
237 operator: 'swapcase', operatorArgs: { shouldMoveCursor: true },
238 motion: 'moveByCharacters', motionArgs: { forward: true }},
240 { keys: ['<C-i>'], type: 'action', action: 'jumpListWalk',
241 actionArgs: { forward: true }},
242 { keys: ['<C-o>'], type: 'action', action: 'jumpListWalk',
243 actionArgs: { forward: false }},
244 { keys: ['a'], type: 'action', action: 'enterInsertMode', isEdit: true,
245 actionArgs: { insertAt: 'charAfter' }},
246 { keys: ['A'], type: 'action', action: 'enterInsertMode', isEdit: true,
247 actionArgs: { insertAt: 'eol' }},
248 { keys: ['i'], type: 'action', action: 'enterInsertMode', isEdit: true,
249 actionArgs: { insertAt: 'inplace' }},
250 { keys: ['I'], type: 'action', action: 'enterInsertMode', isEdit: true,
251 actionArgs: { insertAt: 'firstNonBlank' }},
252 { keys: ['o'], type: 'action', action: 'newLineAndEnterInsertMode',
253 isEdit: true, interlaceInsertRepeat: true,
254 actionArgs: { after: true }},
255 { keys: ['O'], type: 'action', action: 'newLineAndEnterInsertMode',
256 isEdit: true, interlaceInsertRepeat: true,
257 actionArgs: { after: false }},
258 { keys: ['v'], type: 'action', action: 'toggleVisualMode' },
259 { keys: ['V'], type: 'action', action: 'toggleVisualMode',
260 actionArgs: { linewise: true }},
261 { keys: ['J'], type: 'action', action: 'joinLines', isEdit: true },
262 { keys: ['p'], type: 'action', action: 'paste', isEdit: true,
263 actionArgs: { after: true, isEdit: true }},
264 { keys: ['P'], type: 'action', action: 'paste', isEdit: true,
265 actionArgs: { after: false, isEdit: true }},
266 { keys: ['r', 'character'], type: 'action', action: 'replace', isEdit: true },
267 { keys: ['@', 'character'], type: 'action', action: 'replayMacro' },
268 { keys: ['q', 'character'], type: 'action', action: 'enterMacroRecordMode' },
269 // Handle Replace-mode as a special case of insert mode.
270 { keys: ['R'], type: 'action', action: 'enterInsertMode', isEdit: true,
271 actionArgs: { replace: true }},
272 { keys: ['u'], type: 'action', action: 'undo' },
273 { keys: ['<C-r>'], type: 'action', action: 'redo' },
274 { keys: ['m', 'character'], type: 'action', action: 'setMark' },
275 { keys: ['"', 'character'], type: 'action', action: 'setRegister' },
276 { keys: ['z', 'z'], type: 'action', action: 'scrollToCursor',
277 actionArgs: { position: 'center' }},
278 { keys: ['z', '.'], type: 'action', action: 'scrollToCursor',
279 actionArgs: { position: 'center' },
280 motion: 'moveToFirstNonWhiteSpaceCharacter' },
281 { keys: ['z', 't'], type: 'action', action: 'scrollToCursor',
282 actionArgs: { position: 'top' }},
283 { keys: ['z', '<CR>'], type: 'action', action: 'scrollToCursor',
284 actionArgs: { position: 'top' },
285 motion: 'moveToFirstNonWhiteSpaceCharacter' },
286 { keys: ['z', '-'], type: 'action', action: 'scrollToCursor',
287 actionArgs: { position: 'bottom' }},
288 { keys: ['z', 'b'], type: 'action', action: 'scrollToCursor',
289 actionArgs: { position: 'bottom' },
290 motion: 'moveToFirstNonWhiteSpaceCharacter' },
291 { keys: ['.'], type: 'action', action: 'repeatLastEdit' },
292 { keys: ['<C-a>'], type: 'action', action: 'incrementNumberToken',
294 actionArgs: {increase: true, backtrack: false}},
295 { keys: ['<C-x>'], type: 'action', action: 'incrementNumberToken',
297 actionArgs: {increase: false, backtrack: false}},
298 // Text object motions
299 { keys: ['a', 'character'], type: 'motion',
300 motion: 'textObjectManipulation' },
301 { keys: ['i', 'character'], type: 'motion',
302 motion: 'textObjectManipulation',
303 motionArgs: { textObjectInner: true }},
305 { keys: ['/'], type: 'search',
306 searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
307 { keys: ['?'], type: 'search',
308 searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
309 { keys: ['*'], type: 'search',
310 searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
311 { keys: ['#'], type: 'search',
312 searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
314 { keys: [':'], type: 'ex' }
317 var Vim = function() {
318 CodeMirror.defineOption('vimMode', false, function(cm, val) {
320 cm.setOption('keyMap', 'vim');
321 cm.on('beforeSelectionChange', beforeSelectionChange);
322 maybeInitVimState(cm);
323 } else if (cm.state.vim) {
324 cm.setOption('keyMap', 'default');
325 cm.off('beforeSelectionChange', beforeSelectionChange);
329 function beforeSelectionChange(cm, cur) {
330 var vim = cm.state.vim;
331 if (vim.insertMode || vim.exMode) return;
334 if (head.ch && head.ch == cm.doc.getLine(head.line).length) {
339 var numberRegex = /[\d]/;
340 var wordRegexp = [(/\w/), (/[^\w\s]/)], bigWordRegexp = [(/\S/)];
341 function makeKeyRange(start, size) {
343 for (var i = start; i < start + size; i++) {
344 keys.push(String.fromCharCode(i));
348 var upperCaseAlphabet = makeKeyRange(65, 26);
349 var lowerCaseAlphabet = makeKeyRange(97, 26);
350 var numbers = makeKeyRange(48, 10);
351 var specialSymbols = '~`!@#$%^&*()_-+=[{}]\\|/?.,<>:;"\''.split('');
352 var specialKeys = ['Left', 'Right', 'Up', 'Down', 'Space', 'Backspace',
353 'Esc', 'Home', 'End', 'PageUp', 'PageDown', 'Enter'];
354 var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
355 var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"']);
357 function isLine(cm, line) {
358 return line >= cm.firstLine() && line <= cm.lastLine();
360 function isLowerCase(k) {
361 return (/^[a-z]$/).test(k);
363 function isMatchableSymbol(k) {
364 return '()[]{}'.indexOf(k) != -1;
366 function isNumber(k) {
367 return numberRegex.test(k);
369 function isUpperCase(k) {
370 return (/^[A-Z]$/).test(k);
372 function isWhiteSpaceString(k) {
373 return (/^\s*$/).test(k);
375 function inArray(val, arr) {
376 for (var i = 0; i < arr.length; i++) {
384 var createCircularJumpList = function() {
389 var buffer = new Array(size);
390 function add(cm, oldCur, newCur) {
391 var current = pointer % size;
392 var curMark = buffer[current];
393 function useNextSlot(cursor) {
394 var next = ++pointer % size;
395 var trashMark = buffer[next];
399 buffer[next] = cm.setBookmark(cursor);
402 var markPos = curMark.find();
403 // avoid recording redundant cursor position
404 if (markPos && !cursorEqual(markPos, oldCur)) {
412 tail = pointer - size + 1;
417 function move(cm, offset) {
419 if (pointer > head) {
421 } else if (pointer < tail) {
424 var mark = buffer[(size + pointer) % size];
425 // skip marks that are temporarily removed from text buffer
426 if (mark && !mark.find()) {
427 var inc = offset > 0 ? 1 : -1;
429 var oldCur = cm.getCursor();
432 mark = buffer[(size + pointer) % size];
433 // skip marks that are the same as current position
435 (newCur = mark.find()) &&
436 !cursorEqual(oldCur, newCur)) {
439 } while (pointer < head && pointer > tail);
444 cachedCursor: undefined, //used for # and * jumps
450 var createMacroState = function() {
453 latestRegister: undefined,
455 lastInsertModeChanges: {
456 changes: [], // Change list
457 expectCursorActivityForChange: false // Set to true on change, false on cursorActivity.
459 enteredMacroMode: undefined,
460 isMacroPlaying: false,
461 toggle: function(cm, registerName) {
462 if (this.enteredMacroMode) { //onExit
463 this.enteredMacroMode(); // close dialog
464 this.enteredMacroMode = undefined;
466 this.latestRegister = registerName;
467 this.enteredMacroMode = cm.openDialog(
468 '(recording)['+registerName+']', null, {bottom:true});
475 function maybeInitVimState(cm) {
477 // Store instance state in the CodeMirror object.
479 inputState: new InputState(),
480 // Vim's input state that triggered the last edit, used to repeat
481 // motions and operators with '.'.
482 lastEditInputState: undefined,
483 // Vim's action command before the last edit, used to repeat actions
484 // with '.' and insert mode repeat.
485 lastEditActionCommand: undefined,
486 // When using jk for navigation, if you move from a longer line to a
487 // shorter line, the cursor may clip to the end of the shorter line.
488 // If j is pressed again and cursor goes to the next line, the
489 // cursor should go back to its horizontal position on the longer
490 // line if it can. This is to keep track of the horizontal position.
492 // Doing the same with screen-position for gj/gk
494 // The last motion command run. Cleared if a non-motion command gets
495 // executed in between.
499 // Repeat count for changes made in insert mode, triggered by key
500 // sequences like 3,i. Only exists when insertMode is true.
501 insertModeRepeat: undefined,
503 // If we are in visual line mode. No effect if visualMode is false.
510 function resetVimGlobalState() {
512 // The current search query.
514 // Whether we are searching backwards.
515 searchIsReversed: false,
516 jumpList: createCircularJumpList(),
517 macroModeState: createMacroState(),
518 // Recording latest f, t, F or T motion command.
519 lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''},
520 registerController: new RegisterController({})
525 buildKeyMap: function() {
526 // TODO: Convert keymap into dictionary format for fast lookup.
528 // Testing hook, though it might be useful to expose the register
529 // controller anyways.
530 getRegisterController: function() {
531 return vimGlobalState.registerController;
534 resetVimGlobalState_: resetVimGlobalState,
537 getVimGlobalState_: function() {
538 return vimGlobalState;
542 maybeInitVimState_: maybeInitVimState,
544 InsertModeKey: InsertModeKey,
545 map: function(lhs, rhs) {
546 // Add user defined key bindings.
547 exCommandDispatcher.map(lhs, rhs);
549 defineEx: function(name, prefix, func){
550 if (name.indexOf(prefix) !== 0) {
551 throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
553 exCommands[name]=func;
554 exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
556 // This is the outermost function called by CodeMirror, after keys have
557 // been mapped to their Vim equivalents.
558 handleKey: function(cm, key) {
560 var vim = maybeInitVimState(cm);
561 var macroModeState = vimGlobalState.macroModeState;
562 if (macroModeState.enteredMacroMode) {
564 actions.exitMacroRecordMode();
565 vim.inputState = new InputState();
569 if (key == '<Esc>') {
570 // Clear input state and get back to normal mode.
571 vim.inputState = new InputState();
572 if (vim.visualMode) {
577 // Enter visual mode when the mouse selects text.
578 if (!vim.visualMode &&
579 !cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) {
580 vim.visualMode = true;
581 vim.visualLine = false;
582 cm.on('mousedown', exitVisualMode);
584 if (key != '0' || (key == '0' && vim.inputState.getRepeat() === 0)) {
585 // Have to special case 0 since it's both a motion and a number.
586 command = commandDispatcher.matchCommand(key, defaultKeymap, vim);
590 // Increment count unless count is 0 and key is 0.
591 vim.inputState.pushRepeatDigit(key);
595 if (command.type == 'keyToKey') {
596 // TODO: prevent infinite recursion.
597 for (var i = 0; i < command.toKeys.length; i++) {
598 this.handleKey(cm, command.toKeys[i]);
601 if (macroModeState.enteredMacroMode) {
602 logKey(macroModeState, key);
604 commandDispatcher.processCommand(cm, vim, command);
609 // Represents the current input state.
610 function InputState() {
611 this.prefixRepeat = [];
612 this.motionRepeat = [];
614 this.operator = null;
615 this.operatorArgs = null;
617 this.motionArgs = null;
618 this.keyBuffer = []; // For matching multi-key commands.
619 this.registerName = null; // Defaults to the unamed register.
621 InputState.prototype.pushRepeatDigit = function(n) {
622 if (!this.operator) {
623 this.prefixRepeat = this.prefixRepeat.concat(n);
625 this.motionRepeat = this.motionRepeat.concat(n);
628 InputState.prototype.getRepeat = function() {
630 if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
632 if (this.prefixRepeat.length > 0) {
633 repeat *= parseInt(this.prefixRepeat.join(''), 10);
635 if (this.motionRepeat.length > 0) {
636 repeat *= parseInt(this.motionRepeat.join(''), 10);
643 * Register stores information about copy and paste registers. Besides
644 * text, a register must store whether it is linewise (i.e., when it is
645 * pasted, should it insert itself into a new line, or should the text be
646 * inserted at the cursor position.)
648 function Register(text, linewise) {
651 this.set(text, linewise);
654 Register.prototype = {
655 set: function(text, linewise) {
657 this.linewise = !!linewise;
659 append: function(text, linewise) {
660 // if this register has ever been set to linewise, use linewise.
661 if (linewise || this.linewise) {
662 this.text += '\n' + text;
663 this.linewise = true;
670 this.linewise = false;
672 toString: function() { return this.text; }
676 * vim registers allow you to keep many independent copy and paste buffers.
677 * See http://usevim.com/2012/04/13/registers/ for an introduction.
679 * RegisterController keeps the state of all the registers. An initial
680 * state may be passed in. The unnamed register '"' will always be
683 function RegisterController(registers) {
684 this.registers = registers;
685 this.unamedRegister = registers['"'] = new Register();
687 RegisterController.prototype = {
688 pushText: function(registerName, operator, text, linewise) {
689 if (linewise && text.charAt(0) == '\n') {
690 text = text.slice(1) + '\n';
692 // Lowercase and uppercase registers refer to the same register.
693 // Uppercase just means append.
694 var register = this.isValidRegister(registerName) ?
695 this.getRegister(registerName) : null;
696 // if no register/an invalid register was specified, things go to the
701 // The 0 register contains the text from the most recent yank.
702 this.registers['0'] = new Register(text, linewise);
706 if (text.indexOf('\n') == -1) {
707 // Delete less than 1 line. Update the small delete register.
708 this.registers['-'] = new Register(text, linewise);
710 // Shift down the contents of the numbered registers and put the
711 // deleted text into register 1.
712 this.shiftNumericRegisters_();
713 this.registers['1'] = new Register(text, linewise);
717 // Make sure the unnamed register is set to what just happened
718 this.unamedRegister.set(text, linewise);
722 // If we've gotten to this point, we've actually specified a register
723 var append = isUpperCase(registerName);
725 register.append(text, linewise);
726 // The unamed register always has the same value as the last used
728 this.unamedRegister.append(text, linewise);
730 register.set(text, linewise);
731 this.unamedRegister.set(text, linewise);
734 setRegisterText: function(name, text, linewise) {
735 this.getRegister(name).set(text, linewise);
737 // Gets the register named @name. If one of @name doesn't already exist,
738 // create it. If @name is invalid, return the unamedRegister.
739 getRegister: function(name) {
740 if (!this.isValidRegister(name)) {
741 return this.unamedRegister;
743 name = name.toLowerCase();
744 if (!this.registers[name]) {
745 this.registers[name] = new Register();
747 return this.registers[name];
749 isValidRegister: function(name) {
750 return name && inArray(name, validRegisters);
752 shiftNumericRegisters_: function() {
753 for (var i = 9; i >= 2; i--) {
754 this.registers[i] = this.getRegister('' + (i - 1));
759 var commandDispatcher = {
760 matchCommand: function(key, keyMap, vim) {
761 var inputState = vim.inputState;
762 var keys = inputState.keyBuffer.concat(key);
763 for (var i = 0; i < keyMap.length; i++) {
764 var command = keyMap[i];
765 if (matchKeysPartial(keys, command.keys)) {
766 if (keys.length < command.keys.length) {
767 // Matches part of a multi-key command. Buffer and wait for next
769 inputState.keyBuffer.push(key);
772 if (inputState.operator && command.type == 'action') {
773 // Ignore matched action commands after an operator. Operators
774 // only operate on motions. This check is really for text
775 // objects since aW, a[ etcs conflicts with a.
778 // Matches whole comand. Return the command.
779 if (command.keys[keys.length - 1] == 'character') {
780 inputState.selectedCharacter = keys[keys.length - 1];
781 if(inputState.selectedCharacter.length>1){
782 switch(inputState.selectedCharacter){
784 inputState.selectedCharacter='\n';
787 inputState.selectedCharacter=' ';
794 inputState.keyBuffer = [];
798 // Clear the buffer since there are no partial matches.
799 inputState.keyBuffer = [];
802 processCommand: function(cm, vim, command) {
803 vim.inputState.repeatOverride = command.repeatOverride;
804 switch (command.type) {
806 this.processMotion(cm, vim, command);
809 this.processOperator(cm, vim, command);
811 case 'operatorMotion':
812 this.processOperatorMotion(cm, vim, command);
815 this.processAction(cm, vim, command);
818 this.processSearch(cm, vim, command);
822 this.processEx(cm, vim, command);
828 processMotion: function(cm, vim, command) {
829 vim.inputState.motion = command.motion;
830 vim.inputState.motionArgs = copyArgs(command.motionArgs);
831 this.evalInput(cm, vim);
833 processOperator: function(cm, vim, command) {
834 var inputState = vim.inputState;
835 if (inputState.operator) {
836 if (inputState.operator == command.operator) {
837 // Typing an operator twice like 'dd' makes the operator operate
839 inputState.motion = 'expandToLine';
840 inputState.motionArgs = { linewise: true };
841 this.evalInput(cm, vim);
844 // 2 different operators in a row doesn't make sense.
845 vim.inputState = new InputState();
848 inputState.operator = command.operator;
849 inputState.operatorArgs = copyArgs(command.operatorArgs);
850 if (vim.visualMode) {
851 // Operating on a selection in visual mode. We don't need a motion.
852 this.evalInput(cm, vim);
855 processOperatorMotion: function(cm, vim, command) {
856 var visualMode = vim.visualMode;
857 var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
858 if (operatorMotionArgs) {
859 // Operator motions may have special behavior in visual mode.
860 if (visualMode && operatorMotionArgs.visualLine) {
861 vim.visualLine = true;
864 this.processOperator(cm, vim, command);
866 this.processMotion(cm, vim, command);
869 processAction: function(cm, vim, command) {
870 var inputState = vim.inputState;
871 var repeat = inputState.getRepeat();
872 var repeatIsExplicit = !!repeat;
873 var actionArgs = copyArgs(command.actionArgs) || {};
874 if (inputState.selectedCharacter) {
875 actionArgs.selectedCharacter = inputState.selectedCharacter;
877 // Actions may or may not have motions and operators. Do these first.
878 if (command.operator) {
879 this.processOperator(cm, vim, command);
881 if (command.motion) {
882 this.processMotion(cm, vim, command);
884 if (command.motion || command.operator) {
885 this.evalInput(cm, vim);
887 actionArgs.repeat = repeat || 1;
888 actionArgs.repeatIsExplicit = repeatIsExplicit;
889 actionArgs.registerName = inputState.registerName;
890 vim.inputState = new InputState();
891 vim.lastMotion = null;
892 if (command.isEdit) {
893 this.recordLastEdit(vim, inputState, command);
895 actions[command.action](cm, actionArgs, vim);
897 processSearch: function(cm, vim, command) {
898 if (!cm.getSearchCursor) {
899 // Search depends on SearchCursor.
902 var forward = command.searchArgs.forward;
903 getSearchState(cm).setReversed(!forward);
904 var promptPrefix = (forward) ? '/' : '?';
905 var originalQuery = getSearchState(cm).getQuery();
906 var originalScrollPos = cm.getScrollInfo();
907 function handleQuery(query, ignoreCase, smartCase) {
909 updateSearchQuery(cm, query, ignoreCase, smartCase);
911 showConfirm(cm, 'Invalid regex: ' + query);
914 commandDispatcher.processMotion(cm, vim, {
917 motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
920 function onPromptClose(query) {
921 cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
922 handleQuery(query, true /** ignoreCase */, true /** smartCase */);
924 function onPromptKeyUp(_e, query) {
927 parsedQuery = updateSearchQuery(cm, query,
928 true /** ignoreCase */, true /** smartCase */);
930 // Swallow bad regexes for incremental search.
933 cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
935 clearSearchHighlight(cm);
936 cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
939 function onPromptKeyDown(e, _query, close) {
940 var keyName = CodeMirror.keyName(e);
941 if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
942 updateSearchQuery(cm, originalQuery);
943 clearSearchHighlight(cm);
944 cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
946 CodeMirror.e_stop(e);
951 switch (command.searchArgs.querySrc) {
954 onClose: onPromptClose,
955 prefix: promptPrefix,
956 desc: searchPromptDesc,
957 onKeyUp: onPromptKeyUp,
958 onKeyDown: onPromptKeyDown
961 case 'wordUnderCursor':
962 var word = expandWordUnderCursor(cm, false /** inclusive */,
963 true /** forward */, false /** bigWord */,
964 true /** noSymbol */);
965 var isKeyword = true;
967 word = expandWordUnderCursor(cm, false /** inclusive */,
968 true /** forward */, false /** bigWord */,
969 false /** noSymbol */);
975 var query = cm.getLine(word.start.line).substring(word.start.ch,
978 query = '\\b' + query + '\\b';
980 query = escapeRegex(query);
983 // cachedCursor is used to save the old position of the cursor
984 // when * or # causes vim to seek for the nearest word and shift
985 // the cursor before entering the motion.
986 vimGlobalState.jumpList.cachedCursor = cm.getCursor();
987 cm.setCursor(word.start);
989 handleQuery(query, true /** ignoreCase */, false /** smartCase */);
993 processEx: function(cm, vim, command) {
994 function onPromptClose(input) {
995 // Give the prompt some time to close so that if processCommand shows
996 // an error, the elements don't overlap.
997 exCommandDispatcher.processCommand(cm, input);
999 function onPromptKeyDown(e, _input, close) {
1000 var keyName = CodeMirror.keyName(e);
1001 if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
1002 CodeMirror.e_stop(e);
1007 if (command.type == 'keyToEx') {
1008 // Handle user defined Ex to Ex mappings
1009 exCommandDispatcher.processCommand(cm, command.exArgs.input);
1011 if (vim.visualMode) {
1012 showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
1013 onKeyDown: onPromptKeyDown});
1015 showPrompt(cm, { onClose: onPromptClose, prefix: ':',
1016 onKeyDown: onPromptKeyDown});
1020 evalInput: function(cm, vim) {
1021 // If the motion comand is set, execute both the operator and motion.
1022 // Otherwise return.
1023 var inputState = vim.inputState;
1024 var motion = inputState.motion;
1025 var motionArgs = inputState.motionArgs || {};
1026 var operator = inputState.operator;
1027 var operatorArgs = inputState.operatorArgs || {};
1028 var registerName = inputState.registerName;
1029 var selectionEnd = cm.getCursor('head');
1030 var selectionStart = cm.getCursor('anchor');
1031 // The difference between cur and selection cursors are that cur is
1032 // being operated on and ignores that there is a selection.
1033 var curStart = copyCursor(selectionEnd);
1034 var curOriginal = copyCursor(curStart);
1038 this.recordLastEdit(vim, inputState);
1040 if (inputState.repeatOverride !== undefined) {
1041 // If repeatOverride is specified, that takes precedence over the
1042 // input state's repeat. Used by Ex mode and can be user defined.
1043 repeat = inputState.repeatOverride;
1045 repeat = inputState.getRepeat();
1047 if (repeat > 0 && motionArgs.explicitRepeat) {
1048 motionArgs.repeatIsExplicit = true;
1049 } else if (motionArgs.noRepeat ||
1050 (!motionArgs.explicitRepeat && repeat === 0)) {
1052 motionArgs.repeatIsExplicit = false;
1054 if (inputState.selectedCharacter) {
1055 // If there is a character input, stick it in all of the arg arrays.
1056 motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
1057 inputState.selectedCharacter;
1059 motionArgs.repeat = repeat;
1060 vim.inputState = new InputState();
1062 var motionResult = motions[motion](cm, motionArgs, vim);
1063 vim.lastMotion = motions[motion];
1064 if (!motionResult) {
1067 if (motionArgs.toJumplist) {
1068 var jumpList = vimGlobalState.jumpList;
1069 // if the current motion is # or *, use cachedCursor
1070 var cachedCursor = jumpList.cachedCursor;
1072 recordJumpPosition(cm, cachedCursor, motionResult);
1073 delete jumpList.cachedCursor;
1075 recordJumpPosition(cm, curOriginal, motionResult);
1078 if (motionResult instanceof Array) {
1079 curStart = motionResult[0];
1080 curEnd = motionResult[1];
1082 curEnd = motionResult;
1084 // TODO: Handle null returns from motion commands better.
1086 curEnd = { ch: curStart.ch, line: curStart.line };
1088 if (vim.visualMode) {
1089 // Check if the selection crossed over itself. Will need to shift
1090 // the start point if that happened.
1091 if (cursorIsBefore(selectionStart, selectionEnd) &&
1092 (cursorEqual(selectionStart, curEnd) ||
1093 cursorIsBefore(curEnd, selectionStart))) {
1094 // The end of the selection has moved from after the start to
1095 // before the start. We will shift the start right by 1.
1096 selectionStart.ch += 1;
1097 } else if (cursorIsBefore(selectionEnd, selectionStart) &&
1098 (cursorEqual(selectionStart, curEnd) ||
1099 cursorIsBefore(selectionStart, curEnd))) {
1100 // The opposite happened. We will shift the start left by 1.
1101 selectionStart.ch -= 1;
1103 selectionEnd = curEnd;
1104 if (vim.visualLine) {
1105 if (cursorIsBefore(selectionStart, selectionEnd)) {
1106 selectionStart.ch = 0;
1107 selectionEnd.ch = lineLength(cm, selectionEnd.line);
1109 selectionEnd.ch = 0;
1110 selectionStart.ch = lineLength(cm, selectionStart.line);
1113 cm.setSelection(selectionStart, selectionEnd);
1114 updateMark(cm, vim, '<',
1115 cursorIsBefore(selectionStart, selectionEnd) ? selectionStart
1117 updateMark(cm, vim, '>',
1118 cursorIsBefore(selectionStart, selectionEnd) ? selectionEnd
1120 } else if (!operator) {
1121 curEnd = clipCursorToContent(cm, curEnd);
1122 cm.setCursor(curEnd.line, curEnd.ch);
1127 var inverted = false;
1128 vim.lastMotion = null;
1129 operatorArgs.repeat = repeat; // Indent in visual mode needs this.
1130 if (vim.visualMode) {
1131 curStart = selectionStart;
1132 curEnd = selectionEnd;
1133 motionArgs.inclusive = true;
1135 // Swap start and end if motion was backward.
1136 if (cursorIsBefore(curEnd, curStart)) {
1142 if (motionArgs.inclusive && !(vim.visualMode && inverted)) {
1143 // Move the selection end one to the right to include the last
1147 var linewise = motionArgs.linewise ||
1148 (vim.visualMode && vim.visualLine);
1150 // Expand selection to entire line.
1151 expandSelectionToLine(cm, curStart, curEnd);
1152 } else if (motionArgs.forward) {
1153 // Clip to trailing newlines only if the motion goes forward.
1154 clipToLine(cm, curStart, curEnd);
1156 operatorArgs.registerName = registerName;
1157 // Keep track of linewise as it affects how paste and change behave.
1158 operatorArgs.linewise = linewise;
1159 operators[operator](cm, operatorArgs, vim, curStart,
1160 curEnd, curOriginal);
1161 if (vim.visualMode) {
1166 recordLastEdit: function(vim, inputState, actionCommand) {
1167 var macroModeState = vimGlobalState.macroModeState;
1168 if (macroModeState.inReplay) { return; }
1169 vim.lastEditInputState = inputState;
1170 vim.lastEditActionCommand = actionCommand;
1171 macroModeState.lastInsertModeChanges.changes = [];
1172 macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
1177 * typedef {Object{line:number,ch:number}} Cursor An object containing the
1178 * position of the cursor.
1180 // All of the functions below return Cursor objects.
1182 moveToTopLine: function(cm, motionArgs) {
1183 var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
1184 return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
1186 moveToMiddleLine: function(cm) {
1187 var range = getUserVisibleLines(cm);
1188 var line = Math.floor((range.top + range.bottom) * 0.5);
1189 return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
1191 moveToBottomLine: function(cm, motionArgs) {
1192 var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
1193 return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
1195 expandToLine: function(cm, motionArgs) {
1196 // Expands forward to end of line, and then to next line if repeat is
1197 // >1. Does not handle backward motion!
1198 var cur = cm.getCursor();
1199 return { line: cur.line + motionArgs.repeat - 1, ch: Infinity };
1201 findNext: function(cm, motionArgs) {
1202 var state = getSearchState(cm);
1203 var query = state.getQuery();
1207 var prev = !motionArgs.forward;
1208 // If search is initiated with ? instead of /, negate direction.
1209 prev = (state.isReversed()) ? !prev : prev;
1210 highlightSearchMatches(cm, query);
1211 return findNext(cm, prev/** prev */, query, motionArgs.repeat);
1213 goToMark: function(_cm, motionArgs, vim) {
1214 var mark = vim.marks[motionArgs.selectedCharacter];
1220 jumpToMark: function(cm, motionArgs, vim) {
1221 var best = cm.getCursor();
1222 for (var i = 0; i < motionArgs.repeat; i++) {
1224 for (var key in vim.marks) {
1225 if (!isLowerCase(key)) {
1228 var mark = vim.marks[key].find();
1229 var isWrongDirection = (motionArgs.forward) ?
1230 cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
1232 if (isWrongDirection) {
1235 if (motionArgs.linewise && (mark.line == cursor.line)) {
1239 var equal = cursorEqual(cursor, best);
1240 var between = (motionArgs.forward) ?
1241 cusrorIsBetween(cursor, mark, best) :
1242 cusrorIsBetween(best, mark, cursor);
1244 if (equal || between) {
1250 if (motionArgs.linewise) {
1251 // Vim places the cursor on the first non-whitespace character of
1252 // the line if there is one, else it places the cursor at the end
1253 // of the line, regardless of whether a mark was found.
1254 best.ch = findFirstNonWhiteSpaceCharacter(cm.getLine(best.line));
1258 moveByCharacters: function(cm, motionArgs) {
1259 var cur = cm.getCursor();
1260 var repeat = motionArgs.repeat;
1261 var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
1262 return { line: cur.line, ch: ch };
1264 moveByLines: function(cm, motionArgs, vim) {
1265 var cur = cm.getCursor();
1267 // Depending what our last motion was, we may want to do different
1268 // things. If our last motion was moving vertically, we want to
1269 // preserve the HPos from our last horizontal move. If our last motion
1270 // was going to the end of a line, moving vertically we should go to
1271 // the end of the line, etc.
1272 switch (vim.lastMotion) {
1273 case this.moveByLines:
1274 case this.moveByDisplayLines:
1275 case this.moveByScroll:
1276 case this.moveToColumn:
1277 case this.moveToEol:
1278 endCh = vim.lastHPos;
1281 vim.lastHPos = endCh;
1283 var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
1284 var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
1285 var first = cm.firstLine();
1286 var last = cm.lastLine();
1287 // Vim cancels linewise motions that start on an edge and move beyond
1288 // that edge. It does not cancel motions that do not start on an edge.
1289 if ((line < first && cur.line == first) ||
1290 (line > last && cur.line == last)) {
1293 if(motionArgs.toFirstChar){
1294 endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
1295 vim.lastHPos = endCh;
1297 vim.lastHSPos = cm.charCoords({line:line, ch:endCh},'div').left;
1298 return { line: line, ch: endCh };
1300 moveByDisplayLines: function(cm, motionArgs, vim) {
1301 var cur = cm.getCursor();
1302 switch (vim.lastMotion) {
1303 case this.moveByDisplayLines:
1304 case this.moveByScroll:
1305 case this.moveByLines:
1306 case this.moveToColumn:
1307 case this.moveToEol:
1310 vim.lastHSPos = cm.charCoords(cur,'div').left;
1312 var repeat = motionArgs.repeat;
1313 var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
1315 if (motionArgs.forward) {
1316 var lastCharCoords = cm.charCoords(res, 'div');
1317 var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
1318 var res = cm.coordsChar(goalCoords, 'div');
1320 var resCoords = cm.charCoords({ line: cm.firstLine(), ch: 0}, 'div');
1321 resCoords.left = vim.lastHSPos;
1322 res = cm.coordsChar(resCoords, 'div');
1325 vim.lastHPos = res.ch;
1328 moveByPage: function(cm, motionArgs) {
1329 // CodeMirror only exposes functions that move the cursor page down, so
1330 // doing this bad hack to move the cursor and move it back. evalInput
1331 // will move the cursor to where it should be in the end.
1332 var curStart = cm.getCursor();
1333 var repeat = motionArgs.repeat;
1334 cm.moveV((motionArgs.forward ? repeat : -repeat), 'page');
1335 var curEnd = cm.getCursor();
1336 cm.setCursor(curStart);
1339 moveByParagraph: function(cm, motionArgs) {
1340 var line = cm.getCursor().line;
1341 var repeat = motionArgs.repeat;
1342 var inc = motionArgs.forward ? 1 : -1;
1343 for (var i = 0; i < repeat; i++) {
1344 if ((!motionArgs.forward && line === cm.firstLine() ) ||
1345 (motionArgs.forward && line == cm.lastLine())) {
1349 while (line !== cm.firstLine() && line != cm.lastLine() && cm.getLine(line)) {
1353 return { line: line, ch: 0 };
1355 moveByScroll: function(cm, motionArgs, vim) {
1356 var scrollbox = cm.getScrollInfo();
1358 var repeat = motionArgs.repeat;
1360 repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
1362 var orig = cm.charCoords(cm.getCursor(), 'local');
1363 motionArgs.repeat = repeat;
1364 var curEnd = motions.moveByDisplayLines(cm, motionArgs, vim);
1368 var dest = cm.charCoords(curEnd, 'local');
1369 cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
1372 moveByWords: function(cm, motionArgs) {
1373 return moveToWord(cm, motionArgs.repeat, !!motionArgs.forward,
1374 !!motionArgs.wordEnd, !!motionArgs.bigWord);
1376 moveTillCharacter: function(cm, motionArgs) {
1377 var repeat = motionArgs.repeat;
1378 var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
1379 motionArgs.selectedCharacter);
1380 var increment = motionArgs.forward ? -1 : 1;
1381 recordLastCharacterSearch(increment, motionArgs);
1382 if(!curEnd)return cm.getCursor();
1383 curEnd.ch += increment;
1386 moveToCharacter: function(cm, motionArgs) {
1387 var repeat = motionArgs.repeat;
1388 recordLastCharacterSearch(0, motionArgs);
1389 return moveToCharacter(cm, repeat, motionArgs.forward,
1390 motionArgs.selectedCharacter) || cm.getCursor();
1392 moveToSymbol: function(cm, motionArgs) {
1393 var repeat = motionArgs.repeat;
1394 return findSymbol(cm, repeat, motionArgs.forward,
1395 motionArgs.selectedCharacter) || cm.getCursor();
1397 moveToColumn: function(cm, motionArgs, vim) {
1398 var repeat = motionArgs.repeat;
1399 // repeat is equivalent to which column we want to move to!
1400 vim.lastHPos = repeat - 1;
1401 vim.lastHSPos = cm.charCoords(cm.getCursor(),'div').left;
1402 return moveToColumn(cm, repeat);
1404 moveToEol: function(cm, motionArgs, vim) {
1405 var cur = cm.getCursor();
1406 vim.lastHPos = Infinity;
1407 var retval={ line: cur.line + motionArgs.repeat - 1, ch: Infinity };
1408 var end=cm.clipPos(retval);
1410 vim.lastHSPos = cm.charCoords(end,'div').left;
1413 moveToFirstNonWhiteSpaceCharacter: function(cm) {
1414 // Go to the start of the line where the text begins, or the end for
1415 // whitespace-only lines
1416 var cursor = cm.getCursor();
1417 return { line: cursor.line,
1418 ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)) };
1420 moveToMatchedSymbol: function(cm) {
1421 var cursor = cm.getCursor();
1422 var line = cursor.line;
1424 var lineText = cm.getLine(line);
1426 var startContext = cm.getTokenAt(cursor).type;
1427 var startCtxLevel = getContextLevel(startContext);
1429 symbol = lineText.charAt(ch++);
1430 if (symbol && isMatchableSymbol(symbol)) {
1431 var endContext = cm.getTokenAt({line:line, ch:ch}).type;
1432 var endCtxLevel = getContextLevel(endContext);
1433 if (startCtxLevel >= endCtxLevel) {
1439 return findMatchedSymbol(cm, {line:line, ch:ch-1}, symbol);
1444 moveToStartOfLine: function(cm) {
1445 var cursor = cm.getCursor();
1446 return { line: cursor.line, ch: 0 };
1448 moveToLineOrEdgeOfDocument: function(cm, motionArgs) {
1449 var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
1450 if (motionArgs.repeatIsExplicit) {
1451 lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
1453 return { line: lineNum,
1454 ch: findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)) };
1456 textObjectManipulation: function(cm, motionArgs) {
1457 var character = motionArgs.selectedCharacter;
1458 // Inclusive is the difference between a and i
1459 // TODO: Instead of using the additional text object map to perform text
1460 // object operations, merge the map into the defaultKeyMap and use
1461 // motionArgs to define behavior. Define separate entries for 'aw',
1462 // 'iw', 'a[', 'i[', etc.
1463 var inclusive = !motionArgs.textObjectInner;
1464 if (!textObjects[character]) {
1465 // No text object defined for this, don't move.
1468 var tmp = textObjects[character](cm, inclusive);
1469 var start = tmp.start;
1471 return [start, end];
1473 repeatLastCharacterSearch: function(cm, motionArgs) {
1474 var lastSearch = vimGlobalState.lastChararacterSearch;
1475 var repeat = motionArgs.repeat;
1476 var forward = motionArgs.forward === lastSearch.forward;
1477 var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
1478 cm.moveH(-increment, 'char');
1479 motionArgs.inclusive = forward ? true : false;
1480 var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
1482 cm.moveH(increment, 'char');
1483 return cm.getCursor();
1485 curEnd.ch += increment;
1491 change: function(cm, operatorArgs, _vim, curStart, curEnd) {
1492 vimGlobalState.registerController.pushText(
1493 operatorArgs.registerName, 'change', cm.getRange(curStart, curEnd),
1494 operatorArgs.linewise);
1495 if (operatorArgs.linewise) {
1496 // Push the next line back down, if there is a next line.
1497 var replacement = curEnd.line > cm.lastLine() ? '' : '\n';
1498 cm.replaceRange(replacement, curStart, curEnd);
1499 cm.indentLine(curStart.line, 'smart');
1500 // null ch so setCursor moves to end of line.
1503 // Exclude trailing whitespace if the range is not all whitespace.
1504 var text = cm.getRange(curStart, curEnd);
1505 if (!isWhiteSpaceString(text)) {
1506 var match = (/\s+$/).exec(text);
1508 curEnd = offsetCursor(curEnd, 0, - match[0].length);
1511 cm.replaceRange('', curStart, curEnd);
1513 actions.enterInsertMode(cm, {}, cm.state.vim);
1514 cm.setCursor(curStart);
1516 // delete is a javascript keyword.
1517 'delete': function(cm, operatorArgs, _vim, curStart, curEnd) {
1518 // If the ending line is past the last line, inclusive, instead of
1519 // including the trailing \n, include the \n before the starting line
1520 if (operatorArgs.linewise &&
1521 curEnd.line > cm.lastLine() && curStart.line > cm.firstLine()) {
1523 curStart.ch = lineLength(cm, curStart.line);
1525 vimGlobalState.registerController.pushText(
1526 operatorArgs.registerName, 'delete', cm.getRange(curStart, curEnd),
1527 operatorArgs.linewise);
1528 cm.replaceRange('', curStart, curEnd);
1529 if (operatorArgs.linewise) {
1530 cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
1532 cm.setCursor(curStart);
1535 indent: function(cm, operatorArgs, vim, curStart, curEnd) {
1536 var startLine = curStart.line;
1537 var endLine = curEnd.line;
1538 // In visual mode, n> shifts the selection right n times, instead of
1539 // shifting n lines right once.
1540 var repeat = (vim.visualMode) ? operatorArgs.repeat : 1;
1541 if (operatorArgs.linewise) {
1542 // The only way to delete a newline is to delete until the start of
1543 // the next line, so in linewise mode evalInput will include the next
1544 // line. We don't want this in indent, so we go back a line.
1547 for (var i = startLine; i <= endLine; i++) {
1548 for (var j = 0; j < repeat; j++) {
1549 cm.indentLine(i, operatorArgs.indentRight);
1552 cm.setCursor(curStart);
1553 cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
1555 swapcase: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
1556 var toSwap = cm.getRange(curStart, curEnd);
1558 for (var i = 0; i < toSwap.length; i++) {
1559 var character = toSwap.charAt(i);
1560 swapped += isUpperCase(character) ? character.toLowerCase() :
1561 character.toUpperCase();
1563 cm.replaceRange(swapped, curStart, curEnd);
1564 if (!operatorArgs.shouldMoveCursor) {
1565 cm.setCursor(curOriginal);
1568 yank: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
1569 vimGlobalState.registerController.pushText(
1570 operatorArgs.registerName, 'yank',
1571 cm.getRange(curStart, curEnd), operatorArgs.linewise);
1572 cm.setCursor(curOriginal);
1577 jumpListWalk: function(cm, actionArgs, vim) {
1578 if (vim.visualMode) {
1581 var repeat = actionArgs.repeat;
1582 var forward = actionArgs.forward;
1583 var jumpList = vimGlobalState.jumpList;
1585 var mark = jumpList.move(cm, forward ? repeat : -repeat);
1586 var markPos = mark ? mark.find() : undefined;
1587 markPos = markPos ? markPos : cm.getCursor();
1588 cm.setCursor(markPos);
1590 scrollToCursor: function(cm, actionArgs) {
1591 var lineNum = cm.getCursor().line;
1592 var charCoords = cm.charCoords({line: lineNum, ch: 0}, 'local');
1593 var height = cm.getScrollInfo().clientHeight;
1594 var y = charCoords.top;
1595 var lineHeight = charCoords.bottom - y;
1596 switch (actionArgs.position) {
1597 case 'center': y = y - (height / 2) + lineHeight;
1599 case 'bottom': y = y - height + lineHeight*1.4;
1601 case 'top': y = y + lineHeight*0.4;
1604 cm.scrollTo(null, y);
1606 replayMacro: function(cm, actionArgs) {
1607 var registerName = actionArgs.selectedCharacter;
1608 var repeat = actionArgs.repeat;
1609 var macroModeState = vimGlobalState.macroModeState;
1610 if (registerName == '@') {
1611 registerName = macroModeState.latestRegister;
1613 var keyBuffer = parseRegisterToKeyBuffer(macroModeState, registerName);
1615 executeMacroKeyBuffer(cm, macroModeState, keyBuffer);
1618 exitMacroRecordMode: function() {
1619 var macroModeState = vimGlobalState.macroModeState;
1620 macroModeState.toggle();
1621 parseKeyBufferToRegister(macroModeState.latestRegister,
1622 macroModeState.macroKeyBuffer);
1624 enterMacroRecordMode: function(cm, actionArgs) {
1625 var macroModeState = vimGlobalState.macroModeState;
1626 var registerName = actionArgs.selectedCharacter;
1627 macroModeState.toggle(cm, registerName);
1628 emptyMacroKeyBuffer(macroModeState);
1630 enterInsertMode: function(cm, actionArgs, vim) {
1631 if (cm.getOption('readOnly')) { return; }
1632 vim.insertMode = true;
1633 vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
1634 var insertAt = (actionArgs) ? actionArgs.insertAt : null;
1635 if (insertAt == 'eol') {
1636 var cursor = cm.getCursor();
1637 cursor = { line: cursor.line, ch: lineLength(cm, cursor.line) };
1638 cm.setCursor(cursor);
1639 } else if (insertAt == 'charAfter') {
1640 cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
1641 } else if (insertAt == 'firstNonBlank') {
1642 cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
1644 cm.setOption('keyMap', 'vim-insert');
1645 if (actionArgs && actionArgs.replace) {
1646 // Handle Replace-mode as a special case of insert mode.
1647 cm.toggleOverwrite(true);
1648 cm.setOption('keyMap', 'vim-replace');
1650 cm.setOption('keyMap', 'vim-insert');
1652 if (!vimGlobalState.macroModeState.inReplay) {
1653 // Only record if not replaying.
1654 cm.on('change', onChange);
1655 cm.on('cursorActivity', onCursorActivity);
1656 CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
1659 toggleVisualMode: function(cm, actionArgs, vim) {
1660 var repeat = actionArgs.repeat;
1661 var curStart = cm.getCursor();
1663 // TODO: The repeat should actually select number of characters/lines
1664 // equal to the repeat times the size of the previous visual
1666 if (!vim.visualMode) {
1667 cm.on('mousedown', exitVisualMode);
1668 vim.visualMode = true;
1669 vim.visualLine = !!actionArgs.linewise;
1670 if (vim.visualLine) {
1672 curEnd = clipCursorToContent(cm, {
1673 line: curStart.line + repeat - 1,
1674 ch: lineLength(cm, curStart.line)
1675 }, true /** includeLineBreak */);
1677 curEnd = clipCursorToContent(cm, {
1678 line: curStart.line,
1679 ch: curStart.ch + repeat
1680 }, true /** includeLineBreak */);
1682 // Make the initial selection.
1683 if (!actionArgs.repeatIsExplicit && !vim.visualLine) {
1684 // This is a strange case. Here the implicit repeat is 1. The
1685 // following commands lets the cursor hover over the 1 character
1687 cm.setCursor(curEnd);
1688 cm.setSelection(curEnd, curStart);
1690 cm.setSelection(curStart, curEnd);
1693 curStart = cm.getCursor('anchor');
1694 curEnd = cm.getCursor('head');
1695 if (!vim.visualLine && actionArgs.linewise) {
1696 // Shift-V pressed in characterwise visual mode. Switch to linewise
1697 // visual mode instead of exiting visual mode.
1698 vim.visualLine = true;
1699 curStart.ch = cursorIsBefore(curStart, curEnd) ? 0 :
1700 lineLength(cm, curStart.line);
1701 curEnd.ch = cursorIsBefore(curStart, curEnd) ?
1702 lineLength(cm, curEnd.line) : 0;
1703 cm.setSelection(curStart, curEnd);
1704 } else if (vim.visualLine && !actionArgs.linewise) {
1705 // v pressed in linewise visual mode. Switch to characterwise visual
1706 // mode instead of exiting visual mode.
1707 vim.visualLine = false;
1712 updateMark(cm, vim, '<', cursorIsBefore(curStart, curEnd) ? curStart
1714 updateMark(cm, vim, '>', cursorIsBefore(curStart, curEnd) ? curEnd
1717 joinLines: function(cm, actionArgs, vim) {
1718 var curStart, curEnd;
1719 if (vim.visualMode) {
1720 curStart = cm.getCursor('anchor');
1721 curEnd = cm.getCursor('head');
1722 curEnd.ch = lineLength(cm, curEnd.line) - 1;
1724 // Repeat is the number of lines to join. Minimum 2 lines.
1725 var repeat = Math.max(actionArgs.repeat, 2);
1726 curStart = cm.getCursor();
1727 curEnd = clipCursorToContent(cm, { line: curStart.line + repeat - 1,
1731 cm.operation(function() {
1732 for (var i = curStart.line; i < curEnd.line; i++) {
1733 finalCh = lineLength(cm, curStart.line);
1734 var tmp = { line: curStart.line + 1,
1735 ch: lineLength(cm, curStart.line + 1) };
1736 var text = cm.getRange(curStart, tmp);
1737 text = text.replace(/\n\s*/g, ' ');
1738 cm.replaceRange(text, curStart, tmp);
1740 var curFinalPos = { line: curStart.line, ch: finalCh };
1741 cm.setCursor(curFinalPos);
1744 newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
1745 vim.insertMode = true;
1746 var insertAt = cm.getCursor();
1747 if (insertAt.line === cm.firstLine() && !actionArgs.after) {
1748 // Special case for inserting newline before start of document.
1749 cm.replaceRange('\n', { line: cm.firstLine(), ch: 0 });
1750 cm.setCursor(cm.firstLine(), 0);
1752 insertAt.line = (actionArgs.after) ? insertAt.line :
1754 insertAt.ch = lineLength(cm, insertAt.line);
1755 cm.setCursor(insertAt);
1756 var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
1757 CodeMirror.commands.newlineAndIndent;
1760 this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
1762 paste: function(cm, actionArgs) {
1763 var cur = cm.getCursor();
1764 var register = vimGlobalState.registerController.getRegister(
1765 actionArgs.registerName);
1766 if (!register.text) {
1769 for (var text = '', i = 0; i < actionArgs.repeat; i++) {
1770 text += register.text;
1772 var linewise = register.linewise;
1774 if (actionArgs.after) {
1775 // Move the newline at the end to the start instead, and paste just
1776 // before the newline character of the line we are on right now.
1777 text = '\n' + text.slice(0, text.length - 1);
1778 cur.ch = lineLength(cm, cur.line);
1783 cur.ch += actionArgs.after ? 1 : 0;
1785 cm.replaceRange(text, cur);
1786 // Now fine tune the cursor to where we want it.
1789 if (linewise && actionArgs.after) {
1790 curPosFinal = { line: cur.line + 1,
1791 ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)) };
1792 } else if (linewise && !actionArgs.after) {
1793 curPosFinal = { line: cur.line,
1794 ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)) };
1795 } else if (!linewise && actionArgs.after) {
1796 idx = cm.indexFromPos(cur);
1797 curPosFinal = cm.posFromIndex(idx + text.length - 1);
1799 idx = cm.indexFromPos(cur);
1800 curPosFinal = cm.posFromIndex(idx + text.length);
1802 cm.setCursor(curPosFinal);
1804 undo: function(cm, actionArgs) {
1805 cm.operation(function() {
1806 repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
1807 cm.setCursor(cm.getCursor('anchor'));
1810 redo: function(cm, actionArgs) {
1811 repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
1813 setRegister: function(_cm, actionArgs, vim) {
1814 vim.inputState.registerName = actionArgs.selectedCharacter;
1816 setMark: function(cm, actionArgs, vim) {
1817 var markName = actionArgs.selectedCharacter;
1818 updateMark(cm, vim, markName, cm.getCursor());
1820 replace: function(cm, actionArgs, vim) {
1821 var replaceWith = actionArgs.selectedCharacter;
1822 var curStart = cm.getCursor();
1826 curStart=cm.getCursor('start');
1827 curEnd=cm.getCursor('end');
1828 // workaround to catch the character under the cursor
1829 // existing workaround doesn't cover actions
1830 curEnd=cm.clipPos({line: curEnd.line, ch: curEnd.ch+1});
1832 var line = cm.getLine(curStart.line);
1833 replaceTo = curStart.ch + actionArgs.repeat;
1834 if (replaceTo > line.length) {
1835 replaceTo=line.length;
1837 curEnd = { line: curStart.line, ch: replaceTo };
1839 if(replaceWith=='\n'){
1840 if(!vim.visualMode) cm.replaceRange('', curStart, curEnd);
1841 // special case, where vim help says to replace by just one line-break
1842 (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
1844 var replaceWithStr=cm.getRange(curStart, curEnd);
1845 //replace all characters in range by selected, but keep linebreaks
1846 replaceWithStr=replaceWithStr.replace(/[^\n]/g,replaceWith);
1847 cm.replaceRange(replaceWithStr, curStart, curEnd);
1849 cm.setCursor(curStart);
1852 cm.setCursor(offsetCursor(curEnd, 0, -1));
1856 incrementNumberToken: function(cm, actionArgs) {
1857 var cur = cm.getCursor();
1858 var lineStr = cm.getLine(cur.line);
1865 while ((match = re.exec(lineStr)) !== null) {
1867 start = match.index;
1868 end = start + token.length;
1869 if(cur.ch < end)break;
1871 if(!actionArgs.backtrack && (end <= cur.ch))return;
1873 var increment = actionArgs.increase ? 1 : -1;
1874 var number = parseInt(token) + (increment * actionArgs.repeat);
1875 var from = {ch:start, line:cur.line};
1876 var to = {ch:end, line:cur.line};
1877 numberStr = number.toString();
1878 cm.replaceRange(numberStr, from, to);
1882 cm.setCursor({line: cur.line, ch: start + numberStr.length - 1});
1884 repeatLastEdit: function(cm, actionArgs, vim) {
1885 var lastEditInputState = vim.lastEditInputState;
1886 if (!lastEditInputState) { return; }
1887 var repeat = actionArgs.repeat;
1888 if (repeat && actionArgs.repeatIsExplicit) {
1889 vim.lastEditInputState.repeatOverride = repeat;
1891 repeat = vim.lastEditInputState.repeatOverride || repeat;
1893 repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
1898 // TODO: lots of possible exceptions that can be thrown here. Try da(
1899 // outside of a () block.
1900 // TODO: implement text objects for the reverse like }. Should just be
1901 // an additional mapping after moving to the defaultKeyMap.
1902 'w': function(cm, inclusive) {
1903 return expandWordUnderCursor(cm, inclusive, true /** forward */,
1904 false /** bigWord */);
1906 'W': function(cm, inclusive) {
1907 return expandWordUnderCursor(cm, inclusive,
1908 true /** forward */, true /** bigWord */);
1910 '{': function(cm, inclusive) {
1911 return selectCompanionObject(cm, '}', inclusive);
1913 '(': function(cm, inclusive) {
1914 return selectCompanionObject(cm, ')', inclusive);
1916 '[': function(cm, inclusive) {
1917 return selectCompanionObject(cm, ']', inclusive);
1919 '\'': function(cm, inclusive) {
1920 return findBeginningAndEnd(cm, "'", inclusive);
1922 '"': function(cm, inclusive) {
1923 return findBeginningAndEnd(cm, '"', inclusive);
1928 * Below are miscellaneous utility functions used by vim.js
1932 * Clips cursor to ensure that line is within the buffer's range
1933 * If includeLineBreak is true, then allow cur.ch == lineLength.
1935 function clipCursorToContent(cm, cur, includeLineBreak) {
1936 var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
1937 var maxCh = lineLength(cm, line) - 1;
1938 maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
1939 var ch = Math.min(Math.max(0, cur.ch), maxCh);
1940 return { line: line, ch: ch };
1942 function copyArgs(args) {
1944 for (var prop in args) {
1945 if (args.hasOwnProperty(prop)) {
1946 ret[prop] = args[prop];
1951 function offsetCursor(cur, offsetLine, offsetCh) {
1952 return { line: cur.line + offsetLine, ch: cur.ch + offsetCh };
1954 function matchKeysPartial(pressed, mapped) {
1955 for (var i = 0; i < pressed.length; i++) {
1956 // 'character' means any character. For mark, register commads, etc.
1957 if (pressed[i] != mapped[i] && mapped[i] != 'character') {
1963 function repeatFn(cm, fn, repeat) {
1965 for (var i = 0; i < repeat; i++) {
1970 function copyCursor(cur) {
1971 return { line: cur.line, ch: cur.ch };
1973 function cursorEqual(cur1, cur2) {
1974 return cur1.ch == cur2.ch && cur1.line == cur2.line;
1976 function cursorIsBefore(cur1, cur2) {
1977 if (cur1.line < cur2.line) {
1980 if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
1985 function cusrorIsBetween(cur1, cur2, cur3) {
1986 // returns true if cur2 is between cur1 and cur3.
1987 var cur1before2 = cursorIsBefore(cur1, cur2);
1988 var cur2before3 = cursorIsBefore(cur2, cur3);
1989 return cur1before2 && cur2before3;
1991 function lineLength(cm, lineNum) {
1992 return cm.getLine(lineNum).length;
1994 function reverse(s){
1995 return s.split('').reverse().join('');
2001 return s.replace(/^\s+|\s+$/g, '');
2003 function escapeRegex(s) {
2004 return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
2007 function exitVisualMode(cm) {
2008 cm.off('mousedown', exitVisualMode);
2009 var vim = cm.state.vim;
2010 vim.visualMode = false;
2011 vim.visualLine = false;
2012 var selectionStart = cm.getCursor('anchor');
2013 var selectionEnd = cm.getCursor('head');
2014 if (!cursorEqual(selectionStart, selectionEnd)) {
2015 // Clear the selection and set the cursor only if the selection has not
2016 // already been cleared. Otherwise we risk moving the cursor somewhere
2017 // it's not supposed to be.
2018 cm.setCursor(clipCursorToContent(cm, selectionEnd));
2022 // Remove any trailing newlines from the selection. For
2023 // example, with the caret at the start of the last word on the line,
2024 // 'dw' should word, but not the newline, while 'w' should advance the
2025 // caret to the first character of the next line.
2026 function clipToLine(cm, curStart, curEnd) {
2027 var selection = cm.getRange(curStart, curEnd);
2028 // Only clip if the selection ends with trailing newline + whitespace
2029 if (/\n\s*$/.test(selection)) {
2030 var lines = selection.split('\n');
2031 // We know this is all whitepsace.
2035 // 1. Last word is an empty line - do not clip the trailing '\n'
2036 // 2. Last word is not an empty line - clip the trailing '\n'
2038 // Find the line containing the last word, and clip all whitespace up
2040 for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
2044 // If the last word is not an empty line, clip an additional newline
2047 curEnd.ch = lineLength(cm, curEnd.line);
2054 // Expand the selection to line ends.
2055 function expandSelectionToLine(_cm, curStart, curEnd) {
2061 function findFirstNonWhiteSpaceCharacter(text) {
2065 var firstNonWS = text.search(/\S/);
2066 return firstNonWS == -1 ? text.length : firstNonWS;
2069 function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
2070 var cur = cm.getCursor();
2071 var line = cm.getLine(cur.line);
2074 // Seek to first word or non-whitespace character, depending on if
2075 // noSymbol is true.
2076 var textAfterIdx = line.substring(idx);
2077 var firstMatchedChar;
2079 firstMatchedChar = textAfterIdx.search(/\w/);
2081 firstMatchedChar = textAfterIdx.search(/\S/);
2083 if (firstMatchedChar == -1) {
2086 idx += firstMatchedChar;
2087 textAfterIdx = line.substring(idx);
2088 var textBeforeIdx = line.substring(0, idx);
2091 // Greedy matchers for the "word" we are trying to expand.
2093 matchRegex = /^\S+/;
2095 if ((/\w/).test(line.charAt(idx))) {
2096 matchRegex = /^\w+/;
2098 matchRegex = /^[^\w\s]+/;
2102 var wordAfterRegex = matchRegex.exec(textAfterIdx);
2103 var wordStart = idx;
2104 var wordEnd = idx + wordAfterRegex[0].length;
2105 // TODO: Find a better way to do this. It will be slow on very long lines.
2106 var revTextBeforeIdx = reverse(textBeforeIdx);
2107 var wordBeforeRegex = matchRegex.exec(revTextBeforeIdx);
2108 if (wordBeforeRegex) {
2109 wordStart -= wordBeforeRegex[0].length;
2113 // If present, trim all whitespace after word.
2114 // Otherwise, trim all whitespace before word.
2115 var textAfterWordEnd = line.substring(wordEnd);
2116 var whitespacesAfterWord = textAfterWordEnd.match(/^\s*/)[0].length;
2117 if (whitespacesAfterWord > 0) {
2118 wordEnd += whitespacesAfterWord;
2120 var revTrim = revTextBeforeIdx.length - wordStart;
2121 var textBeforeWordStart = revTextBeforeIdx.substring(revTrim);
2122 var whitespacesBeforeWord = textBeforeWordStart.match(/^\s*/)[0].length;
2123 wordStart -= whitespacesBeforeWord;
2127 return { start: { line: cur.line, ch: wordStart },
2128 end: { line: cur.line, ch: wordEnd }};
2131 function recordJumpPosition(cm, oldCur, newCur) {
2132 if(!cursorEqual(oldCur, newCur)) {
2133 vimGlobalState.jumpList.add(cm, oldCur, newCur);
2137 function recordLastCharacterSearch(increment, args) {
2138 vimGlobalState.lastChararacterSearch.increment = increment;
2139 vimGlobalState.lastChararacterSearch.forward = args.forward;
2140 vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter;
2143 var symbolToMode = {
2144 '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
2145 '[': 'section', ']': 'section',
2146 '*': 'comment', '/': 'comment',
2147 'm': 'method', 'M': 'method',
2150 var findSymbolModes = {
2152 isComplete: function(state) {
2153 if (state.nextCh === state.symb) {
2155 if(state.depth >= 1)return true;
2156 } else if (state.nextCh === state.reverseSymb) {
2163 init: function(state) {
2164 state.curMoveThrough = true;
2165 state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
2167 isComplete: function(state) {
2168 return state.index === 0 && state.nextCh === state.symb;
2172 isComplete: function(state) {
2173 var found = state.lastCh === '*' && state.nextCh === '/';
2174 state.lastCh = state.nextCh;
2178 // TODO: The original Vim implementation only operates on level 1 and 2.
2179 // The current implementation doesn't check for code block level and
2180 // therefore it operates on any levels.
2182 init: function(state) {
2183 state.symb = (state.symb === 'm' ? '{' : '}');
2184 state.reverseSymb = state.symb === '{' ? '}' : '{';
2186 isComplete: function(state) {
2187 if(state.nextCh === state.symb)return true;
2192 init: function(state) {
2195 isComplete: function(state) {
2196 if (state.nextCh === '#') {
2197 var token = state.lineText.match(/#(\w+)/)[1];
2198 if (token === 'endif') {
2199 if (state.forward && state.depth === 0) {
2203 } else if (token === 'if') {
2204 if (!state.forward && state.depth === 0) {
2209 if(token === 'else' && state.depth === 0)return true;
2215 function findSymbol(cm, repeat, forward, symb) {
2216 var cur = cm.getCursor();
2217 var increment = forward ? 1 : -1;
2218 var endLine = forward ? cm.lineCount() : -1;
2220 var line = cur.line;
2221 var lineText = cm.getLine(line);
2224 nextCh: lineText.charAt(curCh),
2228 reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
2231 curMoveThrough: false
2233 var mode = symbolToMode[symb];
2234 if(!mode)return cur;
2235 var init = findSymbolModes[mode].init;
2236 var isComplete = findSymbolModes[mode].isComplete;
2237 if(init)init(state);
2238 while (line !== endLine && repeat) {
2239 state.index += increment;
2240 state.nextCh = state.lineText.charAt(state.index);
2241 if (!state.nextCh) {
2243 state.lineText = cm.getLine(line) || '';
2244 if (increment > 0) {
2247 var lineLen = state.lineText.length;
2248 state.index = (lineLen > 0) ? (lineLen-1) : 0;
2250 state.nextCh = state.lineText.charAt(state.index);
2252 if (isComplete(state)) {
2254 cur.ch = state.index;
2258 if (state.nextCh || state.curMoveThrough) {
2259 return { line: line, ch: state.index };
2265 * Returns the boundaries of the next word. If the cursor in the middle of
2266 * the word, then returns the boundaries of the current word, starting at
2267 * the cursor. If the cursor is at the start/end of a word, and we are going
2268 * forward/backward, respectively, find the boundaries of the next word.
2270 * @param {CodeMirror} cm CodeMirror object.
2271 * @param {Cursor} cur The cursor position.
2272 * @param {boolean} forward True to search forward. False to search
2274 * @param {boolean} bigWord True if punctuation count as part of the word.
2275 * False if only [a-zA-Z0-9] characters count as part of the word.
2276 * @param {boolean} emptyLineIsWord True if empty lines should be treated
2278 * @return {Object{from:number, to:number, line: number}} The boundaries of
2279 * the word, or null if there are no more words.
2281 function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
2282 var lineNum = cur.line;
2284 var line = cm.getLine(lineNum);
2285 var dir = forward ? 1 : -1;
2286 var regexps = bigWord ? bigWordRegexp : wordRegexp;
2288 if (emptyLineIsWord && line == '') {
2290 line = cm.getLine(lineNum);
2291 if (!isLine(cm, lineNum)) {
2294 pos = (forward) ? 0 : line.length;
2298 if (emptyLineIsWord && line == '') {
2299 return { from: 0, to: 0, line: lineNum };
2301 var stop = (dir > 0) ? line.length : -1;
2302 var wordStart = stop, wordEnd = stop;
2303 // Find bounds of next word.
2304 while (pos != stop) {
2305 var foundWord = false;
2306 for (var i = 0; i < regexps.length && !foundWord; ++i) {
2307 if (regexps[i].test(line.charAt(pos))) {
2309 // Advance to end of word.
2310 while (pos != stop && regexps[i].test(line.charAt(pos))) {
2314 foundWord = wordStart != wordEnd;
2315 if (wordStart == cur.ch && lineNum == cur.line &&
2316 wordEnd == wordStart + dir) {
2317 // We started at the end of a word. Find the next one.
2321 from: Math.min(wordStart, wordEnd + 1),
2322 to: Math.max(wordStart, wordEnd),
2331 // Advance to next/prev line.
2333 if (!isLine(cm, lineNum)) {
2336 line = cm.getLine(lineNum);
2337 pos = (dir > 0) ? 0 : line.length;
2339 // Should never get here.
2340 throw new Error('The impossible happened.');
2344 * @param {CodeMirror} cm CodeMirror object.
2345 * @param {int} repeat Number of words to move past.
2346 * @param {boolean} forward True to search forward. False to search
2348 * @param {boolean} wordEnd True to move to end of word. False to move to
2349 * beginning of word.
2350 * @param {boolean} bigWord True if punctuation count as part of the word.
2351 * False if only alphabet characters count as part of the word.
2352 * @return {Cursor} The position the cursor should move to.
2354 function moveToWord(cm, repeat, forward, wordEnd, bigWord) {
2355 var cur = cm.getCursor();
2356 var curStart = copyCursor(cur);
2358 if (forward && !wordEnd || !forward && wordEnd) {
2361 // For 'e', empty lines are not considered words, go figure.
2362 var emptyLineIsWord = !(forward && wordEnd);
2363 for (var i = 0; i < repeat; i++) {
2364 var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
2366 var eodCh = lineLength(cm, cm.lastLine());
2368 ? {line: cm.lastLine(), from: eodCh, to: eodCh}
2369 : {line: 0, from: 0, to: 0});
2373 cur = {line: word.line, ch: forward ? (word.to - 1) : word.from};
2375 var shortCircuit = words.length != repeat;
2376 var firstWord = words[0];
2377 var lastWord = words.pop();
2378 if (forward && !wordEnd) {
2380 if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
2381 // We did not start in the middle of a word. Discard the extra word at the end.
2382 lastWord = words.pop();
2384 return {line: lastWord.line, ch: lastWord.from};
2385 } else if (forward && wordEnd) {
2386 return {line: lastWord.line, ch: lastWord.to - 1};
2387 } else if (!forward && wordEnd) {
2389 if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
2390 // We did not start in the middle of a word. Discard the extra word at the end.
2391 lastWord = words.pop();
2393 return {line: lastWord.line, ch: lastWord.to};
2396 return {line: lastWord.line, ch: lastWord.from};
2400 function moveToCharacter(cm, repeat, forward, character) {
2401 var cur = cm.getCursor();
2404 for (var i = 0; i < repeat; i ++) {
2405 var line = cm.getLine(cur.line);
2406 idx = charIdxInLine(start, line, character, forward, true);
2412 return { line: cm.getCursor().line, ch: idx };
2415 function moveToColumn(cm, repeat) {
2416 // repeat is always >= 1, so repeat - 1 always corresponds
2417 // to the column we want to go to.
2418 var line = cm.getCursor().line;
2419 return clipCursorToContent(cm, { line: line, ch: repeat - 1 });
2422 function updateMark(cm, vim, markName, pos) {
2423 if (!inArray(markName, validMarks)) {
2426 if (vim.marks[markName]) {
2427 vim.marks[markName].clear();
2429 vim.marks[markName] = cm.setBookmark(pos);
2432 function charIdxInLine(start, line, character, forward, includeChar) {
2433 // Search for char in line.
2434 // motion_options: {forward, includeChar}
2435 // If includeChar = true, include it too.
2436 // If forward = true, search forward, else search backwards.
2437 // If char is not found on this line, do nothing
2440 idx = line.indexOf(character, start + 1);
2441 if (idx != -1 && !includeChar) {
2445 idx = line.lastIndexOf(character, start - 1);
2446 if (idx != -1 && !includeChar) {
2453 function getContextLevel(ctx) {
2454 return (ctx === 'string' || ctx === 'comment') ? 1 : 0;
2457 function findMatchedSymbol(cm, cur, symb) {
2458 var line = cur.line;
2460 symb = symb ? symb : cm.getLine(line).charAt(ch);
2462 var symbContext = cm.getTokenAt({line:line, ch:ch+1}).type;
2463 var symbCtxLevel = getContextLevel(symbContext);
2465 var reverseSymb = ({
2468 '{': '}', '}': '{'})[symb];
2470 // Couldn't find a matching symbol, abort
2475 // set our increment to move forward (+1) or backwards (-1)
2476 // depending on which bracket we're matching
2477 var increment = ({'(': 1, '{': 1, '[': 1})[symb] || -1;
2478 var endLine = increment === 1 ? cm.lineCount() : -1;
2479 var depth = 1, nextCh = symb, index = ch, lineText = cm.getLine(line);
2480 // Simple search for closing paren--just count openings and closings till
2481 // we find our match
2482 // TODO: use info from CodeMirror to ignore closing brackets in comments
2484 while (line !== endLine && depth > 0) {
2486 nextCh = lineText.charAt(index);
2489 lineText = cm.getLine(line) || '';
2490 if (increment > 0) {
2493 var lineLen = lineText.length;
2494 index = (lineLen > 0) ? (lineLen-1) : 0;
2496 nextCh = lineText.charAt(index);
2498 var revSymbContext = cm.getTokenAt({line:line, ch:index+1}).type;
2499 var revSymbCtxLevel = getContextLevel(revSymbContext);
2500 if (symbCtxLevel >= revSymbCtxLevel) {
2501 if (nextCh === symb) {
2503 } else if (nextCh === reverseSymb) {
2510 return { line: line, ch: index };
2515 function selectCompanionObject(cm, revSymb, inclusive) {
2516 var cur = cm.getCursor();
2518 var end = findMatchedSymbol(cm, cur, revSymb);
2519 var start = findMatchedSymbol(cm, end);
2520 start.ch += inclusive ? 1 : 0;
2521 end.ch += inclusive ? 0 : 1;
2523 return { start: start, end: end };
2526 // Takes in a symbol and a cursor and tries to simulate text objects that
2527 // have identical opening and closing symbols
2528 // TODO support across multiple lines
2529 function findBeginningAndEnd(cm, symb, inclusive) {
2530 var cur = cm.getCursor();
2531 var line = cm.getLine(cur.line);
2532 var chars = line.split('');
2533 var start, end, i, len;
2534 var firstIndex = chars.indexOf(symb);
2536 // the decision tree is to always look backwards for the beginning first,
2537 // but if the cursor is in front of the first instance of the symb,
2538 // then move the cursor forward
2539 if (cur.ch < firstIndex) {
2540 cur.ch = firstIndex;
2541 // Why is this line even here???
2542 // cm.setCursor(cur.line, firstIndex+1);
2544 // otherwise if the cursor is currently on the closing symbol
2545 else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
2546 end = cur.ch; // assign end to the current cursor
2547 --cur.ch; // make sure to look backwards
2550 // if we're currently on the symbol, we've got a start
2551 if (chars[cur.ch] == symb && !end) {
2552 start = cur.ch + 1; // assign start to ahead of the cursor
2554 // go backwards to find the start
2555 for (i = cur.ch; i > -1 && !start; i--) {
2556 if (chars[i] == symb) {
2562 // look forwards for the end symbol
2563 if (start && !end) {
2564 for (i = start, len = chars.length; i < len && !end; i++) {
2565 if (chars[i] == symb) {
2572 if (!start || !end) {
2573 return { start: cur, end: cur };
2576 // include the symbols
2582 start: { line: cur.line, ch: start },
2583 end: { line: cur.line, ch: end }
2588 function SearchState() {}
2589 SearchState.prototype = {
2590 getQuery: function() {
2591 return vimGlobalState.query;
2593 setQuery: function(query) {
2594 vimGlobalState.query = query;
2596 getOverlay: function() {
2597 return this.searchOverlay;
2599 setOverlay: function(overlay) {
2600 this.searchOverlay = overlay;
2602 isReversed: function() {
2603 return vimGlobalState.isReversed;
2605 setReversed: function(reversed) {
2606 vimGlobalState.isReversed = reversed;
2609 function getSearchState(cm) {
2610 var vim = cm.state.vim;
2611 return vim.searchState_ || (vim.searchState_ = new SearchState());
2613 function dialog(cm, template, shortText, onClose, options) {
2614 if (cm.openDialog) {
2615 cm.openDialog(template, onClose, { bottom: true, value: options.value,
2616 onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp });
2619 onClose(prompt(shortText, ''));
2623 function findUnescapedSlashes(str) {
2624 var escapeNextChar = false;
2626 for (var i = 0; i < str.length; i++) {
2627 var c = str.charAt(i);
2628 if (!escapeNextChar && c == '/') {
2631 escapeNextChar = (c == '\\');
2636 * Extract the regular expression from the query and return a Regexp object.
2637 * Returns null if the query is blank.
2638 * If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
2639 * If smartCase is passed in, and the query contains upper case letters,
2640 * then ignoreCase is overridden, and the 'i' flag will not be set.
2641 * If the query contains the /i in the flag part of the regular expression,
2642 * then both ignoreCase and smartCase are ignored, and 'i' will be passed
2643 * through to the Regex object.
2645 function parseQuery(query, ignoreCase, smartCase) {
2646 // Check if the query is already a regex.
2647 if (query instanceof RegExp) { return query; }
2648 // First try to extract regex + flags from the input. If no flags found,
2649 // extract just the regex. IE does not accept flags directly defined in
2650 // the regex string in the form /regex/flags
2651 var slashes = findUnescapedSlashes(query);
2653 var forceIgnoreCase;
2654 if (!slashes.length) {
2655 // Query looks like 'regexp'
2658 // Query looks like 'regexp/...'
2659 regexPart = query.substring(0, slashes[0]);
2660 var flagsPart = query.substring(slashes[0]);
2661 forceIgnoreCase = (flagsPart.indexOf('i') != -1);
2667 ignoreCase = (/^[^A-Z]*$/).test(regexPart);
2669 var regexp = new RegExp(regexPart,
2670 (ignoreCase || forceIgnoreCase) ? 'i' : undefined);
2673 function showConfirm(cm, text) {
2674 if (cm.openConfirm) {
2675 cm.openConfirm('<span style="color: red">' + text +
2676 '</span> <button type="button">OK</button>', function() {},
2682 function makePrompt(prefix, desc) {
2685 raw += '<span style="font-family: monospace">' + prefix + '</span>';
2687 raw += '<input type="text"/> ' +
2688 '<span style="color: #888">';
2690 raw += '<span style="color: #888">';
2696 var searchPromptDesc = '(Javascript regexp)';
2697 function showPrompt(cm, options) {
2698 var shortText = (options.prefix || '') + ' ' + (options.desc || '');
2699 var prompt = makePrompt(options.prefix, options.desc);
2700 dialog(cm, prompt, shortText, options.onClose, options);
2702 function regexEqual(r1, r2) {
2703 if (r1 instanceof RegExp && r2 instanceof RegExp) {
2704 var props = ['global', 'multiline', 'ignoreCase', 'source'];
2705 for (var i = 0; i < props.length; i++) {
2706 var prop = props[i];
2707 if (r1[prop] !== r2[prop]) {
2715 // Returns true if the query is valid.
2716 function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
2720 var state = getSearchState(cm);
2721 var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
2725 highlightSearchMatches(cm, query);
2726 if (regexEqual(query, state.getQuery())) {
2729 state.setQuery(query);
2732 function searchOverlay(query) {
2733 if (query.source.charAt(0) == '^') {
2734 var matchSol = true;
2737 token: function(stream) {
2738 if (matchSol && !stream.sol()) {
2742 var match = stream.match(query, false);
2744 if (match[0].length == 0) {
2745 // Matched empty string, skip to next.
2749 if (!stream.sol()) {
2750 // Backtrack 1 to match \b
2752 if (!query.exec(stream.next() + match[0])) {
2757 stream.match(query);
2760 while (!stream.eol()) {
2762 if (stream.match(query, false)) break;
2768 function highlightSearchMatches(cm, query) {
2769 var overlay = getSearchState(cm).getOverlay();
2770 if (!overlay || query != overlay.query) {
2772 cm.removeOverlay(overlay);
2774 overlay = searchOverlay(query);
2775 cm.addOverlay(overlay);
2776 getSearchState(cm).setOverlay(overlay);
2779 function findNext(cm, prev, query, repeat) {
2780 if (repeat === undefined) { repeat = 1; }
2781 return cm.operation(function() {
2782 var pos = cm.getCursor();
2783 var cursor = cm.getSearchCursor(query, pos);
2784 for (var i = 0; i < repeat; i++) {
2785 var found = cursor.find(prev);
2786 if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
2788 // SearchCursor may have returned null because it hit EOF, wrap
2789 // around and try again.
2790 cursor = cm.getSearchCursor(query,
2791 (prev) ? { line: cm.lastLine() } : {line: cm.firstLine(), ch: 0} );
2792 if (!cursor.find(prev)) {
2797 return cursor.from();
2800 function clearSearchHighlight(cm) {
2801 cm.removeOverlay(getSearchState(cm).getOverlay());
2802 getSearchState(cm).setOverlay(null);
2805 * Check if pos is in the specified range, INCLUSIVE.
2806 * Range can be specified with 1 or 2 arguments.
2807 * If the first range argument is an array, treat it as an array of line
2808 * numbers. Match pos against any of the lines.
2809 * If the first range argument is a number,
2810 * if there is only 1 range argument, check if pos has the same line
2812 * if there are 2 range arguments, then check if pos is in between the two
2815 function isInRange(pos, start, end) {
2816 if (typeof pos != 'number') {
2817 // Assume it is a cursor position. Get the line number.
2820 if (start instanceof Array) {
2821 return inArray(pos, start);
2824 return (pos >= start && pos <= end);
2826 return pos == start;
2830 function getUserVisibleLines(cm) {
2831 var scrollInfo = cm.getScrollInfo();
2832 var occludeToleranceTop = 6;
2833 var occludeToleranceBottom = 10;
2834 var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');
2835 var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;
2836 var to = cm.coordsChar({left:0, top: bottomY}, 'local');
2837 return {top: from.line, bottom: to.line};
2840 // Ex command handling
2841 // Care must be taken when adding to the default Ex command map. For any
2842 // pair of commands that have a shared prefix, at least one of their
2843 // shortNames must not match the prefix of the other command.
2844 var defaultExCommandMap = [
2845 { name: 'map', type: 'builtIn' },
2846 { name: 'write', shortName: 'w', type: 'builtIn' },
2847 { name: 'undo', shortName: 'u', type: 'builtIn' },
2848 { name: 'redo', shortName: 'red', type: 'builtIn' },
2849 { name: 'sort', shortName: 'sor', type: 'builtIn'},
2850 { name: 'substitute', shortName: 's', type: 'builtIn'},
2851 { name: 'nohlsearch', shortName: 'noh', type: 'builtIn'},
2852 { name: 'delmarks', shortName: 'delm', type: 'builtin'}
2854 Vim.ExCommandDispatcher = function() {
2855 this.buildCommandMap_();
2857 Vim.ExCommandDispatcher.prototype = {
2858 processCommand: function(cm, input) {
2859 var vim = cm.state.vim;
2860 if (vim.visualMode) {
2863 var inputStream = new CodeMirror.StringStream(input);
2865 params.input = input;
2867 this.parseInput_(cm, inputStream, params);
2873 if (!params.commandName) {
2874 // If only a line range is defined, move to the line.
2875 if (params.line !== undefined) {
2876 commandName = 'move';
2879 var command = this.matchCommand_(params.commandName);
2881 commandName = command.name;
2882 this.parseCommandArgs_(inputStream, params, command);
2883 if (command.type == 'exToKey') {
2884 // Handle Ex to Key mapping.
2885 for (var i = 0; i < command.toKeys.length; i++) {
2886 CodeMirror.Vim.handleKey(cm, command.toKeys[i]);
2889 } else if (command.type == 'exToEx') {
2890 // Handle Ex to Ex mapping.
2891 this.processCommand(cm, command.toInput);
2897 showConfirm(cm, 'Not an editor command ":' + input + '"');
2901 exCommands[commandName](cm, params);
2906 parseInput_: function(cm, inputStream, result) {
2907 inputStream.eatWhile(':');
2909 if (inputStream.eat('%')) {
2910 result.line = cm.firstLine();
2911 result.lineEnd = cm.lastLine();
2913 result.line = this.parseLineSpec_(cm, inputStream);
2914 if (result.line !== undefined && inputStream.eat(',')) {
2915 result.lineEnd = this.parseLineSpec_(cm, inputStream);
2919 // Parse command name.
2920 var commandMatch = inputStream.match(/^(\w+)/);
2922 result.commandName = commandMatch[1];
2924 result.commandName = inputStream.match(/.*/)[0];
2929 parseLineSpec_: function(cm, inputStream) {
2930 var numberMatch = inputStream.match(/^(\d+)/);
2932 return parseInt(numberMatch[1], 10) - 1;
2934 switch (inputStream.next()) {
2936 return cm.getCursor().line;
2938 return cm.lastLine();
2940 var mark = cm.state.vim.marks[inputStream.next()];
2941 if (mark && mark.find()) {
2942 return mark.find().line;
2944 throw new Error('Mark not set');
2946 inputStream.backUp(1);
2950 parseCommandArgs_: function(inputStream, params, command) {
2951 if (inputStream.eol()) {
2954 params.argString = inputStream.match(/.*/)[0];
2955 // Parse command-line arguments
2956 var delim = command.argDelimiter || /\s+/;
2957 var args = trim(params.argString).split(delim);
2958 if (args.length && args[0]) {
2962 matchCommand_: function(commandName) {
2963 // Return the command in the command map that matches the shortest
2964 // prefix of the passed in command name. The match is guaranteed to be
2965 // unambiguous if the defaultExCommandMap's shortNames are set up
2966 // correctly. (see @code{defaultExCommandMap}).
2967 for (var i = commandName.length; i > 0; i--) {
2968 var prefix = commandName.substring(0, i);
2969 if (this.commandMap_[prefix]) {
2970 var command = this.commandMap_[prefix];
2971 if (command.name.indexOf(commandName) === 0) {
2978 buildCommandMap_: function() {
2979 this.commandMap_ = {};
2980 for (var i = 0; i < defaultExCommandMap.length; i++) {
2981 var command = defaultExCommandMap[i];
2982 var key = command.shortName || command.name;
2983 this.commandMap_[key] = command;
2986 map: function(lhs, rhs) {
2987 if (lhs != ':' && lhs.charAt(0) == ':') {
2988 var commandName = lhs.substring(1);
2989 if (rhs != ':' && rhs.charAt(0) == ':') {
2991 this.commandMap_[commandName] = {
2994 toInput: rhs.substring(1)
2997 // Ex to key mapping
2998 this.commandMap_[commandName] = {
3001 toKeys: parseKeyString(rhs)
3005 if (rhs != ':' && rhs.charAt(0) == ':') {
3006 // Key to Ex mapping.
3007 defaultKeymap.unshift({
3008 keys: parseKeyString(lhs),
3010 exArgs: { input: rhs.substring(1) }});
3012 // Key to key mapping
3013 defaultKeymap.unshift({
3014 keys: parseKeyString(lhs),
3016 toKeys: parseKeyString(rhs)
3023 // Converts a key string sequence of the form a<C-w>bd<Left> into Vim's
3024 // keymap representation.
3025 function parseKeyString(str) {
3029 match = (/<\w+-.+?>|<\w+>|./).exec(str);
3030 if(match === null)break;
3032 str = str.substring(match.index + key.length);
3039 map: function(cm, params) {
3040 var mapArgs = params.args;
3041 if (!mapArgs || mapArgs.length < 2) {
3043 showConfirm(cm, 'Invalid mapping: ' + params.input);
3047 exCommandDispatcher.map(mapArgs[0], mapArgs[1], cm);
3049 move: function(cm, params) {
3050 commandDispatcher.processCommand(cm, cm.state.vim, {
3052 motion: 'moveToLineOrEdgeOfDocument',
3053 motionArgs: { forward: false, explicitRepeat: true,
3055 repeatOverride: params.line+1});
3057 sort: function(cm, params) {
3058 var reverse, ignoreCase, unique, number;
3059 function parseArgs() {
3060 if (params.argString) {
3061 var args = new CodeMirror.StringStream(params.argString);
3062 if (args.eat('!')) { reverse = true; }
3063 if (args.eol()) { return; }
3064 if (!args.eatSpace()) { throw new Error('invalid arguments ' + args.match(/.*/)[0]); }
3065 var opts = args.match(/[a-z]+/);
3068 ignoreCase = opts.indexOf('i') != -1;
3069 unique = opts.indexOf('u') != -1;
3070 var decimal = opts.indexOf('d') != -1 && 1;
3071 var hex = opts.indexOf('x') != -1 && 1;
3072 var octal = opts.indexOf('o') != -1 && 1;
3073 if (decimal + hex + octal > 1) { throw new Error('invalid arguments'); }
3074 number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
3076 if (args.eatSpace() && args.match(/\/.*\//)) { throw new Error('patterns not supported'); }
3080 var lineStart = params.line || cm.firstLine();
3081 var lineEnd = params.lineEnd || params.line || cm.lastLine();
3082 if (lineStart == lineEnd) { return; }
3083 var curStart = { line: lineStart, ch: 0 };
3084 var curEnd = { line: lineEnd, ch: lineLength(cm, lineEnd) };
3085 var text = cm.getRange(curStart, curEnd).split('\n');
3086 var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ :
3087 (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
3088 (number == 'octal') ? /([0-7]+)/ : null;
3089 var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
3090 var numPart = [], textPart = [];
3092 for (var i = 0; i < text.length; i++) {
3093 if (numberRegex.exec(text[i])) {
3094 numPart.push(text[i]);
3096 textPart.push(text[i]);
3102 function compareFn(a, b) {
3103 if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
3104 if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
3105 var anum = number && numberRegex.exec(a);
3106 var bnum = number && numberRegex.exec(b);
3107 if (!anum) { return a < b ? -1 : 1; }
3108 anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
3109 bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
3112 numPart.sort(compareFn);
3113 textPart.sort(compareFn);
3114 text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
3115 if (unique) { // Remove duplicate lines
3119 for (var i = 0; i < textOld.length; i++) {
3120 if (textOld[i] != lastLine) {
3121 text.push(textOld[i]);
3123 lastLine = textOld[i];
3126 cm.replaceRange(text.join('\n'), curStart, curEnd);
3128 substitute: function(cm, params) {
3129 if (!cm.getSearchCursor) {
3130 throw new Error('Search feature not available. Requires searchcursor.js or ' +
3131 'any other getSearchCursor implementation.');
3133 var argString = params.argString;
3134 var slashes = findUnescapedSlashes(argString);
3135 if (slashes[0] !== 0) {
3136 showConfirm(cm, 'Substitutions should be of the form ' +
3137 ':s/pattern/replace/');
3140 var regexPart = argString.substring(slashes[0] + 1, slashes[1]);
3141 var replacePart = '';
3144 var confirm = false; // Whether to confirm each replace.
3146 replacePart = argString.substring(slashes[1] + 1, slashes[2]);
3149 // After the 3rd slash, we can have flags followed by a space followed
3151 var trailing = argString.substring(slashes[2] + 1).split(' ');
3152 flagsPart = trailing[0];
3153 count = parseInt(trailing[1]);
3156 if (flagsPart.indexOf('c') != -1) {
3158 flagsPart.replace('c', '');
3160 regexPart = regexPart + '/' + flagsPart;
3163 // If regex part is empty, then use the previous query. Otherwise use
3164 // the regex part as the new query.
3166 updateSearchQuery(cm, regexPart, true /** ignoreCase */,
3167 true /** smartCase */);
3169 showConfirm(cm, 'Invalid regex: ' + regexPart);
3173 var state = getSearchState(cm);
3174 var query = state.getQuery();
3175 var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
3176 var lineEnd = params.lineEnd || lineStart;
3178 lineStart = lineEnd;
3179 lineEnd = lineStart + count - 1;
3181 var startPos = clipCursorToContent(cm, { line: lineStart, ch: 0 });
3182 var cursor = cm.getSearchCursor(query, startPos);
3183 doReplace(cm, confirm, lineStart, lineEnd, cursor, query, replacePart);
3185 redo: CodeMirror.commands.redo,
3186 undo: CodeMirror.commands.undo,
3187 write: function(cm) {
3188 if (CodeMirror.commands.save) {
3189 // If a save command is defined, call it.
3190 CodeMirror.commands.save(cm);
3192 // Saves to text area if no save command is defined.
3196 nohlsearch: function(cm) {
3197 clearSearchHighlight(cm);
3199 delmarks: function(cm, params) {
3200 if (!params.argString || !params.argString.trim()) {
3201 showConfirm(cm, 'Argument required');
3205 var state = cm.state.vim;
3206 var stream = new CodeMirror.StringStream(params.argString.trim());
3207 while (!stream.eol()) {
3210 // Record the streams position at the beginning of the loop for use
3211 // in error messages.
3212 var count = stream.pos;
3214 if (!stream.match(/[a-zA-Z]/, false)) {
3215 showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
3219 var sym = stream.next();
3220 // Check if this symbol is part of a range
3221 if (stream.match('-', true)) {
3222 // This symbol is part of a range.
3224 // The range must terminate at an alphabetic character.
3225 if (!stream.match(/[a-zA-Z]/, false)) {
3226 showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
3230 var startMark = sym;
3231 var finishMark = stream.next();
3232 // The range must terminate at an alphabetic character which
3233 // shares the same case as the start of the range.
3234 if (isLowerCase(startMark) && isLowerCase(finishMark) ||
3235 isUpperCase(startMark) && isUpperCase(finishMark)) {
3236 var start = startMark.charCodeAt(0);
3237 var finish = finishMark.charCodeAt(0);
3238 if (start >= finish) {
3239 showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
3243 // Because marks are always ASCII values, and we have
3244 // determined that they are the same case, we can use
3245 // their char codes to iterate through the defined range.
3246 for (var j = 0; j <= finish - start; j++) {
3247 var mark = String.fromCharCode(start + j);
3248 delete state.marks[mark];
3251 showConfirm(cm, 'Invalid argument: ' + startMark + '-');
3255 // This symbol is a valid mark, and is not part of a range.
3256 delete state.marks[sym];
3262 var exCommandDispatcher = new Vim.ExCommandDispatcher();
3265 * @param {CodeMirror} cm CodeMirror instance we are in.
3266 * @param {boolean} confirm Whether to confirm each replace.
3267 * @param {Cursor} lineStart Line to start replacing from.
3268 * @param {Cursor} lineEnd Line to stop replacing at.
3269 * @param {RegExp} query Query for performing matches with.
3270 * @param {string} replaceWith Text to replace matches with. May contain $1,
3271 * $2, etc for replacing captured groups using Javascript replace.
3273 function doReplace(cm, confirm, lineStart, lineEnd, searchCursor, query,
3275 // Set up all the functions.
3276 cm.state.vim.exMode = true;
3278 var lastPos = searchCursor.from();
3279 function replaceAll() {
3280 cm.operation(function() {
3288 function replace() {
3289 var text = cm.getRange(searchCursor.from(), searchCursor.to());
3290 var newText = text.replace(query, replaceWith);
3291 searchCursor.replace(newText);
3294 var found = searchCursor.findNext();
3297 } else if (isInRange(searchCursor.from(), lineStart, lineEnd)) {
3298 cm.scrollIntoView(searchCursor.from(), 30);
3299 cm.setSelection(searchCursor.from(), searchCursor.to());
3300 lastPos = searchCursor.from();
3306 function stop(close) {
3307 if (close) { close(); }
3310 cm.setCursor(lastPos);
3311 var vim = cm.state.vim;
3313 vim.lastHPos = vim.lastHSPos = lastPos.ch;
3316 function onPromptKeyDown(e, _value, close) {
3317 // Swallow all keys.
3318 CodeMirror.e_stop(e);
3319 var keyName = CodeMirror.keyName(e);
3322 replace(); next(); break;
3326 cm.operation(replaceAll); break;
3329 // fall through and exit.
3337 if (done) { stop(close); }
3340 // Actually do replace.
3343 throw new Error('No matches for ' + query.source);
3350 prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',
3351 onKeyDown: onPromptKeyDown
3355 // Register Vim with CodeMirror
3356 function buildVimKeyMap() {
3358 * Handle the raw key event from CodeMirror. Translate the
3359 * Shift + key modifier to the resulting letter, while preserving other
3362 // TODO: Figure out a way to catch capslock.
3363 function cmKeyToVimKey(key, modifier) {
3365 if (isUpperCase(vimKey)) {
3366 // Convert to lower case if shift is not the modifier since the key
3367 // we get from CodeMirror is always upper case.
3368 if (modifier == 'Shift') {
3372 vimKey = vimKey.toLowerCase();
3376 // Vim will parse modifier+key combination as a single key.
3377 vimKey = modifier.charAt(0) + '-' + vimKey;
3379 var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey];
3380 vimKey = specialKey ? specialKey : vimKey;
3381 vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey;
3385 // Closure to bind CodeMirror, key, modifier.
3386 function keyMapper(vimKey) {
3387 return function(cm) {
3388 CodeMirror.Vim.handleKey(cm, vimKey);
3392 var cmToVimKeymap = {
3393 'nofallthrough': true,
3394 'disableInput': true,
3395 'style': 'fat-cursor'
3397 function bindKeys(keys, modifier) {
3398 for (var i = 0; i < keys.length; i++) {
3400 if (!modifier && inArray(key, specialSymbols)) {
3401 // Wrap special symbols with '' because that's how CodeMirror binds
3403 key = "'" + key + "'";
3405 var vimKey = cmKeyToVimKey(keys[i], modifier);
3406 var cmKey = modifier ? modifier + '-' + key : key;
3407 cmToVimKeymap[cmKey] = keyMapper(vimKey);
3410 bindKeys(upperCaseAlphabet);
3411 bindKeys(upperCaseAlphabet, 'Shift');
3412 bindKeys(upperCaseAlphabet, 'Ctrl');
3413 bindKeys(specialSymbols);
3414 bindKeys(specialSymbols, 'Ctrl');
3416 bindKeys(numbers, 'Ctrl');
3417 bindKeys(specialKeys);
3418 bindKeys(specialKeys, 'Ctrl');
3419 return cmToVimKeymap;
3421 CodeMirror.keyMap.vim = buildVimKeyMap();
3423 function exitInsertMode(cm) {
3424 var vim = cm.state.vim;
3425 var inReplay = vimGlobalState.macroModeState.inReplay;
3427 cm.off('change', onChange);
3428 cm.off('cursorActivity', onCursorActivity);
3429 CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
3431 if (!inReplay && vim.insertModeRepeat > 1) {
3432 // Perform insert mode repeat for commands like 3,a and 3,o.
3433 repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
3434 true /** repeatForInsert */);
3435 vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
3437 delete vim.insertModeRepeat;
3438 cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1, true);
3439 vim.insertMode = false;
3440 cm.setOption('keyMap', 'vim');
3441 cm.toggleOverwrite(false); // exit replace mode if we were in it.
3444 CodeMirror.keyMap['vim-insert'] = {
3445 // TODO: override navigation keys so that Esc will cancel automatic
3446 // indentation from o, O, i_<CR>
3447 'Esc': exitInsertMode,
3448 'Ctrl-[': exitInsertMode,
3449 'Ctrl-C': exitInsertMode,
3450 'Ctrl-N': 'autocomplete',
3451 'Ctrl-P': 'autocomplete',
3452 'Enter': function(cm) {
3453 var fn = CodeMirror.commands.newlineAndIndentContinueComment ||
3454 CodeMirror.commands.newlineAndIndent;
3457 fallthrough: ['default']
3460 CodeMirror.keyMap['vim-replace'] = {
3461 'Backspace': 'goCharLeft',
3462 fallthrough: ['vim-insert']
3465 function parseRegisterToKeyBuffer(macroModeState, registerName) {
3467 var register = vimGlobalState.registerController.getRegister(registerName);
3468 var text = register.toString();
3469 var macroKeyBuffer = macroModeState.macroKeyBuffer;
3470 emptyMacroKeyBuffer(macroModeState);
3472 match = (/<\w+-.+?>|<\w+>|./).exec(text);
3473 if(match === null)break;
3475 text = text.substring(match.index + key.length);
3476 macroKeyBuffer.push(key);
3478 return macroKeyBuffer;
3481 function parseKeyBufferToRegister(registerName, keyBuffer) {
3482 var text = keyBuffer.join('');
3483 vimGlobalState.registerController.setRegisterText(registerName, text);
3486 function emptyMacroKeyBuffer(macroModeState) {
3487 if(macroModeState.isMacroPlaying)return;
3488 var macroKeyBuffer = macroModeState.macroKeyBuffer;
3489 macroKeyBuffer.length = 0;
3492 function executeMacroKeyBuffer(cm, macroModeState, keyBuffer) {
3493 macroModeState.isMacroPlaying = true;
3494 for (var i = 0, len = keyBuffer.length; i < len; i++) {
3495 CodeMirror.Vim.handleKey(cm, keyBuffer[i]);
3497 macroModeState.isMacroPlaying = false;
3500 function logKey(macroModeState, key) {
3501 if(macroModeState.isMacroPlaying)return;
3502 var macroKeyBuffer = macroModeState.macroKeyBuffer;
3503 macroKeyBuffer.push(key);
3507 * Listens for changes made in insert mode.
3508 * Should only be active in insert mode.
3510 function onChange(_cm, changeObj) {
3511 var macroModeState = vimGlobalState.macroModeState;
3512 var lastChange = macroModeState.lastInsertModeChanges;
3514 lastChange.expectCursorActivityForChange = true;
3515 if (changeObj.origin == '+input' || changeObj.origin == 'paste'
3516 || changeObj.origin === undefined /* only in testing */) {
3517 var text = changeObj.text.join('\n');
3518 lastChange.changes.push(text);
3520 // Change objects may be chained with next.
3521 changeObj = changeObj.next;
3526 * Listens for any kind of cursor activity on CodeMirror.
3527 * - For tracking cursor activity in insert mode.
3528 * - Should only be active in insert mode.
3530 function onCursorActivity() {
3531 var macroModeState = vimGlobalState.macroModeState;
3532 var lastChange = macroModeState.lastInsertModeChanges;
3533 if (lastChange.expectCursorActivityForChange) {
3534 lastChange.expectCursorActivityForChange = false;
3536 // Cursor moved outside the context of an edit. Reset the change.
3537 lastChange.changes = [];
3541 /** Wrapper for special keys pressed in insert mode */
3542 function InsertModeKey(keyName) {
3543 this.keyName = keyName;
3547 * Handles raw key down events from the text area.
3548 * - Should only be active in insert mode.
3549 * - For recording deletes in insert mode.
3551 function onKeyEventTargetKeyDown(e) {
3552 var macroModeState = vimGlobalState.macroModeState;
3553 var lastChange = macroModeState.lastInsertModeChanges;
3554 var keyName = CodeMirror.keyName(e);
3555 function onKeyFound() {
3556 lastChange.changes.push(new InsertModeKey(keyName));
3559 if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
3560 CodeMirror.lookupKey(keyName, ['vim-insert'], onKeyFound);
3565 * Repeats the last edit, which includes exactly 1 command and at most 1
3566 * insert. Operator and motion commands are read from lastEditInputState,
3567 * while action commands are read from lastEditActionCommand.
3569 * If repeatForInsert is true, then the function was called by
3570 * exitInsertMode to repeat the insert mode changes the user just made. The
3571 * corresponding enterInsertMode call was made with a count.
3573 function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
3574 var macroModeState = vimGlobalState.macroModeState;
3575 macroModeState.inReplay = true;
3576 var isAction = !!vim.lastEditActionCommand;
3577 var cachedInputState = vim.inputState;
3578 function repeatCommand() {
3580 commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
3582 commandDispatcher.evalInput(cm, vim);
3585 function repeatInsert(repeat) {
3586 if (macroModeState.lastInsertModeChanges.changes.length > 0) {
3587 // For some reason, repeat cw in desktop VIM will does not repeat
3588 // insert mode changes. Will conform to that behavior.
3589 repeat = !vim.lastEditActionCommand ? 1 : repeat;
3590 repeatLastInsertModeChanges(cm, repeat, macroModeState);
3593 vim.inputState = vim.lastEditInputState;
3594 if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
3595 // o and O repeat have to be interlaced with insert repeats so that the
3596 // insertions appear on separate lines instead of the last line.
3597 for (var i = 0; i < repeat; i++) {
3602 if (!repeatForInsert) {
3603 // Hack to get the cursor to end up at the right place. If I is
3604 // repeated in insert mode repeat, cursor will be 1 insert
3605 // change set left of where it should be.
3608 repeatInsert(repeat);
3610 vim.inputState = cachedInputState;
3611 if (vim.insertMode && !repeatForInsert) {
3612 // Don't exit insert mode twice. If repeatForInsert is set, then we
3613 // were called by an exitInsertMode call lower on the stack.
3616 macroModeState.inReplay = false;
3619 function repeatLastInsertModeChanges(cm, repeat, macroModeState) {
3620 var lastChange = macroModeState.lastInsertModeChanges;
3621 function keyHandler(binding) {
3622 if (typeof binding == 'string') {
3623 CodeMirror.commands[binding](cm);
3629 for (var i = 0; i < repeat; i++) {
3630 for (var j = 0; j < lastChange.changes.length; j++) {
3631 var change = lastChange.changes[j];
3632 if (change instanceof InsertModeKey) {
3633 CodeMirror.lookupKey(change.keyName, ['vim-insert'], keyHandler);
3635 var cur = cm.getCursor();
3636 cm.replaceRange(change, cur, cur);
3642 resetVimGlobalState();
3645 // Initialize Vim and make it available as an API.
3646 CodeMirror.Vim = Vim();