GPQAPP

Форк
0
5734 строки · 219.1 Кб
1
// CodeMirror, copyright (c) by Marijn Haverbeke and others
2
// Distributed under an MIT license: https://codemirror.net/LICENSE
3

4
/**
5
 * Supported keybindings:
6
 *   Too many to list. Refer to defaultKeymap below.
7
 *
8
 * Supported Ex commands:
9
 *   Refer to defaultExCommandMap below.
10
 *
11
 * Registers: unnamed, -, ., :, /, _, a-z, A-Z, 0-9
12
 *   (Does not respect the special case for number registers when delete
13
 *    operator is made with these commands: %, (, ),  , /, ?, n, N, {, } )
14
 *   TODO: Implement the remaining registers.
15
 *
16
 * Marks: a-z, A-Z, and 0-9
17
 *   TODO: Implement the remaining special marks. They have more complex
18
 *       behavior.
19
 *
20
 * Events:
21
 *  'vim-mode-change' - raised on the editor anytime the current mode changes,
22
 *                      Event object: {mode: "visual", subMode: "linewise"}
23
 *
24
 * Code structure:
25
 *  1. Default keymap
26
 *  2. Variable declarations and short basic helpers
27
 *  3. Instance (External API) implementation
28
 *  4. Internal state tracking objects (input state, counter) implementation
29
 *     and instantiation
30
 *  5. Key handler (the main command dispatcher) implementation
31
 *  6. Motion, operator, and action implementations
32
 *  7. Helper functions for the key handler, motions, operators, and actions
33
 *  8. Set up Vim to work as a keymap for CodeMirror.
34
 *  9. Ex command implementations.
35
 */
36

37
(function(mod) {
38
  if (typeof exports == "object" && typeof module == "object") // CommonJS
39
    mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/dialog/dialog"), require("../addon/edit/matchbrackets.js"));
40
  else if (typeof define == "function" && define.amd) // AMD
41
    define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/dialog/dialog", "../addon/edit/matchbrackets"], mod);
42
  else // Plain browser env
43
    mod(CodeMirror);
44
})(function(CodeMirror) {
45
  'use strict';
46

47
  var Pos = CodeMirror.Pos;
48

49
  function transformCursor(cm, range) {
50
    var vim = cm.state.vim;
51
    if (!vim || vim.insertMode) return range.head;
52
    var head = vim.sel.head;
53
    if (!head)  return range.head;
54

55
    if (vim.visualBlock) {
56
      if (range.head.line != head.line) {
57
        return;
58
      }
59
    }
60
    if (range.from() == range.anchor && !range.empty()) {
61
      if (range.head.line == head.line && range.head.ch != head.ch)
62
        return new Pos(range.head.line, range.head.ch - 1);
63
    }
64

65
    return range.head;
66
  }
67

68
  var defaultKeymap = [
69
    // Key to key mapping. This goes first to make it possible to override
70
    // existing mappings.
71
    { keys: '<Left>', type: 'keyToKey', toKeys: 'h' },
72
    { keys: '<Right>', type: 'keyToKey', toKeys: 'l' },
73
    { keys: '<Up>', type: 'keyToKey', toKeys: 'k' },
74
    { keys: '<Down>', type: 'keyToKey', toKeys: 'j' },
75
    { keys: 'g<Up>', type: 'keyToKey', toKeys: 'gk' },
76
    { keys: 'g<Down>', type: 'keyToKey', toKeys: 'gj' },
77
    { keys: '<Space>', type: 'keyToKey', toKeys: 'l' },
78
    { keys: '<BS>', type: 'keyToKey', toKeys: 'h', context: 'normal'},
79
    { keys: '<Del>', type: 'keyToKey', toKeys: 'x', context: 'normal'},
80
    { keys: '<C-Space>', type: 'keyToKey', toKeys: 'W' },
81
    { keys: '<C-BS>', type: 'keyToKey', toKeys: 'B', context: 'normal' },
82
    { keys: '<S-Space>', type: 'keyToKey', toKeys: 'w' },
83
    { keys: '<S-BS>', type: 'keyToKey', toKeys: 'b', context: 'normal' },
84
    { keys: '<C-n>', type: 'keyToKey', toKeys: 'j' },
85
    { keys: '<C-p>', type: 'keyToKey', toKeys: 'k' },
86
    { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>' },
87
    { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>' },
88
    { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
89
    { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
90
    { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' },
91
    { keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual'},
92
    { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' },
93
    { keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' },
94
    { keys: '<Home>', type: 'keyToKey', toKeys: '0' },
95
    { keys: '<End>', type: 'keyToKey', toKeys: '$' },
96
    { keys: '<PageUp>', type: 'keyToKey', toKeys: '<C-b>' },
97
    { keys: '<PageDown>', type: 'keyToKey', toKeys: '<C-f>' },
98
    { keys: '<CR>', type: 'keyToKey', toKeys: 'j^', context: 'normal' },
99
    { keys: '<Ins>', type: 'keyToKey', toKeys: 'i', context: 'normal'},
100
    { keys: '<Ins>', type: 'action', action: 'toggleOverwrite', context: 'insert' },
101
    // Motions
102
    { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }},
103
    { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }},
104
    { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }},
105
    { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }},
106
    { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }},
107
    { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }},
108
    { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }},
109
    { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }},
110
    { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }},
111
    { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }},
112
    { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }},
113
    { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }},
114
    { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }},
115
    { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }},
116
    { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }},
117
    { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }},
118
    { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }},
119
    { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }},
120
    { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }},
121
    { keys: '(', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: false }},
122
    { keys: ')', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: true }},
