8db2767a9e4479bfe1de2a211a77208b856c1e36
[myslice.git] / third-party / codemirror-3.15 / keymap / vim.js
1 /**
2  * Supported keybindings:
3  *
4  *   Motion:
5  *   h, j, k, l
6  *   gj, gk
7  *   e, E, w, W, b, B, ge, gE
8  *   f<character>, F<character>, t<character>, T<character>
9  *   $, ^, 0, -, +, _
10  *   gg, G
11  *   %
12  *   '<character>, `<character>
13  *
14  *   Operator:
15  *   d, y, c
16  *   dd, yy, cc
17  *   g~, g~g~
18  *   >, <, >>, <<
19  *
20  *   Operator-Motion:
21  *   x, X, D, Y, C, ~
22  *
23  *   Action:
24  *   a, i, s, A, I, S, o, O
25  *   zz, z., z<CR>, zt, zb, z-
26  *   J
27  *   u, Ctrl-r
28  *   m<character>
29  *   r<character>
30  *
31  *   Modes:
32  *   ESC - leave insert mode, visual mode, and clear input state.
33  *   Ctrl-[, Ctrl-c - same as ESC.
34  *
35  * Registers: unamed, -, a-z, A-Z, 0-9
36  *   (Does not respect the special case for number registers when delete
37  *    operator is made with these commands: %, (, ),  , /, ?, n, N, {, } )
38  *   TODO: Implement the remaining registers.
39  * Marks: a-z, A-Z, and 0-9
40  *   TODO: Implement the remaining special marks. They have more complex
41  *       behavior.
42  *
43  * Code structure:
44  *  1. Default keymap
45  *  2. Variable declarations and short basic helpers
46  *  3. Instance (External API) implementation
47  *  4. Internal state tracking objects (input state, counter) implementation
48  *     and instanstiation
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.
53  */
54
55 (function() {
56   'use strict';
57
58   var defaultKeymap = [
59     // Key to key mapping. This goes first to make it possible to override
60     // existing mappings.
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>'] },
81     // Motions
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,
121             inclusive: 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,
134             inclusive: 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',
168         motion: 'moveToEol',
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',
205         motionArgs: { }},
206     // Operators
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',
233         operator: 'change',
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 }},
239     // Actions
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',
293         isEdit: true,
294         actionArgs: {increase: true, backtrack: false}},
295     { keys: ['<C-x>'], type: 'action', action: 'incrementNumberToken',
296         isEdit: true,
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 }},
304     // Search
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 }},
313     // Ex command
314     { keys: [':'], type: 'ex' }
315   ];
316
317   var Vim = function() {
318     CodeMirror.defineOption('vimMode', false, function(cm, val) {
319       if (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);
326         cm.state.vim = null;
327       }
328     });
329     function beforeSelectionChange(cm, cur) {
330       var vim = cm.state.vim;
331       if (vim.insertMode || vim.exMode) return;
332
333       var head = cur.head;
334       if (head.ch && head.ch == cm.doc.getLine(head.line).length) {
335         head.ch--;
336       }
337     }
338
339     var numberRegex = /[\d]/;
340     var wordRegexp = [(/\w/), (/[^\w\s]/)], bigWordRegexp = [(/\S/)];
341     function makeKeyRange(start, size) {
342       var keys = [];
343       for (var i = start; i < start + size; i++) {
344         keys.push(String.fromCharCode(i));
345       }
346       return keys;
347     }
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, ['-', '"']);
356
357     function isLine(cm, line) {
358       return line >= cm.firstLine() && line <= cm.lastLine();
359     }
360     function isLowerCase(k) {
361       return (/^[a-z]$/).test(k);
362     }
363     function isMatchableSymbol(k) {
364       return '()[]{}'.indexOf(k) != -1;
365     }
366     function isNumber(k) {
367       return numberRegex.test(k);
368     }
369     function isUpperCase(k) {
370       return (/^[A-Z]$/).test(k);
371     }
372     function isWhiteSpaceString(k) {
373       return (/^\s*$/).test(k);
374     }
375     function inArray(val, arr) {
376       for (var i = 0; i < arr.length; i++) {
377         if (arr[i] == val) {
378           return true;
379         }
380       }
381       return false;
382     }
383
384     var createCircularJumpList = function() {
385       var size = 100;
386       var pointer = -1;
387       var head = 0;
388       var tail = 0;
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];
396           if (trashMark) {
397             trashMark.clear();
398           }
399           buffer[next] = cm.setBookmark(cursor);
400         }
401         if (curMark) {
402           var markPos = curMark.find();
403           // avoid recording redundant cursor position
404           if (markPos && !cursorEqual(markPos, oldCur)) {
405             useNextSlot(oldCur);
406           }
407         } else {
408           useNextSlot(oldCur);
409         }
410         useNextSlot(newCur);
411         head = pointer;
412         tail = pointer - size + 1;
413         if (tail < 0) {
414           tail = 0;
415         }
416       }
417       function move(cm, offset) {
418         pointer += offset;
419         if (pointer > head) {
420           pointer = head;
421         } else if (pointer < tail) {
422           pointer = tail;
423         }
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;
428           var newCur;
429           var oldCur = cm.getCursor();
430           do {
431             pointer += inc;
432             mark = buffer[(size + pointer) % size];
433             // skip marks that are the same as current position
434             if (mark &&
435                 (newCur = mark.find()) &&
436                 !cursorEqual(oldCur, newCur)) {
437               break;
438             }
439           } while (pointer < head && pointer > tail);
440         }
441         return mark;
442       }
443       return {
444         cachedCursor: undefined, //used for # and * jumps
445         add: add,
446         move: move
447       };
448     };
449
450     var createMacroState = function() {
451       return {
452         macroKeyBuffer: [],
453         latestRegister: undefined,
454         inReplay: false,
455         lastInsertModeChanges: {
456           changes: [], // Change list
457           expectCursorActivityForChange: false // Set to true on change, false on cursorActivity.
458         },
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;
465           } else { //onEnter
466             this.latestRegister = registerName;
467             this.enteredMacroMode = cm.openDialog(
468               '(recording)['+registerName+']', null, {bottom:true});
469           }
470         }
471       };
472     };
473
474
475     function maybeInitVimState(cm) {
476       if (!cm.state.vim) {
477         // Store instance state in the CodeMirror object.
478         cm.state.vim = {
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.
491           lastHPos: -1,
492           // Doing the same with screen-position for gj/gk
493           lastHSPos: -1,
494           // The last motion command run. Cleared if a non-motion command gets
495           // executed in between.
496           lastMotion: null,
497           marks: {},
498           insertMode: false,
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,
502           visualMode: false,
503           // If we are in visual line mode. No effect if visualMode is false.
504           visualLine: false
505         };
506       }
507       return cm.state.vim;
508     }
509     var vimGlobalState;
510     function resetVimGlobalState() {
511       vimGlobalState = {
512         // The current search query.
513         searchQuery: null,
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({})
521       };
522     }
523
524     var vimApi= {
525       buildKeyMap: function() {
526         // TODO: Convert keymap into dictionary format for fast lookup.
527       },
528       // Testing hook, though it might be useful to expose the register
529       // controller anyways.
530       getRegisterController: function() {
531         return vimGlobalState.registerController;
532       },
533       // Testing hook.
534       resetVimGlobalState_: resetVimGlobalState,
535
536       // Testing hook.
537       getVimGlobalState_: function() {
538         return vimGlobalState;
539       },
540
541       // Testing hook.
542       maybeInitVimState_: maybeInitVimState,
543
544       InsertModeKey: InsertModeKey,
545       map: function(lhs, rhs) {
546         // Add user defined key bindings.
547         exCommandDispatcher.map(lhs, rhs);
548       },
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');
552         }
553         exCommands[name]=func;
554         exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
555       },
556       // This is the outermost function called by CodeMirror, after keys have
557       // been mapped to their Vim equivalents.
558       handleKey: function(cm, key) {
559         var command;
560         var vim = maybeInitVimState(cm);
561         var macroModeState = vimGlobalState.macroModeState;
562         if (macroModeState.enteredMacroMode) {
563           if (key == 'q') {
564             actions.exitMacroRecordMode();
565             vim.inputState = new InputState();
566             return;
567           }
568         }
569         if (key == '<Esc>') {
570           // Clear input state and get back to normal mode.
571           vim.inputState = new InputState();
572           if (vim.visualMode) {
573             exitVisualMode(cm);
574           }
575           return;
576         }
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);
583         }
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);
587         }
588         if (!command) {
589           if (isNumber(key)) {
590             // Increment count unless count is 0 and key is 0.
591             vim.inputState.pushRepeatDigit(key);
592           }
593           return;
594         }
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]);
599           }
600         } else {
601           if (macroModeState.enteredMacroMode) {
602             logKey(macroModeState, key);
603           }
604           commandDispatcher.processCommand(cm, vim, command);
605         }
606       }
607     };
608
609     // Represents the current input state.
610     function InputState() {
611       this.prefixRepeat = [];
612       this.motionRepeat = [];
613
614       this.operator = null;
615       this.operatorArgs = null;
616       this.motion = null;
617       this.motionArgs = null;
618       this.keyBuffer = []; // For matching multi-key commands.
619       this.registerName = null; // Defaults to the unamed register.
620     }
621     InputState.prototype.pushRepeatDigit = function(n) {
622       if (!this.operator) {
623         this.prefixRepeat = this.prefixRepeat.concat(n);
624       } else {
625         this.motionRepeat = this.motionRepeat.concat(n);
626       }
627     };
628     InputState.prototype.getRepeat = function() {
629       var repeat = 0;
630       if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
631         repeat = 1;
632         if (this.prefixRepeat.length > 0) {
633           repeat *= parseInt(this.prefixRepeat.join(''), 10);
634         }
635         if (this.motionRepeat.length > 0) {
636           repeat *= parseInt(this.motionRepeat.join(''), 10);
637         }
638       }
639       return repeat;
640     };
641
642     /*
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.)
647      */
648     function Register(text, linewise) {
649       this.clear();
650       if (text) {
651         this.set(text, linewise);
652       }
653     }
654     Register.prototype = {
655       set: function(text, linewise) {
656         this.text = text;
657         this.linewise = !!linewise;
658       },
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;
664         } else {
665           this.text += text;
666         }
667       },
668       clear: function() {
669         this.text = '';
670         this.linewise = false;
671       },
672       toString: function() { return this.text; }
673     };
674
675     /*
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.
678      *
679      * RegisterController keeps the state of all the registers.  An initial
680      * state may be passed in.  The unnamed register '"' will always be
681      * overridden.
682      */
683     function RegisterController(registers) {
684       this.registers = registers;
685       this.unamedRegister = registers['"'] = new Register();
686     }
687     RegisterController.prototype = {
688       pushText: function(registerName, operator, text, linewise) {
689         if (linewise && text.charAt(0) == '\n') {
690           text = text.slice(1) + '\n';
691         }
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
697         // default registers
698         if (!register) {
699           switch (operator) {
700             case 'yank':
701               // The 0 register contains the text from the most recent yank.
702               this.registers['0'] = new Register(text, linewise);
703               break;
704             case 'delete':
705             case 'change':
706               if (text.indexOf('\n') == -1) {
707                 // Delete less than 1 line. Update the small delete register.
708                 this.registers['-'] = new Register(text, linewise);
709               } else {
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);
714               }
715               break;
716           }
717           // Make sure the unnamed register is set to what just happened
718           this.unamedRegister.set(text, linewise);
719           return;
720         }
721
722         // If we've gotten to this point, we've actually specified a register
723         var append = isUpperCase(registerName);
724         if (append) {
725           register.append(text, linewise);
726           // The unamed register always has the same value as the last used
727           // register.
728           this.unamedRegister.append(text, linewise);
729         } else {
730           register.set(text, linewise);
731           this.unamedRegister.set(text, linewise);
732         }
733       },
734       setRegisterText: function(name, text, linewise) {
735         this.getRegister(name).set(text, linewise);
736       },
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;
742         }
743         name = name.toLowerCase();
744         if (!this.registers[name]) {
745           this.registers[name] = new Register();
746         }
747         return this.registers[name];
748       },
749       isValidRegister: function(name) {
750         return name && inArray(name, validRegisters);
751       },
752       shiftNumericRegisters_: function() {
753         for (var i = 9; i >= 2; i--) {
754           this.registers[i] = this.getRegister('' + (i - 1));
755         }
756       }
757     };
758
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
768               // stroke.
769               inputState.keyBuffer.push(key);
770               return null;
771             }
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.
776               continue;
777             }
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){
783                   case '<CR>':
784                     inputState.selectedCharacter='\n';
785                     break;
786                   case '<Space>':
787                     inputState.selectedCharacter=' ';
788                     break;
789                   default:
790                     continue;
791                 }
792               }
793             }
794             inputState.keyBuffer = [];
795             return command;
796           }
797         }
798         // Clear the buffer since there are no partial matches.
799         inputState.keyBuffer = [];
800         return null;
801       },
802       processCommand: function(cm, vim, command) {
803         vim.inputState.repeatOverride = command.repeatOverride;
804         switch (command.type) {
805           case 'motion':
806             this.processMotion(cm, vim, command);
807             break;
808           case 'operator':
809             this.processOperator(cm, vim, command);
810             break;
811           case 'operatorMotion':
812             this.processOperatorMotion(cm, vim, command);
813             break;
814           case 'action':
815             this.processAction(cm, vim, command);
816             break;
817           case 'search':
818             this.processSearch(cm, vim, command);
819             break;
820           case 'ex':
821           case 'keyToEx':
822             this.processEx(cm, vim, command);
823             break;
824           default:
825             break;
826         }
827       },
828       processMotion: function(cm, vim, command) {
829         vim.inputState.motion = command.motion;
830         vim.inputState.motionArgs = copyArgs(command.motionArgs);
831         this.evalInput(cm, vim);
832       },
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
838             // linewise
839             inputState.motion = 'expandToLine';
840             inputState.motionArgs = { linewise: true };
841             this.evalInput(cm, vim);
842             return;
843           } else {
844             // 2 different operators in a row doesn't make sense.
845             vim.inputState = new InputState();
846           }
847         }
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);
853         }
854       },
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;
862           }
863         }
864         this.processOperator(cm, vim, command);
865         if (!visualMode) {
866           this.processMotion(cm, vim, command);
867         }
868       },
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;
876         }
877         // Actions may or may not have motions and operators. Do these first.
878         if (command.operator) {
879           this.processOperator(cm, vim, command);
880         }
881         if (command.motion) {
882           this.processMotion(cm, vim, command);
883         }
884         if (command.motion || command.operator) {
885           this.evalInput(cm, vim);
886         }
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);
894         }
895         actions[command.action](cm, actionArgs, vim);
896       },
897       processSearch: function(cm, vim, command) {
898         if (!cm.getSearchCursor) {
899           // Search depends on SearchCursor.
900           return;
901         }
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) {
908           try {
909             updateSearchQuery(cm, query, ignoreCase, smartCase);
910           } catch (e) {
911             showConfirm(cm, 'Invalid regex: ' + query);
912             return;
913           }
914           commandDispatcher.processMotion(cm, vim, {
915             type: 'motion',
916             motion: 'findNext',
917             motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
918           });
919         }
920         function onPromptClose(query) {
921           cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
922           handleQuery(query, true /** ignoreCase */, true /** smartCase */);
923         }
924         function onPromptKeyUp(_e, query) {
925           var parsedQuery;
926           try {
927             parsedQuery = updateSearchQuery(cm, query,
928                 true /** ignoreCase */, true /** smartCase */);
929           } catch (e) {
930             // Swallow bad regexes for incremental search.
931           }
932           if (parsedQuery) {
933             cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
934           } else {
935             clearSearchHighlight(cm);
936             cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
937           }
938         }
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);
945
946             CodeMirror.e_stop(e);
947             close();
948             cm.focus();
949           }
950         }
951         switch (command.searchArgs.querySrc) {
952           case 'prompt':
953             showPrompt(cm, {
954                 onClose: onPromptClose,
955                 prefix: promptPrefix,
956                 desc: searchPromptDesc,
957                 onKeyUp: onPromptKeyUp,
958                 onKeyDown: onPromptKeyDown
959             });
960             break;
961           case 'wordUnderCursor':
962             var word = expandWordUnderCursor(cm, false /** inclusive */,
963                 true /** forward */, false /** bigWord */,
964                 true /** noSymbol */);
965             var isKeyword = true;
966             if (!word) {
967               word = expandWordUnderCursor(cm, false /** inclusive */,
968                   true /** forward */, false /** bigWord */,
969                   false /** noSymbol */);
970               isKeyword = false;
971             }
972             if (!word) {
973               return;
974             }
975             var query = cm.getLine(word.start.line).substring(word.start.ch,
976                 word.end.ch);
977             if (isKeyword) {
978               query = '\\b' + query + '\\b';
979             } else {
980               query = escapeRegex(query);
981             }
982
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);
988
989             handleQuery(query, true /** ignoreCase */, false /** smartCase */);
990             break;
991         }
992       },
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);
998         }
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);
1003             close();
1004             cm.focus();
1005           }
1006         }
1007         if (command.type == 'keyToEx') {
1008           // Handle user defined Ex to Ex mappings
1009           exCommandDispatcher.processCommand(cm, command.exArgs.input);
1010         } else {
1011           if (vim.visualMode) {
1012             showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
1013                 onKeyDown: onPromptKeyDown});
1014           } else {
1015             showPrompt(cm, { onClose: onPromptClose, prefix: ':',
1016                 onKeyDown: onPromptKeyDown});
1017           }
1018         }
1019       },
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);
1035         var curEnd;
1036         var repeat;
1037         if (operator) {
1038           this.recordLastEdit(vim, inputState);
1039         }
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;
1044         } else {
1045           repeat = inputState.getRepeat();
1046         }
1047         if (repeat > 0 && motionArgs.explicitRepeat) {
1048           motionArgs.repeatIsExplicit = true;
1049         } else if (motionArgs.noRepeat ||
1050             (!motionArgs.explicitRepeat && repeat === 0)) {
1051           repeat = 1;
1052           motionArgs.repeatIsExplicit = false;
1053         }
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;
1058         }
1059         motionArgs.repeat = repeat;
1060         vim.inputState = new InputState();
1061         if (motion) {
1062           var motionResult = motions[motion](cm, motionArgs, vim);
1063           vim.lastMotion = motions[motion];
1064           if (!motionResult) {
1065             return;
1066           }
1067           if (motionArgs.toJumplist) {
1068             var jumpList = vimGlobalState.jumpList;
1069             // if the current motion is # or *, use cachedCursor
1070             var cachedCursor = jumpList.cachedCursor;
1071             if (cachedCursor) {
1072               recordJumpPosition(cm, cachedCursor, motionResult);
1073               delete jumpList.cachedCursor;
1074             } else {
1075               recordJumpPosition(cm, curOriginal, motionResult);
1076             }
1077           }
1078           if (motionResult instanceof Array) {
1079             curStart = motionResult[0];
1080             curEnd = motionResult[1];
1081           } else {
1082             curEnd = motionResult;
1083           }
1084           // TODO: Handle null returns from motion commands better.
1085           if (!curEnd) {
1086             curEnd = { ch: curStart.ch, line: curStart.line };
1087           }
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;
1102             }
1103             selectionEnd = curEnd;
1104             if (vim.visualLine) {
1105               if (cursorIsBefore(selectionStart, selectionEnd)) {
1106                 selectionStart.ch = 0;
1107                 selectionEnd.ch = lineLength(cm, selectionEnd.line);
1108               } else {
1109                 selectionEnd.ch = 0;
1110                 selectionStart.ch = lineLength(cm, selectionStart.line);
1111               }
1112             }
1113             cm.setSelection(selectionStart, selectionEnd);
1114             updateMark(cm, vim, '<',
1115                 cursorIsBefore(selectionStart, selectionEnd) ? selectionStart
1116                     : selectionEnd);
1117             updateMark(cm, vim, '>',
1118                 cursorIsBefore(selectionStart, selectionEnd) ? selectionEnd
1119                     : selectionStart);
1120           } else if (!operator) {
1121             curEnd = clipCursorToContent(cm, curEnd);
1122             cm.setCursor(curEnd.line, curEnd.ch);
1123           }
1124         }
1125
1126         if (operator) {
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;
1134           }
1135           // Swap start and end if motion was backward.
1136           if (cursorIsBefore(curEnd, curStart)) {
1137             var tmp = curStart;
1138             curStart = curEnd;
1139             curEnd = tmp;
1140             inverted = true;
1141           }
1142           if (motionArgs.inclusive && !(vim.visualMode && inverted)) {
1143             // Move the selection end one to the right to include the last
1144             // character.
1145             curEnd.ch++;
1146           }
1147           var linewise = motionArgs.linewise ||
1148               (vim.visualMode && vim.visualLine);
1149           if (linewise) {
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);
1155           }
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) {
1162             exitVisualMode(cm);
1163           }
1164         }
1165       },
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;
1173       }
1174     };
1175
1176     /**
1177      * typedef {Object{line:number,ch:number}} Cursor An object containing the
1178      *     position of the cursor.
1179      */
1180     // All of the functions below return Cursor objects.
1181     var motions = {
1182       moveToTopLine: function(cm, motionArgs) {
1183         var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
1184         return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
1185       },
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)) };
1190       },
1191       moveToBottomLine: function(cm, motionArgs) {
1192         var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
1193         return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
1194       },
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 };
1200       },
1201       findNext: function(cm, motionArgs) {
1202         var state = getSearchState(cm);
1203         var query = state.getQuery();
1204         if (!query) {
1205           return;
1206         }
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);
1212       },
1213       goToMark: function(_cm, motionArgs, vim) {
1214         var mark = vim.marks[motionArgs.selectedCharacter];
1215         if (mark) {
1216           return mark.find();
1217         }
1218         return null;
1219       },
1220       jumpToMark: function(cm, motionArgs, vim) {
1221         var best = cm.getCursor();
1222         for (var i = 0; i < motionArgs.repeat; i++) {
1223           var cursor = best;
1224           for (var key in vim.marks) {
1225             if (!isLowerCase(key)) {
1226               continue;
1227             }
1228             var mark = vim.marks[key].find();
1229             var isWrongDirection = (motionArgs.forward) ?
1230               cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
1231
1232             if (isWrongDirection) {
1233               continue;
1234             }
1235             if (motionArgs.linewise && (mark.line == cursor.line)) {
1236               continue;
1237             }
1238
1239             var equal = cursorEqual(cursor, best);
1240             var between = (motionArgs.forward) ?
1241               cusrorIsBetween(cursor, mark, best) :
1242               cusrorIsBetween(best, mark, cursor);
1243
1244             if (equal || between) {
1245               best = mark;
1246             }
1247           }
1248         }
1249
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));
1255         }
1256         return best;
1257       },
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 };
1263       },
1264       moveByLines: function(cm, motionArgs, vim) {
1265         var cur = cm.getCursor();
1266         var endCh = cur.ch;
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;
1279             break;
1280           default:
1281             vim.lastHPos = endCh;
1282         }
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)) {
1291           return;
1292         }
1293         if(motionArgs.toFirstChar){
1294           endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
1295           vim.lastHPos = endCh;
1296         }
1297         vim.lastHSPos = cm.charCoords({line:line, ch:endCh},'div').left;
1298         return { line: line, ch: endCh };
1299       },
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:
1308             break;
1309           default:
1310             vim.lastHSPos = cm.charCoords(cur,'div').left;
1311         }
1312         var repeat = motionArgs.repeat;
1313         var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
1314         if (res.hitSide) {
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');
1319           } else {
1320             var resCoords = cm.charCoords({ line: cm.firstLine(), ch: 0}, 'div');
1321             resCoords.left = vim.lastHSPos;
1322             res = cm.coordsChar(resCoords, 'div');
1323           }
1324         }
1325         vim.lastHPos = res.ch;
1326         return res;
1327       },
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);
1337         return curEnd;
1338       },
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())) {
1346             break;
1347           }
1348           line += inc;
1349           while (line !== cm.firstLine() && line != cm.lastLine() && cm.getLine(line)) {
1350             line += inc;
1351           }
1352         }
1353         return { line: line, ch: 0 };
1354       },
1355       moveByScroll: function(cm, motionArgs, vim) {
1356         var scrollbox = cm.getScrollInfo();
1357         var curEnd = null;
1358         var repeat = motionArgs.repeat;
1359         if (!repeat) {
1360           repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
1361         }
1362         var orig = cm.charCoords(cm.getCursor(), 'local');
1363         motionArgs.repeat = repeat;
1364         var curEnd = motions.moveByDisplayLines(cm, motionArgs, vim);
1365         if (!curEnd) {
1366           return null;
1367         }
1368         var dest = cm.charCoords(curEnd, 'local');
1369         cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
1370         return curEnd;
1371       },
1372       moveByWords: function(cm, motionArgs) {
1373         return moveToWord(cm, motionArgs.repeat, !!motionArgs.forward,
1374             !!motionArgs.wordEnd, !!motionArgs.bigWord);
1375       },
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;
1384         return curEnd;
1385       },
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();
1391       },
1392       moveToSymbol: function(cm, motionArgs) {
1393         var repeat = motionArgs.repeat;
1394         return findSymbol(cm, repeat, motionArgs.forward,
1395             motionArgs.selectedCharacter) || cm.getCursor();
1396       },
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);
1403       },
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);
1409         end.ch--;
1410         vim.lastHSPos = cm.charCoords(end,'div').left;
1411         return retval;
1412       },
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)) };
1419       },
1420       moveToMatchedSymbol: function(cm) {
1421         var cursor = cm.getCursor();
1422         var line = cursor.line;
1423         var ch = cursor.ch;
1424         var lineText = cm.getLine(line);
1425         var symbol;
1426         var startContext = cm.getTokenAt(cursor).type;
1427         var startCtxLevel = getContextLevel(startContext);
1428         do {
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) {
1434               break;
1435             }
1436           }
1437         } while (symbol);
1438         if (symbol) {
1439           return findMatchedSymbol(cm, {line:line, ch:ch-1}, symbol);
1440         } else {
1441           return cursor;
1442         }
1443       },
1444       moveToStartOfLine: function(cm) {
1445         var cursor = cm.getCursor();
1446         return { line: cursor.line, ch: 0 };
1447       },
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');
1452         }
1453         return { line: lineNum,
1454             ch: findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)) };
1455       },
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.
1466           return null;
1467         }
1468         var tmp = textObjects[character](cm, inclusive);
1469         var start = tmp.start;
1470         var end = tmp.end;
1471         return [start, end];
1472       },
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);
1481         if (!curEnd) {
1482           cm.moveH(increment, 'char');
1483           return cm.getCursor();
1484         }
1485         curEnd.ch += increment;
1486         return curEnd;
1487       }
1488     };
1489
1490     var operators = {
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.
1501           curStart.ch = null;
1502         } else {
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);
1507             if (match) {
1508               curEnd = offsetCursor(curEnd, 0, - match[0].length);
1509             }
1510           }
1511           cm.replaceRange('', curStart, curEnd);
1512         }
1513         actions.enterInsertMode(cm, {}, cm.state.vim);
1514         cm.setCursor(curStart);
1515       },
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()) {
1522           curStart.line--;
1523           curStart.ch = lineLength(cm, curStart.line);
1524         }
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));
1531         } else {
1532           cm.setCursor(curStart);
1533         }
1534       },
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.
1545           endLine--;
1546         }
1547         for (var i = startLine; i <= endLine; i++) {
1548           for (var j = 0; j < repeat; j++) {
1549             cm.indentLine(i, operatorArgs.indentRight);
1550           }
1551         }
1552         cm.setCursor(curStart);
1553         cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
1554       },
1555       swapcase: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
1556         var toSwap = cm.getRange(curStart, curEnd);
1557         var swapped = '';
1558         for (var i = 0; i < toSwap.length; i++) {
1559           var character = toSwap.charAt(i);
1560           swapped += isUpperCase(character) ? character.toLowerCase() :
1561               character.toUpperCase();
1562         }
1563         cm.replaceRange(swapped, curStart, curEnd);
1564         if (!operatorArgs.shouldMoveCursor) {
1565           cm.setCursor(curOriginal);
1566         }
1567       },
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);
1573       }
1574     };
1575
1576     var actions = {
1577       jumpListWalk: function(cm, actionArgs, vim) {
1578         if (vim.visualMode) {
1579           return;
1580         }
1581         var repeat = actionArgs.repeat;
1582         var forward = actionArgs.forward;
1583         var jumpList = vimGlobalState.jumpList;
1584
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);
1589       },
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;
1598             break;
1599           case 'bottom': y = y - height + lineHeight*1.4;
1600             break;
1601           case 'top': y = y + lineHeight*0.4;
1602             break;
1603         }
1604         cm.scrollTo(null, y);
1605       },
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;
1612         }
1613         var keyBuffer = parseRegisterToKeyBuffer(macroModeState, registerName);
1614         while(repeat--){
1615           executeMacroKeyBuffer(cm, macroModeState, keyBuffer);
1616         }
1617       },
1618       exitMacroRecordMode: function() {
1619         var macroModeState = vimGlobalState.macroModeState;
1620         macroModeState.toggle();
1621         parseKeyBufferToRegister(macroModeState.latestRegister,
1622                                  macroModeState.macroKeyBuffer);
1623       },
1624       enterMacroRecordMode: function(cm, actionArgs) {
1625         var macroModeState = vimGlobalState.macroModeState;
1626         var registerName = actionArgs.selectedCharacter;
1627         macroModeState.toggle(cm, registerName);
1628         emptyMacroKeyBuffer(macroModeState);
1629       },
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));
1643         }
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');
1649         } else {
1650           cm.setOption('keyMap', 'vim-insert');
1651         }
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);
1657         }
1658       },
1659       toggleVisualMode: function(cm, actionArgs, vim) {
1660         var repeat = actionArgs.repeat;
1661         var curStart = cm.getCursor();
1662         var curEnd;
1663         // TODO: The repeat should actually select number of characters/lines
1664         //     equal to the repeat times the size of the previous visual
1665         //     operation.
1666         if (!vim.visualMode) {
1667           cm.on('mousedown', exitVisualMode);
1668           vim.visualMode = true;
1669           vim.visualLine = !!actionArgs.linewise;
1670           if (vim.visualLine) {
1671             curStart.ch = 0;
1672             curEnd = clipCursorToContent(cm, {
1673               line: curStart.line + repeat - 1,
1674               ch: lineLength(cm, curStart.line)
1675             }, true /** includeLineBreak */);
1676           } else {
1677             curEnd = clipCursorToContent(cm, {
1678               line: curStart.line,
1679               ch: curStart.ch + repeat
1680             }, true /** includeLineBreak */);
1681           }
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
1686             // selection.
1687             cm.setCursor(curEnd);
1688             cm.setSelection(curEnd, curStart);
1689           } else {
1690             cm.setSelection(curStart, curEnd);
1691           }
1692         } else {
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;
1708           } else {
1709             exitVisualMode(cm);
1710           }
1711         }
1712         updateMark(cm, vim, '<', cursorIsBefore(curStart, curEnd) ? curStart
1713             : curEnd);
1714         updateMark(cm, vim, '>', cursorIsBefore(curStart, curEnd) ? curEnd
1715             : curStart);
1716       },
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;
1723         } else {
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,
1728               ch: Infinity });
1729         }
1730         var finalCh = 0;
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);
1739           }
1740           var curFinalPos = { line: curStart.line, ch: finalCh };
1741           cm.setCursor(curFinalPos);
1742         });
1743       },
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);
1751         } else {
1752           insertAt.line = (actionArgs.after) ? insertAt.line :
1753               insertAt.line - 1;
1754           insertAt.ch = lineLength(cm, insertAt.line);
1755           cm.setCursor(insertAt);
1756           var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
1757               CodeMirror.commands.newlineAndIndent;
1758           newlineFn(cm);
1759         }
1760         this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
1761       },
1762       paste: function(cm, actionArgs) {
1763         var cur = cm.getCursor();
1764         var register = vimGlobalState.registerController.getRegister(
1765             actionArgs.registerName);
1766         if (!register.text) {
1767           return;
1768         }
1769         for (var text = '', i = 0; i < actionArgs.repeat; i++) {
1770           text += register.text;
1771         }
1772         var linewise = register.linewise;
1773         if (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);
1779           } else {
1780             cur.ch = 0;
1781           }
1782         } else {
1783           cur.ch += actionArgs.after ? 1 : 0;
1784         }
1785         cm.replaceRange(text, cur);
1786         // Now fine tune the cursor to where we want it.
1787         var curPosFinal;
1788         var idx;
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);
1798         } else {
1799           idx = cm.indexFromPos(cur);
1800           curPosFinal = cm.posFromIndex(idx + text.length);
1801         }
1802         cm.setCursor(curPosFinal);
1803       },
1804       undo: function(cm, actionArgs) {
1805         cm.operation(function() {
1806           repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
1807           cm.setCursor(cm.getCursor('anchor'));
1808         });
1809       },
1810       redo: function(cm, actionArgs) {
1811         repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
1812       },
1813       setRegister: function(_cm, actionArgs, vim) {
1814         vim.inputState.registerName = actionArgs.selectedCharacter;
1815       },
1816       setMark: function(cm, actionArgs, vim) {
1817         var markName = actionArgs.selectedCharacter;
1818         updateMark(cm, vim, markName, cm.getCursor());
1819       },
1820       replace: function(cm, actionArgs, vim) {
1821         var replaceWith = actionArgs.selectedCharacter;
1822         var curStart = cm.getCursor();
1823         var replaceTo;
1824         var curEnd;
1825         if(vim.visualMode){
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});
1831         }else{
1832           var line = cm.getLine(curStart.line);
1833           replaceTo = curStart.ch + actionArgs.repeat;
1834           if (replaceTo > line.length) {
1835             replaceTo=line.length;
1836           }
1837           curEnd = { line: curStart.line, ch: replaceTo };
1838         }
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);
1843         }else {
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);
1848           if(vim.visualMode){
1849             cm.setCursor(curStart);
1850             exitVisualMode(cm);
1851           }else{
1852             cm.setCursor(offsetCursor(curEnd, 0, -1));
1853           }
1854         }
1855       },
1856       incrementNumberToken: function(cm, actionArgs) {
1857         var cur = cm.getCursor();
1858         var lineStr = cm.getLine(cur.line);
1859         var re = /-?\d+/g;
1860         var match;
1861         var start;
1862         var end;
1863         var numberStr;
1864         var token;
1865         while ((match = re.exec(lineStr)) !== null) {
1866           token = match[0];
1867           start = match.index;
1868           end = start + token.length;
1869           if(cur.ch < end)break;
1870         }
1871         if(!actionArgs.backtrack && (end <= cur.ch))return;
1872         if (token) {
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);
1879         } else {
1880           return;
1881         }
1882         cm.setCursor({line: cur.line, ch: start + numberStr.length - 1});
1883       },
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;
1890         } else {
1891           repeat = vim.lastEditInputState.repeatOverride || repeat;
1892         }
1893         repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
1894       }
1895     };
1896
1897     var textObjects = {
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 */);
1905       },
1906       'W': function(cm, inclusive) {
1907         return expandWordUnderCursor(cm, inclusive,
1908             true /** forward */, true /** bigWord */);
1909       },
1910       '{': function(cm, inclusive) {
1911         return selectCompanionObject(cm, '}', inclusive);
1912       },
1913       '(': function(cm, inclusive) {
1914         return selectCompanionObject(cm, ')', inclusive);
1915       },
1916       '[': function(cm, inclusive) {
1917         return selectCompanionObject(cm, ']', inclusive);
1918       },
1919       '\'': function(cm, inclusive) {
1920         return findBeginningAndEnd(cm, "'", inclusive);
1921       },
1922       '"': function(cm, inclusive) {
1923         return findBeginningAndEnd(cm, '"', inclusive);
1924       }
1925     };
1926
1927     /*
1928      * Below are miscellaneous utility functions used by vim.js
1929      */
1930
1931     /**
1932      * Clips cursor to ensure that line is within the buffer's range
1933      * If includeLineBreak is true, then allow cur.ch == lineLength.
1934      */
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 };
1941     }
1942     function copyArgs(args) {
1943       var ret = {};
1944       for (var prop in args) {
1945         if (args.hasOwnProperty(prop)) {
1946           ret[prop] = args[prop];
1947         }
1948       }
1949       return ret;
1950     }
1951     function offsetCursor(cur, offsetLine, offsetCh) {
1952       return { line: cur.line + offsetLine, ch: cur.ch + offsetCh };
1953     }
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') {
1958           return false;
1959         }
1960       }
1961       return true;
1962     }
1963     function repeatFn(cm, fn, repeat) {
1964       return function() {
1965         for (var i = 0; i < repeat; i++) {
1966           fn(cm);
1967         }
1968       };
1969     }
1970     function copyCursor(cur) {
1971       return { line: cur.line, ch: cur.ch };
1972     }
1973     function cursorEqual(cur1, cur2) {
1974       return cur1.ch == cur2.ch && cur1.line == cur2.line;
1975     }
1976     function cursorIsBefore(cur1, cur2) {
1977       if (cur1.line < cur2.line) {
1978         return true;
1979       }
1980       if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
1981         return true;
1982       }
1983       return false;
1984     }
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;
1990     }
1991     function lineLength(cm, lineNum) {
1992       return cm.getLine(lineNum).length;
1993     }
1994     function reverse(s){
1995       return s.split('').reverse().join('');
1996     }
1997     function trim(s) {
1998       if (s.trim) {
1999         return s.trim();
2000       }
2001       return s.replace(/^\s+|\s+$/g, '');
2002     }
2003     function escapeRegex(s) {
2004       return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
2005     }
2006
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));
2019       }
2020     }
2021
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.
2032         lines.pop();
2033
2034         // Cases:
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'
2037         var line;
2038         // Find the line containing the last word, and clip all whitespace up
2039         // to it.
2040         for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
2041           curEnd.line--;
2042           curEnd.ch = 0;
2043         }
2044         // If the last word is not an empty line, clip an additional newline
2045         if (line) {
2046           curEnd.line--;
2047           curEnd.ch = lineLength(cm, curEnd.line);
2048         } else {
2049           curEnd.ch = 0;
2050         }
2051       }
2052     }
2053
2054     // Expand the selection to line ends.
2055     function expandSelectionToLine(_cm, curStart, curEnd) {
2056       curStart.ch = 0;
2057       curEnd.ch = 0;
2058       curEnd.line++;
2059     }
2060
2061     function findFirstNonWhiteSpaceCharacter(text) {
2062       if (!text) {
2063         return 0;
2064       }
2065       var firstNonWS = text.search(/\S/);
2066       return firstNonWS == -1 ? text.length : firstNonWS;
2067     }
2068
2069     function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
2070       var cur = cm.getCursor();
2071       var line = cm.getLine(cur.line);
2072       var idx = cur.ch;
2073
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;
2078       if (noSymbol) {
2079         firstMatchedChar = textAfterIdx.search(/\w/);
2080       } else {
2081         firstMatchedChar = textAfterIdx.search(/\S/);
2082       }
2083       if (firstMatchedChar == -1) {
2084         return null;
2085       }
2086       idx += firstMatchedChar;
2087       textAfterIdx = line.substring(idx);
2088       var textBeforeIdx = line.substring(0, idx);
2089
2090       var matchRegex;
2091       // Greedy matchers for the "word" we are trying to expand.
2092       if (bigWord) {
2093         matchRegex = /^\S+/;
2094       } else {
2095         if ((/\w/).test(line.charAt(idx))) {
2096           matchRegex = /^\w+/;
2097         } else {
2098           matchRegex = /^[^\w\s]+/;
2099         }
2100       }
2101
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;
2110       }
2111
2112       if (inclusive) {
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;
2119         } else {
2120           var revTrim = revTextBeforeIdx.length - wordStart;
2121           var textBeforeWordStart = revTextBeforeIdx.substring(revTrim);
2122           var whitespacesBeforeWord = textBeforeWordStart.match(/^\s*/)[0].length;
2123           wordStart -= whitespacesBeforeWord;
2124         }
2125       }
2126
2127       return { start: { line: cur.line, ch: wordStart },
2128         end: { line: cur.line, ch: wordEnd }};
2129     }
2130
2131     function recordJumpPosition(cm, oldCur, newCur) {
2132       if(!cursorEqual(oldCur, newCur)) {
2133         vimGlobalState.jumpList.add(cm, oldCur, newCur);
2134       }
2135     }
2136
2137     function recordLastCharacterSearch(increment, args) {
2138         vimGlobalState.lastChararacterSearch.increment = increment;
2139         vimGlobalState.lastChararacterSearch.forward = args.forward;
2140         vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter;
2141     }
2142
2143     var symbolToMode = {
2144         '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
2145         '[': 'section', ']': 'section',
2146         '*': 'comment', '/': 'comment',
2147         'm': 'method', 'M': 'method',
2148         '#': 'preprocess'
2149     };
2150     var findSymbolModes = {
2151       bracket: {
2152         isComplete: function(state) {
2153           if (state.nextCh === state.symb) {
2154             state.depth++;
2155             if(state.depth >= 1)return true;
2156           } else if (state.nextCh === state.reverseSymb) {
2157             state.depth--;
2158           }
2159           return false;
2160         }
2161       },
2162       section: {
2163         init: function(state) {
2164           state.curMoveThrough = true;
2165           state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
2166         },
2167         isComplete: function(state) {
2168           return state.index === 0 && state.nextCh === state.symb;
2169         }
2170       },
2171       comment: {
2172         isComplete: function(state) {
2173           var found = state.lastCh === '*' && state.nextCh === '/';
2174           state.lastCh = state.nextCh;
2175           return found;
2176         }
2177       },
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.
2181       method: {
2182         init: function(state) {
2183           state.symb = (state.symb === 'm' ? '{' : '}');
2184           state.reverseSymb = state.symb === '{' ? '}' : '{';
2185         },
2186         isComplete: function(state) {
2187           if(state.nextCh === state.symb)return true;
2188           return false;
2189         }
2190       },
2191       preprocess: {
2192         init: function(state) {
2193           state.index = 0;
2194         },
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) {
2200                 return true;
2201               }
2202               state.depth++;
2203             } else if (token === 'if') {
2204               if (!state.forward && state.depth === 0) {
2205                 return true;
2206               }
2207               state.depth--;
2208             }
2209             if(token === 'else' && state.depth === 0)return true;
2210           }
2211           return false;
2212         }
2213       }
2214     };
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;
2219       var curCh = cur.ch;
2220       var line = cur.line;
2221       var lineText = cm.getLine(line);
2222       var state = {
2223         lineText: lineText,
2224         nextCh: lineText.charAt(curCh),
2225         lastCh: null,
2226         index: curCh,
2227         symb: symb,
2228         reverseSymb: (forward ?  { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
2229         forward: forward,
2230         depth: 0,
2231         curMoveThrough: false
2232       };
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) {
2242           line += increment;
2243           state.lineText = cm.getLine(line) || '';
2244           if (increment > 0) {
2245             state.index = 0;
2246           } else {
2247             var lineLen = state.lineText.length;
2248             state.index = (lineLen > 0) ? (lineLen-1) : 0;
2249           }
2250           state.nextCh = state.lineText.charAt(state.index);
2251         }
2252         if (isComplete(state)) {
2253           cur.line = line;
2254           cur.ch = state.index;
2255           repeat--;
2256         }
2257       }
2258       if (state.nextCh || state.curMoveThrough) {
2259         return { line: line, ch: state.index };
2260       }
2261       return cur;
2262     }
2263
2264     /*
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.
2269      *
2270      * @param {CodeMirror} cm CodeMirror object.
2271      * @param {Cursor} cur The cursor position.
2272      * @param {boolean} forward True to search forward. False to search
2273      *     backward.
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
2277      *     as words.
2278      * @return {Object{from:number, to:number, line: number}} The boundaries of
2279      *     the word, or null if there are no more words.
2280      */
2281     function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
2282       var lineNum = cur.line;
2283       var pos = cur.ch;
2284       var line = cm.getLine(lineNum);
2285       var dir = forward ? 1 : -1;
2286       var regexps = bigWord ? bigWordRegexp : wordRegexp;
2287
2288       if (emptyLineIsWord && line == '') {
2289         lineNum += dir;
2290         line = cm.getLine(lineNum);
2291         if (!isLine(cm, lineNum)) {
2292           return null;
2293         }
2294         pos = (forward) ? 0 : line.length;
2295       }
2296
2297       while (true) {
2298         if (emptyLineIsWord && line == '') {
2299           return { from: 0, to: 0, line: lineNum };
2300         }
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))) {
2308               wordStart = pos;
2309               // Advance to end of word.
2310               while (pos != stop && regexps[i].test(line.charAt(pos))) {
2311                 pos += dir;
2312               }
2313               wordEnd = 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.
2318                 continue;
2319               } else {
2320                 return {
2321                   from: Math.min(wordStart, wordEnd + 1),
2322                   to: Math.max(wordStart, wordEnd),
2323                   line: lineNum };
2324               }
2325             }
2326           }
2327           if (!foundWord) {
2328             pos += dir;
2329           }
2330         }
2331         // Advance to next/prev line.
2332         lineNum += dir;
2333         if (!isLine(cm, lineNum)) {
2334           return null;
2335         }
2336         line = cm.getLine(lineNum);
2337         pos = (dir > 0) ? 0 : line.length;
2338       }
2339       // Should never get here.
2340       throw new Error('The impossible happened.');
2341     }
2342
2343     /**
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
2347      *     backward.
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.
2353      */
2354     function moveToWord(cm, repeat, forward, wordEnd, bigWord) {
2355       var cur = cm.getCursor();
2356       var curStart = copyCursor(cur);
2357       var words = [];
2358       if (forward && !wordEnd || !forward && wordEnd) {
2359         repeat++;
2360       }
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);
2365         if (!word) {
2366           var eodCh = lineLength(cm, cm.lastLine());
2367           words.push(forward
2368               ? {line: cm.lastLine(), from: eodCh, to: eodCh}
2369               : {line: 0, from: 0, to: 0});
2370           break;
2371         }
2372         words.push(word);
2373         cur = {line: word.line, ch: forward ? (word.to - 1) : word.from};
2374       }
2375       var shortCircuit = words.length != repeat;
2376       var firstWord = words[0];
2377       var lastWord = words.pop();
2378       if (forward && !wordEnd) {
2379         // w
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();
2383         }
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) {
2388         // ge
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();
2392         }
2393         return {line: lastWord.line, ch: lastWord.to};
2394       } else {
2395         // b
2396         return {line: lastWord.line, ch: lastWord.from};
2397       }
2398     }
2399
2400     function moveToCharacter(cm, repeat, forward, character) {
2401       var cur = cm.getCursor();
2402       var start = cur.ch;
2403       var idx;
2404       for (var i = 0; i < repeat; i ++) {
2405         var line = cm.getLine(cur.line);
2406         idx = charIdxInLine(start, line, character, forward, true);
2407         if (idx == -1) {
2408           return null;
2409         }
2410         start = idx;
2411       }
2412       return { line: cm.getCursor().line, ch: idx };
2413     }
2414
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 });
2420     }
2421
2422     function updateMark(cm, vim, markName, pos) {
2423       if (!inArray(markName, validMarks)) {
2424         return;
2425       }
2426       if (vim.marks[markName]) {
2427         vim.marks[markName].clear();
2428       }
2429       vim.marks[markName] = cm.setBookmark(pos);
2430     }
2431
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
2438       var idx;
2439       if (forward) {
2440         idx = line.indexOf(character, start + 1);
2441         if (idx != -1 && !includeChar) {
2442           idx -= 1;
2443         }
2444       } else {
2445         idx = line.lastIndexOf(character, start - 1);
2446         if (idx != -1 && !includeChar) {
2447           idx += 1;
2448         }
2449       }
2450       return idx;
2451     }
2452
2453     function getContextLevel(ctx) {
2454       return (ctx === 'string' || ctx === 'comment') ? 1 : 0;
2455     }
2456
2457     function findMatchedSymbol(cm, cur, symb) {
2458       var line = cur.line;
2459       var ch = cur.ch;
2460       symb = symb ? symb : cm.getLine(line).charAt(ch);
2461
2462       var symbContext = cm.getTokenAt({line:line, ch:ch+1}).type;
2463       var symbCtxLevel = getContextLevel(symbContext);
2464
2465       var reverseSymb = ({
2466         '(': ')', ')': '(',
2467         '[': ']', ']': '[',
2468         '{': '}', '}': '{'})[symb];
2469
2470       // Couldn't find a matching symbol, abort
2471       if (!reverseSymb) {
2472         return cur;
2473       }
2474
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
2483       // and quotes, etc.
2484       while (line !== endLine && depth > 0) {
2485         index += increment;
2486         nextCh = lineText.charAt(index);
2487         if (!nextCh) {
2488           line += increment;
2489           lineText = cm.getLine(line) || '';
2490           if (increment > 0) {
2491             index = 0;
2492           } else {
2493             var lineLen = lineText.length;
2494             index = (lineLen > 0) ? (lineLen-1) : 0;
2495           }
2496           nextCh = lineText.charAt(index);
2497         }
2498         var revSymbContext = cm.getTokenAt({line:line, ch:index+1}).type;
2499         var revSymbCtxLevel = getContextLevel(revSymbContext);
2500         if (symbCtxLevel >= revSymbCtxLevel) {
2501           if (nextCh === symb) {
2502             depth++;
2503           } else if (nextCh === reverseSymb) {
2504             depth--;
2505           }
2506         }
2507       }
2508
2509       if (nextCh) {
2510         return { line: line, ch: index };
2511       }
2512       return cur;
2513     }
2514
2515     function selectCompanionObject(cm, revSymb, inclusive) {
2516       var cur = cm.getCursor();
2517
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;
2522
2523       return { start: start, end: end };
2524     }
2525
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);
2535
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);
2543       }
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
2548       }
2549
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
2553       } else {
2554         // go backwards to find the start
2555         for (i = cur.ch; i > -1 && !start; i--) {
2556           if (chars[i] == symb) {
2557             start = i + 1;
2558           }
2559         }
2560       }
2561
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) {
2566             end = i;
2567           }
2568         }
2569       }
2570
2571       // nothing found
2572       if (!start || !end) {
2573         return { start: cur, end: cur };
2574       }
2575
2576       // include the symbols
2577       if (inclusive) {
2578         --start; ++end;
2579       }
2580
2581       return {
2582         start: { line: cur.line, ch: start },
2583         end: { line: cur.line, ch: end }
2584       };
2585     }
2586
2587     // Search functions
2588     function SearchState() {}
2589     SearchState.prototype = {
2590       getQuery: function() {
2591         return vimGlobalState.query;
2592       },
2593       setQuery: function(query) {
2594         vimGlobalState.query = query;
2595       },
2596       getOverlay: function() {
2597         return this.searchOverlay;
2598       },
2599       setOverlay: function(overlay) {
2600         this.searchOverlay = overlay;
2601       },
2602       isReversed: function() {
2603         return vimGlobalState.isReversed;
2604       },
2605       setReversed: function(reversed) {
2606         vimGlobalState.isReversed = reversed;
2607       }
2608     };
2609     function getSearchState(cm) {
2610       var vim = cm.state.vim;
2611       return vim.searchState_ || (vim.searchState_ = new SearchState());
2612     }
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 });
2617       }
2618       else {
2619         onClose(prompt(shortText, ''));
2620       }
2621     }
2622
2623     function findUnescapedSlashes(str) {
2624       var escapeNextChar = false;
2625       var slashes = [];
2626       for (var i = 0; i < str.length; i++) {
2627         var c = str.charAt(i);
2628         if (!escapeNextChar && c == '/') {
2629           slashes.push(i);
2630         }
2631         escapeNextChar = (c == '\\');
2632       }
2633       return slashes;
2634     }
2635     /**
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.
2644      */
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);
2652       var regexPart;
2653       var forceIgnoreCase;
2654       if (!slashes.length) {
2655         // Query looks like 'regexp'
2656         regexPart = query;
2657       } else {
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);
2662       }
2663       if (!regexPart) {
2664         return null;
2665       }
2666       if (smartCase) {
2667         ignoreCase = (/^[^A-Z]*$/).test(regexPart);
2668       }
2669       var regexp = new RegExp(regexPart,
2670           (ignoreCase || forceIgnoreCase) ? 'i' : undefined);
2671       return regexp;
2672     }
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() {},
2677             {bottom: true});
2678       } else {
2679         alert(text);
2680       }
2681     }
2682     function makePrompt(prefix, desc) {
2683       var raw = '';
2684       if (prefix) {
2685         raw += '<span style="font-family: monospace">' + prefix + '</span>';
2686       }
2687       raw += '<input type="text"/> ' +
2688           '<span style="color: #888">';
2689       if (desc) {
2690         raw += '<span style="color: #888">';
2691         raw += desc;
2692         raw += '</span>';
2693       }
2694       return raw;
2695     }
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);
2701     }
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]) {
2708                   return false;
2709               }
2710           }
2711           return true;
2712       }
2713       return false;
2714     }
2715     // Returns true if the query is valid.
2716     function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
2717       if (!rawQuery) {
2718         return;
2719       }
2720       var state = getSearchState(cm);
2721       var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
2722       if (!query) {
2723         return;
2724       }
2725       highlightSearchMatches(cm, query);
2726       if (regexEqual(query, state.getQuery())) {
2727         return query;
2728       }
2729       state.setQuery(query);
2730       return query;
2731     }
2732     function searchOverlay(query) {
2733       if (query.source.charAt(0) == '^') {
2734         var matchSol = true;
2735       }
2736       return {
2737         token: function(stream) {
2738           if (matchSol && !stream.sol()) {
2739             stream.skipToEnd();
2740             return;
2741           }
2742           var match = stream.match(query, false);
2743           if (match) {
2744             if (match[0].length == 0) {
2745               // Matched empty string, skip to next.
2746               stream.next();
2747               return 'searching';
2748             }
2749             if (!stream.sol()) {
2750               // Backtrack 1 to match \b
2751               stream.backUp(1);
2752               if (!query.exec(stream.next() + match[0])) {
2753                 stream.next();
2754                 return null;
2755               }
2756             }
2757             stream.match(query);
2758             return 'searching';
2759           }
2760           while (!stream.eol()) {
2761             stream.next();
2762             if (stream.match(query, false)) break;
2763           }
2764         },
2765         query: query
2766       };
2767     }
2768     function highlightSearchMatches(cm, query) {
2769       var overlay = getSearchState(cm).getOverlay();
2770       if (!overlay || query != overlay.query) {
2771         if (overlay) {
2772           cm.removeOverlay(overlay);
2773         }
2774         overlay = searchOverlay(query);
2775         cm.addOverlay(overlay);
2776         getSearchState(cm).setOverlay(overlay);
2777       }
2778     }
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); }
2787           if (!found) {
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)) {
2793               return;
2794             }
2795           }
2796         }
2797         return cursor.from();
2798       });
2799     }
2800     function clearSearchHighlight(cm) {
2801       cm.removeOverlay(getSearchState(cm).getOverlay());
2802       getSearchState(cm).setOverlay(null);
2803     }
2804     /**
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
2811      *       number
2812      *   if there are 2 range arguments, then check if pos is in between the two
2813      *       range arguments.
2814      */
2815     function isInRange(pos, start, end) {
2816       if (typeof pos != 'number') {
2817         // Assume it is a cursor position. Get the line number.
2818         pos = pos.line;
2819       }
2820       if (start instanceof Array) {
2821         return inArray(pos, start);
2822       } else {
2823         if (end) {
2824           return (pos >= start && pos <= end);
2825         } else {
2826           return pos == start;
2827         }
2828       }
2829     }
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};
2838     }
2839
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'}
2853     ];
2854     Vim.ExCommandDispatcher = function() {
2855       this.buildCommandMap_();
2856     };
2857     Vim.ExCommandDispatcher.prototype = {
2858       processCommand: function(cm, input) {
2859         var vim = cm.state.vim;
2860         if (vim.visualMode) {
2861           exitVisualMode(cm);
2862         }
2863         var inputStream = new CodeMirror.StringStream(input);
2864         var params = {};
2865         params.input = input;
2866         try {
2867           this.parseInput_(cm, inputStream, params);
2868         } catch(e) {
2869           showConfirm(cm, e);
2870           return;
2871         }
2872         var commandName;
2873         if (!params.commandName) {
2874           // If only a line range is defined, move to the line.
2875           if (params.line !== undefined) {
2876             commandName = 'move';
2877           }
2878         } else {
2879           var command = this.matchCommand_(params.commandName);
2880           if (command) {
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]);
2887               }
2888               return;
2889             } else if (command.type == 'exToEx') {
2890               // Handle Ex to Ex mapping.
2891               this.processCommand(cm, command.toInput);
2892               return;
2893             }
2894           }
2895         }
2896         if (!commandName) {
2897           showConfirm(cm, 'Not an editor command ":' + input + '"');
2898           return;
2899         }
2900         try {
2901           exCommands[commandName](cm, params);
2902         } catch(e) {
2903           showConfirm(cm, e);
2904         }
2905       },
2906       parseInput_: function(cm, inputStream, result) {
2907         inputStream.eatWhile(':');
2908         // Parse range.
2909         if (inputStream.eat('%')) {
2910           result.line = cm.firstLine();
2911           result.lineEnd = cm.lastLine();
2912         } else {
2913           result.line = this.parseLineSpec_(cm, inputStream);
2914           if (result.line !== undefined && inputStream.eat(',')) {
2915             result.lineEnd = this.parseLineSpec_(cm, inputStream);
2916           }
2917         }
2918
2919         // Parse command name.
2920         var commandMatch = inputStream.match(/^(\w+)/);
2921         if (commandMatch) {
2922           result.commandName = commandMatch[1];
2923         } else {
2924           result.commandName = inputStream.match(/.*/)[0];
2925         }
2926
2927         return result;
2928       },
2929       parseLineSpec_: function(cm, inputStream) {
2930         var numberMatch = inputStream.match(/^(\d+)/);
2931         if (numberMatch) {
2932           return parseInt(numberMatch[1], 10) - 1;
2933         }
2934         switch (inputStream.next()) {
2935           case '.':
2936             return cm.getCursor().line;
2937           case '$':
2938             return cm.lastLine();
2939           case '\'':
2940             var mark = cm.state.vim.marks[inputStream.next()];
2941             if (mark && mark.find()) {
2942               return mark.find().line;
2943             }
2944             throw new Error('Mark not set');
2945           default:
2946             inputStream.backUp(1);
2947             return undefined;
2948         }
2949       },
2950       parseCommandArgs_: function(inputStream, params, command) {
2951         if (inputStream.eol()) {
2952           return;
2953         }
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]) {
2959           params.args = args;
2960         }
2961       },
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) {
2972               return command;
2973             }
2974           }
2975         }
2976         return null;
2977       },
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;
2984         }
2985       },
2986       map: function(lhs, rhs) {
2987         if (lhs != ':' && lhs.charAt(0) == ':') {
2988           var commandName = lhs.substring(1);
2989           if (rhs != ':' && rhs.charAt(0) == ':') {
2990             // Ex to Ex mapping
2991             this.commandMap_[commandName] = {
2992               name: commandName,
2993               type: 'exToEx',
2994               toInput: rhs.substring(1)
2995             };
2996           } else {
2997             // Ex to key mapping
2998             this.commandMap_[commandName] = {
2999               name: commandName,
3000               type: 'exToKey',
3001               toKeys: parseKeyString(rhs)
3002             };
3003           }
3004         } else {
3005           if (rhs != ':' && rhs.charAt(0) == ':') {
3006             // Key to Ex mapping.
3007             defaultKeymap.unshift({
3008               keys: parseKeyString(lhs),
3009               type: 'keyToEx',
3010               exArgs: { input: rhs.substring(1) }});
3011           } else {
3012             // Key to key mapping
3013             defaultKeymap.unshift({
3014               keys: parseKeyString(lhs),
3015               type: 'keyToKey',
3016               toKeys: parseKeyString(rhs)
3017             });
3018           }
3019         }
3020       }
3021     };
3022
3023     // Converts a key string sequence of the form a<C-w>bd<Left> into Vim's
3024     // keymap representation.
3025     function parseKeyString(str) {
3026       var key, match;
3027       var keys = [];
3028       while (str) {
3029         match = (/<\w+-.+?>|<\w+>|./).exec(str);
3030         if(match === null)break;
3031         key = match[0];
3032         str = str.substring(match.index + key.length);
3033         keys.push(key);
3034       }
3035       return keys;
3036     }
3037
3038     var exCommands = {
3039       map: function(cm, params) {
3040         var mapArgs = params.args;
3041         if (!mapArgs || mapArgs.length < 2) {
3042           if (cm) {
3043             showConfirm(cm, 'Invalid mapping: ' + params.input);
3044           }
3045           return;
3046         }
3047         exCommandDispatcher.map(mapArgs[0], mapArgs[1], cm);
3048       },
3049       move: function(cm, params) {
3050         commandDispatcher.processCommand(cm, cm.state.vim, {
3051             type: 'motion',
3052             motion: 'moveToLineOrEdgeOfDocument',
3053             motionArgs: { forward: false, explicitRepeat: true,
3054               linewise: true },
3055             repeatOverride: params.line+1});
3056       },
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]+/);
3066             if (opts) {
3067               opts = opts[0];
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';
3075             }
3076             if (args.eatSpace() && args.match(/\/.*\//)) { throw new Error('patterns not supported'); }
3077           }
3078         }
3079         parseArgs();
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 = [];
3091         if (number) {
3092           for (var i = 0; i < text.length; i++) {
3093             if (numberRegex.exec(text[i])) {
3094               numPart.push(text[i]);
3095             } else {
3096               textPart.push(text[i]);
3097             }
3098           }
3099         } else {
3100           textPart = text;
3101         }
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);
3110           return anum - bnum;
3111         }
3112         numPart.sort(compareFn);
3113         textPart.sort(compareFn);
3114         text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
3115         if (unique) { // Remove duplicate lines
3116           var textOld = text;
3117           var lastLine;
3118           text = [];
3119           for (var i = 0; i < textOld.length; i++) {
3120             if (textOld[i] != lastLine) {
3121               text.push(textOld[i]);
3122             }
3123             lastLine = textOld[i];
3124           }
3125         }
3126         cm.replaceRange(text.join('\n'), curStart, curEnd);
3127       },
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.');
3132         }
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/');
3138           return;
3139         }
3140         var regexPart = argString.substring(slashes[0] + 1, slashes[1]);
3141         var replacePart = '';
3142         var flagsPart;
3143         var count;
3144         var confirm = false; // Whether to confirm each replace.
3145         if (slashes[1]) {
3146           replacePart = argString.substring(slashes[1] + 1, slashes[2]);
3147         }
3148         if (slashes[2]) {
3149           // After the 3rd slash, we can have flags followed by a space followed
3150           // by count.
3151           var trailing = argString.substring(slashes[2] + 1).split(' ');
3152           flagsPart = trailing[0];
3153           count = parseInt(trailing[1]);
3154         }
3155         if (flagsPart) {
3156           if (flagsPart.indexOf('c') != -1) {
3157             confirm = true;
3158             flagsPart.replace('c', '');
3159           }
3160           regexPart = regexPart + '/' + flagsPart;
3161         }
3162         if (regexPart) {
3163           // If regex part is empty, then use the previous query. Otherwise use
3164           // the regex part as the new query.
3165           try {
3166             updateSearchQuery(cm, regexPart, true /** ignoreCase */,
3167               true /** smartCase */);
3168           } catch (e) {
3169             showConfirm(cm, 'Invalid regex: ' + regexPart);
3170             return;
3171           }
3172         }
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;
3177         if (count) {
3178           lineStart = lineEnd;
3179           lineEnd = lineStart + count - 1;
3180         }
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);
3184       },
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);
3191         } else {
3192           // Saves to text area if no save command is defined.
3193           cm.save();
3194         }
3195       },
3196       nohlsearch: function(cm) {
3197         clearSearchHighlight(cm);
3198       },
3199       delmarks: function(cm, params) {
3200         if (!params.argString || !params.argString.trim()) {
3201           showConfirm(cm, 'Argument required');
3202           return;
3203         }
3204
3205         var state = cm.state.vim;
3206         var stream = new CodeMirror.StringStream(params.argString.trim());
3207         while (!stream.eol()) {
3208           stream.eatSpace();
3209
3210           // Record the streams position at the beginning of the loop for use
3211           // in error messages.
3212           var count = stream.pos;
3213
3214           if (!stream.match(/[a-zA-Z]/, false)) {
3215             showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
3216             return;
3217           }
3218
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.
3223
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));
3227               return;
3228             }
3229
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));
3240                 return;
3241               }
3242
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];
3249               }
3250             } else {
3251               showConfirm(cm, 'Invalid argument: ' + startMark + '-');
3252               return;
3253             }
3254           } else {
3255             // This symbol is a valid mark, and is not part of a range.
3256             delete state.marks[sym];
3257           }
3258         }
3259       }
3260     };
3261
3262     var exCommandDispatcher = new Vim.ExCommandDispatcher();
3263
3264     /**
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.
3272     */
3273     function doReplace(cm, confirm, lineStart, lineEnd, searchCursor, query,
3274         replaceWith) {
3275       // Set up all the functions.
3276       cm.state.vim.exMode = true;
3277       var done = false;
3278       var lastPos = searchCursor.from();
3279       function replaceAll() {
3280         cm.operation(function() {
3281           while (!done) {
3282             replace();
3283             next();
3284           }
3285           stop();
3286         });
3287       }
3288       function replace() {
3289         var text = cm.getRange(searchCursor.from(), searchCursor.to());
3290         var newText = text.replace(query, replaceWith);
3291         searchCursor.replace(newText);
3292       }
3293       function next() {
3294         var found = searchCursor.findNext();
3295         if (!found) {
3296           done = true;
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();
3301           done = false;
3302         } else {
3303           done = true;
3304         }
3305       }
3306       function stop(close) {
3307         if (close) { close(); }
3308         cm.focus();
3309         if (lastPos) {
3310           cm.setCursor(lastPos);
3311           var vim = cm.state.vim;
3312           vim.exMode = false;
3313           vim.lastHPos = vim.lastHSPos = lastPos.ch;
3314         }
3315       }
3316       function onPromptKeyDown(e, _value, close) {
3317         // Swallow all keys.
3318         CodeMirror.e_stop(e);
3319         var keyName = CodeMirror.keyName(e);
3320         switch (keyName) {
3321           case 'Y':
3322             replace(); next(); break;
3323           case 'N':
3324             next(); break;
3325           case 'A':
3326             cm.operation(replaceAll); break;
3327           case 'L':
3328             replace();
3329             // fall through and exit.
3330           case 'Q':
3331           case 'Esc':
3332           case 'Ctrl-C':
3333           case 'Ctrl-[':
3334             stop(close);
3335             break;
3336         }
3337         if (done) { stop(close); }
3338       }
3339
3340       // Actually do replace.
3341       next();
3342       if (done) {
3343         throw new Error('No matches for ' + query.source);
3344       }
3345       if (!confirm) {
3346         replaceAll();
3347         return;
3348       }
3349       showPrompt(cm, {
3350         prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',
3351         onKeyDown: onPromptKeyDown
3352       });
3353     }
3354
3355     // Register Vim with CodeMirror
3356     function buildVimKeyMap() {
3357       /**
3358        * Handle the raw key event from CodeMirror. Translate the
3359        * Shift + key modifier to the resulting letter, while preserving other
3360        * modifers.
3361        */
3362       // TODO: Figure out a way to catch capslock.
3363       function cmKeyToVimKey(key, modifier) {
3364         var vimKey = key;
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') {
3369             modifier = null;
3370           }
3371           else {
3372             vimKey = vimKey.toLowerCase();
3373           }
3374         }
3375         if (modifier) {
3376           // Vim will parse modifier+key combination as a single key.
3377           vimKey = modifier.charAt(0) + '-' + vimKey;
3378         }
3379         var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey];
3380         vimKey = specialKey ? specialKey : vimKey;
3381         vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey;
3382         return vimKey;
3383       }
3384
3385       // Closure to bind CodeMirror, key, modifier.
3386       function keyMapper(vimKey) {
3387         return function(cm) {
3388           CodeMirror.Vim.handleKey(cm, vimKey);
3389         };
3390       }
3391
3392       var cmToVimKeymap = {
3393         'nofallthrough': true,
3394         'disableInput': true,
3395         'style': 'fat-cursor'
3396       };
3397       function bindKeys(keys, modifier) {
3398         for (var i = 0; i < keys.length; i++) {
3399           var key = keys[i];
3400           if (!modifier && inArray(key, specialSymbols)) {
3401             // Wrap special symbols with '' because that's how CodeMirror binds
3402             // them.
3403             key = "'" + key + "'";
3404           }
3405           var vimKey = cmKeyToVimKey(keys[i], modifier);
3406           var cmKey = modifier ? modifier + '-' + key : key;
3407           cmToVimKeymap[cmKey] = keyMapper(vimKey);
3408         }
3409       }
3410       bindKeys(upperCaseAlphabet);
3411       bindKeys(upperCaseAlphabet, 'Shift');
3412       bindKeys(upperCaseAlphabet, 'Ctrl');
3413       bindKeys(specialSymbols);
3414       bindKeys(specialSymbols, 'Ctrl');
3415       bindKeys(numbers);
3416       bindKeys(numbers, 'Ctrl');
3417       bindKeys(specialKeys);
3418       bindKeys(specialKeys, 'Ctrl');
3419       return cmToVimKeymap;
3420     }
3421     CodeMirror.keyMap.vim = buildVimKeyMap();
3422
3423     function exitInsertMode(cm) {
3424       var vim = cm.state.vim;
3425       var inReplay = vimGlobalState.macroModeState.inReplay;
3426       if (!inReplay) {
3427         cm.off('change', onChange);
3428         cm.off('cursorActivity', onCursorActivity);
3429         CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
3430       }
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;
3436       }
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.
3442     }
3443
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;
3455         fn(cm);
3456       },
3457       fallthrough: ['default']
3458     };
3459
3460     CodeMirror.keyMap['vim-replace'] = {
3461       'Backspace': 'goCharLeft',
3462       fallthrough: ['vim-insert']
3463     };
3464
3465     function parseRegisterToKeyBuffer(macroModeState, registerName) {
3466       var match, key;
3467       var register = vimGlobalState.registerController.getRegister(registerName);
3468       var text = register.toString();
3469       var macroKeyBuffer = macroModeState.macroKeyBuffer;
3470       emptyMacroKeyBuffer(macroModeState);
3471       do {
3472         match = (/<\w+-.+?>|<\w+>|./).exec(text);
3473         if(match === null)break;
3474         key = match[0];
3475         text = text.substring(match.index + key.length);
3476         macroKeyBuffer.push(key);
3477       } while (text);
3478       return macroKeyBuffer;
3479     }
3480
3481     function parseKeyBufferToRegister(registerName, keyBuffer) {
3482       var text = keyBuffer.join('');
3483       vimGlobalState.registerController.setRegisterText(registerName, text);
3484     }
3485
3486     function emptyMacroKeyBuffer(macroModeState) {
3487       if(macroModeState.isMacroPlaying)return;
3488       var macroKeyBuffer = macroModeState.macroKeyBuffer;
3489       macroKeyBuffer.length = 0;
3490     }
3491
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]);
3496       };
3497       macroModeState.isMacroPlaying = false;
3498     }
3499
3500     function logKey(macroModeState, key) {
3501       if(macroModeState.isMacroPlaying)return;
3502       var macroKeyBuffer = macroModeState.macroKeyBuffer;
3503       macroKeyBuffer.push(key);
3504     }
3505
3506     /**
3507      * Listens for changes made in insert mode.
3508      * Should only be active in insert mode.
3509      */
3510     function onChange(_cm, changeObj) {
3511       var macroModeState = vimGlobalState.macroModeState;
3512       var lastChange = macroModeState.lastInsertModeChanges;
3513       while (changeObj) {
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);
3519         }
3520         // Change objects may be chained with next.
3521         changeObj = changeObj.next;
3522       }
3523     }
3524
3525     /**
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.
3529     */
3530     function onCursorActivity() {
3531       var macroModeState = vimGlobalState.macroModeState;
3532       var lastChange = macroModeState.lastInsertModeChanges;
3533       if (lastChange.expectCursorActivityForChange) {
3534         lastChange.expectCursorActivityForChange = false;
3535       } else {
3536         // Cursor moved outside the context of an edit. Reset the change.
3537         lastChange.changes = [];
3538       }
3539     }
3540
3541     /** Wrapper for special keys pressed in insert mode */
3542     function InsertModeKey(keyName) {
3543       this.keyName = keyName;
3544     }
3545
3546     /**
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.
3550     */
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));
3557         return true;
3558       }
3559       if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
3560         CodeMirror.lookupKey(keyName, ['vim-insert'], onKeyFound);
3561       }
3562     }
3563
3564     /**
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.
3568      *
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.
3572      */
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() {
3579         if (isAction) {
3580           commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
3581         } else {
3582           commandDispatcher.evalInput(cm, vim);
3583         }
3584       }
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);
3591         }
3592       }
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++) {
3598           repeatCommand();
3599           repeatInsert(1);
3600         }
3601       } else {
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.
3606           repeatCommand();
3607         }
3608         repeatInsert(repeat);
3609       }
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.
3614         exitInsertMode(cm);
3615       }
3616       macroModeState.inReplay = false;
3617     };
3618
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);
3624         } else {
3625           binding(cm);
3626         }
3627         return true;
3628       }
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);
3634           } else {
3635             var cur = cm.getCursor();
3636             cm.replaceRange(change, cur, cur);
3637           }
3638         }
3639       }
3640     }
3641
3642     resetVimGlobalState();
3643     return vimApi;
3644   };
3645   // Initialize Vim and make it available as an API.
3646   CodeMirror.Vim = Vim();
3647 }
3648 )();