123
    { keys: '<C-f>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }},
124
    { keys: '<C-b>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }},
125
    { keys: '<C-d>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }},
126
    { keys: '<C-u>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }},
127
    { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
128
    { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
129
    {keys: "g$", type: "motion", motion: "moveToEndOfDisplayLine"},
130
    {keys: "g^", type: "motion", motion: "moveToStartOfDisplayLine"},
131
    {keys: "g0", type: "motion", motion: "moveToStartOfDisplayLine"},
132
    { keys: '0', type: 'motion', motion: 'moveToStartOfLine' },
133
    { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' },
134
    { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }},
135
    { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }},
136
    { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
137
    { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }},
138
    { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }},
139
    { keys: 'f<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }},
140
    { keys: 'F<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }},
141
    { keys: 't<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }},
142
    { keys: 'T<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }},
143
    { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }},
144
    { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }},
145
    { keys: '\'<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}},
146
    { keys: '`<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}},
147
    { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
148
    { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
149
    { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
150
    { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
151
    // the next two aren't motions but must come before more general motion declarations
152
    { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}},
153
    { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}},
154
    { keys: ']<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}},
155
    { keys: '[<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}},
156
    { keys: '|', type: 'motion', motion: 'moveToColumn'},
157
    { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'},
158
    { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},
159
    // Operators
160
    { keys: 'd', type: 'operator', operator: 'delete' },
161
    { keys: 'y', type: 'operator', operator: 'yank' },
162
    { keys: 'c', type: 'operator', operator: 'change' },
163
    { keys: '=', type: 'operator', operator: 'indentAuto' },
164
    { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }},
165
    { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }},
166
    { keys: 'g~', type: 'operator', operator: 'changeCase' },
167
    { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true },
168
    { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true },
169
    { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }},
170
    { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }},
171
    { keys: 'gn', type: 'motion', motion: 'findAndSelectNextInclusive', motionArgs: { forward: true }},
172
    { keys: 'gN', type: 'motion', motion: 'findAndSelectNextInclusive', motionArgs: { forward: false }},
173
    // Operator-Motion dual commands
174
    { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }},
175
    { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }},
176
    { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
177
    { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'},
178
    { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'expandToLine', motionArgs: { linewise: true }, context: 'normal'},
179
    { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'},
180
    { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
181
    { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'},
182
    { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'},
183
    { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'},
184
    { keys: '<C-u>', type: 'operatorMotion', operator: 'delete', motion: 'moveToStartOfLine', context: 'insert' },
185
    { keys: '<C-w>', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' },
186
    //ignore C-w in normal mode
187
    { keys: '<C-w>', type: 'idle', context: 'normal' },
188
    // Actions
189
    { keys: '<C-i>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }},
190
    { keys: '<C-o>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }},
191
    { keys: '<C-e>', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }},
192
    { keys: '<C-y>', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }},
193
    { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' },
194
    { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' },
195
    { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
196
    { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' },
197
    { keys: 'gi', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'lastEdit' }, context: 'normal' },
198
    { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' },
199
    { keys: 'gI', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'bol'}, context: 'normal' },
200
    { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' },
201
    { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' },
202
    { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' },
203
    { keys: 'v', type: 'action', action: 'toggleVisualMode' },
204
    { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }},
205
    { keys: '<C-v>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
206
    { keys: '<C-q>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
207
    { keys: 'gv', type: 'action', action: 'reselectLastSelection' },
208
    { keys: 'J', type: 'action', action: 'joinLines', isEdit: true },
209
    { keys: 'gJ', type: 'action', action: 'joinLines', actionArgs: { keepSpaces: true }, isEdit: true },
210
    { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }},
211
    { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }},
212
    { keys: 'r<character>', type: 'action', action: 'replace', isEdit: true },
213
    { keys: '@<character>', type: 'action', action: 'replayMacro' },
214
    { keys: 'q<character>', type: 'action', action: 'enterMacroRecordMode' },
215
    // Handle Replace-mode as a special case of insert mode.
216
    { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }, context: 'normal'},
217
    { keys: 'R', type: 'operator', operator: 'change', operatorArgs: { linewise: true, fullLine: true }, context: 'visual', exitVisualBlock: true},
218
    { keys: 'u', type: 'action', action: 'undo', context: 'normal' },
219
    { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true },
220
    { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true },
221
    { keys: '<C-r>', type: 'action', action: 'redo' },
222
    { keys: 'm<character>', type: 'action', action: 'setMark' },
223
    { keys: '"<character>', type: 'action', action: 'setRegister' },
224
    { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},
225
    { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
226
    { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},
227
    { keys: 'z<CR>', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
228
    { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }},
229
    { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
230
    { keys: '.', type: 'action', action: 'repeatLastEdit' },
231
    { keys: '<C-a>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}},
232
    { keys: '<C-x>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}},
233
    { keys: '<C-t>', type: 'action', action: 'indent', actionArgs: { indentRight: true }, context: 'insert' },
234
    { keys: '<C-d>', type: 'action', action: 'indent', actionArgs: { indentRight: false }, context: 'insert' },
235
    // Text object motions
236
    { keys: 'a<character>', type: 'motion', motion: 'textObjectManipulation' },
237
    { keys: 'i<character>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
238
    // Search
239
    { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
240
    { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
241
    { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
242
    { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
243
    { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
244
    { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
245
    // Ex command
246
    { keys: ':', type: 'ex' }
247
  ];
248
  var defaultKeymapLength = defaultKeymap.length;
249

250
  /**
251
   * Ex commands
252
   * Care must be taken when adding to the default Ex command map. For any
253
   * pair of commands that have a shared prefix, at least one of their
254
   * shortNames must not match the prefix of the other command.
255
   */
256
  var defaultExCommandMap = [
257
    { name: 'colorscheme', shortName: 'colo' },
258
    { name: 'map' },
259
    { name: 'imap', shortName: 'im' },
260
    { name: 'nmap', shortName: 'nm' },
261
    { name: 'vmap', shortName: 'vm' },
262
    { name: 'unmap' },
263
    { name: 'write', shortName: 'w' },
264
    { name: 'undo', shortName: 'u' },
265
    { name: 'redo', shortName: 'red' },
266
    { name: 'set', shortName: 'se' },
267
    { name: 'setlocal', shortName: 'setl' },
268
    { name: 'setglobal', shortName: 'setg' },
269
    { name: 'sort', shortName: 'sor' },
270
    { name: 'substitute', shortName: 's', possiblyAsync: true },
271
    { name: 'nohlsearch', shortName: 'noh' },
272
    { name: 'yank', shortName: 'y' },
273
    { name: 'delmarks', shortName: 'delm' },
274
    { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true },
275
    { name: 'vglobal', shortName: 'v' },
276
    { name: 'global', shortName: 'g' }
277
  ];
278

279
  var Vim = function() {
280
    function enterVimMode(cm) {
281
      cm.setOption('disableInput', true);
282
      cm.setOption('showCursorWhenSelecting', false);
283
      CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
284
      cm.on('cursorActivity', onCursorActivity);
285
      maybeInitVimState(cm);
286
      CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
287
    }
288

289
    function leaveVimMode(cm) {
290
      cm.setOption('disableInput', false);
291
      cm.off('cursorActivity', onCursorActivity);
292
      CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
293
      cm.state.vim = null;
294
      if (highlightTimeout) clearTimeout(highlightTimeout);
295
    }
296

297
    function detachVimMap(cm, next) {
298
      if (this == CodeMirror.keyMap.vim) {
299
        cm.options.$customCursor = null;
300
        CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor");
301
      }
302

303
      if (!next || next.attach != attachVimMap)
304
        leaveVimMode(cm);
305
    }
306
    function attachVimMap(cm, prev) {
307
      if (this == CodeMirror.keyMap.vim) {
308
        if (cm.curOp) cm.curOp.selectionChanged = true;
309
        cm.options.$customCursor = transformCursor;
310
        CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor");
311
      }
312

313
      if (!prev || prev.attach != attachVimMap)
314
        enterVimMode(cm);
315
    }
316

317
    // Deprecated, simply setting the keymap works again.
318
    CodeMirror.defineOption('vimMode', false, function(cm, val, prev) {
319
      if (val && cm.getOption("keyMap") != "vim")
320
        cm.setOption("keyMap", "vim");
321
      else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap")))
322
        cm.setOption("keyMap", "default");
323
    });
324

325
    function cmKey(key, cm) {
326
      if (!cm) { return undefined; }
327
      if (this[key]) { return this[key]; }
328
      var vimKey = cmKeyToVimKey(key);
329
      if (!vimKey) {
330
        return false;
331
      }
332
      var cmd = vimApi.findKey(cm, vimKey);
333
      if (typeof cmd == 'function') {
334
        CodeMirror.signal(cm, 'vim-keypress', vimKey);
335
      }
336
      return cmd;
337
    }
338

339
    var modifiers = {Shift:'S',Ctrl:'C',Alt:'A',Cmd:'D',Mod:'A',CapsLock:''};
340
    var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del',Insert:'Ins'};
341
    function cmKeyToVimKey(key) {
342
      if (key.charAt(0) == '\'') {
343
        // Keypress character binding of format "'a'"
344
        return key.charAt(1);
345
      }
346
      var pieces = key.split(/-(?!$)/);
347
      var lastPiece = pieces[pieces.length - 1];
348
      if (pieces.length == 1 && pieces[0].length == 1) {
349
        // No-modifier bindings use literal character bindings above. Skip.
350
        return false;
351
      } else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) {
352
        // Ignore Shift+char bindings as they should be handled by literal character.
353
        return false;
354
      }
355
      var hasCharacter = false;
356
      for (var i = 0; i < pieces.length; i++) {
357
        var piece = pieces[i];
358
        if (piece in modifiers) { pieces[i] = modifiers[piece]; }
359
        else { hasCharacter = true; }
360
        if (piece in specialKeys) { pieces[i] = specialKeys[piece]; }
361
      }
362
      if (!hasCharacter) {
363
        // Vim does not support modifier only keys.
364
        return false;
365
      }
366
      // TODO: Current bindings expect the character to be lower case, but
367
      // it looks like vim key notation uses upper case.
368
      if (isUpperCase(lastPiece)) {
369
        pieces[pieces.length - 1] = lastPiece.toLowerCase();
370
      }
371
      return '<' + pieces.join('-') + '>';
372
    }
373

374
    function getOnPasteFn(cm) {
375
      var vim = cm.state.vim;
376
      if (!vim.onPasteFn) {
377
        vim.onPasteFn = function() {
378
          if (!vim.insertMode) {
379
            cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
380
            actions.enterInsertMode(cm, {}, vim);
381
          }
382
        };
383
      }
384
      return vim.onPasteFn;
385
    }
386

387
    var numberRegex = /[\d]/;
388
    var wordCharTest = [CodeMirror.isWordChar, function(ch) {
389
      return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch);
390
    }], bigWordCharTest = [function(ch) {
391
      return /\S/.test(ch);
392
    }];
393
    function makeKeyRange(start, size) {
394
      var keys = [];
395
      for (var i = start; i < start + size; i++) {
396
        keys.push(String.fromCharCode(i));
397
      }
398
      return keys;
399
    }
400
    var upperCaseAlphabet = makeKeyRange(65, 26);
401
    var lowerCaseAlphabet = makeKeyRange(97, 26);
402
    var numbers = makeKeyRange(48, 10);
403
    var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
404
    var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '_', '/']);
405
    var upperCaseChars;
406
    try { upperCaseChars = new RegExp("^[\\p{Lu}]$", "u"); }
407
    catch (_) { upperCaseChars = /^[A-Z]$/; }
408

409
    function isLine(cm, line) {
410
      return line >= cm.firstLine() && line <= cm.lastLine();
411
    }
412
    function isLowerCase(k) {
413
      return (/^[a-z]$/).test(k);
414
    }
415
    function isMatchableSymbol(k) {
416
      return '()[]{}'.indexOf(k) != -1;
417
    }
418
    function isNumber(k) {
419
      return numberRegex.test(k);
420
    }
421
    function isUpperCase(k) {
422
      return upperCaseChars.test(k);
423
    }
424
    function isWhiteSpaceString(k) {
425
      return (/^\s*$/).test(k);
426
    }
427
    function isEndOfSentenceSymbol(k) {
428
      return '.?!'.indexOf(k) != -1;
429
    }
430
    function inArray(val, arr) {
431
      for (var i = 0; i < arr.length; i++) {
432
        if (arr[i] == val) {
433
          return true;
434
        }
435
      }
436
      return false;
437
    }
438

439
    var options = {};
440
    function defineOption(name, defaultValue, type, aliases, callback) {
441
      if (defaultValue === undefined && !callback) {
442
        throw Error('defaultValue is required unless callback is provided');
443
      }
444
      if (!type) { type = 'string'; }
445
      options[name] = {
446
        type: type,
447
        defaultValue: defaultValue,
448
        callback: callback
449
      };
450
      if (aliases) {
451
        for (var i = 0; i < aliases.length; i++) {
452
          options[aliases[i]] = options[name];
453
        }
454
      }
455
      if (defaultValue) {
456
        setOption(name, defaultValue);
457
      }
458
    }
459

460
    function setOption(name, value, cm, cfg) {
461
      var option = options[name];
462
      cfg = cfg || {};
463
      var scope = cfg.scope;
464
      if (!option) {
465
        return new Error('Unknown option: ' + name);
466
      }
467
      if (option.type == 'boolean') {
468
        if (value && value !== true) {
469
          return new Error('Invalid argument: ' + name + '=' + value);
470
        } else if (value !== false) {
471
          // Boolean options are set to true if value is not defined.
472
          value = true;
473
        }
474
      }
475
      if (option.callback) {
476
        if (scope !== 'local') {
477
          option.callback(value, undefined);
478
        }
479
        if (scope !== 'global' && cm) {
480
          option.callback(value, cm);
481
        }
482
      } else {
483
        if (scope !== 'local') {
484
          option.value = option.type == 'boolean' ? !!value : value;
485
        }
486
        if (scope !== 'global' && cm) {
487
          cm.state.vim.options[name] = {value: value};
488
        }
489
      }
490
    }
491

492
    function getOption(name, cm, cfg) {
493
      var option = options[name];
494
      cfg = cfg || {};
495
      var scope = cfg.scope;
496
      if (!option) {
497
        return new Error('Unknown option: ' + name);
498
      }
499
      if (option.callback) {
500
        var local = cm && option.callback(undefined, cm);
501
        if (scope !== 'global' && local !== undefined) {
502
          return local;
503
        }
504
        if (scope !== 'local') {
505
          return option.callback();
506
        }
507
        return;
508
      } else {
509
        var local = (scope !== 'global') && (cm && cm.state.vim.options[name]);
510
        return (local || (scope !== 'local') && option || {}).value;
511
      }
512
    }
513

514
    defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) {
515
      // Option is local. Do nothing for global.
516
      if (cm === undefined) {
517
        return;
518
      }
519
      // The 'filetype' option proxies to the CodeMirror 'mode' option.
520
      if (name === undefined) {
521
        var mode = cm.getOption('mode');
522
        return mode == 'null' ? '' : mode;
523
      } else {
524
        var mode = name == '' ? 'null' : name;
525
        cm.setOption('mode', mode);
526
      }
527
    });
528

529
    var createCircularJumpList = function() {
530
      var size = 100;
531
      var pointer = -1;
532
      var head = 0;
533
      var tail = 0;
534
      var buffer = new Array(size);
535
      function add(cm, oldCur, newCur) {
536
        var current = pointer % size;
537
        var curMark = buffer[current];
538
        function useNextSlot(cursor) {
539
          var next = ++pointer % size;
540
          var trashMark = buffer[next];
541
          if (trashMark) {
542
            trashMark.clear();
543
          }
544
          buffer[next] = cm.setBookmark(cursor);
545
        }
546
        if (curMark) {
547
          var markPos = curMark.find();
548
          // avoid recording redundant cursor position
549
          if (markPos && !cursorEqual(markPos, oldCur)) {
550
            useNextSlot(oldCur);
551
          }
552
        } else {
553
          useNextSlot(oldCur);
554
        }
555
        useNextSlot(newCur);
556
        head = pointer;
557
        tail = pointer - size + 1;
558
        if (tail < 0) {
559
          tail = 0;
560
        }
561
      }
562
      function move(cm, offset) {
563
        pointer += offset;
564
        if (pointer > head) {
565
          pointer = head;
566
        } else if (pointer < tail) {
567
          pointer = tail;
568
        }
569
        var mark = buffer[(size + pointer) % size];
570
        // skip marks that are temporarily removed from text buffer
571
        if (mark && !mark.find()) {
572
          var inc = offset > 0 ? 1 : -1;
573
          var newCur;
574
          var oldCur = cm.getCursor();
575
          do {
576
            pointer += inc;
577
            mark = buffer[(size + pointer) % size];
578
            // skip marks that are the same as current position
579
            if (mark &&
580
                (newCur = mark.find()) &&
581
                !cursorEqual(oldCur, newCur)) {
582
              break;
583
            }
584
          } while (pointer < head && pointer > tail);
585
        }
586
        return mark;
587
      }
588
      function find(cm, offset) {
589
        var oldPointer = pointer;
590
        var mark = move(cm, offset);
591
        pointer = oldPointer;
592
        return mark && mark.find();
593
      }
594
      return {
595
        cachedCursor: undefined, //used for # and * jumps
596
        add: add,
597
        find: find,
598
        move: move
599
      };
600
    };
601

602
    // Returns an object to track the changes associated insert mode.  It
603
    // clones the object that is passed in, or creates an empty object one if
604
    // none is provided.
605
    var createInsertModeChanges = function(c) {
606
      if (c) {
607
        // Copy construction
608
        return {
609
          changes: c.changes,
610
          expectCursorActivityForChange: c.expectCursorActivityForChange
611
        };
612
      }
613
      return {
614
        // Change list
615
        changes: [],
616
        // Set to true on change, false on cursorActivity.
617
        expectCursorActivityForChange: false
618
      };
619
    };
620

621
    function MacroModeState() {
622
      this.latestRegister = undefined;
623
      this.isPlaying = false;
624
      this.isRecording = false;
625
      this.replaySearchQueries = [];
626
      this.onRecordingDone = undefined;
627
      this.lastInsertModeChanges = createInsertModeChanges();
628
    }
629
    MacroModeState.prototype = {
630
      exitMacroRecordMode: function() {
631
        var macroModeState = vimGlobalState.macroModeState;
632
        if (macroModeState.onRecordingDone) {
633
          macroModeState.onRecordingDone(); // close dialog
634
        }
635
        macroModeState.onRecordingDone = undefined;
636
        macroModeState.isRecording = false;
637
      },
638
      enterMacroRecordMode: function(cm, registerName) {
639
        var register =
640
            vimGlobalState.registerController.getRegister(registerName);
641
        if (register) {
642
          register.clear();
643
          this.latestRegister = registerName;
644
          if (cm.openDialog) {
645
            this.onRecordingDone = cm.openDialog(
646
                document.createTextNode('(recording)['+registerName+']'), null, {bottom:true});
647
          }
648
          this.isRecording = true;
649
        }
650
      }
651
    };
652

653
    function maybeInitVimState(cm) {
654
      if (!cm.state.vim) {
655
        // Store instance state in the CodeMirror object.
656
        cm.state.vim = {
657
          inputState: new InputState(),
658
          // Vim's input state that triggered the last edit, used to repeat
659
          // motions and operators with '.'.
660
          lastEditInputState: undefined,
661
          // Vim's action command before the last edit, used to repeat actions
662
          // with '.' and insert mode repeat.
663
          lastEditActionCommand: undefined,
664
          // When using jk for navigation, if you move from a longer line to a
665
          // shorter line, the cursor may clip to the end of the shorter line.
666
          // If j is pressed again and cursor goes to the next line, the
667
          // cursor should go back to its horizontal position on the longer
668
          // line if it can. This is to keep track of the horizontal position.
669
          lastHPos: -1,
670
          // Doing the same with screen-position for gj/gk
671
          lastHSPos: -1,
672
          // The last motion command run. Cleared if a non-motion command gets
673
          // executed in between.
674
          lastMotion: null,
675
          marks: {},
676
          insertMode: false,
677
          // Repeat count for changes made in insert mode, triggered by key
678
          // sequences like 3,i. Only exists when insertMode is true.
679
          insertModeRepeat: undefined,
680
          visualMode: false,
681
          // If we are in visual line mode. No effect if visualMode is false.
682
          visualLine: false,
683
          visualBlock: false,
684
          lastSelection: null,
685
          lastPastedText: null,
686
          sel: {},
687
          // Buffer-local/window-local values of vim options.
688
          options: {}
689
        };
690
      }
691
      return cm.state.vim;
692
    }
693
    var vimGlobalState;
694
    function resetVimGlobalState() {
695
      vimGlobalState = {
696
        // The current search query.
697
        searchQuery: null,
698
        // Whether we are searching backwards.
699
        searchIsReversed: false,
700
        // Replace part of the last substituted pattern
701
        lastSubstituteReplacePart: undefined,
702
        jumpList: createCircularJumpList(),
703
        macroModeState: new MacroModeState,
704
        // Recording latest f, t, F or T motion command.
705
        lastCharacterSearch: {increment:0, forward:true, selectedCharacter:''},
706
        registerController: new RegisterController({}),
707
        // search history buffer
708
        searchHistoryController: new HistoryController(),
709
        // ex Command history buffer
710
        exCommandHistoryController : new HistoryController()
711
      };
712
      for (var optionName in options) {
713
        var option = options[optionName];
714
        option.value = option.defaultValue;
715
      }
716
    }
717

718
    var lastInsertModeKeyTimer;
719
    var vimApi= {
720
      buildKeyMap: function() {
721
        // TODO: Convert keymap into dictionary format for fast lookup.
722
      },
723
      // Testing hook, though it might be useful to expose the register
724
      // controller anyway.
725
      getRegisterController: function() {
726
        return vimGlobalState.registerController;
727
      },
728
      // Testing hook.
729
      resetVimGlobalState_: resetVimGlobalState,
730

731
      // Testing hook.
732
      getVimGlobalState_: function() {
733
        return vimGlobalState;
734
      },
735

736
      // Testing hook.
737
      maybeInitVimState_: maybeInitVimState,
738

739
      suppressErrorLogging: false,
740

741
      InsertModeKey: InsertModeKey,
742
      map: function(lhs, rhs, ctx) {
743
        // Add user defined key bindings.
744
        exCommandDispatcher.map(lhs, rhs, ctx);
745
      },
746
      unmap: function(lhs, ctx) {
747
        return exCommandDispatcher.unmap(lhs, ctx);
748
      },
749
      // Non-recursive map function.
750
      // NOTE: This will not create mappings to key maps that aren't present
751
      // in the default key map. See TODO at bottom of function.
752
      noremap: function(lhs, rhs, ctx) {
753
        function toCtxArray(ctx) {
754
          return ctx ? [ctx] : ['normal', 'insert', 'visual'];
755
        }
756
        var ctxsToMap = toCtxArray(ctx);
757
        // Look through all actual defaults to find a map candidate.
758
        var actualLength = defaultKeymap.length, origLength = defaultKeymapLength;
759
        for (var i = actualLength - origLength;
760
             i < actualLength && ctxsToMap.length;
761
             i++) {
762
          var mapping = defaultKeymap[i];
763
          // Omit mappings that operate in the wrong context(s) and those of invalid type.
764
          if (mapping.keys == rhs &&
765
              (!ctx || !mapping.context || mapping.context === ctx) &&
766
              mapping.type.substr(0, 2) !== 'ex' &&
767
              mapping.type.substr(0, 3) !== 'key') {
768
            // Make a shallow copy of the original keymap entry.
769
            var newMapping = {};
770
            for (var key in mapping) {
771
              newMapping[key] = mapping[key];
772
            }
773
            // Modify it point to the new mapping with the proper context.
774
            newMapping.keys = lhs;
775
            if (ctx && !newMapping.context) {
776
              newMapping.context = ctx;
777
            }
778
            // Add it to the keymap with a higher priority than the original.
779
            this._mapCommand(newMapping);
780
            // Record the mapped contexts as complete.
781
            var mappedCtxs = toCtxArray(mapping.context);
782
            ctxsToMap = ctxsToMap.filter(function(el) { return mappedCtxs.indexOf(el) === -1; });
783
          }
784
        }
785
        // TODO: Create non-recursive keyToKey mappings for the unmapped contexts once those exist.
786
      },
787
      // Remove all user-defined mappings for the provided context.
788
      mapclear: function(ctx) {
789
        // Partition the existing keymap into user-defined and true defaults.
790
        var actualLength = defaultKeymap.length,
791
            origLength = defaultKeymapLength;
792
        var userKeymap = defaultKeymap.slice(0, actualLength - origLength);
793
        defaultKeymap = defaultKeymap.slice(actualLength - origLength);
794
        if (ctx) {
795
          // If a specific context is being cleared, we need to keep mappings
796
          // from all other contexts.
797
          for (var i = userKeymap.length - 1; i >= 0; i--) {
798
            var mapping = userKeymap[i];
799
            if (ctx !== mapping.context) {
800
              if (mapping.context) {
801
                this._mapCommand(mapping);
802
              } else {
803
                // `mapping` applies to all contexts so create keymap copies
804
                // for each context except the one being cleared.
805
                var contexts = ['normal', 'insert', 'visual'];
806
                for (var j in contexts) {
807
                  if (contexts[j] !== ctx) {
808
                    var newMapping = {};
809
                    for (var key in mapping) {
810
                      newMapping[key] = mapping[key];
811
                    }
812
                    newMapping.context = contexts[j];
813
                    this._mapCommand(newMapping);
814
                  }
815
                }
816
              }
817
            }
818
          }
819
        }
820
      },
821
      // TODO: Expose setOption and getOption as instance methods. Need to decide how to namespace
822
      // them, or somehow make them work with the existing CodeMirror setOption/getOption API.
823
      setOption: setOption,
824
      getOption: getOption,
825
      defineOption: defineOption,
826
      defineEx: function(name, prefix, func){
827
        if (!prefix) {
828
          prefix = name;
829
        } else if (name.indexOf(prefix) !== 0) {
830
          throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
831
        }
832
        exCommands[name]=func;
833
        exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
834
      },
835
      handleKey: function (cm, key, origin) {
836
        var command = this.findKey(cm, key, origin);
837
        if (typeof command === 'function') {
838
          return command();
839
        }
840
      },
841
      /**
842
       * This is the outermost function called by CodeMirror, after keys have
843
       * been mapped to their Vim equivalents.
844
       *
845
       * Finds a command based on the key (and cached keys if there is a
846
       * multi-key sequence). Returns `undefined` if no key is matched, a noop
847
       * function if a partial match is found (multi-key), and a function to
848
       * execute the bound command if a a key is matched. The function always
849
       * returns true.
850
       */
851
      findKey: function(cm, key, origin) {
852
        var vim = maybeInitVimState(cm);
853
        function handleMacroRecording() {
854
          var macroModeState = vimGlobalState.macroModeState;
855
          if (macroModeState.isRecording) {
856
            if (key == 'q') {
857
              macroModeState.exitMacroRecordMode();
858
              clearInputState(cm);
859
              return true;
860
            }
861
            if (origin != 'mapping') {
862
              logKey(macroModeState, key);
863
            }
864
          }
865
        }
866
        function handleEsc() {
867
          if (key == '<Esc>') {
868
            // Clear input state and get back to normal mode.
869
            clearInputState(cm);
870
            if (vim.visualMode) {
871
              exitVisualMode(cm);
872
            } else if (vim.insertMode) {
873
              exitInsertMode(cm);
874
            }
875
            return true;
876
          }
877
        }
878
        function doKeyToKey(keys) {
879
          // TODO: prevent infinite recursion.
880
          var match;
881
          while (keys) {
882
            // Pull off one command key, which is either a single character
883
            // or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
884
            match = (/<\w+-.+?>|<\w+>|./).exec(keys);
885
            key = match[0];
886
            keys = keys.substring(match.index + key.length);
887
            vimApi.handleKey(cm, key, 'mapping');
888
          }
889
        }
890

891
        function handleKeyInsertMode() {
892
          if (handleEsc()) { return true; }
893
          var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
894
          var keysAreChars = key.length == 1;
895
          var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
896
          // Need to check all key substrings in insert mode.
897
          while (keys.length > 1 && match.type != 'full') {
898
            var keys = vim.inputState.keyBuffer = keys.slice(1);
899
            var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
900
            if (thisMatch.type != 'none') { match = thisMatch; }
901
          }
902
          if (match.type == 'none') { clearInputState(cm); return false; }
903
          else if (match.type == 'partial') {
904
            if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
905
            lastInsertModeKeyTimer = window.setTimeout(
906
              function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } },
907
              getOption('insertModeEscKeysTimeout'));
908
            return !keysAreChars;
909
          }
910

911
          if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
912
          if (keysAreChars) {
913
            var selections = cm.listSelections();
914
            for (var i = 0; i < selections.length; i++) {
915
              var here = selections[i].head;
916
              cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input');
917
            }
918
            vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop();
919
          }
920
          clearInputState(cm);
921
          return match.command;
922
        }
923

924
        function handleKeyNonInsertMode() {
925
          if (handleMacroRecording() || handleEsc()) { return true; }
926

927
          var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
928
          if (/^[1-9]\d*$/.test(keys)) { return true; }
929

930
          var keysMatcher = /^(\d*)(.*)$/.exec(keys);
931
          if (!keysMatcher) { clearInputState(cm); return false; }
932
          var context = vim.visualMode ? 'visual' :
933
                                         'normal';
934
          var mainKey = keysMatcher[2] || keysMatcher[1];
935
          if (vim.inputState.operatorShortcut && vim.inputState.operatorShortcut.slice(-1) == mainKey) {
936
            // multikey operators act linewise by repeating only the last character
937
            mainKey = vim.inputState.operatorShortcut;
938
          }
939
          var match = commandDispatcher.matchCommand(mainKey, defaultKeymap, vim.inputState, context);
940
          if (match.type == 'none') { clearInputState(cm); return false; }
941
          else if (match.type == 'partial') { return true; }
942

943
          vim.inputState.keyBuffer = '';
944
          var keysMatcher = /^(\d*)(.*)$/.exec(keys);
945
          if (keysMatcher[1] && keysMatcher[1] != '0') {
946
            vim.inputState.pushRepeatDigit(keysMatcher[1]);
947
          }
948
          return match.command;
949
        }
950

951
        var command;
952
        if (vim.insertMode) { command = handleKeyInsertMode(); }
953
        else { command = handleKeyNonInsertMode(); }
954
        if (command === false) {
955
          return !vim.insertMode && key.length === 1 ? function() { return true; } : undefined;
956
        } else if (command === true) {
957
          // TODO: Look into using CodeMirror's multi-key handling.
958
          // Return no-op since we are caching the key. Counts as handled, but
959
          // don't want act on it just yet.
960
          return function() { return true; };
961
        } else {
962
          return function() {
963
            return cm.operation(function() {
964
              cm.curOp.isVimOp = true;
965
              try {
966
                if (command.type == 'keyToKey') {
967
                  doKeyToKey(command.toKeys);
968
                } else {
969
                  commandDispatcher.processCommand(cm, vim, command);
970
                }
971
              } catch (e) {
972
                // clear VIM state in case it's in a bad state.
973
                cm.state.vim = undefined;
974
                maybeInitVimState(cm);
975
                if (!vimApi.suppressErrorLogging) {
976
                  console['log'](e);
977
                }
978
                throw e;
979
              }
980
              return true;
981
            });
982
          };
983
        }
984
      },
985
      handleEx: function(cm, input) {
986
        exCommandDispatcher.processCommand(cm, input);
987
      },
988

989
      defineMotion: defineMotion,
990
      defineAction: defineAction,
991
      defineOperator: defineOperator,
992
      mapCommand: mapCommand,
993
      _mapCommand: _mapCommand,
994

995
      defineRegister: defineRegister,
996

997
      exitVisualMode: exitVisualMode,
998
      exitInsertMode: exitInsertMode
999
    };
1000

1001
    // Represents the current input state.
1002
    function InputState() {
1003
      this.prefixRepeat = [];
1004
      this.motionRepeat = [];
1005

1006
      this.operator = null;
1007
      this.operatorArgs = null;
1008
      this.motion = null;
1009
      this.motionArgs = null;
1010
      this.keyBuffer = []; // For matching multi-key commands.
1011
      this.registerName = null; // Defaults to the unnamed register.
1012
    }
1013
    InputState.prototype.pushRepeatDigit = function(n) {
1014
      if (!this.operator) {
1015
        this.prefixRepeat = this.prefixRepeat.concat(n);
1016
      } else {
1017
        this.motionRepeat = this.motionRepeat.concat(n);
1018
      }
1019
    };
1020
    InputState.prototype.getRepeat = function() {
1021
      var repeat = 0;
1022
      if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
1023
        repeat = 1;
1024
        if (this.prefixRepeat.length > 0) {
1025
          repeat *= parseInt(this.prefixRepeat.join(''), 10);
1026
        }
1027
        if (this.motionRepeat.length > 0) {
1028
          repeat *= parseInt(this.motionRepeat.join(''), 10);
1029
        }
1030
      }
1031
      return repeat;
1032
    };
1033

1034
    function clearInputState(cm, reason) {
1035
      cm.state.vim.inputState = new InputState();
1036
      CodeMirror.signal(cm, 'vim-command-done', reason);
1037
    }
1038

1039
    /*
1040
     * Register stores information about copy and paste registers.  Besides
1041
     * text, a register must store whether it is linewise (i.e., when it is
1042
     * pasted, should it insert itself into a new line, or should the text be
1043
     * inserted at the cursor position.)
1044
     */
1045
    function Register(text, linewise, blockwise) {
1046
      this.clear();
1047
      this.keyBuffer = [text || ''];
1048
      this.insertModeChanges = [];
1049
      this.searchQueries = [];
1050
      this.linewise = !!linewise;
1051
      this.blockwise = !!blockwise;
1052
    }
1053
    Register.prototype = {
1054
      setText: function(text, linewise, blockwise) {
1055
        this.keyBuffer = [text || ''];
1056
        this.linewise = !!linewise;
1057
        this.blockwise = !!blockwise;
1058
      },
1059
      pushText: function(text, linewise) {
1060
        // if this register has ever been set to linewise, use linewise.
1061
        if (linewise) {
1062
          if (!this.linewise) {
1063
            this.keyBuffer.push('\n');
1064
          }
1065
          this.linewise = true;
1066
        }
1067
        this.keyBuffer.push(text);
1068
      },
1069
      pushInsertModeChanges: function(changes) {
1070
        this.insertModeChanges.push(createInsertModeChanges(changes));
1071
      },
1072
      pushSearchQuery: function(query) {
1073
        this.searchQueries.push(query);
1074
      },
1075
      clear: function() {
1076
        this.keyBuffer = [];
1077
        this.insertModeChanges = [];
1078
        this.searchQueries = [];
1079
        this.linewise = false;
1080
      },
1081
      toString: function() {
1082
        return this.keyBuffer.join('');
1083
      }
1084
    };
1085

1086
    /**
1087
     * Defines an external register.
1088
     *
1089
     * The name should be a single character that will be used to reference the register.
1090
     * The register should support setText, pushText, clear, and toString(). See Register
1091
     * for a reference implementation.
1092
     */
1093
    function defineRegister(name, register) {
1094
      var registers = vimGlobalState.registerController.registers;
1095
      if (!name || name.length != 1) {
1096
        throw Error('Register name must be 1 character');
1097
      }
1098
      if (registers[name]) {
1099
        throw Error('Register already defined ' + name);
1100
      }
1101
      registers[name] = register;
1102
      validRegisters.push(name);
1103
    }
1104

1105
    /*
1106
     * vim registers allow you to keep many independent copy and paste buffers.
1107
     * See http://usevim.com/2012/04/13/registers/ for an introduction.
1108
     *
1109
     * RegisterController keeps the state of all the registers.  An initial
1110
     * state may be passed in.  The unnamed register '"' will always be
1111
     * overridden.
1112
     */
1113
    function RegisterController(registers) {
1114
      this.registers = registers;
1115
      this.unnamedRegister = registers['"'] = new Register();
1116
      registers['.'] = new Register();
1117
      registers[':'] = new Register();
1118
      registers['/'] = new Register();
1119
    }
1120
    RegisterController.prototype = {
1121
      pushText: function(registerName, operator, text, linewise, blockwise) {
1122
        // The black hole register, "_, means delete/yank to nowhere.
1123
        if (registerName === '_') return;
1124
        if (linewise && text.charAt(text.length - 1) !== '\n'){
1125
          text += '\n';
1126
        }
1127
        // Lowercase and uppercase registers refer to the same register.
1128
        // Uppercase just means append.
1129
        var register = this.isValidRegister(registerName) ?
1130
            this.getRegister(registerName) : null;
1131
        // if no register/an invalid register was specified, things go to the
1132
        // default registers
1133
        if (!register) {
1134
          switch (operator) {
1135
            case 'yank':
1136
              // The 0 register contains the text from the most recent yank.
1137
              this.registers['0'] = new Register(text, linewise, blockwise);
1138
              break;
1139
            case 'delete':
1140
            case 'change':
1141
              if (text.indexOf('\n') == -1) {
1142
                // Delete less than 1 line. Update the small delete register.
1143
                this.registers['-'] = new Register(text, linewise);
1144
              } else {
1145
                // Shift down the contents of the numbered registers and put the
1146
                // deleted text into register 1.
1147
                this.shiftNumericRegisters_();
1148
                this.registers['1'] = new Register(text, linewise);
1149
              }
1150
              break;
1151
          }
1152
          // Make sure the unnamed register is set to what just happened
1153
          this.unnamedRegister.setText(text, linewise, blockwise);
1154
          return;
1155
        }
1156

1157
        // If we've gotten to this point, we've actually specified a register
1158
        var append = isUpperCase(registerName);
1159
        if (append) {
1160
          register.pushText(text, linewise);
1161
        } else {
1162
          register.setText(text, linewise, blockwise);
1163
        }
1164
        // The unnamed register always has the same value as the last used
1165
        // register.
1166
        this.unnamedRegister.setText(register.toString(), linewise);
1167
      },
1168
      // Gets the register named @name.  If one of @name doesn't already exist,
1169
      // create it.  If @name is invalid, return the unnamedRegister.
1170
      getRegister: function(name) {
1171
        if (!this.isValidRegister(name)) {
1172
          return this.unnamedRegister;
1173
        }
1174
        name = name.toLowerCase();
1175
        if (!this.registers[name]) {
1176
          this.registers[name] = new Register();
1177
        }
1178
        return this.registers[name];
1179
      },
1180
      isValidRegister: function(name) {
1181
        return name && inArray(name, validRegisters);
1182
      },
1183
      shiftNumericRegisters_: function() {
1184
        for (var i = 9; i >= 2; i--) {
1185
          this.registers[i] = this.getRegister('' + (i - 1));
1186
        }
1187
      }
1188
    };
1189
    function HistoryController() {
1190
        this.historyBuffer = [];
1191
        this.iterator = 0;
1192
        this.initialPrefix = null;
1193
    }
1194
    HistoryController.prototype = {
1195
      // the input argument here acts a user entered prefix for a small time
1196
      // until we start autocompletion in which case it is the autocompleted.
1197
      nextMatch: function (input, up) {
1198
        var historyBuffer = this.historyBuffer;
1199
        var dir = up ? -1 : 1;
1200
        if (this.initialPrefix === null) this.initialPrefix = input;
1201
        for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) {
1202
          var element = historyBuffer[i];
1203
          for (var j = 0; j <= element.length; j++) {
1204
            if (this.initialPrefix == element.substring(0, j)) {
1205
              this.iterator = i;
1206
              return element;
1207
            }
1208
          }
1209
        }
1210
        // should return the user input in case we reach the end of buffer.
1211
        if (i >= historyBuffer.length) {
1212
          this.iterator = historyBuffer.length;
1213
          return this.initialPrefix;
1214
        }
1215
        // return the last autocompleted query or exCommand as it is.
1216
        if (i < 0 ) return input;
1217
      },
1218
      pushInput: function(input) {
1219
        var index = this.historyBuffer.indexOf(input);
1220
        if (index > -1) this.historyBuffer.splice(index, 1);
1221
        if (input.length) this.historyBuffer.push(input);
1222
      },
1223
      reset: function() {
1224
        this.initialPrefix = null;
1225
        this.iterator = this.historyBuffer.length;
1226
      }
1227
    };
1228
    var commandDispatcher = {
1229
      matchCommand: function(keys, keyMap, inputState, context) {
1230
        var matches = commandMatches(keys, keyMap, context, inputState);
1231
        if (!matches.full && !matches.partial) {
1232
          return {type: 'none'};
1233
        } else if (!matches.full && matches.partial) {
1234
          return {type: 'partial'};
1235
        }
1236

1237
        var bestMatch;
1238
        for (var i = 0; i < matches.full.length; i++) {
1239
          var match = matches.full[i];
1240
          if (!bestMatch) {
1241
            bestMatch = match;
1242
          }
1243
        }
1244
        if (bestMatch.keys.slice(-11) == '<character>') {
1245
          var character = lastChar(keys);
1246
          if (!character) return {type: 'none'};
1247
          inputState.selectedCharacter = character;
1248
        }
1249
        return {type: 'full', command: bestMatch};
1250
      },
1251
      processCommand: function(cm, vim, command) {
1252
        vim.inputState.repeatOverride = command.repeatOverride;
1253
        switch (command.type) {
1254
          case 'motion':
1255
            this.processMotion(cm, vim, command);
1256
            break;
1257
          case 'operator':
1258
            this.processOperator(cm, vim, command);
1259
            break;
1260
          case 'operatorMotion':
1261
            this.processOperatorMotion(cm, vim, command);
1262
            break;
1263
          case 'action':
1264
            this.processAction(cm, vim, command);
1265
            break;
1266
          case 'search':
1267
            this.processSearch(cm, vim, command);
1268
            break;
1269
          case 'ex':
1270
          case 'keyToEx':
1271
            this.processEx(cm, vim, command);
1272
            break;
1273
          default:
1274
            break;
1275
        }
1276
      },
1277
      processMotion: function(cm, vim, command) {
1278
        vim.inputState.motion = command.motion;
1279
        vim.inputState.motionArgs = copyArgs(command.motionArgs);
1280
        this.evalInput(cm, vim);
1281
      },
1282
      processOperator: function(cm, vim, command) {
1283
        var inputState = vim.inputState;
1284
        if (inputState.operator) {
1285
          if (inputState.operator == command.operator) {
1286
            // Typing an operator twice like 'dd' makes the operator operate
1287
            // linewise
1288
            inputState.motion = 'expandToLine';
1289
            inputState.motionArgs = { linewise: true };
1290
            this.evalInput(cm, vim);
1291
            return;
1292
          } else {
1293
            // 2 different operators in a row doesn't make sense.
1294
            clearInputState(cm);
1295
          }
1296
        }
1297
        inputState.operator = command.operator;
1298
        inputState.operatorArgs = copyArgs(command.operatorArgs);
1299
        if (command.keys.length > 1) {
1300
          inputState.operatorShortcut = command.keys;
1301
        }
1302
        if (command.exitVisualBlock) {
1303
            vim.visualBlock = false;
1304
            updateCmSelection(cm);
1305
        }
1306
        if (vim.visualMode) {
1307
          // Operating on a selection in visual mode. We don't need a motion.
1308
          this.evalInput(cm, vim);
1309
        }
1310
      },
1311
      processOperatorMotion: function(cm, vim, command) {
1312
        var visualMode = vim.visualMode;
1313
        var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
1314
        if (operatorMotionArgs) {
1315
          // Operator motions may have special behavior in visual mode.
1316
          if (visualMode && operatorMotionArgs.visualLine) {
1317
            vim.visualLine = true;
1318
          }
1319
        }
1320
        this.processOperator(cm, vim, command);
1321
        if (!visualMode) {
1322
          this.processMotion(cm, vim, command);
1323
        }
1324
      },
1325
      processAction: function(cm, vim, command) {
1326
        var inputState = vim.inputState;
1327
        var repeat = inputState.getRepeat();
1328
        var repeatIsExplicit = !!repeat;
1329
        var actionArgs = copyArgs(command.actionArgs) || {};
1330
        if (inputState.selectedCharacter) {
1331
          actionArgs.selectedCharacter = inputState.selectedCharacter;
1332
        }
1333
        // Actions may or may not have motions and operators. Do these first.
1334
        if (command.operator) {
1335
          this.processOperator(cm, vim, command);
1336
        }
1337
        if (command.motion) {
1338
          this.processMotion(cm, vim, command);
1339
        }
1340
        if (command.motion || command.operator) {
1341
          this.evalInput(cm, vim);
1342
        }
1343
        actionArgs.repeat = repeat || 1;
1344
        actionArgs.repeatIsExplicit = repeatIsExplicit;
1345
        actionArgs.registerName = inputState.registerName;
1346
        clearInputState(cm);
1347
        vim.lastMotion = null;
1348
        if (command.isEdit) {
1349
          this.recordLastEdit(vim, inputState, command);
1350
        }
1351
        actions[command.action](cm, actionArgs, vim);
1352
      },
1353
      processSearch: function(cm, vim, command) {
1354
        if (!cm.getSearchCursor) {
1355
          // Search depends on SearchCursor.
1356
          return;
1357
        }
1358
        var forward = command.searchArgs.forward;
1359
        var wholeWordOnly = command.searchArgs.wholeWordOnly;
1360
        getSearchState(cm).setReversed(!forward);
1361
        var promptPrefix = (forward) ? '/' : '?';
1362
        var originalQuery = getSearchState(cm).getQuery();
1363
        var originalScrollPos = cm.getScrollInfo();
1364
        function handleQuery(query, ignoreCase, smartCase) {
1365
          vimGlobalState.searchHistoryController.pushInput(query);
1366
          vimGlobalState.searchHistoryController.reset();
1367
          try {
1368
            updateSearchQuery(cm, query, ignoreCase, smartCase);
1369
          } catch (e) {
1370
            showConfirm(cm, 'Invalid regex: ' + query);
1371
            clearInputState(cm);
1372
            return;
1373
          }
1374
          commandDispatcher.processMotion(cm, vim, {
1375
            type: 'motion',
1376
            motion: 'findNext',
1377
            motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
1378
          });
1379
        }
1380
        function onPromptClose(query) {
1381
          cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
1382
          handleQuery(query, true /** ignoreCase */, true /** smartCase */);
1383
          var macroModeState = vimGlobalState.macroModeState;
1384
          if (macroModeState.isRecording) {
1385
            logSearchQuery(macroModeState, query);
1386
          }
1387
        }
1388
        function onPromptKeyUp(e, query, close) {
1389
          var keyName = CodeMirror.keyName(e), up, offset;
1390
          if (keyName == 'Up' || keyName == 'Down') {
1391
            up = keyName == 'Up' ? true : false;
1392
            offset = e.target ? e.target.selectionEnd : 0;
1393
            query = vimGlobalState.searchHistoryController.nextMatch(query, up) || '';
1394
            close(query);
1395
            if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
1396
          } else {
1397
            if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
1398
              vimGlobalState.searchHistoryController.reset();
1399
          }
1400
          var parsedQuery;
1401
          try {
1402
            parsedQuery = updateSearchQuery(cm, query,
1403
                true /** ignoreCase */, true /** smartCase */);
1404
          } catch (e) {
1405
            // Swallow bad regexes for incremental search.
1406
          }
1407
          if (parsedQuery) {
1408
            cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
1409
          } else {
1410
            clearSearchHighlight(cm);
1411
            cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
1412
          }
1413
        }
1414
        function onPromptKeyDown(e, query, close) {
1415
          var keyName = CodeMirror.keyName(e);
1416
          if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
1417
              (keyName == 'Backspace' && query == '')) {
1418
            vimGlobalState.searchHistoryController.pushInput(query);
1419
            vimGlobalState.searchHistoryController.reset();
1420
            updateSearchQuery(cm, originalQuery);
1421
            clearSearchHighlight(cm);
1422
            cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
1423
            CodeMirror.e_stop(e);
1424
            clearInputState(cm);
1425
            close();
1426
            cm.focus();
1427
          } else if (keyName == 'Up' || keyName == 'Down') {
1428
            CodeMirror.e_stop(e);
1429
          } else if (keyName == 'Ctrl-U') {
1430
            // Ctrl-U clears input.
1431
            CodeMirror.e_stop(e);
1432
            close('');
1433
          }
1434
        }
1435
        switch (command.searchArgs.querySrc) {
1436
          case 'prompt':
1437
            var macroModeState = vimGlobalState.macroModeState;
1438
            if (macroModeState.isPlaying) {
1439
              var query = macroModeState.replaySearchQueries.shift();
1440
              handleQuery(query, true /** ignoreCase */, false /** smartCase */);
1441
            } else {
1442
              showPrompt(cm, {
1443
                  onClose: onPromptClose,
1444
                  prefix: promptPrefix,
1445
                  desc: '(JavaScript regexp)',
1446
                  onKeyUp: onPromptKeyUp,
1447
                  onKeyDown: onPromptKeyDown
1448
              });
1449
            }
1450
            break;
1451
          case 'wordUnderCursor':
1452
            var word = expandWordUnderCursor(cm, false /** inclusive */,
1453
                true /** forward */, false /** bigWord */,
1454
                true /** noSymbol */);
1455
            var isKeyword = true;
1456
            if (!word) {
1457
              word = expandWordUnderCursor(cm, false /** inclusive */,
1458
                  true /** forward */, false /** bigWord */,
1459
                  false /** noSymbol */);
1460
              isKeyword = false;
1461
            }
1462
            if (!word) {
1463
              return;
1464
            }
1465
            var query = cm.getLine(word.start.line).substring(word.start.ch,
1466
                word.end.ch);
1467
            if (isKeyword && wholeWordOnly) {
1468
                query = '\\b' + query + '\\b';
1469
            } else {
1470
              query = escapeRegex(query);
1471
            }
1472

1473
            // cachedCursor is used to save the old position of the cursor
1474
            // when * or # causes vim to seek for the nearest word and shift
1475
            // the cursor before entering the motion.
1476
            vimGlobalState.jumpList.cachedCursor = cm.getCursor();
1477
            cm.setCursor(word.start);
1478

1479
            handleQuery(query, true /** ignoreCase */, false /** smartCase */);
1480
            break;
1481
        }
1482
      },
1483
      processEx: function(cm, vim, command) {
1484
        function onPromptClose(input) {
1485
          // Give the prompt some time to close so that if processCommand shows
1486
          // an error, the elements don't overlap.
1487
          vimGlobalState.exCommandHistoryController.pushInput(input);
1488
          vimGlobalState.exCommandHistoryController.reset();
1489
          exCommandDispatcher.processCommand(cm, input);
1490
        }
1491
        function onPromptKeyDown(e, input, close) {
1492
          var keyName = CodeMirror.keyName(e), up, offset;
1493
          if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
1494
              (keyName == 'Backspace' && input == '')) {
1495
            vimGlobalState.exCommandHistoryController.pushInput(input);
1496
            vimGlobalState.exCommandHistoryController.reset();
1497
            CodeMirror.e_stop(e);
1498
            clearInputState(cm);
1499
            close();
1500
            cm.focus();
1501
          }
1502
          if (keyName == 'Up' || keyName == 'Down') {
1503
            CodeMirror.e_stop(e);
1504
            up = keyName == 'Up' ? true : false;
1505
            offset = e.target ? e.target.selectionEnd : 0;
1506
            input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || '';
1507
            close(input);
1508
            if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
1509
          } else if (keyName == 'Ctrl-U') {
1510
            // Ctrl-U clears input.
1511
            CodeMirror.e_stop(e);
1512
            close('');
1513
          } else {
1514
            if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
1515
              vimGlobalState.exCommandHistoryController.reset();
1516
          }
1517
        }
1518
        if (command.type == 'keyToEx') {
1519
          // Handle user defined Ex to Ex mappings
1520
          exCommandDispatcher.processCommand(cm, command.exArgs.input);
1521
        } else {
1522
          if (vim.visualMode) {
1523
            showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
1524
                onKeyDown: onPromptKeyDown, selectValueOnOpen: false});
1525
          } else {
1526
            showPrompt(cm, { onClose: onPromptClose, prefix: ':',
1527
                onKeyDown: onPromptKeyDown});
1528
          }
1529
        }
1530
      },
1531
      evalInput: function(cm, vim) {
1532
        // If the motion command is set, execute both the operator and motion.
1533
        // Otherwise return.
1534
        var inputState = vim.inputState;
1535
        var motion = inputState.motion;
1536
        var motionArgs = inputState.motionArgs || {};
1537
        var operator = inputState.operator;
1538
        var operatorArgs = inputState.operatorArgs || {};
1539
        var registerName = inputState.registerName;
1540
        var sel = vim.sel;
1541
        // TODO: Make sure cm and vim selections are identical outside visual mode.
1542
        var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head'));
1543
        var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor'));
1544
        var oldHead = copyCursor(origHead);
1545
        var oldAnchor = copyCursor(origAnchor);
1546
        var newHead, newAnchor;
1547
        var repeat;
1548
        if (operator) {
1549
          this.recordLastEdit(vim, inputState);
1550
        }
1551
        if (inputState.repeatOverride !== undefined) {
1552
          // If repeatOverride is specified, that takes precedence over the
1553
          // input state's repeat. Used by Ex mode and can be user defined.
1554
          repeat = inputState.repeatOverride;
1555
        } else {
1556
          repeat = inputState.getRepeat();
1557
        }
1558
        if (repeat > 0 && motionArgs.explicitRepeat) {
1559
          motionArgs.repeatIsExplicit = true;
1560
        } else if (motionArgs.noRepeat ||
1561
            (!motionArgs.explicitRepeat && repeat === 0)) {
1562
          repeat = 1;
1563
          motionArgs.repeatIsExplicit = false;
1564
        }
1565
        if (inputState.selectedCharacter) {
1566
          // If there is a character input, stick it in all of the arg arrays.
1567
          motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
1568
              inputState.selectedCharacter;
1569
        }
1570
        motionArgs.repeat = repeat;
1571
        clearInputState(cm);
1572
        if (motion) {
1573
          var motionResult = motions[motion](cm, origHead, motionArgs, vim, inputState);
1574
          vim.lastMotion = motions[motion];
1575
          if (!motionResult) {
1576
            return;
1577
          }
1578
          if (motionArgs.toJumplist) {
1579
            var jumpList = vimGlobalState.jumpList;
1580
            // if the current motion is # or *, use cachedCursor
1581
            var cachedCursor = jumpList.cachedCursor;
1582
            if (cachedCursor) {
1583
              recordJumpPosition(cm, cachedCursor, motionResult);
1584
              delete jumpList.cachedCursor;
1585
            } else {
1586
              recordJumpPosition(cm, origHead, motionResult);
1587
            }
1588
          }
1589
          if (motionResult instanceof Array) {
1590
            newAnchor = motionResult[0];
1591
            newHead = motionResult[1];
1592
          } else {
1593
            newHead = motionResult;
1594
          }
1595
          // TODO: Handle null returns from motion commands better.
1596
          if (!newHead) {
1597
            newHead = copyCursor(origHead);
1598
          }
1599
          if (vim.visualMode) {
1600
            if (!(vim.visualBlock && newHead.ch === Infinity)) {
1601
              newHead = clipCursorToContent(cm, newHead);
1602
            }
1603
            if (newAnchor) {
1604
              newAnchor = clipCursorToContent(cm, newAnchor);
1605
            }
1606
            newAnchor = newAnchor || oldAnchor;
1607
            sel.anchor = newAnchor;
1608
            sel.head = newHead;
1609
            updateCmSelection(cm);
1610
            updateMark(cm, vim, '<',
1611
                cursorIsBefore(newAnchor, newHead) ? newAnchor
1612
                    : newHead);
1613
            updateMark(cm, vim, '>',
1614
                cursorIsBefore(newAnchor, newHead) ? newHead
1615
                    : newAnchor);
1616
          } else if (!operator) {
1617
            newHead = clipCursorToContent(cm, newHead);
1618
            cm.setCursor(newHead.line, newHead.ch);
1619
          }
1620
        }
1621
        if (operator) {
1622
          if (operatorArgs.lastSel) {
1623
            // Replaying a visual mode operation
1624
            newAnchor = oldAnchor;
1625
            var lastSel = operatorArgs.lastSel;
1626
            var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line);
1627
            var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch);
1628
            if (lastSel.visualLine) {
1629
              // Linewise Visual mode: The same number of lines.
1630
              newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
1631
            } else if (lastSel.visualBlock) {
1632
              // Blockwise Visual mode: The same number of lines and columns.
1633
              newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);
1634
            } else if (lastSel.head.line == lastSel.anchor.line) {
1635
              // Normal Visual mode within one line: The same number of characters.
1636
              newHead = new Pos(oldAnchor.line, oldAnchor.ch + chOffset);
1637
            } else {
1638
              // Normal Visual mode with several lines: The same number of lines, in the
1639
              // last line the same number of characters as in the last line the last time.
1640
              newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
1641
            }
1642
            vim.visualMode = true;
1643
            vim.visualLine = lastSel.visualLine;
1644
            vim.visualBlock = lastSel.visualBlock;
1645
            sel = vim.sel = {
1646
              anchor: newAnchor,
1647
              head: newHead
1648
            };
1649
            updateCmSelection(cm);
1650
          } else if (vim.visualMode) {
1651
            operatorArgs.lastSel = {
1652
              anchor: copyCursor(sel.anchor),
1653
              head: copyCursor(sel.head),
1654
              visualBlock: vim.visualBlock,
1655
              visualLine: vim.visualLine
1656
            };
1657
          }
1658
          var curStart, curEnd, linewise, mode;
1659
          var cmSel;
1660
          if (vim.visualMode) {
1661
            // Init visual op
1662
            curStart = cursorMin(sel.head, sel.anchor);
1663
            curEnd = cursorMax(sel.head, sel.anchor);
1664
            linewise = vim.visualLine || operatorArgs.linewise;
1665
            mode = vim.visualBlock ? 'block' :
1666
                   linewise ? 'line' :
1667
                   'char';
1668
            cmSel = makeCmSelection(cm, {
1669
              anchor: curStart,
1670
              head: curEnd
1671
            }, mode);
1672
            if (linewise) {
1673
              var ranges = cmSel.ranges;
1674
              if (mode == 'block') {
1675
                // Linewise operators in visual block mode extend to end of line
1676
                for (var i = 0; i < ranges.length; i++) {
1677
                  ranges[i].head.ch = lineLength(cm, ranges[i].head.line);
1678
                }
1679
              } else if (mode == 'line') {
1680
                ranges[0].head = new Pos(ranges[0].head.line + 1, 0);
1681
              }
1682
            }
1683
          } else {
1684
            // Init motion op
1685
            curStart = copyCursor(newAnchor || oldAnchor);
1686
            curEnd = copyCursor(newHead || oldHead);
1687
            if (cursorIsBefore(curEnd, curStart)) {
1688
              var tmp = curStart;
1689
              curStart = curEnd;
1690
              curEnd = tmp;
1691
            }
1692
            linewise = motionArgs.linewise || operatorArgs.linewise;
1693
            if (linewise) {
1694
              // Expand selection to entire line.
1695
              expandSelectionToLine(cm, curStart, curEnd);
1696
            } else if (motionArgs.forward) {
1697
              // Clip to trailing newlines only if the motion goes forward.
1698
              clipToLine(cm, curStart, curEnd);
1699
            }
1700
            mode = 'char';
1701
            var exclusive = !motionArgs.inclusive || linewise;
1702
            cmSel = makeCmSelection(cm, {
1703
              anchor: curStart,
1704
              head: curEnd
1705
            }, mode, exclusive);
1706
          }
1707
          cm.setSelections(cmSel.ranges, cmSel.primary);
1708
          vim.lastMotion = null;
1709
          operatorArgs.repeat = repeat; // For indent in visual mode.
1710
          operatorArgs.registerName = registerName;
1711
          // Keep track of linewise as it affects how paste and change behave.
1712
          operatorArgs.linewise = linewise;
1713
          var operatorMoveTo = operators[operator](
1714
            cm, operatorArgs, cmSel.ranges, oldAnchor, newHead);
1715
          if (vim.visualMode) {
1716
            exitVisualMode(cm, operatorMoveTo != null);
1717
          }
1718
          if (operatorMoveTo) {
1719
            cm.setCursor(operatorMoveTo);
1720
          }
1721
        }
1722
      },
1723
      recordLastEdit: function(vim, inputState, actionCommand) {
1724
        var macroModeState = vimGlobalState.macroModeState;
1725
        if (macroModeState.isPlaying) { return; }
1726
        vim.lastEditInputState = inputState;
1727
        vim.lastEditActionCommand = actionCommand;
1728
        macroModeState.lastInsertModeChanges.changes = [];
1729
        macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
1730
        macroModeState.lastInsertModeChanges.visualBlock = vim.visualBlock ? vim.sel.head.line - vim.sel.anchor.line : 0;
1731
      }
1732
    };
1733

1734
    /**
1735
     * typedef {Object{line:number,ch:number}} Cursor An object containing the
1736
     *     position of the cursor.
1737
     */
1738
    // All of the functions below return Cursor objects.
1739
    var motions = {
1740
      moveToTopLine: function(cm, _head, motionArgs) {
1741
        var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
1742
        return new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
1743
      },
1744
      moveToMiddleLine: function(cm) {
1745
        var range = getUserVisibleLines(cm);
1746
        var line = Math.floor((range.top + range.bottom) * 0.5);
1747
        return new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
1748
      },
1749
      moveToBottomLine: function(cm, _head, motionArgs) {
1750
        var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
1751
        return new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
1752
      },
1753
      expandToLine: function(_cm, head, motionArgs) {
1754
        // Expands forward to end of line, and then to next line if repeat is
1755
        // >1. Does not handle backward motion!
1756
        var cur = head;
1757
        return new Pos(cur.line + motionArgs.repeat - 1, Infinity);
1758
      },
1759
      findNext: function(cm, _head, motionArgs) {
1760
        var state = getSearchState(cm);
1761
        var query = state.getQuery();
1762
        if (!query) {
1763
          return;
1764
        }
1765
        var prev = !motionArgs.forward;
1766
        // If search is initiated with ? instead of /, negate direction.
1767
        prev = (state.isReversed()) ? !prev : prev;
1768
        highlightSearchMatches(cm, query);
1769
        return findNext(cm, prev/** prev */, query, motionArgs.repeat);
1770
      },
1771
      /**
1772
       * Find and select the next occurrence of the search query. If the cursor is currently
1773
       * within a match, then find and select the current match. Otherwise, find the next occurrence in the
1774
       * appropriate direction.
1775
       *
1776
       * This differs from `findNext` in the following ways:
1777
       *
1778
       * 1. Instead of only returning the "from", this returns a "from", "to" range.
1779
       * 2. If the cursor is currently inside a search match, this selects the current match
1780
       *    instead of the next match.
1781
       * 3. If there is no associated operator, this will turn on visual mode.
1782
       */
1783
      findAndSelectNextInclusive: function(cm, _head, motionArgs, vim, prevInputState) {
1784
        var state = getSearchState(cm);
1785
        var query = state.getQuery();
1786

1787
        if (!query) {
1788
          return;
1789
        }
1790

1791
        var prev = !motionArgs.forward;
1792
        prev = (state.isReversed()) ? !prev : prev;
1793

1794
        // next: [from, to] | null
1795
        var next = findNextFromAndToInclusive(cm, prev, query, motionArgs.repeat, vim);
1796

1797
        // No matches.
1798
        if (!next) {
1799
          return;
1800
        }
1801

1802
        // If there's an operator that will be executed, return the selection.
1803
        if (prevInputState.operator) {
1804
          return next;
1805
        }
1806

1807
        // At this point, we know that there is no accompanying operator -- let's
1808
        // deal with visual mode in order to select an appropriate match.
1809

1810
        var from = next[0];
1811
        // For whatever reason, when we use the "to" as returned by searchcursor.js directly,
1812
        // the resulting selection is extended by 1 char. Let's shrink it so that only the
1813
        // match is selected.
1814
        var to = new Pos(next[1].line, next[1].ch - 1);
1815

1816
        if (vim.visualMode) {
1817
          // If we were in visualLine or visualBlock mode, get out of it.
1818
          if (vim.visualLine || vim.visualBlock) {
1819
            vim.visualLine = false;
1820
            vim.visualBlock = false;
1821
            CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: ""});
1822
          }
1823

1824
          // If we're currently in visual mode, we should extend the selection to include
1825
          // the search result.
1826
          var anchor = vim.sel.anchor;
1827
          if (anchor) {
1828
            if (state.isReversed()) {
1829
              if (motionArgs.forward) {
1830
                return [anchor, from];
1831
              }
1832

1833
              return [anchor, to];
1834
            } else {
1835
              if (motionArgs.forward) {
1836
                return [anchor, to];
1837
              }
1838

1839
              return [anchor, from];
1840
            }
1841
          }
1842
        } else {
1843
          // Let's turn visual mode on.
1844
          vim.visualMode = true;
1845
          vim.visualLine = false;
1846
          vim.visualBlock = false;
1847
          CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: ""});
1848
        }
1849

1850
        return prev ? [to, from] : [from, to];
1851
      },
1852
      goToMark: function(cm, _head, motionArgs, vim) {
1853
        var pos = getMarkPos(cm, vim, motionArgs.selectedCharacter);
1854
        if (pos) {
1855
          return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos;
1856
        }
1857
        return null;
1858
      },
1859
      moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) {
1860
        if (vim.visualBlock && motionArgs.sameLine) {
1861
          var sel = vim.sel;
1862
          return [
1863
            clipCursorToContent(cm, new Pos(sel.anchor.line, sel.head.ch)),
1864
            clipCursorToContent(cm, new Pos(sel.head.line, sel.anchor.ch))
1865
          ];
1866
        } else {
1867
          return ([vim.sel.head, vim.sel.anchor]);
1868
        }
1869
      },
1870
      jumpToMark: function(cm, head, motionArgs, vim) {
1871
        var best = head;
1872
        for (var i = 0; i < motionArgs.repeat; i++) {
1873
          var cursor = best;
1874
          for (var key in vim.marks) {
1875
            if (!isLowerCase(key)) {
1876
              continue;
1877
            }
1878
            var mark = vim.marks[key].find();
1879
            var isWrongDirection = (motionArgs.forward) ?
1880
              cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
1881

1882
            if (isWrongDirection) {
1883
              continue;
1884
            }
1885
            if (motionArgs.linewise && (mark.line == cursor.line)) {
1886
              continue;
1887
            }
1888

1889
            var equal = cursorEqual(cursor, best);
1890
            var between = (motionArgs.forward) ?
1891
              cursorIsBetween(cursor, mark, best) :
1892
              cursorIsBetween(best, mark, cursor);
1893

1894
            if (equal || between) {
1895
              best = mark;
1896
            }
1897
          }
1898
        }
1899

1900
        if (motionArgs.linewise) {
1901
          // Vim places the cursor on the first non-whitespace character of
1902
          // the line if there is one, else it places the cursor at the end
1903
          // of the line, regardless of whether a mark was found.
1904
          best = new Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));
1905
        }
1906
        return best;
1907
      },
1908
      moveByCharacters: function(_cm, head, motionArgs) {
1909
        var cur = head;
1910
        var repeat = motionArgs.repeat;
1911
        var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
1912
        return new Pos(cur.line, ch);
1913
      },
1914
      moveByLines: function(cm, head, motionArgs, vim) {
1915
        var cur = head;
1916
        var endCh = cur.ch;
1917
        // Depending what our last motion was, we may want to do different
1918
        // things. If our last motion was moving vertically, we want to
1919
        // preserve the HPos from our last horizontal move.  If our last motion
1920
        // was going to the end of a line, moving vertically we should go to
1921
        // the end of the line, etc.
1922
        switch (vim.lastMotion) {
1923
          case this.moveByLines:
1924
          case this.moveByDisplayLines:
1925
          case this.moveByScroll:
1926
          case this.moveToColumn:
1927
          case this.moveToEol:
1928
            endCh = vim.lastHPos;
1929
            break;
1930
          default:
1931
            vim.lastHPos = endCh;
1932
        }
1933
        var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
1934
        var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
1935
        var first = cm.firstLine();
1936
        var last = cm.lastLine();
1937
        var posV = cm.findPosV(cur, (motionArgs.forward ? repeat : -repeat), 'line', vim.lastHSPos);
1938
        var hasMarkedText = motionArgs.forward ? posV.line > line : posV.line < line;
1939
        if (hasMarkedText) {
1940
          line = posV.line;
1941
          endCh = posV.ch;
1942
        }
1943
        // Vim go to line begin or line end when cursor at first/last line and
1944
        // move to previous/next line is triggered.
1945
        if (line < first && cur.line == first){
1946
          return this.moveToStartOfLine(cm, head, motionArgs, vim);
1947
        } else if (line > last && cur.line == last){
1948
            return moveToEol(cm, head, motionArgs, vim, true);
1949
        }
1950
        if (motionArgs.toFirstChar){
1951
          endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
1952
          vim.lastHPos = endCh;
1953
        }
1954
        vim.lastHSPos = cm.charCoords(new Pos(line, endCh),'div').left;
1955
        return new Pos(line, endCh);
1956
      },
1957
      moveByDisplayLines: function(cm, head, motionArgs, vim) {
1958
        var cur = head;
1959
        switch (vim.lastMotion) {
1960
          case this.moveByDisplayLines:
1961
          case this.moveByScroll:
1962
          case this.moveByLines:
1963
          case this.moveToColumn:
1964
          case this.moveToEol:
1965
            break;
1966
          default:
1967
            vim.lastHSPos = cm.charCoords(cur,'div').left;
1968
        }
1969
        var repeat = motionArgs.repeat;
1970
        var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
1971
        if (res.hitSide) {
1972
          if (motionArgs.forward) {
1973
            var lastCharCoords = cm.charCoords(res, 'div');
1974
            var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
1975
            var res = cm.coordsChar(goalCoords, 'div');
1976
          } else {
1977
            var resCoords = cm.charCoords(new Pos(cm.firstLine(), 0), 'div');
1978
            resCoords.left = vim.lastHSPos;
1979
            res = cm.coordsChar(resCoords, 'div');
1980
          }
1981
        }
1982
        vim.lastHPos = res.ch;
1983
        return res;
1984
      },
1985
      moveByPage: function(cm, head, motionArgs) {
1986
        // CodeMirror only exposes functions that move the cursor page down, so
1987
        // doing this bad hack to move the cursor and move it back. evalInput
1988
        // will move the cursor to where it should be in the end.
1989
        var curStart = head;
1990
        var repeat = motionArgs.repeat;
1991
        return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
1992
      },
1993
      moveByParagraph: function(cm, head, motionArgs) {
1994
        var dir = motionArgs.forward ? 1 : -1;
1995
        return findParagraph(cm, head, motionArgs.repeat, dir);
1996
      },
1997
      moveBySentence: function(cm, head, motionArgs) {
1998
        var dir = motionArgs.forward ? 1 : -1;
1999
        return findSentence(cm, head, motionArgs.repeat, dir);
2000
      },
2001
      moveByScroll: function(cm, head, motionArgs, vim) {
2002
        var scrollbox = cm.getScrollInfo();
2003
        var curEnd = null;
2004
        var repeat = motionArgs.repeat;
2005
        if (!repeat) {
2006
          repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
2007
        }
2008
        var orig = cm.charCoords(head, 'local');
2009
        motionArgs.repeat = repeat;
2010
        var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);
2011
        if (!curEnd) {
2012
          return null;
2013
        }
2014
        var dest = cm.charCoords(curEnd, 'local');
2015
        cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
2016
        return curEnd;
2017
      },
2018
      moveByWords: function(cm, head, motionArgs) {
2019
        return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward,
2020
            !!motionArgs.wordEnd, !!motionArgs.bigWord);
2021
      },
2022
      moveTillCharacter: function(cm, _head, motionArgs) {
2023
        var repeat = motionArgs.repeat;
2024
        var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
2025
            motionArgs.selectedCharacter);
2026
        var increment = motionArgs.forward ? -1 : 1;
2027
        recordLastCharacterSearch(increment, motionArgs);
2028
        if (!curEnd) return null;
2029
        curEnd.ch += increment;
2030
        return curEnd;
2031
      },
2032
      moveToCharacter: function(cm, head, motionArgs) {
2033
        var repeat = motionArgs.repeat;
2034
        recordLastCharacterSearch(0, motionArgs);
2035
        return moveToCharacter(cm, repeat, motionArgs.forward,
2036
            motionArgs.selectedCharacter) || head;
2037
      },
2038
      moveToSymbol: function(cm, head, motionArgs) {
2039
        var repeat = motionArgs.repeat;
2040
        return findSymbol(cm, repeat, motionArgs.forward,
2041
            motionArgs.selectedCharacter) || head;
2042
      },
2043
      moveToColumn: function(cm, head, motionArgs, vim) {
2044
        var repeat = motionArgs.repeat;
2045
        // repeat is equivalent to which column we want to move to!
2046
        vim.lastHPos = repeat - 1;
2047
        vim.lastHSPos = cm.charCoords(head,'div').left;
2048
        return moveToColumn(cm, repeat);
2049
      },
2050
      moveToEol: function(cm, head, motionArgs, vim) {
2051
        return moveToEol(cm, head, motionArgs, vim, false);
2052
      },
2053
      moveToFirstNonWhiteSpaceCharacter: function(cm, head) {
2054
        // Go to the start of the line where the text begins, or the end for
2055
        // whitespace-only lines
2056
        var cursor = head;
2057
        return new Pos(cursor.line,
2058
                   findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
2059
      },
2060
      moveToMatchedSymbol: function(cm, head) {
2061
        var cursor = head;
2062
        var line = cursor.line;
2063
        var ch = cursor.ch;
2064
        var lineText = cm.getLine(line);
2065
        var symbol;
2066
        for (; ch < lineText.length; ch++) {
2067
          symbol = lineText.charAt(ch);
2068
          if (symbol && isMatchableSymbol(symbol)) {
2069
            var style = cm.getTokenTypeAt(new Pos(line, ch + 1));
2070
            if (style !== "string" && style !== "comment") {
2071
              break;
2072
            }
2073
          }
2074
        }
2075
        if (ch < lineText.length) {
2076
          // Only include angle brackets in analysis if they are being matched.
2077
          var re = (ch === '<' || ch === '>') ? /[(){}[\]<>]/ : /[(){}[\]]/;
2078
          var matched = cm.findMatchingBracket(new Pos(line, ch), {bracketRegex: re});
2079
          return matched.to;
2080
        } else {
2081
          return cursor;
2082
        }
2083
      },
2084
      moveToStartOfLine: function(_cm, head) {
2085
        return new Pos(head.line, 0);
2086
      },
2087
      moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) {
2088
        var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
2089
        if (motionArgs.repeatIsExplicit) {
2090
          lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
2091
        }
2092
        return new Pos(lineNum,
2093
                   findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
2094
      },
2095
      moveToStartOfDisplayLine: function(cm) {
2096
        cm.execCommand("goLineLeft");
2097
        return cm.getCursor();
2098
      },
2099
      moveToEndOfDisplayLine: function(cm) {
2100
        cm.execCommand("goLineRight");
2101
        var head = cm.getCursor();
2102
        if (head.sticky == "before") head.ch--;
2103
        return head;
2104
      },
2105
      textObjectManipulation: function(cm, head, motionArgs, vim) {
2106
        // TODO: lots of possible exceptions that can be thrown here. Try da(
2107
        //     outside of a () block.
2108
        var mirroredPairs = {'(': ')', ')': '(',
2109
                             '{': '}', '}': '{',
2110
                             '[': ']', ']': '[',
2111
                             '<': '>', '>': '<'};
2112
        var selfPaired = {'\'': true, '"': true, '`': true};
2113

2114
        var character = motionArgs.selectedCharacter;
2115
        // 'b' refers to  '()' block.
2116
        // 'B' refers to  '{}' block.
2117
        if (character == 'b') {
2118
          character = '(';
2119
        } else if (character == 'B') {
2120
          character = '{';
2121
        }
2122

2123
        // Inclusive is the difference between a and i
2124
        // TODO: Instead of using the additional text object map to perform text
2125
        //     object operations, merge the map into the defaultKeyMap and use
2126
        //     motionArgs to define behavior. Define separate entries for 'aw',
2127
        //     'iw', 'a[', 'i[', etc.
2128
        var inclusive = !motionArgs.textObjectInner;
2129

2130
        var tmp;
2131
        if (mirroredPairs[character]) {
2132
          tmp = selectCompanionObject(cm, head, character, inclusive);
2133
        } else if (selfPaired[character]) {
2134
          tmp = findBeginningAndEnd(cm, head, character, inclusive);
2135
        } else if (character === 'W') {
2136
          tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
2137
                                                     true /** bigWord */);
2138
        } else if (character === 'w') {
2139
          tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
2140
                                                     false /** bigWord */);
2141
        } else if (character === 'p') {
2142
          tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive);
2143
          motionArgs.linewise = true;
2144
          if (vim.visualMode) {
2145
            if (!vim.visualLine) { vim.visualLine = true; }
2146
          } else {
2147
            var operatorArgs = vim.inputState.operatorArgs;
2148
            if (operatorArgs) { operatorArgs.linewise = true; }
2149
            tmp.end.line--;
2150
          }
2151
        } else if (character === 't') {
2152
          tmp = expandTagUnderCursor(cm, head, inclusive);
2153
        } else {
2154
          // No text object defined for this, don't move.
2155
          return null;
2156
        }
2157

2158
        if (!cm.state.vim.visualMode) {
2159
          return [tmp.start, tmp.end];
2160
        } else {
2161
          return expandSelection(cm, tmp.start, tmp.end);
2162
        }
2163
      },
2164

2165
      repeatLastCharacterSearch: function(cm, head, motionArgs) {
2166
        var lastSearch = vimGlobalState.lastCharacterSearch;
2167
        var repeat = motionArgs.repeat;
2168
        var forward = motionArgs.forward === lastSearch.forward;
2169
        var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
2170
        cm.moveH(-increment, 'char');
2171
        motionArgs.inclusive = forward ? true : false;
2172
        var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
2173
        if (!curEnd) {
2174
          cm.moveH(increment, 'char');
2175
          return head;
2176
        }
2177
        curEnd.ch += increment;
2178
        return curEnd;
2179
      }
2180
    };
2181

2182
    function defineMotion(name, fn) {
2183
      motions[name] = fn;
2184
    }
2185

2186
    function fillArray(val, times) {
2187
      var arr = [];
2188
      for (var i = 0; i < times; i++) {
2189
        arr.push(val);
2190
      }
2191
      return arr;
2192
    }
2193
    /**
2194
     * An operator acts on a text selection. It receives the list of selections
2195
     * as input. The corresponding CodeMirror selection is guaranteed to
2196
    * match the input selection.
2197
     */
2198
    var operators = {
2199
      change: function(cm, args, ranges) {
2200
        var finalHead, text;
2201
        var vim = cm.state.vim;
2202
        var anchor = ranges[0].anchor,
2203
            head = ranges[0].head;
2204
        if (!vim.visualMode) {
2205
          text = cm.getRange(anchor, head);
2206
          var lastState = vim.lastEditInputState || {};
2207
          if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) {
2208
            // Exclude trailing whitespace if the range is not all whitespace.
2209
            var match = (/\s+$/).exec(text);
2210
            if (match && lastState.motionArgs && lastState.motionArgs.forward) {
2211
              head = offsetCursor(head, 0, - match[0].length);
2212
              text = text.slice(0, - match[0].length);
2213
            }
2214
          }
2215
          var prevLineEnd = new Pos(anchor.line - 1, Number.MAX_VALUE);
2216
          var wasLastLine = cm.firstLine() == cm.lastLine();
2217
          if (head.line > cm.lastLine() && args.linewise && !wasLastLine) {
2218
            cm.replaceRange('', prevLineEnd, head);
2219
          } else {
2220
            cm.replaceRange('', anchor, head);
2221
          }
2222
          if (args.linewise) {
2223
            // Push the next line back down, if there is a next line.
2224
            if (!wasLastLine) {
2225
              cm.setCursor(prevLineEnd);
2226
              CodeMirror.commands.newlineAndIndent(cm);
2227
            }
2228
            // make sure cursor ends up at the end of the line.
2229
            anchor.ch = Number.MAX_VALUE;
2230
          }
2231
          finalHead = anchor;
2232
        } else if (args.fullLine) {
2233
            head.ch = Number.MAX_VALUE;
2234
            head.line--;
2235
            cm.setSelection(anchor, head)
2236
            text = cm.getSelection();
2237
            cm.replaceSelection("");
2238
            finalHead = anchor;
2239
        } else {
2240
          text = cm.getSelection();
2241
          var replacement = fillArray('', ranges.length);
2242
          cm.replaceSelections(replacement);
2243
          finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
2244
        }
2245
        vimGlobalState.registerController.pushText(
2246
            args.registerName, 'change', text,
2247
            args.linewise, ranges.length > 1);
2248
        actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim);
2249
      },
2250
      // delete is a javascript keyword.
2251
      'delete': function(cm, args, ranges) {
2252
        var finalHead, text;
2253
        var vim = cm.state.vim;
2254
        if (!vim.visualBlock) {
2255
          var anchor = ranges[0].anchor,
2256
              head = ranges[0].head;
2257
          if (args.linewise &&
2258
              head.line != cm.firstLine() &&
2259
              anchor.line == cm.lastLine() &&
2260
              anchor.line == head.line - 1) {
2261
            // Special case for dd on last line (and first line).
2262
            if (anchor.line == cm.firstLine()) {
2263
              anchor.ch = 0;
2264
            } else {
2265
              anchor = new Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));
2266
            }
2267
          }
2268
          text = cm.getRange(anchor, head);
2269
          cm.replaceRange('', anchor, head);
2270
          finalHead = anchor;
2271
          if (args.linewise) {
2272
            finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);
2273
          }
2274
        } else {
2275
          text = cm.getSelection();
2276
          var replacement = fillArray('', ranges.length);
2277
          cm.replaceSelections(replacement);
2278
          finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
2279
        }
2280
        vimGlobalState.registerController.pushText(
2281
            args.registerName, 'delete', text,
2282
            args.linewise, vim.visualBlock);
2283
        return clipCursorToContent(cm, finalHead);
2284
      },
2285
      indent: function(cm, args, ranges) {
2286
        var vim = cm.state.vim;
2287
        var startLine = ranges[0].anchor.line;
2288
        var endLine = vim.visualBlock ?
2289
          ranges[ranges.length - 1].anchor.line :
2290
          ranges[0].head.line;
2291
        // In visual mode, n> shifts the selection right n times, instead of
2292
        // shifting n lines right once.
2293
        var repeat = (vim.visualMode) ? args.repeat : 1;
2294
        if (args.linewise) {
2295
          // The only way to delete a newline is to delete until the start of
2296
          // the next line, so in linewise mode evalInput will include the next
2297
          // line. We don't want this in indent, so we go back a line.
2298
          endLine--;
2299
        }
2300
        for (var i = startLine; i <= endLine; i++) {
2301
          for (var j = 0; j < repeat; j++) {
2302
            cm.indentLine(i, args.indentRight);
2303
          }
2304
        }
2305
        return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
2306
      },
2307
      indentAuto: function(cm, _args, ranges) {
2308
        cm.execCommand("indentAuto");
2309
        return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
2310
      },
2311
      changeCase: function(cm, args, ranges, oldAnchor, newHead) {
2312
        var selections = cm.getSelections();
2313
        var swapped = [];
2314
        var toLower = args.toLower;
2315
        for (var j = 0; j < selections.length; j++) {
2316
          var toSwap = selections[j];
2317
          var text = '';
2318
          if (toLower === true) {
2319
            text = toSwap.toLowerCase();
2320
          } else if (toLower === false) {
2321
            text = toSwap.toUpperCase();
2322
          } else {
2323
            for (var i = 0; i < toSwap.length; i++) {
2324
              var character = toSwap.charAt(i);
2325
              text += isUpperCase(character) ? character.toLowerCase() :
2326
                  character.toUpperCase();
2327
            }
2328
          }
2329
          swapped.push(text);
2330
        }
2331
        cm.replaceSelections(swapped);
2332
        if (args.shouldMoveCursor){
2333
          return newHead;
2334
        } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) {
2335
          return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor);
2336
        } else if (args.linewise){
2337
          return oldAnchor;
2338
        } else {
2339
          return cursorMin(ranges[0].anchor, ranges[0].head);
2340
        }
2341
      },
2342
      yank: function(cm, args, ranges, oldAnchor) {
2343
        var vim = cm.state.vim;
2344
        var text = cm.getSelection();
2345
        var endPos = vim.visualMode
2346
          ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)
2347
          : oldAnchor;
2348
        vimGlobalState.registerController.pushText(
2349
            args.registerName, 'yank',
2350
            text, args.linewise, vim.visualBlock);
2351
        return endPos;
2352
      }
2353
    };
2354

2355
    function defineOperator(name, fn) {
2356
      operators[name] = fn;
2357
    }
2358

2359
    var actions = {
2360
      jumpListWalk: function(cm, actionArgs, vim) {
2361
        if (vim.visualMode) {
2362
          return;
2363
        }
2364
        var repeat = actionArgs.repeat;
2365
        var forward = actionArgs.forward;
2366
        var jumpList = vimGlobalState.jumpList;
2367

2368
        var mark = jumpList.move(cm, forward ? repeat : -repeat);
2369
        var markPos = mark ? mark.find() : undefined;
2370
        markPos = markPos ? markPos : cm.getCursor();
2371
        cm.setCursor(markPos);
2372
      },
2373
      scroll: function(cm, actionArgs, vim) {
2374
        if (vim.visualMode) {
2375
          return;
2376
        }
2377
        var repeat = actionArgs.repeat || 1;
2378
        var lineHeight = cm.defaultTextHeight();
2379
        var top = cm.getScrollInfo().top;
2380
        var delta = lineHeight * repeat;
2381
        var newPos = actionArgs.forward ? top + delta : top - delta;
2382
        var cursor = copyCursor(cm.getCursor());
2383
        var cursorCoords = cm.charCoords(cursor, 'local');
2384
        if (actionArgs.forward) {
2385
          if (newPos > cursorCoords.top) {
2386
             cursor.line += (newPos - cursorCoords.top) / lineHeight;
2387
             cursor.line = Math.ceil(cursor.line);
2388
             cm.setCursor(cursor);
2389
             cursorCoords = cm.charCoords(cursor, 'local');
2390
             cm.scrollTo(null, cursorCoords.top);
2391
          } else {
2392
             // Cursor stays within bounds.  Just reposition the scroll window.
2393
             cm.scrollTo(null, newPos);
2394
          }
2395
        } else {
2396
          var newBottom = newPos + cm.getScrollInfo().clientHeight;
2397
          if (newBottom < cursorCoords.bottom) {
2398
             cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
2399
             cursor.line = Math.floor(cursor.line);
2400
             cm.setCursor(cursor);
2401
             cursorCoords = cm.charCoords(cursor, 'local');
2402
             cm.scrollTo(
2403
                 null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
2404
          } else {
2405
             // Cursor stays within bounds.  Just reposition the scroll window.
2406
             cm.scrollTo(null, newPos);
2407
          }
2408
        }
2409
      },
2410
      scrollToCursor: function(cm, actionArgs) {
2411
        var lineNum = cm.getCursor().line;
2412
        var charCoords = cm.charCoords(new Pos(lineNum, 0), 'local');
2413
        var height = cm.getScrollInfo().clientHeight;
2414
        var y = charCoords.top;
2415
        var lineHeight = charCoords.bottom - y;
2416
        switch (actionArgs.position) {
2417
          case 'center': y = y - (height / 2) + lineHeight;
2418
            break;
2419
          case 'bottom': y = y - height + lineHeight;
2420
            break;
2421
        }
2422
        cm.scrollTo(null, y);
2423
      },
2424
      replayMacro: function(cm, actionArgs, vim) {
2425
        var registerName = actionArgs.selectedCharacter;
2426
        var repeat = actionArgs.repeat;
2427
        var macroModeState = vimGlobalState.macroModeState;
2428
        if (registerName == '@') {
2429
          registerName = macroModeState.latestRegister;
2430
        } else {
2431
          macroModeState.latestRegister = registerName;
2432
        }
2433
        while(repeat--){
2434
          executeMacroRegister(cm, vim, macroModeState, registerName);
2435
        }
2436
      },
2437
      enterMacroRecordMode: function(cm, actionArgs) {
2438
        var macroModeState = vimGlobalState.macroModeState;
2439
        var registerName = actionArgs.selectedCharacter;
2440
        if (vimGlobalState.registerController.isValidRegister(registerName)) {
2441
          macroModeState.enterMacroRecordMode(cm, registerName);
2442
        }
2443
      },
2444
      toggleOverwrite: function(cm) {
2445
        if (!cm.state.overwrite) {
2446
          cm.toggleOverwrite(true);
2447
          cm.setOption('keyMap', 'vim-replace');
2448
          CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
2449
        } else {
2450
          cm.toggleOverwrite(false);
2451
          cm.setOption('keyMap', 'vim-insert');
2452
          CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
2453
        }
2454
      },
2455
      enterInsertMode: function(cm, actionArgs, vim) {
2456
        if (cm.getOption('readOnly')) { return; }
2457
        vim.insertMode = true;
2458
        vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
2459
        var insertAt = (actionArgs) ? actionArgs.insertAt : null;
2460
        var sel = vim.sel;
2461
        var head = actionArgs.head || cm.getCursor('head');
2462
        var height = cm.listSelections().length;
2463
        if (insertAt == 'eol') {
2464
          head = new Pos(head.line, lineLength(cm, head.line));
2465
        } else if (insertAt == 'bol') {
2466
          head = new Pos(head.line, 0);
2467
        } else if (insertAt == 'charAfter') {
2468
          head = offsetCursor(head, 0, 1);
2469
        } else if (insertAt == 'firstNonBlank') {
2470
          head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head);
2471
        } else if (insertAt == 'startOfSelectedArea') {
2472
          if (!vim.visualMode)
2473
              return;
2474
          if (!vim.visualBlock) {
2475
            if (sel.head.line < sel.anchor.line) {
2476
              head = sel.head;
2477
            } else {
2478
              head = new Pos(sel.anchor.line, 0);
2479
            }
2480
          } else {
2481
            head = new Pos(
2482
                Math.min(sel.head.line, sel.anchor.line),
2483
                Math.min(sel.head.ch, sel.anchor.ch));
2484
            height = Math.abs(sel.head.line - sel.anchor.line) + 1;
2485
          }
2486
        } else if (insertAt == 'endOfSelectedArea') {
2487
            if (!vim.visualMode)
2488
              return;
2489
          if (!vim.visualBlock) {
2490
            if (sel.head.line >= sel.anchor.line) {
2491
              head = offsetCursor(sel.head, 0, 1);
2492
            } else {
2493
              head = new Pos(sel.anchor.line, 0);
2494
            }
2495
          } else {
2496
            head = new Pos(
2497
                Math.min(sel.head.line, sel.anchor.line),
2498
                Math.max(sel.head.ch, sel.anchor.ch) + 1);
2499
            height = Math.abs(sel.head.line - sel.anchor.line) + 1;
2500
          }
2501
        } else if (insertAt == 'inplace') {
2502
          if (vim.visualMode){
2503
            return;
2504
          }
2505
        } else if (insertAt == 'lastEdit') {
2506
          head = getLastEditPos(cm) || head;
2507
        }
2508
        cm.setOption('disableInput', false);
2509
        if (actionArgs && actionArgs.replace) {
2510
          // Handle Replace-mode as a special case of insert mode.
2511
          cm.toggleOverwrite(true);
2512
          cm.setOption('keyMap', 'vim-replace');
2513
          CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
2514
        } else {
2515
          cm.toggleOverwrite(false);
2516
          cm.setOption('keyMap', 'vim-insert');
2517
          CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
2518
        }
2519
        if (!vimGlobalState.macroModeState.isPlaying) {
2520
          // Only record if not replaying.
2521
          cm.on('change', onChange);
2522
          CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
2523
        }
2524
        if (vim.visualMode) {
2525
          exitVisualMode(cm);
2526
        }
2527
        selectForInsert(cm, head, height);
2528
      },
2529
      toggleVisualMode: function(cm, actionArgs, vim) {
2530
        var repeat = actionArgs.repeat;
2531
        var anchor = cm.getCursor();
2532
        var head;
2533
        // TODO: The repeat should actually select number of characters/lines
2534
        //     equal to the repeat times the size of the previous visual
2535
        //     operation.
2536
        if (!vim.visualMode) {
2537
          // Entering visual mode
2538
          vim.visualMode = true;
2539
          vim.visualLine = !!actionArgs.linewise;
2540
          vim.visualBlock = !!actionArgs.blockwise;
2541
          head = clipCursorToContent(
2542
              cm, new Pos(anchor.line, anchor.ch + repeat - 1));
2543
          vim.sel = {
2544
            anchor: anchor,
2545
            head: head
2546
          };
2547
          CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
2548
          updateCmSelection(cm);
2549
          updateMark(cm, vim, '<', cursorMin(anchor, head));
2550
          updateMark(cm, vim, '>', cursorMax(anchor, head));
2551
        } else if (vim.visualLine ^ actionArgs.linewise ||
2552
            vim.visualBlock ^ actionArgs.blockwise) {
2553
          // Toggling between modes
2554
          vim.visualLine = !!actionArgs.linewise;
2555
          vim.visualBlock = !!actionArgs.blockwise;
2556
          CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
2557
          updateCmSelection(cm);
2558
        } else {
2559
          exitVisualMode(cm);
2560
        }
2561
      },
2562
      reselectLastSelection: function(cm, _actionArgs, vim) {
2563
        var lastSelection = vim.lastSelection;
2564
        if (vim.visualMode) {
2565
          updateLastSelection(cm, vim);
2566
        }
2567
        if (lastSelection) {
2568
          var anchor = lastSelection.anchorMark.find();
2569
          var head = lastSelection.headMark.find();
2570
          if (!anchor || !head) {
2571
            // If the marks have been destroyed due to edits, do nothing.
2572
            return;
2573
          }
2574
          vim.sel = {
2575
            anchor: anchor,
2576
            head: head
2577
          };
2578
          vim.visualMode = true;
2579
          vim.visualLine = lastSelection.visualLine;
2580
          vim.visualBlock = lastSelection.visualBlock;
2581
          updateCmSelection(cm);
2582
          updateMark(cm, vim, '<', cursorMin(anchor, head));
2583
          updateMark(cm, vim, '>', cursorMax(anchor, head));
2584
          CodeMirror.signal(cm, 'vim-mode-change', {
2585
            mode: 'visual',
2586
            subMode: vim.visualLine ? 'linewise' :
2587
                     vim.visualBlock ? 'blockwise' : ''});
2588
        }
2589
      },
2590
      joinLines: function(cm, actionArgs, vim) {
2591
        var curStart, curEnd;
2592
        if (vim.visualMode) {
2593
          curStart = cm.getCursor('anchor');
2594
          curEnd = cm.getCursor('head');
2595
          if (cursorIsBefore(curEnd, curStart)) {
2596
            var tmp = curEnd;
2597
            curEnd = curStart;
2598
            curStart = tmp;
2599
          }
2600
          curEnd.ch = lineLength(cm, curEnd.line) - 1;
2601
        } else {
2602
          // Repeat is the number of lines to join. Minimum 2 lines.
2603
          var repeat = Math.max(actionArgs.repeat, 2);
2604
          curStart = cm.getCursor();
2605
          curEnd = clipCursorToContent(cm, new Pos(curStart.line + repeat - 1,
2606
                                               Infinity));
2607
        }
2608
        var finalCh = 0;
2609
        for (var i = curStart.line; i < curEnd.line; i++) {
2610
          finalCh = lineLength(cm, curStart.line);
2611
          var tmp = new Pos(curStart.line + 1,
2612
                        lineLength(cm, curStart.line + 1));
2613
          var text = cm.getRange(curStart, tmp);
2614
          text = actionArgs.keepSpaces
2615
            ? text.replace(/\n\r?/g, '')
2616
            : text.replace(/\n\s*/g, ' ');
2617
          cm.replaceRange(text, curStart, tmp);
2618
        }
2619
        var curFinalPos = new Pos(curStart.line, finalCh);
2620
        if (vim.visualMode) {
2621
          exitVisualMode(cm, false);
2622
        }
2623
        cm.setCursor(curFinalPos);
2624
      },
2625
      newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
2626
        vim.insertMode = true;
2627
        var insertAt = copyCursor(cm.getCursor());
2628
        if (insertAt.line === cm.firstLine() && !actionArgs.after) {
2629
          // Special case for inserting newline before start of document.
2630
          cm.replaceRange('\n', new Pos(cm.firstLine(), 0));
2631
          cm.setCursor(cm.firstLine(), 0);
2632
        } else {
2633
          insertAt.line = (actionArgs.after) ? insertAt.line :
2634
              insertAt.line - 1;
2635
          insertAt.ch = lineLength(cm, insertAt.line);
2636
          cm.setCursor(insertAt);
2637
          var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
2638
              CodeMirror.commands.newlineAndIndent;
2639
          newlineFn(cm);
2640
        }
2641
        this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
2642
      },
2643
      paste: function(cm, actionArgs, vim) {
2644
        var cur = copyCursor(cm.getCursor());
2645
        var register = vimGlobalState.registerController.getRegister(
2646
            actionArgs.registerName);
2647
        var text = register.toString();
2648
        if (!text) {
2649
          return;
2650
        }
2651
        if (actionArgs.matchIndent) {
2652
          var tabSize = cm.getOption("tabSize");
2653
          // length that considers tabs and tabSize
2654
          var whitespaceLength = function(str) {
2655
            var tabs = (str.split("\t").length - 1);
2656
            var spaces = (str.split(" ").length - 1);
2657
            return tabs * tabSize + spaces * 1;
2658
          };
2659
          var currentLine = cm.getLine(cm.getCursor().line);
2660
          var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
2661
          // chomp last newline b/c don't want it to match /^\s*/gm
2662
          var chompedText = text.replace(/\n$/, '');
2663
          var wasChomped = text !== chompedText;
2664
          var firstIndent = whitespaceLength(text.match(/^\s*/)[0]);
2665
          var text = chompedText.replace(/^\s*/gm, function(wspace) {
2666
            var newIndent = indent + (whitespaceLength(wspace) - firstIndent);
2667
            if (newIndent < 0) {
2668
              return "";
2669
            }
2670
            else if (cm.getOption("indentWithTabs")) {
2671
              var quotient = Math.floor(newIndent / tabSize);
2672
              return Array(quotient + 1).join('\t');
2673
            }
2674
            else {
2675
              return Array(newIndent + 1).join(' ');
2676
            }
2677
          });
2678
          text += wasChomped ? "\n" : "";
2679
        }
2680
        if (actionArgs.repeat > 1) {
2681
          var text = Array(actionArgs.repeat + 1).join(text);
2682
        }
2683
        var linewise = register.linewise;
2684
        var blockwise = register.blockwise;
2685
        if (blockwise) {
2686
          text = text.split('\n');
2687
          if (linewise) {
2688
              text.pop();
2689
          }
2690
          for (var i = 0; i < text.length; i++) {
2691
            text[i] = (text[i] == '') ? ' ' : text[i];
2692
          }
2693
          cur.ch += actionArgs.after ? 1 : 0;
2694
          cur.ch = Math.min(lineLength(cm, cur.line), cur.ch);
2695
        } else if (linewise) {
2696
          if(vim.visualMode) {
2697
            text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n';
2698
          } else if (actionArgs.after) {
2699
            // Move the newline at the end to the start instead, and paste just
2700
            // before the newline character of the line we are on right now.
2701
            text = '\n' + text.slice(0, text.length - 1);
2702
            cur.ch = lineLength(cm, cur.line);
2703
          } else {
2704
            cur.ch = 0;
2705
          }
2706
        } else {
2707
          cur.ch += actionArgs.after ? 1 : 0;
2708
        }
2709
        var curPosFinal;
2710
        var idx;
2711
        if (vim.visualMode) {
2712
          //  save the pasted text for reselection if the need arises
2713
          vim.lastPastedText = text;
2714
          var lastSelectionCurEnd;
2715
          var selectedArea = getSelectedAreaRange(cm, vim);
2716
          var selectionStart = selectedArea[0];
2717
          var selectionEnd = selectedArea[1];
2718
          var selectedText = cm.getSelection();
2719
          var selections = cm.listSelections();
2720
          var emptyStrings = new Array(selections.length).join('1').split('1');
2721
          // save the curEnd marker before it get cleared due to cm.replaceRange.
2722
          if (vim.lastSelection) {
2723
            lastSelectionCurEnd = vim.lastSelection.headMark.find();
2724
          }
2725
          // push the previously selected text to unnamed register
2726
          vimGlobalState.registerController.unnamedRegister.setText(selectedText);
2727
          if (blockwise) {
2728
            // first delete the selected text
2729
            cm.replaceSelections(emptyStrings);
2730
            // Set new selections as per the block length of the yanked text
2731
            selectionEnd = new Pos(selectionStart.line + text.length-1, selectionStart.ch);
2732
            cm.setCursor(selectionStart);
2733
            selectBlock(cm, selectionEnd);
2734
            cm.replaceSelections(text);
2735
            curPosFinal = selectionStart;
2736
          } else if (vim.visualBlock) {
2737
            cm.replaceSelections(emptyStrings);
2738
            cm.setCursor(selectionStart);
2739
            cm.replaceRange(text, selectionStart, selectionStart);
2740
            curPosFinal = selectionStart;
2741
          } else {
2742
            cm.replaceRange(text, selectionStart, selectionEnd);
2743
            curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1);
2744
          }
2745
          // restore the the curEnd marker
2746
          if(lastSelectionCurEnd) {
2747
            vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);
2748
          }
2749
          if (linewise) {
2750
            curPosFinal.ch=0;
2751
          }
2752
        } else {
2753
          if (blockwise) {
2754
            cm.setCursor(cur);
2755
            for (var i = 0; i < text.length; i++) {
2756
              var line = cur.line+i;
2757
              if (line > cm.lastLine()) {
2758
                cm.replaceRange('\n',  new Pos(line, 0));
2759
              }
2760
              var lastCh = lineLength(cm, line);
2761
              if (lastCh < cur.ch) {
2762
                extendLineToColumn(cm, line, cur.ch);
2763
              }
2764
            }
2765
            cm.setCursor(cur);
2766
            selectBlock(cm, new Pos(cur.line + text.length-1, cur.ch));
2767
            cm.replaceSelections(text);
2768
            curPosFinal = cur;
2769
          } else {
2770
            cm.replaceRange(text, cur);
2771
            // Now fine tune the cursor to where we want it.
2772
            if (linewise && actionArgs.after) {
2773
              curPosFinal = new Pos(
2774
              cur.line + 1,
2775
              findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)));
2776
            } else if (linewise && !actionArgs.after) {
2777
              curPosFinal = new Pos(
2778
                cur.line,
2779
                findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)));
2780
            } else if (!linewise && actionArgs.after) {
2781
              idx = cm.indexFromPos(cur);
2782
              curPosFinal = cm.posFromIndex(idx + text.length - 1);
2783
            } else {
2784
              idx = cm.indexFromPos(cur);
2785
              curPosFinal = cm.posFromIndex(idx + text.length);
2786
            }
2787
          }
2788
        }
2789
        if (vim.visualMode) {
2790
          exitVisualMode(cm, false);
2791
        }
2792
        cm.setCursor(curPosFinal);
2793
      },
2794
      undo: function(cm, actionArgs) {
2795
        cm.operation(function() {
2796
          repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
2797
          cm.setCursor(cm.getCursor('anchor'));
2798
        });
2799
      },
2800
      redo: function(cm, actionArgs) {
2801
        repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
2802
      },
2803
      setRegister: function(_cm, actionArgs, vim) {
2804
        vim.inputState.registerName = actionArgs.selectedCharacter;
2805
      },
2806
      setMark: function(cm, actionArgs, vim) {
2807
        var markName = actionArgs.selectedCharacter;
2808
        updateMark(cm, vim, markName, cm.getCursor());
2809
      },
2810
      replace: function(cm, actionArgs, vim) {
2811
        var replaceWith = actionArgs.selectedCharacter;
2812
        var curStart = cm.getCursor();
2813
        var replaceTo;
2814
        var curEnd;
2815
        var selections = cm.listSelections();
2816
        if (vim.visualMode) {
2817
          curStart = cm.getCursor('start');
2818
          curEnd = cm.getCursor('end');
2819
        } else {
2820
          var line = cm.getLine(curStart.line);
2821
          replaceTo = curStart.ch + actionArgs.repeat;
2822
          if (replaceTo > line.length) {
2823
            replaceTo=line.length;
2824
          }
2825
          curEnd = new Pos(curStart.line, replaceTo);
2826
        }
2827
        if (replaceWith=='\n') {
2828
          if (!vim.visualMode) cm.replaceRange('', curStart, curEnd);
2829
          // special case, where vim help says to replace by just one line-break
2830
          (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
2831
        } else {
2832
          var replaceWithStr = cm.getRange(curStart, curEnd);
2833
          //replace all characters in range by selected, but keep linebreaks
2834
          replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith);
2835
          if (vim.visualBlock) {
2836
            // Tabs are split in visua block before replacing
2837
            var spaces = new Array(cm.getOption("tabSize")+1).join(' ');
2838
            replaceWithStr = cm.getSelection();
2839
            replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n');
2840
            cm.replaceSelections(replaceWithStr);
2841
          } else {
2842
            cm.replaceRange(replaceWithStr, curStart, curEnd);
2843
          }
2844
          if (vim.visualMode) {
2845
            curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ?
2846
                         selections[0].anchor : selections[0].head;
2847
            cm.setCursor(curStart);
2848
            exitVisualMode(cm, false);
2849
          } else {
2850
            cm.setCursor(offsetCursor(curEnd, 0, -1));
2851
          }
2852
        }
2853
      },
2854
      incrementNumberToken: function(cm, actionArgs) {
2855
        var cur = cm.getCursor();
2856
        var lineStr = cm.getLine(cur.line);
2857
        var re = /(-?)(?:(0x)([\da-f]+)|(0b|0|)(\d+))/gi;
2858
        var match;
2859
        var start;
2860
        var end;
2861
        var numberStr;
2862
        while ((match = re.exec(lineStr)) !== null) {
2863
          start = match.index;
2864
          end = start + match[0].length;
2865
          if (cur.ch < end)break;
2866
        }
2867
        if (!actionArgs.backtrack && (end <= cur.ch))return;
2868
        if (match) {
2869
          var baseStr = match[2] || match[4]
2870
          var digits = match[3] || match[5]
2871
          var increment = actionArgs.increase ? 1 : -1;
2872
          var base = {'0b': 2, '0': 8, '': 10, '0x': 16}[baseStr.toLowerCase()];
2873
          var number = parseInt(match[1] + digits, base) + (increment * actionArgs.repeat);
2874
          numberStr = number.toString(base);
2875
          var zeroPadding = baseStr ? new Array(digits.length - numberStr.length + 1 + match[1].length).join('0') : ''
2876
          if (numberStr.charAt(0) === '-') {
2877
            numberStr = '-' + baseStr + zeroPadding + numberStr.substr(1);
2878
          } else {
2879
            numberStr = baseStr + zeroPadding + numberStr;
2880
          }
2881
          var from = new Pos(cur.line, start);
2882
          var to = new Pos(cur.line, end);
2883
          cm.replaceRange(numberStr, from, to);
2884
        } else {
2885
          return;
2886
        }
2887
        cm.setCursor(new Pos(cur.line, start + numberStr.length - 1));
2888
      },
2889
      repeatLastEdit: function(cm, actionArgs, vim) {
2890
        var lastEditInputState = vim.lastEditInputState;
2891
        if (!lastEditInputState) { return; }
2892
        var repeat = actionArgs.repeat;
2893
        if (repeat && actionArgs.repeatIsExplicit) {
2894
          vim.lastEditInputState.repeatOverride = repeat;
2895
        } else {
2896
          repeat = vim.lastEditInputState.repeatOverride || repeat;
2897
        }
2898
        repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
2899
      },
2900
      indent: function(cm, actionArgs) {
2901
        cm.indentLine(cm.getCursor().line, actionArgs.indentRight);
2902
      },
2903
      exitInsertMode: exitInsertMode
2904
    };
2905

2906
    function defineAction(name, fn) {
2907
      actions[name] = fn;
2908
    }
2909

2910
    /*
2911
     * Below are miscellaneous utility functions used by vim.js
2912
     */
2913

2914
    /**
2915
     * Clips cursor to ensure that line is within the buffer's range
2916
     * If includeLineBreak is true, then allow cur.ch == lineLength.
2917
     */
2918
    function clipCursorToContent(cm, cur) {
2919
      var vim = cm.state.vim;
2920
      var includeLineBreak = vim.insertMode || vim.visualMode;
2921
      var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
2922
      var maxCh = lineLength(cm, line) - 1 + !!includeLineBreak;
2923
      var ch = Math.min(Math.max(0, cur.ch), maxCh);
2924
      return new Pos(line, ch);
2925
    }
2926
    function copyArgs(args) {
2927
      var ret = {};
2928
      for (var prop in args) {
2929
        if (args.hasOwnProperty(prop)) {
2930
          ret[prop] = args[prop];
2931
        }
2932
      }
2933
      return ret;
2934
    }
2935
    function offsetCursor(cur, offsetLine, offsetCh) {
2936
      if (typeof offsetLine === 'object') {
2937
        offsetCh = offsetLine.ch;
2938
        offsetLine = offsetLine.line;
2939
      }
2940
      return new Pos(cur.line + offsetLine, cur.ch + offsetCh);
2941
    }
2942
    function commandMatches(keys, keyMap, context, inputState) {
2943
      // Partial matches are not applied. They inform the key handler
2944
      // that the current key sequence is a subsequence of a valid key
2945
      // sequence, so that the key buffer is not cleared.
2946
      var match, partial = [], full = [];
2947
      for (var i = 0; i < keyMap.length; i++) {
2948
        var command = keyMap[i];
2949
        if (context == 'insert' && command.context != 'insert' ||
2950
            command.context && command.context != context ||
2951
            inputState.operator && command.type == 'action' ||
2952
            !(match = commandMatch(keys, command.keys))) { continue; }
2953
        if (match == 'partial') { partial.push(command); }
2954
        if (match == 'full') { full.push(command); }
2955
      }
2956
      return {
2957
        partial: partial.length && partial,
2958
        full: full.length && full
2959
      };
2960
    }
2961
    function commandMatch(pressed, mapped) {
2962
      if (mapped.slice(-11) == '<character>') {
2963
        // Last character matches anything.
2964
        var prefixLen = mapped.length - 11;
2965
        var pressedPrefix = pressed.slice(0, prefixLen);
2966
        var mappedPrefix = mapped.slice(0, prefixLen);
2967
        return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' :
2968
               mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false;
2969
      } else {
2970
        return pressed == mapped ? 'full' :
2971
               mapped.indexOf(pressed) == 0 ? 'partial' : false;
2972
      }
2973
    }
2974
    function lastChar(keys) {
2975
      var match = /^.*(<[^>]+>)$/.exec(keys);
2976
      var selectedCharacter = match ? match[1] : keys.slice(-1);
2977
      if (selectedCharacter.length > 1){
2978
        switch(selectedCharacter){
2979
          case '<CR>':
2980
            selectedCharacter='\n';
2981
            break;
2982
          case '<Space>':
2983
            selectedCharacter=' ';
2984
            break;
2985
          default:
2986
            selectedCharacter='';
2987
            break;
2988
        }
2989
      }
2990
      return selectedCharacter;
2991
    }
2992
    function repeatFn(cm, fn, repeat) {
2993
      return function() {
2994
        for (var i = 0; i < repeat; i++) {
2995
          fn(cm);
2996
        }
2997
      };
2998
    }
2999
    function copyCursor(cur) {
3000
      return new Pos(cur.line, cur.ch);
3001
    }
3002
    function cursorEqual(cur1, cur2) {
3003
      return cur1.ch == cur2.ch && cur1.line == cur2.line;
3004
    }
3005
    function cursorIsBefore(cur1, cur2) {
3006
      if (cur1.line < cur2.line) {
3007
        return true;
3008
      }
3009
      if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
3010
        return true;
3011
      }
3012
      return false;
3013
    }
3014
    function cursorMin(cur1, cur2) {
3015
      if (arguments.length > 2) {
3016
        cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));
3017
      }
3018
      return cursorIsBefore(cur1, cur2) ? cur1 : cur2;
3019
    }
3020
    function cursorMax(cur1, cur2) {
3021
      if (arguments.length > 2) {
3022
        cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));
3023
      }
3024
      return cursorIsBefore(cur1, cur2) ? cur2 : cur1;
3025
    }
3026
    function cursorIsBetween(cur1, cur2, cur3) {
3027
      // returns true if cur2 is between cur1 and cur3.
3028
      var cur1before2 = cursorIsBefore(cur1, cur2);
3029
      var cur2before3 = cursorIsBefore(cur2, cur3);
3030
      return cur1before2 && cur2before3;
3031
    }
3032
    function lineLength(cm, lineNum) {
3033
      return cm.getLine(lineNum).length;
3034
    }
3035
    function trim(s) {
3036
      if (s.trim) {
3037
        return s.trim();
3038
      }
3039
      return s.replace(/^\s+|\s+$/g, '');
3040
    }
3041
    function escapeRegex(s) {
3042
      return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
3043
    }
3044
    function extendLineToColumn(cm, lineNum, column) {
3045
      var endCh = lineLength(cm, lineNum);
3046
      var spaces = new Array(column-endCh+1).join(' ');
3047
      cm.setCursor(new Pos(lineNum, endCh));
3048
      cm.replaceRange(spaces, cm.getCursor());
3049
    }
3050
    // This functions selects a rectangular block
3051
    // of text with selectionEnd as any of its corner
3052
    // Height of block:
3053
    // Difference in selectionEnd.line and first/last selection.line
3054
    // Width of the block:
3055
    // Distance between selectionEnd.ch and any(first considered here) selection.ch
3056
    function selectBlock(cm, selectionEnd) {
3057
      var selections = [], ranges = cm.listSelections();
3058
      var head = copyCursor(cm.clipPos(selectionEnd));
3059
      var isClipped = !cursorEqual(selectionEnd, head);
3060
      var curHead = cm.getCursor('head');
3061
      var primIndex = getIndex(ranges, curHead);
3062
      var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor);
3063
      var max = ranges.length - 1;
3064
      var index = max - primIndex > primIndex ? max : 0;
3065
      var base = ranges[index].anchor;
3066

3067
      var firstLine = Math.min(base.line, head.line);
3068
      var lastLine = Math.max(base.line, head.line);
3069
      var baseCh = base.ch, headCh = head.ch;
3070

3071
      var dir = ranges[index].head.ch - baseCh;
3072
      var newDir = headCh - baseCh;
3073
      if (dir > 0 && newDir <= 0) {
3074
        baseCh++;
3075
        if (!isClipped) { headCh--; }
3076
      } else if (dir < 0 && newDir >= 0) {
3077
        baseCh--;
3078
        if (!wasClipped) { headCh++; }
3079
      } else if (dir < 0 && newDir == -1) {
3080
        baseCh--;
3081
        headCh++;
3082
      }
3083
      for (var line = firstLine; line <= lastLine; line++) {
3084
        var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)};
3085
        selections.push(range);
3086
      }
3087
      cm.setSelections(selections);
3088
      selectionEnd.ch = headCh;
3089
      base.ch = baseCh;
3090
      return base;
3091
    }
3092
    function selectForInsert(cm, head, height) {
3093
      var sel = [];
3094
      for (var i = 0; i < height; i++) {
3095
        var lineHead = offsetCursor(head, i, 0);
3096
        sel.push({anchor: lineHead, head: lineHead});
3097
      }
3098
      cm.setSelections(sel, 0);
3099
    }
3100
    // getIndex returns the index of the cursor in the selections.
3101
    function getIndex(ranges, cursor, end) {
3102
      for (var i = 0; i < ranges.length; i++) {
3103
        var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor);
3104
        var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor);
3105
        if (atAnchor || atHead) {
3106
          return i;
3107
        }
3108
      }
3109
      return -1;
3110
    }
3111
    function getSelectedAreaRange(cm, vim) {
3112
      var lastSelection = vim.lastSelection;
3113
      var getCurrentSelectedAreaRange = function() {
3114
        var selections = cm.listSelections();
3115
        var start =  selections[0];
3116
        var end = selections[selections.length-1];
3117
        var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
3118
        var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
3119
        return [selectionStart, selectionEnd];
3120
      };
3121
      var getLastSelectedAreaRange = function() {
3122
        var selectionStart = cm.getCursor();
3123
        var selectionEnd = cm.getCursor();
3124
        var block = lastSelection.visualBlock;
3125
        if (block) {
3126
          var width = block.width;
3127
          var height = block.height;
3128
          selectionEnd = new Pos(selectionStart.line + height, selectionStart.ch + width);
3129
          var selections = [];
3130
          // selectBlock creates a 'proper' rectangular block.
3131
          // We do not want that in all cases, so we manually set selections.
3132
          for (var i = selectionStart.line; i < selectionEnd.line; i++) {
3133
            var anchor = new Pos(i, selectionStart.ch);
3134
            var head = new Pos(i, selectionEnd.ch);
3135
            var range = {anchor: anchor, head: head};
3136
            selections.push(range);
3137
          }
3138
          cm.setSelections(selections);
3139
        } else {
3140
          var start = lastSelection.anchorMark.find();
3141
          var end = lastSelection.headMark.find();
3142
          var line = end.line - start.line;
3143
          var ch = end.ch - start.ch;
3144
          selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch};
3145
          if (lastSelection.visualLine) {
3146
            selectionStart = new Pos(selectionStart.line, 0);
3147
            selectionEnd = new Pos(selectionEnd.line, lineLength(cm, selectionEnd.line));
3148
          }
3149
          cm.setSelection(selectionStart, selectionEnd);
3150
        }
3151
        return [selectionStart, selectionEnd];
3152
      };
3153
      if (!vim.visualMode) {
3154
      // In case of replaying the action.
3155
        return getLastSelectedAreaRange();
3156
      } else {
3157
        return getCurrentSelectedAreaRange();
3158
      }
3159
    }
3160
    // Updates the previous selection with the current selection's values. This
3161
    // should only be called in visual mode.
3162
    function updateLastSelection(cm, vim) {
3163
      var anchor = vim.sel.anchor;
3164
      var head = vim.sel.head;
3165
      // To accommodate the effect of lastPastedText in the last selection
3166
      if (vim.lastPastedText) {
3167
        head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);
3168
        vim.lastPastedText = null;
3169
      }
3170
      vim.lastSelection = {'anchorMark': cm.setBookmark(anchor),
3171
                           'headMark': cm.setBookmark(head),
3172
                           'anchor': copyCursor(anchor),
3173
                           'head': copyCursor(head),
3174
                           'visualMode': vim.visualMode,
3175
                           'visualLine': vim.visualLine,
3176
                           'visualBlock': vim.visualBlock};
3177
    }
3178
    function expandSelection(cm, start, end) {
3179
      var sel = cm.state.vim.sel;
3180
      var head = sel.head;
3181
      var anchor = sel.anchor;
3182
      var tmp;
3183
      if (cursorIsBefore(end, start)) {
3184
        tmp = end;
3185
        end = start;
3186
        start = tmp;
3187
      }
3188
      if (cursorIsBefore(head, anchor)) {
3189
        head = cursorMin(start, head);
3190
        anchor = cursorMax(anchor, end);
3191
      } else {
3192
        anchor = cursorMin(start, anchor);
3193
        head = cursorMax(head, end);
3194
        head = offsetCursor(head, 0, -1);
3195
        if (head.ch == -1 && head.line != cm.firstLine()) {
3196
          head = new Pos(head.line - 1, lineLength(cm, head.line - 1));
3197
        }
3198
      }
3199
      return [anchor, head];
3200
    }
3201
    /**
3202
     * Updates the CodeMirror selection to match the provided vim selection.
3203
     * If no arguments are given, it uses the current vim selection state.
3204
     */
3205
    function updateCmSelection(cm, sel, mode) {
3206
      var vim = cm.state.vim;
3207
      sel = sel || vim.sel;
3208
      var mode = mode ||
3209
        vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';
3210
      var cmSel = makeCmSelection(cm, sel, mode);
3211
      cm.setSelections(cmSel.ranges, cmSel.primary);
3212
    }
3213
    function makeCmSelection(cm, sel, mode, exclusive) {
3214
      var head = copyCursor(sel.head);
3215
      var anchor = copyCursor(sel.anchor);
3216
      if (mode == 'char') {
3217
        var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
3218
        var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
3219
        head = offsetCursor(sel.head, 0, headOffset);
3220
        anchor = offsetCursor(sel.anchor, 0, anchorOffset);
3221
        return {
3222
          ranges: [{anchor: anchor, head: head}],
3223
          primary: 0
3224
        };
3225
      } else if (mode == 'line') {
3226
        if (!cursorIsBefore(sel.head, sel.anchor)) {
3227
          anchor.ch = 0;
3228

3229
          var lastLine = cm.lastLine();
3230
          if (head.line > lastLine) {
3231
            head.line = lastLine;
3232
          }
3233
          head.ch = lineLength(cm, head.line);
3234
        } else {
3235
          head.ch = 0;
3236
          anchor.ch = lineLength(cm, anchor.line);
3237
        }
3238
        return {
3239
          ranges: [{anchor: anchor, head: head}],
3240
          primary: 0
3241
        };
3242
      } else if (mode == 'block') {
3243
        var top = Math.min(anchor.line, head.line),
3244
            fromCh = anchor.ch,
3245
            bottom = Math.max(anchor.line, head.line),
3246
            toCh = head.ch;
3247
        if (fromCh < toCh) { toCh += 1 }
3248
        else { fromCh += 1 };
3249
        var height = bottom - top + 1;
3250
        var primary = head.line == top ? 0 : height - 1;
3251
        var ranges = [];
3252
        for (var i = 0; i < height; i++) {
3253
          ranges.push({
3254
            anchor: new Pos(top + i, fromCh),
3255
            head: new Pos(top + i, toCh)
3256
          });
3257
        }
3258
        return {
3259
          ranges: ranges,
3260
          primary: primary
3261
        };
3262
      }
3263
    }
3264
    function getHead(cm) {
3265
      var cur = cm.getCursor('head');
3266
      if (cm.getSelection().length == 1) {
3267
        // Small corner case when only 1 character is selected. The "real"
3268
        // head is the left of head and anchor.
3269
        cur = cursorMin(cur, cm.getCursor('anchor'));
3270
      }
3271
      return cur;
3272
    }
3273

3274
    /**
3275
     * If moveHead is set to false, the CodeMirror selection will not be
3276
     * touched. The caller assumes the responsibility of putting the cursor
3277
    * in the right place.
3278
     */
3279
    function exitVisualMode(cm, moveHead) {
3280
      var vim = cm.state.vim;
3281
      if (moveHead !== false) {
3282
        cm.setCursor(clipCursorToContent(cm, vim.sel.head));
3283
      }
3284
      updateLastSelection(cm, vim);
3285
      vim.visualMode = false;
3286
      vim.visualLine = false;
3287
      vim.visualBlock = false;
3288
      if (!vim.insertMode) CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
3289
    }
3290

3291
    // Remove any trailing newlines from the selection. For
3292
    // example, with the caret at the start of the last word on the line,
3293
    // 'dw' should word, but not the newline, while 'w' should advance the
3294
    // caret to the first character of the next line.
3295
    function clipToLine(cm, curStart, curEnd) {
3296
      var selection = cm.getRange(curStart, curEnd);
3297
      // Only clip if the selection ends with trailing newline + whitespace
3298
      if (/\n\s*$/.test(selection)) {
3299
        var lines = selection.split('\n');
3300
        // We know this is all whitespace.
3301
        lines.pop();
3302

3303
        // Cases:
3304
        // 1. Last word is an empty line - do not clip the trailing '\n'
3305
        // 2. Last word is not an empty line - clip the trailing '\n'
3306
        var line;
3307
        // Find the line containing the last word, and clip all whitespace up
3308
        // to it.
3309
        for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
3310
          curEnd.line--;
3311
          curEnd.ch = 0;
3312
        }
3313
        // If the last word is not an empty line, clip an additional newline
3314
        if (line) {
3315
          curEnd.line--;
3316
          curEnd.ch = lineLength(cm, curEnd.line);
3317
        } else {
3318
          curEnd.ch = 0;
3319
        }
3320
      }
3321
    }
3322

3323
    // Expand the selection to line ends.
3324
    function expandSelectionToLine(_cm, curStart, curEnd) {
3325
      curStart.ch = 0;
3326
      curEnd.ch = 0;
3327
      curEnd.line++;
3328
    }
3329

3330
    function findFirstNonWhiteSpaceCharacter(text) {
3331
      if (!text) {
3332
        return 0;
3333
      }
3334
      var firstNonWS = text.search(/\S/);
3335
      return firstNonWS == -1 ? text.length : firstNonWS;
3336
    }
3337

3338
    function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
3339
      var cur = getHead(cm);
3340
      var line = cm.getLine(cur.line);
3341
      var idx = cur.ch;
3342

3343
      // Seek to first word or non-whitespace character, depending on if
3344
      // noSymbol is true.
3345
      var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0];
3346
      while (!test(line.charAt(idx))) {
3347
        idx++;
3348
        if (idx >= line.length) { return null; }
3349
      }
3350

3351
      if (bigWord) {
3352
        test = bigWordCharTest[0];
3353
      } else {
3354
        test = wordCharTest[0];
3355
        if (!test(line.charAt(idx))) {
3356
          test = wordCharTest[1];
3357
        }
3358
      }
3359

3360
      var end = idx, start = idx;
3361
      while (test(line.charAt(end)) && end < line.length) { end++; }
3362
      while (test(line.charAt(start)) && start >= 0) { start--; }
3363
      start++;
3364

3365
      if (inclusive) {
3366
        // If present, include all whitespace after word.
3367
        // Otherwise, include all whitespace before word, except indentation.
3368
        var wordEnd = end;
3369
        while (/\s/.test(line.charAt(end)) && end < line.length) { end++; }
3370
        if (wordEnd == end) {
3371
          var wordStart = start;
3372
          while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; }
3373
          if (!start) { start = wordStart; }
3374
        }
3375
      }
3376
      return { start: new Pos(cur.line, start), end: new Pos(cur.line, end) };
3377
    }
3378

3379
    /**
3380
     * Depends on the following:
3381
     *
3382
     * - editor mode should be htmlmixedmode / xml
3383
     * - mode/xml/xml.js should be loaded
3384
     * - addon/fold/xml-fold.js should be loaded
3385
     *
3386
     * If any of the above requirements are not true, this function noops.
3387
     *
3388
     * This is _NOT_ a 100% accurate implementation of vim tag text objects.
3389
     * The following caveats apply (based off cursory testing, I'm sure there
3390
     * are other discrepancies):
3391
     *
3392
     * - Does not work inside comments:
3393
     *   ```
3394
     *   <!-- <div>broken</div> -->
3395
     *   ```
3396
     * - Does not work when tags have different cases:
3397
     *   ```
3398
     *   <div>broken</DIV>
3399
     *   ```
3400
     * - Does not work when cursor is inside a broken tag:
3401
     *   ```
3402
     *   <div><brok><en></div>
3403
     *   ```
3404
     */
3405
    function expandTagUnderCursor(cm, head, inclusive) {
3406
      var cur = head;
3407
      if (!CodeMirror.findMatchingTag || !CodeMirror.findEnclosingTag) {
3408
        return { start: cur, end: cur };
3409
      }
3410

3411
      var tags = CodeMirror.findMatchingTag(cm, head) || CodeMirror.findEnclosingTag(cm, head);
3412
      if (!tags || !tags.open || !tags.close) {
3413
        return { start: cur, end: cur };
3414
      }
3415

3416
      if (inclusive) {
3417
        return { start: tags.open.from, end: tags.close.to };
3418
      }
3419
      return { start: tags.open.to, end: tags.close.from };
3420
    }
3421

3422
    function recordJumpPosition(cm, oldCur, newCur) {
3423
      if (!cursorEqual(oldCur, newCur)) {
3424
        vimGlobalState.jumpList.add(cm, oldCur, newCur);
3425
      }
3426
    }
3427

3428
    function recordLastCharacterSearch(increment, args) {
3429
        vimGlobalState.lastCharacterSearch.increment = increment;
3430
        vimGlobalState.lastCharacterSearch.forward = args.forward;
3431
        vimGlobalState.lastCharacterSearch.selectedCharacter = args.selectedCharacter;
3432
    }
3433

3434
    var symbolToMode = {
3435
        '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
3436
        '[': 'section', ']': 'section',
3437
        '*': 'comment', '/': 'comment',
3438
        'm': 'method', 'M': 'method',
3439
        '#': 'preprocess'
3440
    };
3441
    var findSymbolModes = {
3442
      bracket: {
3443
        isComplete: function(state) {
3444
          if (state.nextCh === state.symb) {
3445
            state.depth++;
3446
            if (state.depth >= 1)return true;
3447
          } else if (state.nextCh === state.reverseSymb) {
3448
            state.depth--;
3449
          }
3450
          return false;
3451
        }
3452
      },
3453
      section: {
3454
        init: function(state) {
3455
          state.curMoveThrough = true;
3456
          state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
3457
        },
3458
        isComplete: function(state) {
3459
          return state.index === 0 && state.nextCh === state.symb;
3460
        }
3461
      },
3462
      comment: {
3463
        isComplete: function(state) {
3464
          var found = state.lastCh === '*' && state.nextCh === '/';
3465
          state.lastCh = state.nextCh;
3466
          return found;
3467
        }
3468
      },
3469
      // TODO: The original Vim implementation only operates on level 1 and 2.
3470
      // The current implementation doesn't check for code block level and
3471
      // therefore it operates on any levels.
3472
      method: {
3473
        init: function(state) {
3474
          state.symb = (state.symb === 'm' ? '{' : '}');
3475
          state.reverseSymb = state.symb === '{' ? '}' : '{';
3476
        },
3477
        isComplete: function(state) {
3478
          if (state.nextCh === state.symb)return true;
3479
          return false;
3480
        }
3481
      },
3482
      preprocess: {
3483
        init: function(state) {
3484
          state.index = 0;
3485
        },
3486
        isComplete: function(state) {
3487
          if (state.nextCh === '#') {
3488
            var token = state.lineText.match(/^#(\w+)/)[1];
3489
            if (token === 'endif') {
3490
              if (state.forward && state.depth === 0) {
3491
                return true;
3492
              }
3493
              state.depth++;
3494
            } else if (token === 'if') {
3495
              if (!state.forward && state.depth === 0) {
3496
                return true;
3497
              }
3498
              state.depth--;
3499
            }
3500
            if (token === 'else' && state.depth === 0)return true;
3501
          }
3502
          return false;
3503
        }
3504
      }
3505
    };
3506
    function findSymbol(cm, repeat, forward, symb) {
3507
      var cur = copyCursor(cm.getCursor());
3508
      var increment = forward ? 1 : -1;
3509
      var endLine = forward ? cm.lineCount() : -1;
3510
      var curCh = cur.ch;
3511
      var line = cur.line;
3512
      var lineText = cm.getLine(line);
3513
      var state = {
3514
        lineText: lineText,
3515
        nextCh: lineText.charAt(curCh),
3516
        lastCh: null,
3517
        index: curCh,
3518
        symb: symb,
3519
        reverseSymb: (forward ?  { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
3520
        forward: forward,
3521
        depth: 0,
3522
        curMoveThrough: false
3523
      };
3524
      var mode = symbolToMode[symb];
3525
      if (!mode)return cur;
3526
      var init = findSymbolModes[mode].init;
3527
      var isComplete = findSymbolModes[mode].isComplete;
3528
      if (init) { init(state); }
3529
      while (line !== endLine && repeat) {
3530
        state.index += increment;
3531
        state.nextCh = state.lineText.charAt(state.index);
3532
        if (!state.nextCh) {
3533
          line += increment;
3534
          state.lineText = cm.getLine(line) || '';
3535
          if (increment > 0) {
3536
            state.index = 0;
3537
          } else {
3538
            var lineLen = state.lineText.length;
3539
            state.index = (lineLen > 0) ? (lineLen-1) : 0;
3540
          }
3541
          state.nextCh = state.lineText.charAt(state.index);
3542
        }
3543
        if (isComplete(state)) {
3544
          cur.line = line;
3545
          cur.ch = state.index;
3546
          repeat--;
3547
        }
3548
      }
3549
      if (state.nextCh || state.curMoveThrough) {
3550
        return new Pos(line, state.index);
3551
      }
3552
      return cur;
3553
    }
3554

3555
    /*
3556
     * Returns the boundaries of the next word. If the cursor in the middle of
3557
     * the word, then returns the boundaries of the current word, starting at
3558
     * the cursor. If the cursor is at the start/end of a word, and we are going
3559
     * forward/backward, respectively, find the boundaries of the next word.
3560
     *
3561
     * @param {CodeMirror} cm CodeMirror object.
3562
     * @param {Cursor} cur The cursor position.
3563
     * @param {boolean} forward True to search forward. False to search
3564
     *     backward.
3565
     * @param {boolean} bigWord True if punctuation count as part of the word.
3566
     *     False if only [a-zA-Z0-9] characters count as part of the word.
3567
     * @param {boolean} emptyLineIsWord True if empty lines should be treated
3568
     *     as words.
3569
     * @return {Object{from:number, to:number, line: number}} The boundaries of
3570
     *     the word, or null if there are no more words.
3571
     */
3572
    function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
3573
      var lineNum = cur.line;
3574
      var pos = cur.ch;
3575
      var line = cm.getLine(lineNum);
3576
      var dir = forward ? 1 : -1;
3577
      var charTests = bigWord ? bigWordCharTest: wordCharTest;
3578

3579
      if (emptyLineIsWord && line == '') {
3580
        lineNum += dir;
3581
        line = cm.getLine(lineNum);
3582
        if (!isLine(cm, lineNum)) {
3583
          return null;
3584
        }
3585
        pos = (forward) ? 0 : line.length;
3586
      }
3587

3588
      while (true) {
3589
        if (emptyLineIsWord && line == '') {
3590
          return { from: 0, to: 0, line: lineNum };
3591
        }
3592
        var stop = (dir > 0) ? line.length : -1;
3593
        var wordStart = stop, wordEnd = stop;
3594
        // Find bounds of next word.
3595
        while (pos != stop) {
3596
          var foundWord = false;
3597
          for (var i = 0; i < charTests.length && !foundWord; ++i) {
3598
            if (charTests[i](line.charAt(pos))) {
3599
              wordStart = pos;
3600
              // Advance to end of word.
3601
              while (pos != stop && charTests[i](line.charAt(pos))) {
3602
                pos += dir;
3603
              }
3604
              wordEnd = pos;
3605
              foundWord = wordStart != wordEnd;
3606
              if (wordStart == cur.ch && lineNum == cur.line &&
3607
                  wordEnd == wordStart + dir) {
3608
                // We started at the end of a word. Find the next one.
3609
                continue;
3610
              } else {
3611
                return {
3612
                  from: Math.min(wordStart, wordEnd + 1),
3613
                  to: Math.max(wordStart, wordEnd),
3614
                  line: lineNum };
3615
              }
3616
            }
3617
          }
3618
          if (!foundWord) {
3619
            pos += dir;
3620
          }
3621
        }
3622
        // Advance to next/prev line.
3623
        lineNum += dir;
3624
        if (!isLine(cm, lineNum)) {
3625
          return null;
3626
        }
3627
        line = cm.getLine(lineNum);
3628
        pos = (dir > 0) ? 0 : line.length;
3629
      }
3630
    }
3631

3632
    /**
3633
     * @param {CodeMirror} cm CodeMirror object.
3634
     * @param {Pos} cur The position to start from.
3635
     * @param {int} repeat Number of words to move past.
3636
     * @param {boolean} forward True to search forward. False to search
3637
     *     backward.
3638
     * @param {boolean} wordEnd True to move to end of word. False to move to
3639
     *     beginning of word.
3640
     * @param {boolean} bigWord True if punctuation count as part of the word.
3641
     *     False if only alphabet characters count as part of the word.
3642
     * @return {Cursor} The position the cursor should move to.
3643
     */
3644
    function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {
3645
      var curStart = copyCursor(cur);
3646
      var words = [];
3647
      if (forward && !wordEnd || !forward && wordEnd) {
3648
        repeat++;
3649
      }
3650
      // For 'e', empty lines are not considered words, go figure.
3651
      var emptyLineIsWord = !(forward && wordEnd);
3652
      for (var i = 0; i < repeat; i++) {
3653
        var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
3654
        if (!word) {
3655
          var eodCh = lineLength(cm, cm.lastLine());
3656
          words.push(forward
3657
              ? {line: cm.lastLine(), from: eodCh, to: eodCh}
3658
              : {line: 0, from: 0, to: 0});
3659
          break;
3660
        }
3661
        words.push(word);
3662
        cur = new Pos(word.line, forward ? (word.to - 1) : word.from);
3663
      }
3664
      var shortCircuit = words.length != repeat;
3665
      var firstWord = words[0];
3666
      var lastWord = words.pop();
3667
      if (forward && !wordEnd) {
3668
        // w
3669
        if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
3670
          // We did not start in the middle of a word. Discard the extra word at the end.
3671
          lastWord = words.pop();
3672
        }
3673
        return new Pos(lastWord.line, lastWord.from);
3674
      } else if (forward && wordEnd) {
3675
        return new Pos(lastWord.line, lastWord.to - 1);
3676
      } else if (!forward && wordEnd) {
3677
        // ge
3678
        if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
3679
          // We did not start in the middle of a word. Discard the extra word at the end.
3680
          lastWord = words.pop();
3681
        }
3682
        return new Pos(lastWord.line, lastWord.to);
3683
      } else {
3684
        // b
3685
        return new Pos(lastWord.line, lastWord.from);
3686
      }
3687
    }
3688

3689
    function moveToEol(cm, head, motionArgs, vim, keepHPos) {
3690
      var cur = head;
3691
      var retval= new Pos(cur.line + motionArgs.repeat - 1, Infinity);
3692
      var end=cm.clipPos(retval);
3693
      end.ch--;
3694
      if (!keepHPos) {
3695
        vim.lastHPos = Infinity;
3696
        vim.lastHSPos = cm.charCoords(end,'div').left;
3697
      }
3698
      return retval;
3699
    }
3700

3701
    function moveToCharacter(cm, repeat, forward, character) {
3702
      var cur = cm.getCursor();
3703
      var start = cur.ch;
3704
      var idx;
3705
      for (var i = 0; i < repeat; i ++) {
3706
        var line = cm.getLine(cur.line);
3707
        idx = charIdxInLine(start, line, character, forward, true);
3708
        if (idx == -1) {
3709
          return null;
3710
        }
3711
        start = idx;
3712
      }
3713
      return new Pos(cm.getCursor().line, idx);
3714
    }
3715

3716
    function moveToColumn(cm, repeat) {
3717
      // repeat is always >= 1, so repeat - 1 always corresponds
3718
      // to the column we want to go to.
3719
      var line = cm.getCursor().line;
3720
      return clipCursorToContent(cm, new Pos(line, repeat - 1));
3721
    }
3722

3723
    function updateMark(cm, vim, markName, pos) {
3724
      if (!inArray(markName, validMarks)) {
3725
        return;
3726
      }
3727
      if (vim.marks[markName]) {
3728
        vim.marks[markName].clear();
3729
      }
3730
      vim.marks[markName] = cm.setBookmark(pos);
3731
    }
3732

3733
    function charIdxInLine(start, line, character, forward, includeChar) {
3734
      // Search for char in line.
3735
      // motion_options: {forward, includeChar}
3736
      // If includeChar = true, include it too.
3737
      // If forward = true, search forward, else search backwards.
3738
      // If char is not found on this line, do nothing
3739
      var idx;
3740
      if (forward) {
3741
        idx = line.indexOf(character, start + 1);
3742
        if (idx != -1 && !includeChar) {
3743
          idx -= 1;
3744
        }
3745
      } else {
3746
        idx = line.lastIndexOf(character, start - 1);
3747
        if (idx != -1 && !includeChar) {
3748
          idx += 1;
3749
        }
3750
      }
3751
      return idx;
3752
    }
3753

3754
    function findParagraph(cm, head, repeat, dir, inclusive) {
3755
      var line = head.line;
3756
      var min = cm.firstLine();
3757
      var max = cm.lastLine();
3758
      var start, end, i = line;
3759
      function isEmpty(i) { return !cm.getLine(i); }
3760
      function isBoundary(i, dir, any) {
3761
        if (any) { return isEmpty(i) != isEmpty(i + dir); }
3762
        return !isEmpty(i) && isEmpty(i + dir);
3763
      }
3764
      if (dir) {
3765
        while (min <= i && i <= max && repeat > 0) {
3766
          if (isBoundary(i, dir)) { repeat--; }
3767
          i += dir;
3768
        }
3769
        return new Pos(i, 0);
3770
      }
3771

3772
      var vim = cm.state.vim;
3773
      if (vim.visualLine && isBoundary(line, 1, true)) {
3774
        var anchor = vim.sel.anchor;
3775
        if (isBoundary(anchor.line, -1, true)) {
3776
          if (!inclusive || anchor.line != line) {
3777
            line += 1;
3778
          }
3779
        }
3780
      }
3781
      var startState = isEmpty(line);
3782
      for (i = line; i <= max && repeat; i++) {
3783
        if (isBoundary(i, 1, true)) {
3784
          if (!inclusive || isEmpty(i) != startState) {
3785
            repeat--;
3786
          }
3787
        }
3788
      }
3789
      end = new Pos(i, 0);
3790
      // select boundary before paragraph for the last one
3791
      if (i > max && !startState) { startState = true; }
3792
      else { inclusive = false; }
3793
      for (i = line; i > min; i--) {
3794
        if (!inclusive || isEmpty(i) == startState || i == line) {
3795
          if (isBoundary(i, -1, true)) { break; }
3796
        }
3797
      }
3798
      start = new Pos(i, 0);
3799
      return { start: start, end: end };
3800
    }
3801

3802
    function findSentence(cm, cur, repeat, dir) {
3803

3804
      /*
3805
        Takes an index object
3806
        {
3807
          line: the line string,
3808
          ln: line number,
3809
          pos: index in line,
3810
          dir: direction of traversal (-1 or 1)
3811
        }
3812
        and modifies the line, ln, and pos members to represent the
3813
        next valid position or sets them to null if there are
3814
        no more valid positions.
3815
       */
3816
      function nextChar(cm, idx) {
3817
        if (idx.pos + idx.dir < 0 || idx.pos + idx.dir >= idx.line.length) {
3818
          idx.ln += idx.dir;
3819
          if (!isLine(cm, idx.ln)) {
3820
            idx.line = null;
3821
            idx.ln = null;
3822
            idx.pos = null;
3823
            return;
3824
          }
3825
          idx.line = cm.getLine(idx.ln);
3826
          idx.pos = (idx.dir > 0) ? 0 : idx.line.length - 1;
3827
        }
3828
        else {
3829
          idx.pos += idx.dir;
3830
        }
3831
      }
3832

3833
      /*
3834
        Performs one iteration of traversal in forward direction
3835
        Returns an index object of the new location
3836
       */
3837
      function forward(cm, ln, pos, dir) {
3838
        var line = cm.getLine(ln);
3839
        var stop = (line === "");
3840

3841
        var curr = {
3842
          line: line,
3843
          ln: ln,
3844
          pos: pos,
3845
          dir: dir,
3846
        }
3847

3848
        var last_valid = {
3849
          ln: curr.ln,
3850
          pos: curr.pos,
3851
        }
3852

3853
        var skip_empty_lines = (curr.line === "");
3854

3855
        // Move one step to skip character we start on
3856
        nextChar(cm, curr);
3857

3858
        while (curr.line !== null) {
3859
          last_valid.ln = curr.ln;
3860
          last_valid.pos = curr.pos;
3861

3862
          if (curr.line === "" && !skip_empty_lines) {
3863
            return { ln: curr.ln, pos: curr.pos, };
3864
          }
3865
          else if (stop && curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
3866
            return { ln: curr.ln, pos: curr.pos, };
3867
          }
3868
          else if (isEndOfSentenceSymbol(curr.line[curr.pos])
3869
            && !stop
3870
            && (curr.pos === curr.line.length - 1
3871
              || isWhiteSpaceString(curr.line[curr.pos + 1]))) {
3872
            stop = true;
3873
          }
3874

3875
          nextChar(cm, curr);
3876
        }
3877

3878
        /*
3879
          Set the position to the last non whitespace character on the last
3880
          valid line in the case that we reach the end of the document.
3881
        */
3882
        var line = cm.getLine(last_valid.ln);
3883
        last_valid.pos = 0;
3884
        for(var i = line.length - 1; i >= 0; --i) {
3885
          if (!isWhiteSpaceString(line[i])) {
3886
            last_valid.pos = i;
3887
            break;
3888
          }
3889
        }
3890

3891
        return last_valid;
3892

3893
      }
3894

3895
      /*
3896
        Performs one iteration of traversal in reverse direction
3897
        Returns an index object of the new location
3898
       */
3899
      function reverse(cm, ln, pos, dir) {
3900
        var line = cm.getLine(ln);
3901

3902
        var curr = {
3903
          line: line,
3904
          ln: ln,
3905
          pos: pos,
3906
          dir: dir,
3907
        }
3908

3909
        var last_valid = {
3910
          ln: curr.ln,
3911
          pos: null,
3912
        };
3913

3914
        var skip_empty_lines = (curr.line === "");
3915

3916
        // Move one step to skip character we start on
3917
        nextChar(cm, curr);
3918

3919
        while (curr.line !== null) {
3920

3921
          if (curr.line === "" && !skip_empty_lines) {
3922
            if (last_valid.pos !== null) {
3923
              return last_valid;
3924
            }
3925
            else {
3926
              return { ln: curr.ln, pos: curr.pos };
3927
            }
3928
          }
3929
          else if (isEndOfSentenceSymbol(curr.line[curr.pos])
3930
              && last_valid.pos !== null
3931
              && !(curr.ln === last_valid.ln && curr.pos + 1 === last_valid.pos)) {
3932
            return last_valid;
3933
          }
3934
          else if (curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
3935
            skip_empty_lines = false;
3936
            last_valid = { ln: curr.ln, pos: curr.pos }
3937
          }
3938

3939
          nextChar(cm, curr);
3940
        }
3941

3942
        /*
3943
          Set the position to the first non whitespace character on the last
3944
          valid line in the case that we reach the beginning of the document.
3945
        */
3946
        var line = cm.getLine(last_valid.ln);
3947
        last_valid.pos = 0;
3948
        for(var i = 0; i < line.length; ++i) {
3949
          if (!isWhiteSpaceString(line[i])) {
3950
            last_valid.pos = i;
3951
            break;
3952
          }
3953
        }
3954
        return last_valid;
3955
      }
3956

3957
      var curr_index = {
3958
        ln: cur.line,
3959
        pos: cur.ch,
3960
      };
3961

3962
      while (repeat > 0) {
3963
        if (dir < 0) {
3964
          curr_index = reverse(cm, curr_index.ln, curr_index.pos, dir);
3965
        }
3966
        else {
3967
          curr_index = forward(cm, curr_index.ln, curr_index.pos, dir);
3968
        }
3969
        repeat--;
3970
      }
3971

3972
      return new Pos(curr_index.ln, curr_index.pos);
3973
    }
3974

3975
    // TODO: perhaps this finagling of start and end positions belongs
3976
    // in codemirror/replaceRange?
3977
    function selectCompanionObject(cm, head, symb, inclusive) {
3978
      var cur = head, start, end;
3979

3980
      var bracketRegexp = ({
3981
        '(': /[()]/, ')': /[()]/,
3982
        '[': /[[\]]/, ']': /[[\]]/,
3983
        '{': /[{}]/, '}': /[{}]/,
3984
        '<': /[<>]/, '>': /[<>]/})[symb];
3985
      var openSym = ({
3986
        '(': '(', ')': '(',
3987
        '[': '[', ']': '[',
3988
        '{': '{', '}': '{',
3989
        '<': '<', '>': '<'})[symb];
3990
      var curChar = cm.getLine(cur.line).charAt(cur.ch);
3991
      // Due to the behavior of scanForBracket, we need to add an offset if the
3992
      // cursor is on a matching open bracket.
3993
      var offset = curChar === openSym ? 1 : 0;
3994

3995
      start = cm.scanForBracket(new Pos(cur.line, cur.ch + offset), -1, undefined, {'bracketRegex': bracketRegexp});
3996
      end = cm.scanForBracket(new Pos(cur.line, cur.ch + offset), 1, undefined, {'bracketRegex': bracketRegexp});
3997

3998
      if (!start || !end) {
3999
        return { start: cur, end: cur };
4000
      }
4001

4002
      start = start.pos;
4003
      end = end.pos;
4004

4005
      if ((start.line == end.line && start.ch > end.ch)
4006
          || (start.line > end.line)) {
4007
        var tmp = start;
4008
        start = end;
4009
        end = tmp;
4010
      }
4011

4012
      if (inclusive) {
4013
        end.ch += 1;
4014
      } else {
4015
        start.ch += 1;
4016
      }
4017

4018
      return { start: start, end: end };
4019
    }
4020

4021
    // Takes in a symbol and a cursor and tries to simulate text objects that
4022
    // have identical opening and closing symbols
4023
    // TODO support across multiple lines
4024
    function findBeginningAndEnd(cm, head, symb, inclusive) {
4025
      var cur = copyCursor(head);
4026
      var line = cm.getLine(cur.line);
4027
      var chars = line.split('');
4028
      var start, end, i, len;
4029
      var firstIndex = chars.indexOf(symb);
4030

4031
      // the decision tree is to always look backwards for the beginning first,
4032
      // but if the cursor is in front of the first instance of the symb,
4033
      // then move the cursor forward
4034
      if (cur.ch < firstIndex) {
4035
        cur.ch = firstIndex;
4036
        // Why is this line even here???
4037
        // cm.setCursor(cur.line, firstIndex+1);
4038
      }
4039
      // otherwise if the cursor is currently on the closing symbol
4040
      else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
4041
        end = cur.ch; // assign end to the current cursor
4042
        --cur.ch; // make sure to look backwards
4043
      }
4044

4045
      // if we're currently on the symbol, we've got a start
4046
      if (chars[cur.ch] == symb && !end) {
4047
        start = cur.ch + 1; // assign start to ahead of the cursor
4048
      } else {
4049
        // go backwards to find the start
4050
        for (i = cur.ch; i > -1 && !start; i--) {
4051
          if (chars[i] == symb) {
4052
            start = i + 1;
4053
          }
4054
        }
4055
      }
4056

4057
      // look forwards for the end symbol
4058
      if (start && !end) {
4059
        for (i = start, len = chars.length; i < len && !end; i++) {
4060
          if (chars[i] == symb) {
4061
            end = i;
4062
          }
4063
        }
4064
      }
4065

4066
      // nothing found
4067
      if (!start || !end) {
4068
        return { start: cur, end: cur };
4069
      }
4070

4071
      // include the symbols
4072
      if (inclusive) {
4073
        --start; ++end;
4074
      }
4075

4076
      return {
4077
        start: new Pos(cur.line, start),
4078
        end: new Pos(cur.line, end)
4079
      };
4080
    }
4081

4082
    // Search functions
4083
    defineOption('pcre', true, 'boolean');
4084
    function SearchState() {}
4085
    SearchState.prototype = {
4086
      getQuery: function() {
4087
        return vimGlobalState.query;
4088
      },
4089
      setQuery: function(query) {
4090
        vimGlobalState.query = query;
4091
      },
4092
      getOverlay: function() {
4093
        return this.searchOverlay;
4094
      },
4095
      setOverlay: function(overlay) {
4096
        this.searchOverlay = overlay;
4097
      },
4098
      isReversed: function() {
4099
        return vimGlobalState.isReversed;
4100
      },
4101
      setReversed: function(reversed) {
4102
        vimGlobalState.isReversed = reversed;
4103
      },
4104
      getScrollbarAnnotate: function() {
4105
        return this.annotate;
4106
      },
4107
      setScrollbarAnnotate: function(annotate) {
4108
        this.annotate = annotate;
4109
      }
4110
    };
4111
    function getSearchState(cm) {
4112
      var vim = cm.state.vim;
4113
      return vim.searchState_ || (vim.searchState_ = new SearchState());
4114
    }
4115
    function splitBySlash(argString) {
4116
      return splitBySeparator(argString, '/');
4117
    }
4118

4119
    function findUnescapedSlashes(argString) {
4120
      return findUnescapedSeparators(argString, '/');
4121
    }
4122

4123
    function splitBySeparator(argString, separator) {
4124
      var slashes = findUnescapedSeparators(argString, separator) || [];
4125
      if (!slashes.length) return [];
4126
      var tokens = [];
4127
      // in case of strings like foo/bar
4128
      if (slashes[0] !== 0) return;
4129
      for (var i = 0; i < slashes.length; i++) {
4130
        if (typeof slashes[i] == 'number')
4131
          tokens.push(argString.substring(slashes[i] + 1, slashes[i+1]));
4132
      }
4133
      return tokens;
4134
    }
4135

4136
    function findUnescapedSeparators(str, separator) {
4137
      if (!separator)
4138
        separator = '/';
4139

4140
      var escapeNextChar = false;
4141
      var slashes = [];
4142
      for (var i = 0; i < str.length; i++) {
4143
        var c = str.charAt(i);
4144
        if (!escapeNextChar && c == separator) {
4145
          slashes.push(i);
4146
        }
4147
        escapeNextChar = !escapeNextChar && (c == '\\');
4148
      }
4149
      return slashes;
4150
    }
4151

4152
    // Translates a search string from ex (vim) syntax into javascript form.
4153
    function translateRegex(str) {
4154
      // When these match, add a '\' if unescaped or remove one if escaped.
4155
      var specials = '|(){';
4156
      // Remove, but never add, a '\' for these.
4157
      var unescape = '}';
4158
      var escapeNextChar = false;
4159
      var out = [];
4160
      for (var i = -1; i < str.length; i++) {
4161
        var c = str.charAt(i) || '';
4162
        var n = str.charAt(i+1) || '';
4163
        var specialComesNext = (n && specials.indexOf(n) != -1);
4164
        if (escapeNextChar) {
4165
          if (c !== '\\' || !specialComesNext) {
4166
            out.push(c);
4167
          }
4168
          escapeNextChar = false;
4169
        } else {
4170
          if (c === '\\') {
4171
            escapeNextChar = true;
4172
            // Treat the unescape list as special for removing, but not adding '\'.
4173
            if (n && unescape.indexOf(n) != -1) {
4174
              specialComesNext = true;
4175
            }
4176
            // Not passing this test means removing a '\'.
4177
            if (!specialComesNext || n === '\\') {
4178
              out.push(c);
4179
            }
4180
          } else {
4181
            out.push(c);
4182
            if (specialComesNext && n !== '\\') {
4183
              out.push('\\');
4184
            }
4185
          }
4186
        }
4187
      }
4188
      return out.join('');
4189
    }
4190

4191
    // Translates the replace part of a search and replace from ex (vim) syntax into
4192
    // javascript form.  Similar to translateRegex, but additionally fixes back references
4193
    // (translates '\[0..9]' to '$[0..9]') and follows different rules for escaping '$'.
4194
    var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'};
4195
    function translateRegexReplace(str) {
4196
      var escapeNextChar = false;
4197
      var out = [];
4198
      for (var i = -1; i < str.length; i++) {
4199
        var c = str.charAt(i) || '';
4200
        var n = str.charAt(i+1) || '';
4201
        if (charUnescapes[c + n]) {
4202
          out.push(charUnescapes[c+n]);
4203
          i++;
4204
        } else if (escapeNextChar) {
4205
          // At any point in the loop, escapeNextChar is true if the previous
4206
          // character was a '\' and was not escaped.
4207
          out.push(c);
4208
          escapeNextChar = false;
4209
        } else {
4210
          if (c === '\\') {
4211
            escapeNextChar = true;
4212
            if ((isNumber(n) || n === '$')) {
4213
              out.push('$');
4214
            } else if (n !== '/' && n !== '\\') {
4215
              out.push('\\');
4216
            }
4217
          } else {
4218
            if (c === '$') {
4219
              out.push('$');
4220
            }
4221
            out.push(c);
4222
            if (n === '/') {
4223
              out.push('\\');
4224
            }
4225
          }
4226
        }
4227
      }
4228
      return out.join('');
4229
    }
4230

4231
    // Unescape \ and / in the replace part, for PCRE mode.
4232
    var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t', '\\&':'&'};
4233
    function unescapeRegexReplace(str) {
4234
      var stream = new CodeMirror.StringStream(str);
4235
      var output = [];
4236
      while (!stream.eol()) {
4237
        // Search for \.
4238
        while (stream.peek() && stream.peek() != '\\') {
4239
          output.push(stream.next());
4240
        }
4241
        var matched = false;
4242
        for (var matcher in unescapes) {
4243
          if (stream.match(matcher, true)) {
4244
            matched = true;
4245
            output.push(unescapes[matcher]);
4246
            break;
4247
          }
4248
        }
4249
        if (!matched) {
4250
          // Don't change anything
4251
          output.push(stream.next());
4252
        }
4253
      }
4254
      return output.join('');
4255
    }
4256

4257
    /**
4258
     * Extract the regular expression from the query and return a Regexp object.
4259
     * Returns null if the query is blank.
4260
     * If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
4261
     * If smartCase is passed in, and the query contains upper case letters,
4262
     *   then ignoreCase is overridden, and the 'i' flag will not be set.
4263
     * If the query contains the /i in the flag part of the regular expression,
4264
     *   then both ignoreCase and smartCase are ignored, and 'i' will be passed
4265
     *   through to the Regex object.
4266
     */
4267
    function parseQuery(query, ignoreCase, smartCase) {
4268
      // First update the last search register
4269
      var lastSearchRegister = vimGlobalState.registerController.getRegister('/');
4270
      lastSearchRegister.setText(query);
4271
      // Check if the query is already a regex.
4272
      if (query instanceof RegExp) { return query; }
4273
      // First try to extract regex + flags from the input. If no flags found,
4274
      // extract just the regex. IE does not accept flags directly defined in
4275
      // the regex string in the form /regex/flags
4276
      var slashes = findUnescapedSlashes(query);
4277
      var regexPart;
4278
      var forceIgnoreCase;
4279
      if (!slashes.length) {
4280
        // Query looks like 'regexp'
4281
        regexPart = query;
4282
      } else {
4283
        // Query looks like 'regexp/...'
4284
        regexPart = query.substring(0, slashes[0]);
4285
        var flagsPart = query.substring(slashes[0]);
4286
        forceIgnoreCase = (flagsPart.indexOf('i') != -1);
4287
      }
4288
      if (!regexPart) {
4289
        return null;
4290
      }
4291
      if (!getOption('pcre')) {
4292
        regexPart = translateRegex(regexPart);
4293
      }
4294
      if (smartCase) {
4295
        ignoreCase = (/^[^A-Z]*$/).test(regexPart);
4296
      }
4297
      var regexp = new RegExp(regexPart,
4298
          (ignoreCase || forceIgnoreCase) ? 'im' : 'm');
4299
      return regexp;
4300
    }
4301

4302
    /**
4303
     * dom - Document Object Manipulator
4304
     * Usage:
4305
     *   dom('<tag>'|<node>[, ...{<attributes>|<$styles>}|<child-node>|'<text>'])
4306
     * Examples:
4307
     *   dom('div', {id:'xyz'}, dom('p', 'CM rocks!', {$color:'red'}))
4308
     *   dom(document.head, dom('script', 'alert("hello!")'))
4309
     * Not supported:
4310
     *   dom('p', ['arrays are objects'], Error('objects specify attributes'))
4311
     */
4312
    function dom(n) {
4313
      if (typeof n === 'string') n = document.createElement(n);
4314
      for (var a, i = 1; i < arguments.length; i++) {
4315
        if (!(a = arguments[i])) continue;
4316
        if (typeof a !== 'object') a = document.createTextNode(a);
4317
        if (a.nodeType) n.appendChild(a);
4318
        else for (var key in a) {
4319
          if (!Object.prototype.hasOwnProperty.call(a, key)) continue;
4320
          if (key[0] === '$') n.style[key.slice(1)] = a[key];
4321
          else n.setAttribute(key, a[key]);
4322
        }
4323
      }
4324
      return n;
4325
    }
4326

4327
    function showConfirm(cm, template) {
4328
      var pre = dom('pre', {$color: 'red', class: 'cm-vim-message'}, template);
4329
      if (cm.openNotification) {
4330
        cm.openNotification(pre, {bottom: true, duration: 5000});
4331
      } else {
4332
        alert(pre.innerText);
4333
      }
4334
    }
4335

4336
    function makePrompt(prefix, desc) {
4337
      return dom(document.createDocumentFragment(),
4338
               dom('span', {$fontFamily: 'monospace', $whiteSpace: 'pre'},
4339
                 prefix,
4340
                 dom('input', {type: 'text', autocorrect: 'off',
4341
                               autocapitalize: 'off', spellcheck: 'false'})),
4342
               desc && dom('span', {$color: '#888'}, desc));
4343
    }
4344

4345
    function showPrompt(cm, options) {
4346
      var template = makePrompt(options.prefix, options.desc);
4347
      if (cm.openDialog) {
4348
        cm.openDialog(template, options.onClose, {
4349
          onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp,
4350
          bottom: true, selectValueOnOpen: false, value: options.value
4351
        });
4352
      }
4353
      else {
4354
        var shortText = '';
4355
        if (typeof options.prefix != "string" && options.prefix) shortText += options.prefix.textContent;
4356
        if (options.desc) shortText += " " + options.desc;
4357
        options.onClose(prompt(shortText, ''));
4358
      }
4359
    }
4360

4361
    function regexEqual(r1, r2) {
4362
      if (r1 instanceof RegExp && r2 instanceof RegExp) {
4363
          var props = ['global', 'multiline', 'ignoreCase', 'source'];
4364
          for (var i = 0; i < props.length; i++) {
4365
              var prop = props[i];
4366
              if (r1[prop] !== r2[prop]) {
4367
                  return false;
4368
              }
4369
          }
4370
          return true;
4371
      }
4372
      return false;
4373
    }
4374
    // Returns true if the query is valid.
4375
    function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
4376
      if (!rawQuery) {
4377
        return;
4378
      }
4379
      var state = getSearchState(cm);
4380
      var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
4381
      if (!query) {
4382
        return;
4383
      }
4384
      highlightSearchMatches(cm, query);
4385
      if (regexEqual(query, state.getQuery())) {
4386
        return query;
4387
      }
4388
      state.setQuery(query);
4389
      return query;
4390
    }
4391
    function searchOverlay(query) {
4392
      if (query.source.charAt(0) == '^') {
4393
        var matchSol = true;
4394
      }
4395
      return {
4396
        token: function(stream) {
4397
          if (matchSol && !stream.sol()) {
4398
            stream.skipToEnd();
4399
            return;
4400
          }
4401
          var match = stream.match(query, false);
4402
          if (match) {
4403
            if (match[0].length == 0) {
4404
              // Matched empty string, skip to next.
4405
              stream.next();
4406
              return 'searching';
4407
            }
4408
            if (!stream.sol()) {
4409
              // Backtrack 1 to match \b
4410
              stream.backUp(1);
4411
              if (!query.exec(stream.next() + match[0])) {
4412
                stream.next();
4413
                return null;
4414
              }
4415
            }
4416
            stream.match(query);
4417
            return 'searching';
4418
          }
4419
          while (!stream.eol()) {
4420
            stream.next();
4421
            if (stream.match(query, false)) break;
4422
          }
4423
        },
4424
        query: query
4425
      };
4426
    }
4427
    var highlightTimeout = 0;
4428
    function highlightSearchMatches(cm, query) {
4429
      clearTimeout(highlightTimeout);
4430
      highlightTimeout = setTimeout(function() {
4431
        if (!cm.state.vim) return;
4432
        var searchState = getSearchState(cm);
4433
        var overlay = searchState.getOverlay();
4434
        if (!overlay || query != overlay.query) {
4435
          if (overlay) {
4436
            cm.removeOverlay(overlay);
4437
          }
4438
          overlay = searchOverlay(query);
4439
          cm.addOverlay(overlay);
4440
          if (cm.showMatchesOnScrollbar) {
4441
            if (searchState.getScrollbarAnnotate()) {
4442
              searchState.getScrollbarAnnotate().clear();
4443
            }
4444
            searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query));
4445
          }
4446
          searchState.setOverlay(overlay);
4447
        }
4448
      }, 50);
4449
    }
4450
    function findNext(cm, prev, query, repeat) {
4451
      if (repeat === undefined) { repeat = 1; }
4452
      return cm.operation(function() {
4453
        var pos = cm.getCursor();
4454
        var cursor = cm.getSearchCursor(query, pos);
4455
        for (var i = 0; i < repeat; i++) {
4456
          var found = cursor.find(prev);
4457
          if (i == 0 && found && cursorEqual(cursor.from(), pos)) {
4458
            var lastEndPos = prev ? cursor.from() : cursor.to();
4459
            found = cursor.find(prev);
4460
            if (found && !found[0] && cursorEqual(cursor.from(), lastEndPos)) {
4461
              if (cm.getLine(lastEndPos.line).length == lastEndPos.ch)
4462
                found = cursor.find(prev);
4463
            }
4464
          }
4465
          if (!found) {
4466
            // SearchCursor may have returned null because it hit EOF, wrap
4467
            // around and try again.
4468
            cursor = cm.getSearchCursor(query,
4469
                (prev) ? new Pos(cm.lastLine()) : new Pos(cm.firstLine(), 0) );
4470
            if (!cursor.find(prev)) {
4471
              return;
4472
            }
4473
          }
4474
        }
4475
        return cursor.from();
4476
      });
4477
    }
4478
    /**
4479
     * Pretty much the same as `findNext`, except for the following differences:
4480
     *
4481
     * 1. Before starting the search, move to the previous search. This way if our cursor is
4482
     * already inside a match, we should return the current match.
4483
     * 2. Rather than only returning the cursor's from, we return the cursor's from and to as a tuple.
4484
     */
4485
    function findNextFromAndToInclusive(cm, prev, query, repeat, vim) {
4486
      if (repeat === undefined) { repeat = 1; }
4487
      return cm.operation(function() {
4488
        var pos = cm.getCursor();
4489
        var cursor = cm.getSearchCursor(query, pos);
4490

4491
        // Go back one result to ensure that if the cursor is currently a match, we keep it.
4492
        var found = cursor.find(!prev);
4493

4494
        // If we haven't moved, go back one more (similar to if i==0 logic in findNext).
4495
        if (!vim.visualMode && found && cursorEqual(cursor.from(), pos)) {
4496
          cursor.find(!prev);
4497
        }
4498

4499
        for (var i = 0; i < repeat; i++) {
4500
          found = cursor.find(prev);
4501
          if (!found) {
4502
            // SearchCursor may have returned null because it hit EOF, wrap
4503
            // around and try again.
4504
            cursor = cm.getSearchCursor(query,
4505
                (prev) ? new Pos(cm.lastLine()) : new Pos(cm.firstLine(), 0) );
4506
            if (!cursor.find(prev)) {
4507
              return;
4508
            }
4509
          }
4510
        }
4511
        return [cursor.from(), cursor.to()];
4512
      });
4513
    }
4514
    function clearSearchHighlight(cm) {
4515
      var state = getSearchState(cm);
4516
      cm.removeOverlay(getSearchState(cm).getOverlay());
4517
      state.setOverlay(null);
4518
      if (state.getScrollbarAnnotate()) {
4519
        state.getScrollbarAnnotate().clear();
4520
        state.setScrollbarAnnotate(null);
4521
      }
4522
    }
4523
    /**
4524
     * Check if pos is in the specified range, INCLUSIVE.
4525
     * Range can be specified with 1 or 2 arguments.
4526
     * If the first range argument is an array, treat it as an array of line
4527
     * numbers. Match pos against any of the lines.
4528
     * If the first range argument is a number,
4529
     *   if there is only 1 range argument, check if pos has the same line
4530
     *       number
4531
     *   if there are 2 range arguments, then check if pos is in between the two
4532
     *       range arguments.
4533
     */
4534
    function isInRange(pos, start, end) {
4535
      if (typeof pos != 'number') {
4536
        // Assume it is a cursor position. Get the line number.
4537
        pos = pos.line;
4538
      }
4539
      if (start instanceof Array) {
4540
        return inArray(pos, start);
4541
      } else {
4542
        if (typeof end == 'number') {
4543
          return (pos >= start && pos <= end);
4544
        } else {
4545
          return pos == start;
4546
        }
4547
      }
4548
    }
4549
    function getUserVisibleLines(cm) {
4550
      var scrollInfo = cm.getScrollInfo();
4551
      var occludeToleranceTop = 6;
4552
      var occludeToleranceBottom = 10;
4553
      var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');
4554
      var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;
4555
      var to = cm.coordsChar({left:0, top: bottomY}, 'local');
4556
      return {top: from.line, bottom: to.line};
4557
    }
4558

4559
    function getMarkPos(cm, vim, markName) {
4560
      if (markName == '\'' || markName == '`') {
4561
        return vimGlobalState.jumpList.find(cm, -1) || new Pos(0, 0);
4562
      } else if (markName == '.') {
4563
        return getLastEditPos(cm);
4564
      }
4565

4566
      var mark = vim.marks[markName];
4567
      return mark && mark.find();
4568
    }
4569

4570
    function getLastEditPos(cm) {
4571
      var done = cm.doc.history.done;
4572
      for (var i = done.length; i--;) {
4573
        if (done[i].changes) {
4574
          return copyCursor(done[i].changes[0].to);
4575
        }
4576
      }
4577
    }
4578

4579
    var ExCommandDispatcher = function() {
4580
      this.buildCommandMap_();
4581
    };
4582
    ExCommandDispatcher.prototype = {
4583
      processCommand: function(cm, input, opt_params) {
4584
        var that = this;
4585
        cm.operation(function () {
4586
          cm.curOp.isVimOp = true;
4587
          that._processCommand(cm, input, opt_params);
4588
        });
4589
      },
4590
      _processCommand: function(cm, input, opt_params) {
4591
        var vim = cm.state.vim;
4592
        var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');
4593
        var previousCommand = commandHistoryRegister.toString();
4594
        if (vim.visualMode) {
4595
          exitVisualMode(cm);
4596
        }
4597
        var inputStream = new CodeMirror.StringStream(input);
4598
        // update ": with the latest command whether valid or invalid
4599
        commandHistoryRegister.setText(input);
4600
        var params = opt_params || {};
4601
        params.input = input;
4602
        try {
4603
          this.parseInput_(cm, inputStream, params);
4604
        } catch(e) {
4605
          showConfirm(cm, e.toString());
4606
          throw e;
4607
        }
4608
        var command;
4609
        var commandName;
4610
        if (!params.commandName) {
4611
          // If only a line range is defined, move to the line.
4612
          if (params.line !== undefined) {
4613
            commandName = 'move';
4614
          }
4615
        } else {
4616
          command = this.matchCommand_(params.commandName);
4617
          if (command) {
4618
            commandName = command.name;
4619
            if (command.excludeFromCommandHistory) {
4620
              commandHistoryRegister.setText(previousCommand);
4621
            }
4622
            this.parseCommandArgs_(inputStream, params, command);
4623
            if (command.type == 'exToKey') {
4624
              // Handle Ex to Key mapping.
4625
              for (var i = 0; i < command.toKeys.length; i++) {
4626
                vimApi.handleKey(cm, command.toKeys[i], 'mapping');
4627
              }
4628
              return;
4629
            } else if (command.type == 'exToEx') {
4630
              // Handle Ex to Ex mapping.
4631
              this.processCommand(cm, command.toInput);
4632
              return;
4633
            }
4634
          }
4635
        }
4636
        if (!commandName) {
4637
          showConfirm(cm, 'Not an editor command ":' + input + '"');
4638
          return;
4639
        }
4640
        try {
4641
          exCommands[commandName](cm, params);
4642
          // Possibly asynchronous commands (e.g. substitute, which might have a
4643
          // user confirmation), are responsible for calling the callback when
4644
          // done. All others have it taken care of for them here.
4645
          if ((!command || !command.possiblyAsync) && params.callback) {
4646
            params.callback();
4647
          }
4648
        } catch(e) {
4649
          showConfirm(cm, e.toString());
4650
          throw e;
4651
        }
4652
      },
4653
      parseInput_: function(cm, inputStream, result) {
4654
        inputStream.eatWhile(':');
4655
        // Parse range.
4656
        if (inputStream.eat('%')) {
4657
          result.line = cm.firstLine();
4658
          result.lineEnd = cm.lastLine();
4659
        } else {
4660
          result.line = this.parseLineSpec_(cm, inputStream);
4661
          if (result.line !== undefined && inputStream.eat(',')) {
4662
            result.lineEnd = this.parseLineSpec_(cm, inputStream);
4663
          }
4664
        }
4665

4666
        // Parse command name.
4667
        var commandMatch = inputStream.match(/^(\w+|!!|@@|[!#&*<=>@~])/);
4668
        if (commandMatch) {
4669
          result.commandName = commandMatch[1];
4670
        } else {
4671
          result.commandName = inputStream.match(/.*/)[0];
4672
        }
4673

4674
        return result;
4675
      },
4676
      parseLineSpec_: function(cm, inputStream) {
4677
        var numberMatch = inputStream.match(/^(\d+)/);
4678
        if (numberMatch) {
4679
          // Absolute line number plus offset (N+M or N-M) is probably a typo,
4680
          // not something the user actually wanted. (NB: vim does allow this.)
4681
          return parseInt(numberMatch[1], 10) - 1;
4682
        }
4683
        switch (inputStream.next()) {
4684
          case '.':
4685
            return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
4686
          case '$':
4687
            return this.parseLineSpecOffset_(inputStream, cm.lastLine());
4688
          case '\'':
4689
            var markName = inputStream.next();
4690
            var markPos = getMarkPos(cm, cm.state.vim, markName);
4691
            if (!markPos) throw new Error('Mark not set');
4692
            return this.parseLineSpecOffset_(inputStream, markPos.line);
4693
          case '-':
4694
          case '+':
4695
            inputStream.backUp(1);
4696
            // Offset is relative to current line if not otherwise specified.
4697
            return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
4698
          default:
4699
            inputStream.backUp(1);
4700
            return undefined;
4701
        }
4702
      },
4703
      parseLineSpecOffset_: function(inputStream, line) {
4704
        var offsetMatch = inputStream.match(/^([+-])?(\d+)/);
4705
        if (offsetMatch) {
4706
          var offset = parseInt(offsetMatch[2], 10);
4707
          if (offsetMatch[1] == "-") {
4708
            line -= offset;
4709
          } else {
4710
            line += offset;
4711
          }
4712
        }
4713
        return line;
4714
      },
4715
      parseCommandArgs_: function(inputStream, params, command) {
4716
        if (inputStream.eol()) {
4717
          return;
4718
        }
4719
        params.argString = inputStream.match(/.*/)[0];
4720
        // Parse command-line arguments
4721
        var delim = command.argDelimiter || /\s+/;
4722
        var args = trim(params.argString).split(delim);
4723
        if (args.length && args[0]) {
4724
          params.args = args;
4725
        }
4726
      },
4727
      matchCommand_: function(commandName) {
4728
        // Return the command in the command map that matches the shortest
4729
        // prefix of the passed in command name. The match is guaranteed to be
4730
        // unambiguous if the defaultExCommandMap's shortNames are set up
4731
        // correctly. (see @code{defaultExCommandMap}).
4732
        for (var i = commandName.length; i > 0; i--) {
4733
          var prefix = commandName.substring(0, i);
4734
          if (this.commandMap_[prefix]) {
4735
            var command = this.commandMap_[prefix];
4736
            if (command.name.indexOf(commandName) === 0) {
4737
              return command;
4738
            }
4739
          }
4740
        }
4741
        return null;
4742
      },
4743
      buildCommandMap_: function() {
4744
        this.commandMap_ = {};
4745
        for (var i = 0; i < defaultExCommandMap.length; i++) {
4746
          var command = defaultExCommandMap[i];
4747
          var key = command.shortName || command.name;
4748
          this.commandMap_[key] = command;
4749
        }
4750
      },
4751
      map: function(lhs, rhs, ctx) {
4752
        if (lhs != ':' && lhs.charAt(0) == ':') {
4753
          if (ctx) { throw Error('Mode not supported for ex mappings'); }
4754
          var commandName = lhs.substring(1);
4755
          if (rhs != ':' && rhs.charAt(0) == ':') {
4756
            // Ex to Ex mapping
4757
            this.commandMap_[commandName] = {
4758
              name: commandName,
4759
              type: 'exToEx',
4760
              toInput: rhs.substring(1),
4761
              user: true
4762
            };
4763
          } else {
4764
            // Ex to key mapping
4765
            this.commandMap_[commandName] = {
4766
              name: commandName,
4767
              type: 'exToKey',
4768
              toKeys: rhs,
4769
              user: true
4770
            };
4771
          }
4772
        } else {
4773
          if (rhs != ':' && rhs.charAt(0) == ':') {
4774
            // Key to Ex mapping.
4775
            var mapping = {
4776
              keys: lhs,
4777
              type: 'keyToEx',
4778
              exArgs: { input: rhs.substring(1) }
4779
            };
4780
            if (ctx) { mapping.context = ctx; }
4781
            defaultKeymap.unshift(mapping);
4782
          } else {
4783
            // Key to key mapping
4784
            var mapping = {
4785
              keys: lhs,
4786
              type: 'keyToKey',
4787
              toKeys: rhs
4788
            };
4789
            if (ctx) { mapping.context = ctx; }
4790
            defaultKeymap.unshift(mapping);
4791
          }
4792
        }
4793
      },
4794
      unmap: function(lhs, ctx) {
4795
        if (lhs != ':' && lhs.charAt(0) == ':') {
4796
          // Ex to Ex or Ex to key mapping
4797
          if (ctx) { throw Error('Mode not supported for ex mappings'); }
4798
          var commandName = lhs.substring(1);
4799
          if (this.commandMap_[commandName] && this.commandMap_[commandName].user) {
4800
            delete this.commandMap_[commandName];
4801
            return true;
4802
          }
4803
        } else {
4804
          // Key to Ex or key to key mapping
4805
          var keys = lhs;
4806
          for (var i = 0; i < defaultKeymap.length; i++) {
4807
            if (keys == defaultKeymap[i].keys
4808
                && defaultKeymap[i].context === ctx) {
4809
              defaultKeymap.splice(i, 1);
4810
              return true;
4811
            }
4812
          }
4813
        }
4814
      }
4815
    };
4816

4817
    var exCommands = {
4818
      colorscheme: function(cm, params) {
4819
        if (!params.args || params.args.length < 1) {
4820
          showConfirm(cm, cm.getOption('theme'));
4821
          return;
4822
        }
4823
        cm.setOption('theme', params.args[0]);
4824
      },
4825
      map: function(cm, params, ctx) {
4826
        var mapArgs = params.args;
4827
        if (!mapArgs || mapArgs.length < 2) {
4828
          if (cm) {
4829
            showConfirm(cm, 'Invalid mapping: ' + params.input);
4830
          }
4831
          return;
4832
        }
4833
        exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
4834
      },
4835
      imap: function(cm, params) { this.map(cm, params, 'insert'); },
4836
      nmap: function(cm, params) { this.map(cm, params, 'normal'); },
4837
      vmap: function(cm, params) { this.map(cm, params, 'visual'); },
4838
      unmap: function(cm, params, ctx) {
4839
        var mapArgs = params.args;
4840
        if (!mapArgs || mapArgs.length < 1 || !exCommandDispatcher.unmap(mapArgs[0], ctx)) {
4841
          if (cm) {
4842
            showConfirm(cm, 'No such mapping: ' + params.input);
4843
          }
4844
        }
4845
      },
4846
      move: function(cm, params) {
4847
        commandDispatcher.processCommand(cm, cm.state.vim, {
4848
            type: 'motion',
4849
            motion: 'moveToLineOrEdgeOfDocument',
4850
            motionArgs: { forward: false, explicitRepeat: true,
4851
              linewise: true },
4852
            repeatOverride: params.line+1});
4853
      },
4854
      set: function(cm, params) {
4855
        var setArgs = params.args;
4856
        // Options passed through to the setOption/getOption calls. May be passed in by the
4857
        // local/global versions of the set command
4858
        var setCfg = params.setCfg || {};
4859
        if (!setArgs || setArgs.length < 1) {
4860
          if (cm) {
4861
            showConfirm(cm, 'Invalid mapping: ' + params.input);
4862
          }
4863
          return;
4864
        }
4865
        var expr = setArgs[0].split('=');
4866
        var optionName = expr[0];
4867
        var value = expr[1];
4868
        var forceGet = false;
4869

4870
        if (optionName.charAt(optionName.length - 1) == '?') {
4871
          // If post-fixed with ?, then the set is actually a get.
4872
          if (value) { throw Error('Trailing characters: ' + params.argString); }
4873
          optionName = optionName.substring(0, optionName.length - 1);
4874
          forceGet = true;
4875
        }
4876
        if (value === undefined && optionName.substring(0, 2) == 'no') {
4877
          // To set boolean options to false, the option name is prefixed with
4878
          // 'no'.
4879
          optionName = optionName.substring(2);
4880
          value = false;
4881
        }
4882

4883
        var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';
4884
        if (optionIsBoolean && value == undefined) {
4885
          // Calling set with a boolean option sets it to true.
4886
          value = true;
4887
        }
4888
        // If no value is provided, then we assume this is a get.
4889
        if (!optionIsBoolean && value === undefined || forceGet) {
4890
          var oldValue = getOption(optionName, cm, setCfg);
4891
          if (oldValue instanceof Error) {
4892
            showConfirm(cm, oldValue.message);
4893
          } else if (oldValue === true || oldValue === false) {
4894
            showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName);
4895
          } else {
4896
            showConfirm(cm, '  ' + optionName + '=' + oldValue);
4897
          }
4898
        } else {
4899
          var setOptionReturn = setOption(optionName, value, cm, setCfg);
4900
          if (setOptionReturn instanceof Error) {
4901
            showConfirm(cm, setOptionReturn.message);
4902
          }
4903
        }
4904
      },
4905
      setlocal: function (cm, params) {
4906
        // setCfg is passed through to setOption
4907
        params.setCfg = {scope: 'local'};
4908
        this.set(cm, params);
4909
      },
4910
      setglobal: function (cm, params) {
4911
        // setCfg is passed through to setOption
4912
        params.setCfg = {scope: 'global'};
4913
        this.set(cm, params);
4914
      },
4915
      registers: function(cm, params) {
4916
        var regArgs = params.args;
4917
        var registers = vimGlobalState.registerController.registers;
4918
        var regInfo = '----------Registers----------\n\n';
4919
        if (!regArgs) {
4920
          for (var registerName in registers) {
4921
            var text = registers[registerName].toString();
4922
            if (text.length) {
4923
              regInfo += '"' + registerName + '    ' + text + '\n'
4924
            }
4925
          }
4926
        } else {
4927
          var registerName;
4928
          regArgs = regArgs.join('');
4929
          for (var i = 0; i < regArgs.length; i++) {
4930
            registerName = regArgs.charAt(i);
4931
            if (!vimGlobalState.registerController.isValidRegister(registerName)) {
4932
              continue;
4933
            }
4934
            var register = registers[registerName] || new Register();
4935
            regInfo += '"' + registerName + '    ' + register.toString() + '\n'
4936
          }
4937
        }
4938
        showConfirm(cm, regInfo);
4939
      },
4940
      sort: function(cm, params) {
4941
        var reverse, ignoreCase, unique, number, pattern;
4942
        function parseArgs() {
4943
          if (params.argString) {
4944
            var args = new CodeMirror.StringStream(params.argString);
4945
            if (args.eat('!')) { reverse = true; }
4946
            if (args.eol()) { return; }
4947
            if (!args.eatSpace()) { return 'Invalid arguments'; }
4948
            var opts = args.match(/([dinuox]+)?\s*(\/.+\/)?\s*/);
4949
            if (!opts && !args.eol()) { return 'Invalid arguments'; }
4950
            if (opts[1]) {
4951
              ignoreCase = opts[1].indexOf('i') != -1;
4952
              unique = opts[1].indexOf('u') != -1;
4953
              var decimal = opts[1].indexOf('d') != -1 || opts[1].indexOf('n') != -1 && 1;
4954
              var hex = opts[1].indexOf('x') != -1 && 1;
4955
              var octal = opts[1].indexOf('o') != -1 && 1;
4956
              if (decimal + hex + octal > 1) { return 'Invalid arguments'; }
4957
              number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
4958
            }
4959
            if (opts[2]) {
4960
              pattern = new RegExp(opts[2].substr(1, opts[2].length - 2), ignoreCase ? 'i' : '');
4961
            }
4962
          }
4963
        }
4964
        var err = parseArgs();
4965
        if (err) {
4966
          showConfirm(cm, err + ': ' + params.argString);
4967
          return;
4968
        }
4969
        var lineStart = params.line || cm.firstLine();
4970
        var lineEnd = params.lineEnd || params.line || cm.lastLine();
4971
        if (lineStart == lineEnd) { return; }
4972
        var curStart = new Pos(lineStart, 0);
4973
        var curEnd = new Pos(lineEnd, lineLength(cm, lineEnd));
4974
        var text = cm.getRange(curStart, curEnd).split('\n');
4975
        var numberRegex = pattern ? pattern :
4976
           (number == 'decimal') ? /(-?)([\d]+)/ :
4977
           (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
4978
           (number == 'octal') ? /([0-7]+)/ : null;
4979
        var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
4980
        var numPart = [], textPart = [];
4981
        if (number || pattern) {
4982
          for (var i = 0; i < text.length; i++) {
4983
            var matchPart = pattern ? text[i].match(pattern) : null;
4984
            if (matchPart && matchPart[0] != '') {
4985
              numPart.push(matchPart);
4986
            } else if (!pattern && numberRegex.exec(text[i])) {
4987
              numPart.push(text[i]);
4988
            } else {
4989
              textPart.push(text[i]);
4990
            }
4991
          }
4992
        } else {
4993
          textPart = text;
4994
        }
4995
        function compareFn(a, b) {
4996
          if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
4997
          if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
4998
          var anum = number && numberRegex.exec(a);
4999
          var bnum = number && numberRegex.exec(b);
5000
          if (!anum) { return a < b ? -1 : 1; }
5001
          anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
5002
          bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
5003
          return anum - bnum;
5004
        }
5005
        function comparePatternFn(a, b) {
5006
          if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
5007
          if (ignoreCase) { a[0] = a[0].toLowerCase(); b[0] = b[0].toLowerCase(); }
5008
          return (a[0] < b[0]) ? -1 : 1;
5009
        }
5010
        numPart.sort(pattern ? comparePatternFn : compareFn);
5011
        if (pattern) {
5012
          for (var i = 0; i < numPart.length; i++) {
5013
            numPart[i] = numPart[i].input;
5014
          }
5015
        } else if (!number) { textPart.sort(compareFn); }
5016
        text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
5017
        if (unique) { // Remove duplicate lines
5018
          var textOld = text;
5019
          var lastLine;
5020
          text = [];
5021
          for (var i = 0; i < textOld.length; i++) {
5022
            if (textOld[i] != lastLine) {
5023
              text.push(textOld[i]);
5024
            }
5025
            lastLine = textOld[i];
5026
          }
5027
        }
5028
        cm.replaceRange(text.join('\n'), curStart, curEnd);
5029
      },
5030
      vglobal: function(cm, params) {
5031
        // global inspects params.commandName
5032
        this.global(cm, params);
5033
      },
5034
      global: function(cm, params) {
5035
        // a global command is of the form
5036
        // :[range]g/pattern/[cmd]
5037
        // argString holds the string /pattern/[cmd]
5038
        var argString = params.argString;
5039
        if (!argString) {
5040
          showConfirm(cm, 'Regular Expression missing from global');
5041
          return;
5042
        }
5043
        var inverted = params.commandName[0] === 'v';
5044
        // range is specified here
5045
        var lineStart = (params.line !== undefined) ? params.line : cm.firstLine();
5046
        var lineEnd = params.lineEnd || params.line || cm.lastLine();
5047
        // get the tokens from argString
5048
        var tokens = splitBySlash(argString);
5049
        var regexPart = argString, cmd;
5050
        if (tokens.length) {
5051
          regexPart = tokens[0];
5052
          cmd = tokens.slice(1, tokens.length).join('/');
5053
        }
5054
        if (regexPart) {
5055
          // If regex part is empty, then use the previous query. Otherwise
5056
          // use the regex part as the new query.
5057
          try {
5058
           updateSearchQuery(cm, regexPart, true /** ignoreCase */,
5059
             true /** smartCase */);
5060
          } catch (e) {
5061
           showConfirm(cm, 'Invalid regex: ' + regexPart);
5062
           return;
5063
          }
5064
        }
5065
        // now that we have the regexPart, search for regex matches in the
5066
        // specified range of lines
5067
        var query = getSearchState(cm).getQuery();
5068
        var matchedLines = [];
5069
        for (var i = lineStart; i <= lineEnd; i++) {
5070
          var line = cm.getLineHandle(i);
5071
          var matched = query.test(line.text);
5072
          if (matched !== inverted) {
5073
            matchedLines.push(cmd ? line : line.text);
5074
          }
5075
        }
5076
        // if there is no [cmd], just display the list of matched lines
5077
        if (!cmd) {
5078
          showConfirm(cm, matchedLines.join('\n'));
5079
          return;
5080
        }
5081
        var index = 0;
5082
        var nextCommand = function() {
5083
          if (index < matchedLines.length) {
5084
            var line = matchedLines[index++];
5085
            var lineNum = cm.getLineNumber(line);
5086
            if (lineNum == null) {
5087
              nextCommand();
5088
              return;
5089
            }
5090
            var command = (lineNum + 1) + cmd;
5091
            exCommandDispatcher.processCommand(cm, command, {
5092
              callback: nextCommand
5093
            });
5094
          }
5095
        };
5096
        nextCommand();
5097
      },
5098
      substitute: function(cm, params) {
5099
        if (!cm.getSearchCursor) {
5100
          throw new Error('Search feature not available. Requires searchcursor.js or ' +
5101
              'any other getSearchCursor implementation.');
5102
        }
5103
        var argString = params.argString;
5104
        var tokens = argString ? splitBySeparator(argString, argString[0]) : [];
5105
        var regexPart, replacePart = '', trailing, flagsPart, count;
5106
        var confirm = false; // Whether to confirm each replace.
5107
        var global = false; // True to replace all instances on a line, false to replace only 1.
5108
        if (tokens.length) {
5109
          regexPart = tokens[0];
5110
          if (getOption('pcre') && regexPart !== '') {
5111
              regexPart = new RegExp(regexPart).source; //normalize not escaped characters
5112
          }
5113
          replacePart = tokens[1];
5114
          if (replacePart !== undefined) {
5115
            if (getOption('pcre')) {
5116
              replacePart = unescapeRegexReplace(replacePart.replace(/([^\\])&/g,"$1$$&"));
5117
            } else {
5118
              replacePart = translateRegexReplace(replacePart);
5119
            }
5120
            vimGlobalState.lastSubstituteReplacePart = replacePart;
5121
          }
5122
          trailing = tokens[2] ? tokens[2].split(' ') : [];
5123
        } else {
5124
          // either the argString is empty or its of the form ' hello/world'
5125
          // actually splitBySlash returns a list of tokens
5126
          // only if the string starts with a '/'
5127
          if (argString && argString.length) {
5128
            showConfirm(cm, 'Substitutions should be of the form ' +
5129
                ':s/pattern/replace/');
5130
            return;
5131
          }
5132
        }
5133
        // After the 3rd slash, we can have flags followed by a space followed
5134
        // by count.
5135
        if (trailing) {
5136
          flagsPart = trailing[0];
5137
          count = parseInt(trailing[1]);
5138
          if (flagsPart) {
5139
            if (flagsPart.indexOf('c') != -1) {
5140
              confirm = true;
5141
            }
5142
            if (flagsPart.indexOf('g') != -1) {
5143
              global = true;
5144
            }
5145
            if (getOption('pcre')) {
5146
               regexPart = regexPart + '/' + flagsPart;
5147
            } else {
5148
               regexPart = regexPart.replace(/\//g, "\\/") + '/' + flagsPart;
5149
            }
5150
          }
5151
        }
5152
        if (regexPart) {
5153
          // If regex part is empty, then use the previous query. Otherwise use
5154
          // the regex part as the new query.
5155
          try {
5156
            updateSearchQuery(cm, regexPart, true /** ignoreCase */,
5157
              true /** smartCase */);
5158
          } catch (e) {
5159
            showConfirm(cm, 'Invalid regex: ' + regexPart);
5160
            return;
5161
          }
5162
        }
5163
        replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart;
5164
        if (replacePart === undefined) {
5165
          showConfirm(cm, 'No previous substitute regular expression');
5166
          return;
5167
        }
5168
        var state = getSearchState(cm);
5169
        var query = state.getQuery();
5170
        var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
5171
        var lineEnd = params.lineEnd || lineStart;
5172
        if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) {
5173
          lineEnd = Infinity;
5174
        }
5175
        if (count) {
5176
          lineStart = lineEnd;
5177
          lineEnd = lineStart + count - 1;
5178
        }
5179
        var startPos = clipCursorToContent(cm, new Pos(lineStart, 0));
5180
        var cursor = cm.getSearchCursor(query, startPos);
5181
        doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback);
5182
      },
5183
      redo: CodeMirror.commands.redo,
5184
      undo: CodeMirror.commands.undo,
5185
      write: function(cm) {
5186
        if (CodeMirror.commands.save) {
5187
          // If a save command is defined, call it.
5188
          CodeMirror.commands.save(cm);
5189
        } else if (cm.save) {
5190
          // Saves to text area if no save command is defined and cm.save() is available.
5191
          cm.save();
5192
        }
5193
      },
5194
      nohlsearch: function(cm) {
5195
        clearSearchHighlight(cm);
5196
      },
5197
      yank: function (cm) {
5198
        var cur = copyCursor(cm.getCursor());
5199
        var line = cur.line;
5200
        var lineText = cm.getLine(line);
5201
        vimGlobalState.registerController.pushText(
5202
          '0', 'yank', lineText, true, true);
5203
      },
5204
      delmarks: function(cm, params) {
5205
        if (!params.argString || !trim(params.argString)) {
5206
          showConfirm(cm, 'Argument required');
5207
          return;
5208
        }
5209

5210
        var state = cm.state.vim;
5211
        var stream = new CodeMirror.StringStream(trim(params.argString));
5212
        while (!stream.eol()) {
5213
          stream.eatSpace();
5214

5215
          // Record the streams position at the beginning of the loop for use
5216
          // in error messages.
5217
          var count = stream.pos;
5218

5219
          if (!stream.match(/[a-zA-Z]/, false)) {
5220
            showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
5221
            return;
5222
          }
5223

5224
          var sym = stream.next();
5225
          // Check if this symbol is part of a range
5226
          if (stream.match('-', true)) {
5227
            // This symbol is part of a range.
5228

5229
            // The range must terminate at an alphabetic character.
5230
            if (!stream.match(/[a-zA-Z]/, false)) {
5231
              showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
5232
              return;
5233
            }
5234

5235
            var startMark = sym;
5236
            var finishMark = stream.next();
5237
            // The range must terminate at an alphabetic character which
5238
            // shares the same case as the start of the range.
5239
            if (isLowerCase(startMark) && isLowerCase(finishMark) ||
5240
                isUpperCase(startMark) && isUpperCase(finishMark)) {
5241
              var start = startMark.charCodeAt(0);
5242
              var finish = finishMark.charCodeAt(0);
5243
              if (start >= finish) {
5244
                showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
5245
                return;
5246
              }
5247

5248
              // Because marks are always ASCII values, and we have
5249
              // determined that they are the same case, we can use
5250
              // their char codes to iterate through the defined range.
5251
              for (var j = 0; j <= finish - start; j++) {
5252
                var mark = String.fromCharCode(start + j);
5253
                delete state.marks[mark];
5254
              }
5255
            } else {
5256
              showConfirm(cm, 'Invalid argument: ' + startMark + '-');
5257
              return;
5258
            }
5259
          } else {
5260
            // This symbol is a valid mark, and is not part of a range.
5261
            delete state.marks[sym];
5262
          }
5263
        }
5264
      }
5265
    };
5266

5267
    var exCommandDispatcher = new ExCommandDispatcher();
5268

5269
    /**
5270
    * @param {CodeMirror} cm CodeMirror instance we are in.
5271
    * @param {boolean} confirm Whether to confirm each replace.
5272
    * @param {Cursor} lineStart Line to start replacing from.
5273
    * @param {Cursor} lineEnd Line to stop replacing at.
5274
    * @param {RegExp} query Query for performing matches with.
5275
    * @param {string} replaceWith Text to replace matches with. May contain $1,
5276
    *     $2, etc for replacing captured groups using JavaScript replace.
5277
    * @param {function()} callback A callback for when the replace is done.
5278
    */
5279
    function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query,
5280
        replaceWith, callback) {
5281
      // Set up all the functions.
5282
      cm.state.vim.exMode = true;
5283
      var done = false;
5284
      var lastPos, modifiedLineNumber, joined;
5285
      function replaceAll() {
5286
        cm.operation(function() {
5287
          while (!done) {
5288
            replace();
5289
            next();
5290
          }
5291
          stop();
5292
        });
5293
      }
5294
      function replace() {
5295
        var text = cm.getRange(searchCursor.from(), searchCursor.to());
5296
        var newText = text.replace(query, replaceWith);
5297
        var unmodifiedLineNumber = searchCursor.to().line;
5298
        searchCursor.replace(newText);
5299
        modifiedLineNumber = searchCursor.to().line;
5300
        lineEnd += modifiedLineNumber - unmodifiedLineNumber;
5301
        joined = modifiedLineNumber < unmodifiedLineNumber;
5302
      }
5303
      function findNextValidMatch() {
5304
        var lastMatchTo = lastPos && copyCursor(searchCursor.to());
5305
        var match = searchCursor.findNext();
5306
        if (match && !match[0] && lastMatchTo && cursorEqual(searchCursor.from(), lastMatchTo)) {
5307
          match = searchCursor.findNext();
5308
        }
5309
        return match;
5310
      }
5311
      function next() {
5312
        // The below only loops to skip over multiple occurrences on the same
5313
        // line when 'global' is not true.
5314
        while(findNextValidMatch() &&
5315
              isInRange(searchCursor.from(), lineStart, lineEnd)) {
5316
          if (!global && searchCursor.from().line == modifiedLineNumber && !joined) {
5317
            continue;
5318
          }
5319
          cm.scrollIntoView(searchCursor.from(), 30);
5320
          cm.setSelection(searchCursor.from(), searchCursor.to());
5321
          lastPos = searchCursor.from();
5322
          done = false;
5323
          return;
5324
        }
5325
        done = true;
5326
      }
5327
      function stop(close) {
5328
        if (close) { close(); }
5329
        cm.focus();
5330
        if (lastPos) {
5331
          cm.setCursor(lastPos);
5332
          var vim = cm.state.vim;
5333
          vim.exMode = false;
5334
          vim.lastHPos = vim.lastHSPos = lastPos.ch;
5335
        }
5336
        if (callback) { callback(); }
5337
      }
5338
      function onPromptKeyDown(e, _value, close) {
5339
        // Swallow all keys.
5340
        CodeMirror.e_stop(e);
5341
        var keyName = CodeMirror.keyName(e);
5342
        switch (keyName) {
5343
          case 'Y':
5344
            replace(); next(); break;
5345
          case 'N':
5346
            next(); break;
5347
          case 'A':
5348
            // replaceAll contains a call to close of its own. We don't want it
5349
            // to fire too early or multiple times.
5350
            var savedCallback = callback;
5351
            callback = undefined;
5352
            cm.operation(replaceAll);
5353
            callback = savedCallback;
5354
            break;
5355
          case 'L':
5356
            replace();
5357
            // fall through and exit.
5358
          case 'Q':
5359
          case 'Esc':
5360
          case 'Ctrl-C':
5361
          case 'Ctrl-[':
5362
            stop(close);
5363
            break;
5364
        }
5365
        if (done) { stop(close); }
5366
        return true;
5367
      }
5368

5369
      // Actually do replace.
5370
      next();
5371
      if (done) {
5372
        showConfirm(cm, 'No matches for ' + query.source);
5373
        return;
5374
      }
5375
      if (!confirm) {
5376
        replaceAll();
5377
        if (callback) { callback(); }
5378
        return;
5379
      }
5380
      showPrompt(cm, {
5381
        prefix: dom('span', 'replace with ', dom('strong', replaceWith), ' (y/n/a/q/l)'),
5382
        onKeyDown: onPromptKeyDown
5383
      });
5384
    }
5385

5386
    CodeMirror.keyMap.vim = {
5387
      attach: attachVimMap,
5388
      detach: detachVimMap,
5389
      call: cmKey
5390
    };
5391

5392
    function exitInsertMode(cm) {
5393
      var vim = cm.state.vim;
5394
      var macroModeState = vimGlobalState.macroModeState;
5395
      var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.');
5396
      var isPlaying = macroModeState.isPlaying;
5397
      var lastChange = macroModeState.lastInsertModeChanges;
5398
      if (!isPlaying) {
5399
        cm.off('change', onChange);
5400
        CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
5401
      }
5402
      if (!isPlaying && vim.insertModeRepeat > 1) {
5403
        // Perform insert mode repeat for commands like 3,a and 3,o.
5404
        repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
5405
            true /** repeatForInsert */);
5406
        vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
5407
      }
5408
      delete vim.insertModeRepeat;
5409
      vim.insertMode = false;
5410
      cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1);
5411
      cm.setOption('keyMap', 'vim');
5412
      cm.setOption('disableInput', true);
5413
      cm.toggleOverwrite(false); // exit replace mode if we were in it.
5414
      // update the ". register before exiting insert mode
5415
      insertModeChangeRegister.setText(lastChange.changes.join(''));
5416
      CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
5417
      if (macroModeState.isRecording) {
5418
        logInsertModeChange(macroModeState);
5419
      }
5420
    }
5421

5422
    function _mapCommand(command) {
5423
      defaultKeymap.unshift(command);
5424
    }
5425

5426
    function mapCommand(keys, type, name, args, extra) {
5427
      var command = {keys: keys, type: type};
5428
      command[type] = name;
5429
      command[type + "Args"] = args;
5430
      for (var key in extra)
5431
        command[key] = extra[key];
5432
      _mapCommand(command);
5433
    }
5434

5435
    // The timeout in milliseconds for the two-character ESC keymap should be
5436
    // adjusted according to your typing speed to prevent false positives.
5437
    defineOption('insertModeEscKeysTimeout', 200, 'number');
5438

5439
    CodeMirror.keyMap['vim-insert'] = {
5440
      // TODO: override navigation keys so that Esc will cancel automatic
5441
      // indentation from o, O, i_<CR>
5442
      fallthrough: ['default'],
5443
      attach: attachVimMap,
5444
      detach: detachVimMap,
5445
      call: cmKey
5446
    };
5447

5448
    CodeMirror.keyMap['vim-replace'] = {
5449
      'Backspace': 'goCharLeft',
5450
      fallthrough: ['vim-insert'],
5451
      attach: attachVimMap,
5452
      detach: detachVimMap,
5453
      call: cmKey
5454
    };
5455

5456
    function executeMacroRegister(cm, vim, macroModeState, registerName) {
5457
      var register = vimGlobalState.registerController.getRegister(registerName);
5458
      if (registerName == ':') {
5459
        // Read-only register containing last Ex command.
5460
        if (register.keyBuffer[0]) {
5461
          exCommandDispatcher.processCommand(cm, register.keyBuffer[0]);
5462
        }
5463
        macroModeState.isPlaying = false;
5464
        return;
5465
      }
5466
      var keyBuffer = register.keyBuffer;
5467
      var imc = 0;
5468
      macroModeState.isPlaying = true;
5469
      macroModeState.replaySearchQueries = register.searchQueries.slice(0);
5470
      for (var i = 0; i < keyBuffer.length; i++) {
5471
        var text = keyBuffer[i];
5472
        var match, key;
5473
        while (text) {
5474
          // Pull off one command key, which is either a single character
5475
          // or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
5476
          match = (/<\w+-.+?>|<\w+>|./).exec(text);
5477
          key = match[0];
5478
          text = text.substring(match.index + key.length);
5479
          vimApi.handleKey(cm, key, 'macro');
5480
          if (vim.insertMode) {
5481
            var changes = register.insertModeChanges[imc++].changes;
5482
            vimGlobalState.macroModeState.lastInsertModeChanges.changes =
5483
                changes;
5484
            repeatInsertModeChanges(cm, changes, 1);
5485
            exitInsertMode(cm);
5486
          }
5487
        }
5488
      }
5489
      macroModeState.isPlaying = false;
5490
    }
5491

5492
    function logKey(macroModeState, key) {
5493
      if (macroModeState.isPlaying) { return; }
5494
      var registerName = macroModeState.latestRegister;
5495
      var register = vimGlobalState.registerController.getRegister(registerName);
5496
      if (register) {
5497
        register.pushText(key);
5498
      }
5499
    }
5500

5501
    function logInsertModeChange(macroModeState) {
5502
      if (macroModeState.isPlaying) { return; }
5503
      var registerName = macroModeState.latestRegister;
5504
      var register = vimGlobalState.registerController.getRegister(registerName);
5505
      if (register && register.pushInsertModeChanges) {
5506
        register.pushInsertModeChanges(macroModeState.lastInsertModeChanges);
5507
      }
5508
    }
5509

5510
    function logSearchQuery(macroModeState, query) {
5511
      if (macroModeState.isPlaying) { return; }
5512
      var registerName = macroModeState.latestRegister;
5513
      var register = vimGlobalState.registerController.getRegister(registerName);
5514
      if (register && register.pushSearchQuery) {
5515
        register.pushSearchQuery(query);
5516
      }
5517
    }
5518

5519
    /**
5520
     * Listens for changes made in insert mode.
5521
     * Should only be active in insert mode.
5522
     */
5523
    function onChange(cm, changeObj) {
5524
      var macroModeState = vimGlobalState.macroModeState;
5525
      var lastChange = macroModeState.lastInsertModeChanges;
5526
      if (!macroModeState.isPlaying) {
5527
        while(changeObj) {
5528
          lastChange.expectCursorActivityForChange = true;
5529
          if (lastChange.ignoreCount > 1) {
5530
            lastChange.ignoreCount--;
5531
          } else if (changeObj.origin == '+input' || changeObj.origin == 'paste'
5532
              || changeObj.origin === undefined /* only in testing */) {
5533
            var selectionCount = cm.listSelections().length;
5534
            if (selectionCount > 1)
5535
              lastChange.ignoreCount = selectionCount;
5536
            var text = changeObj.text.join('\n');
5537
            if (lastChange.maybeReset) {
5538
              lastChange.changes = [];
5539
              lastChange.maybeReset = false;
5540
            }
5541
            if (text) {
5542
              if (cm.state.overwrite && !/\n/.test(text)) {
5543
                lastChange.changes.push([text]);
5544
              } else {
5545
                lastChange.changes.push(text);
5546
              }
5547
            }
5548
          }
5549
          // Change objects may be chained with next.
5550
          changeObj = changeObj.next;
5551
        }
5552
      }
5553
    }
5554

5555
    /**
5556
    * Listens for any kind of cursor activity on CodeMirror.
5557
    */
5558
    function onCursorActivity(cm) {
5559
      var vim = cm.state.vim;
5560
      if (vim.insertMode) {
5561
        // Tracking cursor activity in insert mode (for macro support).
5562
        var macroModeState = vimGlobalState.macroModeState;
5563
        if (macroModeState.isPlaying) { return; }
5564
        var lastChange = macroModeState.lastInsertModeChanges;
5565
        if (lastChange.expectCursorActivityForChange) {
5566
          lastChange.expectCursorActivityForChange = false;
5567
        } else {
5568
          // Cursor moved outside the context of an edit. Reset the change.
5569
          lastChange.maybeReset = true;
5570
        }
5571
      } else if (!cm.curOp.isVimOp) {
5572
        handleExternalSelection(cm, vim);
5573
      }
5574
    }
5575
    function handleExternalSelection(cm, vim) {
5576
      var anchor = cm.getCursor('anchor');
5577
      var head = cm.getCursor('head');
5578
      // Enter or exit visual mode to match mouse selection.
5579
      if (vim.visualMode && !cm.somethingSelected()) {
5580
        exitVisualMode(cm, false);
5581
      } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) {
5582
        vim.visualMode = true;
5583
        vim.visualLine = false;
5584
        CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
5585
      }
5586
      if (vim.visualMode) {
5587
        // Bind CodeMirror selection model to vim selection model.
5588
        // Mouse selections are considered visual characterwise.
5589
        var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
5590
        var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
5591
        head = offsetCursor(head, 0, headOffset);
5592
        anchor = offsetCursor(anchor, 0, anchorOffset);
5593
        vim.sel = {
5594
          anchor: anchor,
5595
          head: head
5596
        };
5597
        updateMark(cm, vim, '<', cursorMin(head, anchor));
5598
        updateMark(cm, vim, '>', cursorMax(head, anchor));
5599
      } else if (!vim.insertMode) {
5600
        // Reset lastHPos if selection was modified by something outside of vim mode e.g. by mouse.
5601
        vim.lastHPos = cm.getCursor().ch;
5602
      }
5603
    }
5604

5605
    /** Wrapper for special keys pressed in insert mode */
5606
    function InsertModeKey(keyName) {
5607
      this.keyName = keyName;
5608
    }
5609

5610
    /**
5611
    * Handles raw key down events from the text area.
5612
    * - Should only be active in insert mode.
5613
    * - For recording deletes in insert mode.
5614
    */
5615
    function onKeyEventTargetKeyDown(e) {
5616
      var macroModeState = vimGlobalState.macroModeState;
5617
      var lastChange = macroModeState.lastInsertModeChanges;
5618
      var keyName = CodeMirror.keyName(e);
5619
      if (!keyName) { return; }
5620
      function onKeyFound() {
5621
        if (lastChange.maybeReset) {
5622
          lastChange.changes = [];
5623
          lastChange.maybeReset = false;
5624
        }
5625
        lastChange.changes.push(new InsertModeKey(keyName));
5626
        return true;
5627
      }
5628
      if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
5629
        CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound);
5630
      }
5631
    }
5632

5633
    /**
5634
     * Repeats the last edit, which includes exactly 1 command and at most 1
5635
     * insert. Operator and motion commands are read from lastEditInputState,
5636
     * while action commands are read from lastEditActionCommand.
5637
     *
5638
     * If repeatForInsert is true, then the function was called by
5639
     * exitInsertMode to repeat the insert mode changes the user just made. The
5640
     * corresponding enterInsertMode call was made with a count.
5641
     */
5642
    function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
5643
      var macroModeState = vimGlobalState.macroModeState;
5644
      macroModeState.isPlaying = true;
5645
      var isAction = !!vim.lastEditActionCommand;
5646
      var cachedInputState = vim.inputState;
5647
      function repeatCommand() {
5648
        if (isAction) {
5649
          commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
5650
        } else {
5651
          commandDispatcher.evalInput(cm, vim);
5652
        }
5653
      }
5654
      function repeatInsert(repeat) {
5655
        if (macroModeState.lastInsertModeChanges.changes.length > 0) {
5656
          // For some reason, repeat cw in desktop VIM does not repeat
5657
          // insert mode changes. Will conform to that behavior.
5658
          repeat = !vim.lastEditActionCommand ? 1 : repeat;
5659
          var changeObject = macroModeState.lastInsertModeChanges;
5660
          repeatInsertModeChanges(cm, changeObject.changes, repeat);
5661
        }
5662
      }
5663
      vim.inputState = vim.lastEditInputState;
5664
      if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
5665
        // o and O repeat have to be interlaced with insert repeats so that the
5666
        // insertions appear on separate lines instead of the last line.
5667
        for (var i = 0; i < repeat; i++) {
5668
          repeatCommand();
5669
          repeatInsert(1);
5670
        }
5671
      } else {
5672
        if (!repeatForInsert) {
5673
          // Hack to get the cursor to end up at the right place. If I is
5674
          // repeated in insert mode repeat, cursor will be 1 insert
5675
          // change set left of where it should be.
5676
          repeatCommand();
5677
        }
5678
        repeatInsert(repeat);
5679
      }
5680
      vim.inputState = cachedInputState;
5681
      if (vim.insertMode && !repeatForInsert) {
5682
        // Don't exit insert mode twice. If repeatForInsert is set, then we
5683
        // were called by an exitInsertMode call lower on the stack.
5684
        exitInsertMode(cm);
5685
      }
5686
      macroModeState.isPlaying = false;
5687
    }
5688

5689
    function repeatInsertModeChanges(cm, changes, repeat) {
5690
      function keyHandler(binding) {
5691
        if (typeof binding == 'string') {
5692
          CodeMirror.commands[binding](cm);
5693
        } else {
5694
          binding(cm);
5695
        }
5696
        return true;
5697
      }
5698
      var head = cm.getCursor('head');
5699
      var visualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.visualBlock;
5700
      if (visualBlock) {
5701
        // Set up block selection again for repeating the changes.
5702
        selectForInsert(cm, head, visualBlock + 1);
5703
        repeat = cm.listSelections().length;
5704
        cm.setCursor(head);
5705
      }
5706
      for (var i = 0; i < repeat; i++) {
5707
        if (visualBlock) {
5708
          cm.setCursor(offsetCursor(head, i, 0));
5709
        }
5710
        for (var j = 0; j < changes.length; j++) {
5711
          var change = changes[j];
5712
          if (change instanceof InsertModeKey) {
5713
            CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler);
5714
          } else if (typeof change == "string") {
5715
            cm.replaceSelection(change);
5716
          } else {
5717
            var start = cm.getCursor();
5718
            var end = offsetCursor(start, 0, change[0].length);
5719
            cm.replaceRange(change[0], start, end);
5720
            cm.setCursor(end);
5721
          }
5722
        }
5723
      }
5724
      if (visualBlock) {
5725
        cm.setCursor(offsetCursor(head, 0, 1));
5726
      }
5727
    }
5728

5729
    resetVimGlobalState();
5730
    return vimApi;
5731
  };
5732
  // Initialize Vim and make it available as an API.
5733
  CodeMirror.Vim = Vim();
5734
});
5735

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.