38
if (typeof exports == "object" && typeof module == "object")
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)
41
define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/dialog/dialog", "../addon/edit/matchbrackets"], mod);
44
})(function(CodeMirror) {
47
var Pos = CodeMirror.Pos;
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;
55
if (vim.visualBlock) {
56
if (range.head.line != head.line) {
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);
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' },
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 } },
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'},
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 }},
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' },
187
{ keys: '<C-w>', type: 'idle', context: 'normal' },
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' },
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' },
236
{ keys: 'a<character>', type: 'motion', motion: 'textObjectManipulation' },
237
{ keys: 'i<character>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
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 }},
246
{ keys: ':', type: 'ex' }
248
var defaultKeymapLength = defaultKeymap.length;
256
var defaultExCommandMap = [
257
{ name: 'colorscheme', shortName: 'colo' },
259
{ name: 'imap', shortName: 'im' },
260
{ name: 'nmap', shortName: 'nm' },
261
{ name: 'vmap', shortName: 'vm' },
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' }
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));
289
function leaveVimMode(cm) {
290
cm.setOption('disableInput', false);
291
cm.off('cursorActivity', onCursorActivity);
292
CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
294
if (highlightTimeout) clearTimeout(highlightTimeout);
297
function detachVimMap(cm, next) {
298
if (this == CodeMirror.keyMap.vim) {
299
cm.options.$customCursor = null;
300
CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor");
303
if (!next || next.attach != attachVimMap)
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");
313
if (!prev || prev.attach != attachVimMap)
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");
325
function cmKey(key, cm) {
326
if (!cm) { return undefined; }
327
if (this[key]) { return this[key]; }
328
var vimKey = cmKeyToVimKey(key);
332
var cmd = vimApi.findKey(cm, vimKey);
333
if (typeof cmd == 'function') {
334
CodeMirror.signal(cm, 'vim-keypress', vimKey);
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) == '\'') {
344
return key.charAt(1);
346
var pieces = key.split(/-(?!$)/);
347
var lastPiece = pieces[pieces.length - 1];
348
if (pieces.length == 1 && pieces[0].length == 1) {
351
} else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) {
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]; }
368
if (isUpperCase(lastPiece)) {
369
pieces[pieces.length - 1] = lastPiece.toLowerCase();
371
return '<' + pieces.join('-') + '>';
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);
384
return vim.onPasteFn;
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);
393
function makeKeyRange(start, size) {
395
for (var i = start; i < start + size; i++) {
396
keys.push(String.fromCharCode(i));
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, ['-', '"', '.', ':', '_', '/']);
406
try { upperCaseChars = new RegExp("^[\\p{Lu}]$", "u"); }
407
catch (_) { upperCaseChars = /^[A-Z]$/; }
409
function isLine(cm, line) {
410
return line >= cm.firstLine() && line <= cm.lastLine();
412
function isLowerCase(k) {
413
return (/^[a-z]$/).test(k);
415
function isMatchableSymbol(k) {
416
return '()[]{}'.indexOf(k) != -1;
418
function isNumber(k) {
419
return numberRegex.test(k);
421
function isUpperCase(k) {
422
return upperCaseChars.test(k);
424
function isWhiteSpaceString(k) {
425
return (/^\s*$/).test(k);
427
function isEndOfSentenceSymbol(k) {
428
return '.?!'.indexOf(k) != -1;
430
function inArray(val, arr) {
431
for (var i = 0; i < arr.length; i++) {
440
function defineOption(name, defaultValue, type, aliases, callback) {
441
if (defaultValue === undefined && !callback) {
442
throw Error('defaultValue is required unless callback is provided');
444
if (!type) { type = 'string'; }
447
defaultValue: defaultValue,
451
for (var i = 0; i < aliases.length; i++) {
452
options[aliases[i]] = options[name];
456
setOption(name, defaultValue);
460
function setOption(name, value, cm, cfg) {
461
var option = options[name];
463
var scope = cfg.scope;
465
return new Error('Unknown option: ' + name);
467
if (option.type == 'boolean') {
468
if (value && value !== true) {
469
return new Error('Invalid argument: ' + name + '=' + value);
470
} else if (value !== false) {
475
if (option.callback) {
476
if (scope !== 'local') {
477
option.callback(value, undefined);
479
if (scope !== 'global' && cm) {
480
option.callback(value, cm);
483
if (scope !== 'local') {
484
option.value = option.type == 'boolean' ? !!value : value;
486
if (scope !== 'global' && cm) {
487
cm.state.vim.options[name] = {value: value};
492
function getOption(name, cm, cfg) {
493
var option = options[name];
495
var scope = cfg.scope;
497
return new Error('Unknown option: ' + name);
499
if (option.callback) {
500
var local = cm && option.callback(undefined, cm);
501
if (scope !== 'global' && local !== undefined) {
504
if (scope !== 'local') {
505
return option.callback();
509
var local = (scope !== 'global') && (cm && cm.state.vim.options[name]);
510
return (local || (scope !== 'local') && option || {}).value;
514
defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) {
516
if (cm === undefined) {
520
if (name === undefined) {
521
var mode = cm.getOption('mode');
522
return mode == 'null' ? '' : mode;
524
var mode = name == '' ? 'null' : name;
525
cm.setOption('mode', mode);
529
var createCircularJumpList = function() {
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];
544
buffer[next] = cm.setBookmark(cursor);
547
var markPos = curMark.find();
549
if (markPos && !cursorEqual(markPos, oldCur)) {
557
tail = pointer - size + 1;
562
function move(cm, offset) {
564
if (pointer > head) {
566
} else if (pointer < tail) {
569
var mark = buffer[(size + pointer) % size];
571
if (mark && !mark.find()) {
572
var inc = offset > 0 ? 1 : -1;
574
var oldCur = cm.getCursor();
577
mark = buffer[(size + pointer) % size];
580
(newCur = mark.find()) &&
581
!cursorEqual(oldCur, newCur)) {
584
} while (pointer < head && pointer > tail);
588
function find(cm, offset) {
589
var oldPointer = pointer;
590
var mark = move(cm, offset);
591
pointer = oldPointer;
592
return mark && mark.find();
595
cachedCursor: undefined,
605
var createInsertModeChanges = function(c) {
610
expectCursorActivityForChange: c.expectCursorActivityForChange
617
expectCursorActivityForChange: false
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();
629
MacroModeState.prototype = {
630
exitMacroRecordMode: function() {
631
var macroModeState = vimGlobalState.macroModeState;
632
if (macroModeState.onRecordingDone) {
633
macroModeState.onRecordingDone();
635
macroModeState.onRecordingDone = undefined;
636
macroModeState.isRecording = false;
638
enterMacroRecordMode: function(cm, registerName) {
640
vimGlobalState.registerController.getRegister(registerName);
643
this.latestRegister = registerName;
645
this.onRecordingDone = cm.openDialog(
646
document.createTextNode('(recording)['+registerName+']'), null, {bottom:true});
648
this.isRecording = true;
653
function maybeInitVimState(cm) {
657
inputState: new InputState(),
660
lastEditInputState: undefined,
663
lastEditActionCommand: undefined,
679
insertModeRepeat: undefined,
685
lastPastedText: null,
694
function resetVimGlobalState() {
699
searchIsReversed: false,
701
lastSubstituteReplacePart: undefined,
702
jumpList: createCircularJumpList(),
703
macroModeState: new MacroModeState,
705
lastCharacterSearch: {increment:0, forward:true, selectedCharacter:''},
706
registerController: new RegisterController({}),
708
searchHistoryController: new HistoryController(),
710
exCommandHistoryController : new HistoryController()
712
for (var optionName in options) {
713
var option = options[optionName];
714
option.value = option.defaultValue;
718
var lastInsertModeKeyTimer;
720
buildKeyMap: function() {
725
getRegisterController: function() {
726
return vimGlobalState.registerController;
729
resetVimGlobalState_: resetVimGlobalState,
732
getVimGlobalState_: function() {
733
return vimGlobalState;
737
maybeInitVimState_: maybeInitVimState,
739
suppressErrorLogging: false,
741
InsertModeKey: InsertModeKey,
742
map: function(lhs, rhs, ctx) {
744
exCommandDispatcher.map(lhs, rhs, ctx);
746
unmap: function(lhs, ctx) {
747
return exCommandDispatcher.unmap(lhs, ctx);
752
noremap: function(lhs, rhs, ctx) {
753
function toCtxArray(ctx) {
754
return ctx ? [ctx] : ['normal', 'insert', 'visual'];
756
var ctxsToMap = toCtxArray(ctx);
758
var actualLength = defaultKeymap.length, origLength = defaultKeymapLength;
759
for (var i = actualLength - origLength;
760
i < actualLength && ctxsToMap.length;
762
var mapping = defaultKeymap[i];
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') {
770
for (var key in mapping) {
771
newMapping[key] = mapping[key];
774
newMapping.keys = lhs;
775
if (ctx && !newMapping.context) {
776
newMapping.context = ctx;
779
this._mapCommand(newMapping);
781
var mappedCtxs = toCtxArray(mapping.context);
782
ctxsToMap = ctxsToMap.filter(function(el) { return mappedCtxs.indexOf(el) === -1; });
788
mapclear: function(ctx) {
790
var actualLength = defaultKeymap.length,
791
origLength = defaultKeymapLength;
792
var userKeymap = defaultKeymap.slice(0, actualLength - origLength);
793
defaultKeymap = defaultKeymap.slice(actualLength - origLength);
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);
805
var contexts = ['normal', 'insert', 'visual'];
806
for (var j in contexts) {
807
if (contexts[j] !== ctx) {
809
for (var key in mapping) {
810
newMapping[key] = mapping[key];
812
newMapping.context = contexts[j];
813
this._mapCommand(newMapping);
823
setOption: setOption,
824
getOption: getOption,
825
defineOption: defineOption,
826
defineEx: function(name, prefix, func){
829
} else if (name.indexOf(prefix) !== 0) {
830
throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
832
exCommands[name]=func;
833
exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
835
handleKey: function (cm, key, origin) {
836
var command = this.findKey(cm, key, origin);
837
if (typeof command === 'function') {
851
findKey: function(cm, key, origin) {
852
var vim = maybeInitVimState(cm);
853
function handleMacroRecording() {
854
var macroModeState = vimGlobalState.macroModeState;
855
if (macroModeState.isRecording) {
857
macroModeState.exitMacroRecordMode();
861
if (origin != 'mapping') {
862
logKey(macroModeState, key);
866
function handleEsc() {
867
if (key == '<Esc>') {
870
if (vim.visualMode) {
872
} else if (vim.insertMode) {
878
function doKeyToKey(keys) {
884
match = (/<\w+-.+?>|<\w+>|./).exec(keys);
886
keys = keys.substring(match.index + key.length);
887
vimApi.handleKey(cm, key, 'mapping');
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');
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; }
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;
911
if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
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');
918
vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop();
921
return match.command;
924
function handleKeyNonInsertMode() {
925
if (handleMacroRecording() || handleEsc()) { return true; }
927
var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
928
if (/^[1-9]\d*$/.test(keys)) { return true; }
930
var keysMatcher = /^(\d*)(.*)$/.exec(keys);
931
if (!keysMatcher) { clearInputState(cm); return false; }
932
var context = vim.visualMode ? 'visual' :
934
var mainKey = keysMatcher[2] || keysMatcher[1];
935
if (vim.inputState.operatorShortcut && vim.inputState.operatorShortcut.slice(-1) == mainKey) {
937
mainKey = vim.inputState.operatorShortcut;
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; }
943
vim.inputState.keyBuffer = '';
944
var keysMatcher = /^(\d*)(.*)$/.exec(keys);
945
if (keysMatcher[1] && keysMatcher[1] != '0') {
946
vim.inputState.pushRepeatDigit(keysMatcher[1]);
948
return match.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) {
960
return function() { return true; };
963
return cm.operation(function() {
964
cm.curOp.isVimOp = true;
966
if (command.type == 'keyToKey') {
967
doKeyToKey(command.toKeys);
969
commandDispatcher.processCommand(cm, vim, command);
973
cm.state.vim = undefined;
974
maybeInitVimState(cm);
975
if (!vimApi.suppressErrorLogging) {
985
handleEx: function(cm, input) {
986
exCommandDispatcher.processCommand(cm, input);
989
defineMotion: defineMotion,
990
defineAction: defineAction,
991
defineOperator: defineOperator,
992
mapCommand: mapCommand,
993
_mapCommand: _mapCommand,
995
defineRegister: defineRegister,
997
exitVisualMode: exitVisualMode,
998
exitInsertMode: exitInsertMode
1002
function InputState() {
1003
this.prefixRepeat = [];
1004
this.motionRepeat = [];
1006
this.operator = null;
1007
this.operatorArgs = null;
1009
this.motionArgs = null;
1010
this.keyBuffer = [];
1011
this.registerName = null;
1013
InputState.prototype.pushRepeatDigit = function(n) {
1014
if (!this.operator) {
1015
this.prefixRepeat = this.prefixRepeat.concat(n);
1017
this.motionRepeat = this.motionRepeat.concat(n);
1020
InputState.prototype.getRepeat = function() {
1022
if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
1024
if (this.prefixRepeat.length > 0) {
1025
repeat *= parseInt(this.prefixRepeat.join(''), 10);
1027
if (this.motionRepeat.length > 0) {
1028
repeat *= parseInt(this.motionRepeat.join(''), 10);
1034
function clearInputState(cm, reason) {
1035
cm.state.vim.inputState = new InputState();
1036
CodeMirror.signal(cm, 'vim-command-done', reason);
1045
function Register(text, linewise, blockwise) {
1047
this.keyBuffer = [text || ''];
1048
this.insertModeChanges = [];
1049
this.searchQueries = [];
1050
this.linewise = !!linewise;
1051
this.blockwise = !!blockwise;
1053
Register.prototype = {
1054
setText: function(text, linewise, blockwise) {
1055
this.keyBuffer = [text || ''];
1056
this.linewise = !!linewise;
1057
this.blockwise = !!blockwise;
1059
pushText: function(text, linewise) {
1062
if (!this.linewise) {
1063
this.keyBuffer.push('\n');
1065
this.linewise = true;
1067
this.keyBuffer.push(text);
1069
pushInsertModeChanges: function(changes) {
1070
this.insertModeChanges.push(createInsertModeChanges(changes));
1072
pushSearchQuery: function(query) {
1073
this.searchQueries.push(query);
1076
this.keyBuffer = [];
1077
this.insertModeChanges = [];
1078
this.searchQueries = [];
1079
this.linewise = false;
1081
toString: function() {
1082
return this.keyBuffer.join('');
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');
1098
if (registers[name]) {
1099
throw Error('Register already defined ' + name);
1101
registers[name] = register;
1102
validRegisters.push(name);
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();
1120
RegisterController.prototype = {
1121
pushText: function(registerName, operator, text, linewise, blockwise) {
1123
if (registerName === '_') return;
1124
if (linewise && text.charAt(text.length - 1) !== '\n'){
1129
var register = this.isValidRegister(registerName) ?
1130
this.getRegister(registerName) : null;
1137
this.registers['0'] = new Register(text, linewise, blockwise);
1141
if (text.indexOf('\n') == -1) {
1143
this.registers['-'] = new Register(text, linewise);
1147
this.shiftNumericRegisters_();
1148
this.registers['1'] = new Register(text, linewise);
1153
this.unnamedRegister.setText(text, linewise, blockwise);
1158
var append = isUpperCase(registerName);
1160
register.pushText(text, linewise);
1162
register.setText(text, linewise, blockwise);
1166
this.unnamedRegister.setText(register.toString(), linewise);
1170
getRegister: function(name) {
1171
if (!this.isValidRegister(name)) {
1172
return this.unnamedRegister;
1174
name = name.toLowerCase();
1175
if (!this.registers[name]) {
1176
this.registers[name] = new Register();
1178
return this.registers[name];
1180
isValidRegister: function(name) {
1181
return name && inArray(name, validRegisters);
1183
shiftNumericRegisters_: function() {
1184
for (var i = 9; i >= 2; i--) {
1185
this.registers[i] = this.getRegister('' + (i - 1));
1189
function HistoryController() {
1190
this.historyBuffer = [];
1192
this.initialPrefix = null;
1194
HistoryController.prototype = {
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)) {
1211
if (i >= historyBuffer.length) {
1212
this.iterator = historyBuffer.length;
1213
return this.initialPrefix;
1216
if (i < 0 ) return input;
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);
1224
this.initialPrefix = null;
1225
this.iterator = this.historyBuffer.length;
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'};
1238
for (var i = 0; i < matches.full.length; i++) {
1239
var match = matches.full[i];
1244
if (bestMatch.keys.slice(-11) == '<character>') {
1245
var character = lastChar(keys);
1246
if (!character) return {type: 'none'};
1247
inputState.selectedCharacter = character;
1249
return {type: 'full', command: bestMatch};
1251
processCommand: function(cm, vim, command) {
1252
vim.inputState.repeatOverride = command.repeatOverride;
1253
switch (command.type) {
1255
this.processMotion(cm, vim, command);
1258
this.processOperator(cm, vim, command);
1260
case 'operatorMotion':
1261
this.processOperatorMotion(cm, vim, command);
1264
this.processAction(cm, vim, command);
1267
this.processSearch(cm, vim, command);
1271
this.processEx(cm, vim, command);
1277
processMotion: function(cm, vim, command) {
1278
vim.inputState.motion = command.motion;
1279
vim.inputState.motionArgs = copyArgs(command.motionArgs);
1280
this.evalInput(cm, vim);
1282
processOperator: function(cm, vim, command) {
1283
var inputState = vim.inputState;
1284
if (inputState.operator) {
1285
if (inputState.operator == command.operator) {
1288
inputState.motion = 'expandToLine';
1289
inputState.motionArgs = { linewise: true };
1290
this.evalInput(cm, vim);
1294
clearInputState(cm);
1297
inputState.operator = command.operator;
1298
inputState.operatorArgs = copyArgs(command.operatorArgs);
1299
if (command.keys.length > 1) {
1300
inputState.operatorShortcut = command.keys;
1302
if (command.exitVisualBlock) {
1303
vim.visualBlock = false;
1304
updateCmSelection(cm);
1306
if (vim.visualMode) {
1308
this.evalInput(cm, vim);
1311
processOperatorMotion: function(cm, vim, command) {
1312
var visualMode = vim.visualMode;
1313
var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
1314
if (operatorMotionArgs) {
1316
if (visualMode && operatorMotionArgs.visualLine) {
1317
vim.visualLine = true;
1320
this.processOperator(cm, vim, command);
1322
this.processMotion(cm, vim, command);
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;
1334
if (command.operator) {
1335
this.processOperator(cm, vim, command);
1337
if (command.motion) {
1338
this.processMotion(cm, vim, command);
1340
if (command.motion || command.operator) {
1341
this.evalInput(cm, vim);
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);
1351
actions[command.action](cm, actionArgs, vim);
1353
processSearch: function(cm, vim, command) {
1354
if (!cm.getSearchCursor) {
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();
1368
updateSearchQuery(cm, query, ignoreCase, smartCase);
1370
showConfirm(cm, 'Invalid regex: ' + query);
1371
clearInputState(cm);
1374
commandDispatcher.processMotion(cm, vim, {
1377
motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
1380
function onPromptClose(query) {
1381
cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
1382
handleQuery(query, true , true );
1383
var macroModeState = vimGlobalState.macroModeState;
1384
if (macroModeState.isRecording) {
1385
logSearchQuery(macroModeState, query);
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) || '';
1395
if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
1397
if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
1398
vimGlobalState.searchHistoryController.reset();
1402
parsedQuery = updateSearchQuery(cm, query,
1408
cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
1410
clearSearchHighlight(cm);
1411
cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
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);
1427
} else if (keyName == 'Up' || keyName == 'Down') {
1428
CodeMirror.e_stop(e);
1429
} else if (keyName == 'Ctrl-U') {
1431
CodeMirror.e_stop(e);
1435
switch (command.searchArgs.querySrc) {
1437
var macroModeState = vimGlobalState.macroModeState;
1438
if (macroModeState.isPlaying) {
1439
var query = macroModeState.replaySearchQueries.shift();
1440
handleQuery(query, true , false );
1443
onClose: onPromptClose,
1444
prefix: promptPrefix,
1445
desc: '(JavaScript regexp)',
1446
onKeyUp: onPromptKeyUp,
1447
onKeyDown: onPromptKeyDown
1451
case 'wordUnderCursor':
1452
var word = expandWordUnderCursor(cm, false ,
1455
var isKeyword = true;
1457
word = expandWordUnderCursor(cm, false ,
1465
var query = cm.getLine(word.start.line).substring(word.start.ch,
1467
if (isKeyword && wholeWordOnly) {
1468
query = '\\b' + query + '\\b';
1470
query = escapeRegex(query);
1476
vimGlobalState.jumpList.cachedCursor = cm.getCursor();
1477
cm.setCursor(word.start);
1479
handleQuery(query, true , false );
1483
processEx: function(cm, vim, command) {
1484
function onPromptClose(input) {
1487
vimGlobalState.exCommandHistoryController.pushInput(input);
1488
vimGlobalState.exCommandHistoryController.reset();
1489
exCommandDispatcher.processCommand(cm, input);
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);
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) || '';
1508
if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
1509
} else if (keyName == 'Ctrl-U') {
1511
CodeMirror.e_stop(e);
1514
if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
1515
vimGlobalState.exCommandHistoryController.reset();
1518
if (command.type == 'keyToEx') {
1520
exCommandDispatcher.processCommand(cm, command.exArgs.input);
1522
if (vim.visualMode) {
1523
showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
1524
onKeyDown: onPromptKeyDown, selectValueOnOpen: false});
1526
showPrompt(cm, { onClose: onPromptClose, prefix: ':',
1527
onKeyDown: onPromptKeyDown});
1531
evalInput: function(cm, vim) {
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;
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;
1549
this.recordLastEdit(vim, inputState);
1551
if (inputState.repeatOverride !== undefined) {
1554
repeat = inputState.repeatOverride;
1556
repeat = inputState.getRepeat();
1558
if (repeat > 0 && motionArgs.explicitRepeat) {
1559
motionArgs.repeatIsExplicit = true;
1560
} else if (motionArgs.noRepeat ||
1561
(!motionArgs.explicitRepeat && repeat === 0)) {
1563
motionArgs.repeatIsExplicit = false;
1565
if (inputState.selectedCharacter) {
1567
motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
1568
inputState.selectedCharacter;
1570
motionArgs.repeat = repeat;
1571
clearInputState(cm);
1573
var motionResult = motions[motion](cm, origHead, motionArgs, vim, inputState);
1574
vim.lastMotion = motions[motion];
1575
if (!motionResult) {
1578
if (motionArgs.toJumplist) {
1579
var jumpList = vimGlobalState.jumpList;
1581
var cachedCursor = jumpList.cachedCursor;
1583
recordJumpPosition(cm, cachedCursor, motionResult);
1584
delete jumpList.cachedCursor;
1586
recordJumpPosition(cm, origHead, motionResult);
1589
if (motionResult instanceof Array) {
1590
newAnchor = motionResult[0];
1591
newHead = motionResult[1];
1593
newHead = motionResult;
1597
newHead = copyCursor(origHead);
1599
if (vim.visualMode) {
1600
if (!(vim.visualBlock && newHead.ch === Infinity)) {
1601
newHead = clipCursorToContent(cm, newHead);
1604
newAnchor = clipCursorToContent(cm, newAnchor);
1606
newAnchor = newAnchor || oldAnchor;
1607
sel.anchor = newAnchor;
1609
updateCmSelection(cm);
1610
updateMark(cm, vim, '<',
1611
cursorIsBefore(newAnchor, newHead) ? newAnchor
1613
updateMark(cm, vim, '>',
1614
cursorIsBefore(newAnchor, newHead) ? newHead
1616
} else if (!operator) {
1617
newHead = clipCursorToContent(cm, newHead);
1618
cm.setCursor(newHead.line, newHead.ch);
1622
if (operatorArgs.lastSel) {
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) {
1630
newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
1631
} else if (lastSel.visualBlock) {
1633
newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);
1634
} else if (lastSel.head.line == lastSel.anchor.line) {
1636
newHead = new Pos(oldAnchor.line, oldAnchor.ch + chOffset);
1640
newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
1642
vim.visualMode = true;
1643
vim.visualLine = lastSel.visualLine;
1644
vim.visualBlock = lastSel.visualBlock;
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
1658
var curStart, curEnd, linewise, mode;
1660
if (vim.visualMode) {
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' :
1668
cmSel = makeCmSelection(cm, {
1673
var ranges = cmSel.ranges;
1674
if (mode == 'block') {
1676
for (var i = 0; i < ranges.length; i++) {
1677
ranges[i].head.ch = lineLength(cm, ranges[i].head.line);
1679
} else if (mode == 'line') {
1680
ranges[0].head = new Pos(ranges[0].head.line + 1, 0);
1685
curStart = copyCursor(newAnchor || oldAnchor);
1686
curEnd = copyCursor(newHead || oldHead);
1687
if (cursorIsBefore(curEnd, curStart)) {
1692
linewise = motionArgs.linewise || operatorArgs.linewise;
1695
expandSelectionToLine(cm, curStart, curEnd);
1696
} else if (motionArgs.forward) {
1698
clipToLine(cm, curStart, curEnd);
1701
var exclusive = !motionArgs.inclusive || linewise;
1702
cmSel = makeCmSelection(cm, {
1705
}, mode, exclusive);
1707
cm.setSelections(cmSel.ranges, cmSel.primary);
1708
vim.lastMotion = null;
1709
operatorArgs.repeat = repeat;
1710
operatorArgs.registerName = registerName;
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);
1718
if (operatorMoveTo) {
1719
cm.setCursor(operatorMoveTo);
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;
1740
moveToTopLine: function(cm, _head, motionArgs) {
1741
var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
1742
return new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
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)));
1749
moveToBottomLine: function(cm, _head, motionArgs) {
1750
var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
1751
return new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
1753
expandToLine: function(_cm, head, motionArgs) {
1757
return new Pos(cur.line + motionArgs.repeat - 1, Infinity);
1759
findNext: function(cm, _head, motionArgs) {
1760
var state = getSearchState(cm);
1761
var query = state.getQuery();
1765
var prev = !motionArgs.forward;
1767
prev = (state.isReversed()) ? !prev : prev;
1768
highlightSearchMatches(cm, query);
1769
return findNext(cm, prev, query, motionArgs.repeat);
1783
findAndSelectNextInclusive: function(cm, _head, motionArgs, vim, prevInputState) {
1784
var state = getSearchState(cm);
1785
var query = state.getQuery();
1791
var prev = !motionArgs.forward;
1792
prev = (state.isReversed()) ? !prev : prev;
1795
var next = findNextFromAndToInclusive(cm, prev, query, motionArgs.repeat, vim);
1803
if (prevInputState.operator) {
1814
var to = new Pos(next[1].line, next[1].ch - 1);
1816
if (vim.visualMode) {
1818
if (vim.visualLine || vim.visualBlock) {
1819
vim.visualLine = false;
1820
vim.visualBlock = false;
1821
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: ""});
1826
var anchor = vim.sel.anchor;
1828
if (state.isReversed()) {
1829
if (motionArgs.forward) {
1830
return [anchor, from];
1833
return [anchor, to];
1835
if (motionArgs.forward) {
1836
return [anchor, to];
1839
return [anchor, from];
1844
vim.visualMode = true;
1845
vim.visualLine = false;
1846
vim.visualBlock = false;
1847
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: ""});
1850
return prev ? [to, from] : [from, to];
1852
goToMark: function(cm, _head, motionArgs, vim) {
1853
var pos = getMarkPos(cm, vim, motionArgs.selectedCharacter);
1855
return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos;
1859
moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) {
1860
if (vim.visualBlock && motionArgs.sameLine) {
1863
clipCursorToContent(cm, new Pos(sel.anchor.line, sel.head.ch)),
1864
clipCursorToContent(cm, new Pos(sel.head.line, sel.anchor.ch))
1867
return ([vim.sel.head, vim.sel.anchor]);
1870
jumpToMark: function(cm, head, motionArgs, vim) {
1872
for (var i = 0; i < motionArgs.repeat; i++) {
1874
for (var key in vim.marks) {
1875
if (!isLowerCase(key)) {
1878
var mark = vim.marks[key].find();
1879
var isWrongDirection = (motionArgs.forward) ?
1880
cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
1882
if (isWrongDirection) {
1885
if (motionArgs.linewise && (mark.line == cursor.line)) {
1889
var equal = cursorEqual(cursor, best);
1890
var between = (motionArgs.forward) ?
1891
cursorIsBetween(cursor, mark, best) :
1892
cursorIsBetween(best, mark, cursor);
1894
if (equal || between) {
1900
if (motionArgs.linewise) {
1904
best = new Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));
1908
moveByCharacters: function(_cm, head, motionArgs) {
1910
var repeat = motionArgs.repeat;
1911
var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
1912
return new Pos(cur.line, ch);
1914
moveByLines: function(cm, head, motionArgs, vim) {
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;
1931
vim.lastHPos = endCh;
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) {
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);
1950
if (motionArgs.toFirstChar){
1951
endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
1952
vim.lastHPos = endCh;
1954
vim.lastHSPos = cm.charCoords(new Pos(line, endCh),'div').left;
1955
return new Pos(line, endCh);
1957
moveByDisplayLines: function(cm, head, motionArgs, vim) {
1959
switch (vim.lastMotion) {
1960
case this.moveByDisplayLines:
1961
case this.moveByScroll:
1962
case this.moveByLines:
1963
case this.moveToColumn:
1964
case this.moveToEol:
1967
vim.lastHSPos = cm.charCoords(cur,'div').left;
1969
var repeat = motionArgs.repeat;
1970
var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
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');
1977
var resCoords = cm.charCoords(new Pos(cm.firstLine(), 0), 'div');
1978
resCoords.left = vim.lastHSPos;
1979
res = cm.coordsChar(resCoords, 'div');
1982
vim.lastHPos = res.ch;
1985
moveByPage: function(cm, head, motionArgs) {
1989
var curStart = head;
1990
var repeat = motionArgs.repeat;
1991
return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
1993
moveByParagraph: function(cm, head, motionArgs) {
1994
var dir = motionArgs.forward ? 1 : -1;
1995
return findParagraph(cm, head, motionArgs.repeat, dir);
1997
moveBySentence: function(cm, head, motionArgs) {
1998
var dir = motionArgs.forward ? 1 : -1;
1999
return findSentence(cm, head, motionArgs.repeat, dir);
2001
moveByScroll: function(cm, head, motionArgs, vim) {
2002
var scrollbox = cm.getScrollInfo();
2004
var repeat = motionArgs.repeat;
2006
repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
2008
var orig = cm.charCoords(head, 'local');
2009
motionArgs.repeat = repeat;
2010
var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);
2014
var dest = cm.charCoords(curEnd, 'local');
2015
cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
2018
moveByWords: function(cm, head, motionArgs) {
2019
return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward,
2020
!!motionArgs.wordEnd, !!motionArgs.bigWord);
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;
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;
2038
moveToSymbol: function(cm, head, motionArgs) {
2039
var repeat = motionArgs.repeat;
2040
return findSymbol(cm, repeat, motionArgs.forward,
2041
motionArgs.selectedCharacter) || head;
2043
moveToColumn: function(cm, head, motionArgs, vim) {
2044
var repeat = motionArgs.repeat;
2046
vim.lastHPos = repeat - 1;
2047
vim.lastHSPos = cm.charCoords(head,'div').left;
2048
return moveToColumn(cm, repeat);
2050
moveToEol: function(cm, head, motionArgs, vim) {
2051
return moveToEol(cm, head, motionArgs, vim, false);
2053
moveToFirstNonWhiteSpaceCharacter: function(cm, head) {
2057
return new Pos(cursor.line,
2058
findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
2060
moveToMatchedSymbol: function(cm, head) {
2062
var line = cursor.line;
2064
var lineText = cm.getLine(line);
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") {
2075
if (ch < lineText.length) {
2077
var re = (ch === '<' || ch === '>') ? /[(){}[\]<>]/ : /[(){}[\]]/;
2078
var matched = cm.findMatchingBracket(new Pos(line, ch), {bracketRegex: re});
2084
moveToStartOfLine: function(_cm, head) {
2085
return new Pos(head.line, 0);
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');
2092
return new Pos(lineNum,
2093
findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
2095
moveToStartOfDisplayLine: function(cm) {
2096
cm.execCommand("goLineLeft");
2097
return cm.getCursor();
2099
moveToEndOfDisplayLine: function(cm) {
2100
cm.execCommand("goLineRight");
2101
var head = cm.getCursor();
2102
if (head.sticky == "before") head.ch--;
2105
textObjectManipulation: function(cm, head, motionArgs, vim) {
2108
var mirroredPairs = {'(': ')', ')': '(',
2111
'<': '>', '>': '<'};
2112
var selfPaired = {'\'': true, '"': true, '`': true};
2114
var character = motionArgs.selectedCharacter;
2117
if (character == 'b') {
2119
} else if (character == 'B') {
2128
var inclusive = !motionArgs.textObjectInner;
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 ,
2138
} else if (character === 'w') {
2139
tmp = expandWordUnderCursor(cm, inclusive, true ,
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; }
2147
var operatorArgs = vim.inputState.operatorArgs;
2148
if (operatorArgs) { operatorArgs.linewise = true; }
2151
} else if (character === 't') {
2152
tmp = expandTagUnderCursor(cm, head, inclusive);
2158
if (!cm.state.vim.visualMode) {
2159
return [tmp.start, tmp.end];
2161
return expandSelection(cm, tmp.start, tmp.end);
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);
2174
cm.moveH(increment, 'char');
2177
curEnd.ch += increment;
2182
function defineMotion(name, fn) {
2186
function fillArray(val, times) {
2188
for (var i = 0; i < times; i++) {
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)) {
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);
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);
2220
cm.replaceRange('', anchor, head);
2222
if (args.linewise) {
2225
cm.setCursor(prevLineEnd);
2226
CodeMirror.commands.newlineAndIndent(cm);
2229
anchor.ch = Number.MAX_VALUE;
2232
} else if (args.fullLine) {
2233
head.ch = Number.MAX_VALUE;
2235
cm.setSelection(anchor, head)
2236
text = cm.getSelection();
2237
cm.replaceSelection("");
2240
text = cm.getSelection();
2241
var replacement = fillArray('', ranges.length);
2242
cm.replaceSelections(replacement);
2243
finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
2245
vimGlobalState.registerController.pushText(
2246
args.registerName, 'change', text,
2247
args.linewise, ranges.length > 1);
2248
actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim);
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) {
2262
if (anchor.line == cm.firstLine()) {
2265
anchor = new Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));
2268
text = cm.getRange(anchor, head);
2269
cm.replaceRange('', anchor, head);
2271
if (args.linewise) {
2272
finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);
2275
text = cm.getSelection();
2276
var replacement = fillArray('', ranges.length);
2277
cm.replaceSelections(replacement);
2278
finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
2280
vimGlobalState.registerController.pushText(
2281
args.registerName, 'delete', text,
2282
args.linewise, vim.visualBlock);
2283
return clipCursorToContent(cm, finalHead);
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;
2293
var repeat = (vim.visualMode) ? args.repeat : 1;
2294
if (args.linewise) {
2300
for (var i = startLine; i <= endLine; i++) {
2301
for (var j = 0; j < repeat; j++) {
2302
cm.indentLine(i, args.indentRight);
2305
return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
2307
indentAuto: function(cm, _args, ranges) {
2308
cm.execCommand("indentAuto");
2309
return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
2311
changeCase: function(cm, args, ranges, oldAnchor, newHead) {
2312
var selections = cm.getSelections();
2314
var toLower = args.toLower;
2315
for (var j = 0; j < selections.length; j++) {
2316
var toSwap = selections[j];
2318
if (toLower === true) {
2319
text = toSwap.toLowerCase();
2320
} else if (toLower === false) {
2321
text = toSwap.toUpperCase();
2323
for (var i = 0; i < toSwap.length; i++) {
2324
var character = toSwap.charAt(i);
2325
text += isUpperCase(character) ? character.toLowerCase() :
2326
character.toUpperCase();
2331
cm.replaceSelections(swapped);
2332
if (args.shouldMoveCursor){
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){
2339
return cursorMin(ranges[0].anchor, ranges[0].head);
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)
2348
vimGlobalState.registerController.pushText(
2349
args.registerName, 'yank',
2350
text, args.linewise, vim.visualBlock);
2355
function defineOperator(name, fn) {
2356
operators[name] = fn;
2360
jumpListWalk: function(cm, actionArgs, vim) {
2361
if (vim.visualMode) {
2364
var repeat = actionArgs.repeat;
2365
var forward = actionArgs.forward;
2366
var jumpList = vimGlobalState.jumpList;
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);
2373
scroll: function(cm, actionArgs, vim) {
2374
if (vim.visualMode) {
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);
2393
cm.scrollTo(null, newPos);
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');
2403
null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
2406
cm.scrollTo(null, newPos);
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;
2419
case 'bottom': y = y - height + lineHeight;
2422
cm.scrollTo(null, y);
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;
2431
macroModeState.latestRegister = registerName;
2434
executeMacroRegister(cm, vim, macroModeState, registerName);
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);
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"});
2450
cm.toggleOverwrite(false);
2451
cm.setOption('keyMap', 'vim-insert');
2452
CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
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;
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)
2474
if (!vim.visualBlock) {
2475
if (sel.head.line < sel.anchor.line) {
2478
head = new Pos(sel.anchor.line, 0);
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;
2486
} else if (insertAt == 'endOfSelectedArea') {
2487
if (!vim.visualMode)
2489
if (!vim.visualBlock) {
2490
if (sel.head.line >= sel.anchor.line) {
2491
head = offsetCursor(sel.head, 0, 1);
2493
head = new Pos(sel.anchor.line, 0);
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;
2501
} else if (insertAt == 'inplace') {
2502
if (vim.visualMode){
2505
} else if (insertAt == 'lastEdit') {
2506
head = getLastEditPos(cm) || head;
2508
cm.setOption('disableInput', false);
2509
if (actionArgs && actionArgs.replace) {
2511
cm.toggleOverwrite(true);
2512
cm.setOption('keyMap', 'vim-replace');
2513
CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
2515
cm.toggleOverwrite(false);
2516
cm.setOption('keyMap', 'vim-insert');
2517
CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
2519
if (!vimGlobalState.macroModeState.isPlaying) {
2521
cm.on('change', onChange);
2522
CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
2524
if (vim.visualMode) {
2527
selectForInsert(cm, head, height);
2529
toggleVisualMode: function(cm, actionArgs, vim) {
2530
var repeat = actionArgs.repeat;
2531
var anchor = cm.getCursor();
2536
if (!vim.visualMode) {
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));
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) {
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);
2562
reselectLastSelection: function(cm, _actionArgs, vim) {
2563
var lastSelection = vim.lastSelection;
2564
if (vim.visualMode) {
2565
updateLastSelection(cm, vim);
2567
if (lastSelection) {
2568
var anchor = lastSelection.anchorMark.find();
2569
var head = lastSelection.headMark.find();
2570
if (!anchor || !head) {
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', {
2586
subMode: vim.visualLine ? 'linewise' :
2587
vim.visualBlock ? 'blockwise' : ''});
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)) {
2600
curEnd.ch = lineLength(cm, curEnd.line) - 1;
2603
var repeat = Math.max(actionArgs.repeat, 2);
2604
curStart = cm.getCursor();
2605
curEnd = clipCursorToContent(cm, new Pos(curStart.line + repeat - 1,
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);
2619
var curFinalPos = new Pos(curStart.line, finalCh);
2620
if (vim.visualMode) {
2621
exitVisualMode(cm, false);
2623
cm.setCursor(curFinalPos);
2625
newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
2626
vim.insertMode = true;
2627
var insertAt = copyCursor(cm.getCursor());
2628
if (insertAt.line === cm.firstLine() && !actionArgs.after) {
2630
cm.replaceRange('\n', new Pos(cm.firstLine(), 0));
2631
cm.setCursor(cm.firstLine(), 0);
2633
insertAt.line = (actionArgs.after) ? insertAt.line :
2635
insertAt.ch = lineLength(cm, insertAt.line);
2636
cm.setCursor(insertAt);
2637
var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
2638
CodeMirror.commands.newlineAndIndent;
2641
this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
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();
2651
if (actionArgs.matchIndent) {
2652
var tabSize = cm.getOption("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;
2659
var currentLine = cm.getLine(cm.getCursor().line);
2660
var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
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) {
2670
else if (cm.getOption("indentWithTabs")) {
2671
var quotient = Math.floor(newIndent / tabSize);
2672
return Array(quotient + 1).join('\t');
2675
return Array(newIndent + 1).join(' ');
2678
text += wasChomped ? "\n" : "";
2680
if (actionArgs.repeat > 1) {
2681
var text = Array(actionArgs.repeat + 1).join(text);
2683
var linewise = register.linewise;
2684
var blockwise = register.blockwise;
2686
text = text.split('\n');
2690
for (var i = 0; i < text.length; i++) {
2691
text[i] = (text[i] == '') ? ' ' : text[i];
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) {
2701
text = '\n' + text.slice(0, text.length - 1);
2702
cur.ch = lineLength(cm, cur.line);
2707
cur.ch += actionArgs.after ? 1 : 0;
2711
if (vim.visualMode) {
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');
2722
if (vim.lastSelection) {
2723
lastSelectionCurEnd = vim.lastSelection.headMark.find();
2726
vimGlobalState.registerController.unnamedRegister.setText(selectedText);
2729
cm.replaceSelections(emptyStrings);
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;
2742
cm.replaceRange(text, selectionStart, selectionEnd);
2743
curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1);
2746
if(lastSelectionCurEnd) {
2747
vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);
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));
2760
var lastCh = lineLength(cm, line);
2761
if (lastCh < cur.ch) {
2762
extendLineToColumn(cm, line, cur.ch);
2766
selectBlock(cm, new Pos(cur.line + text.length-1, cur.ch));
2767
cm.replaceSelections(text);
2770
cm.replaceRange(text, cur);
2772
if (linewise && actionArgs.after) {
2773
curPosFinal = new Pos(
2775
findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)));
2776
} else if (linewise && !actionArgs.after) {
2777
curPosFinal = new Pos(
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);
2784
idx = cm.indexFromPos(cur);
2785
curPosFinal = cm.posFromIndex(idx + text.length);
2789
if (vim.visualMode) {
2790
exitVisualMode(cm, false);
2792
cm.setCursor(curPosFinal);
2794
undo: function(cm, actionArgs) {
2795
cm.operation(function() {
2796
repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
2797
cm.setCursor(cm.getCursor('anchor'));
2800
redo: function(cm, actionArgs) {
2801
repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
2803
setRegister: function(_cm, actionArgs, vim) {
2804
vim.inputState.registerName = actionArgs.selectedCharacter;
2806
setMark: function(cm, actionArgs, vim) {
2807
var markName = actionArgs.selectedCharacter;
2808
updateMark(cm, vim, markName, cm.getCursor());
2810
replace: function(cm, actionArgs, vim) {
2811
var replaceWith = actionArgs.selectedCharacter;
2812
var curStart = cm.getCursor();
2815
var selections = cm.listSelections();
2816
if (vim.visualMode) {
2817
curStart = cm.getCursor('start');
2818
curEnd = cm.getCursor('end');
2820
var line = cm.getLine(curStart.line);
2821
replaceTo = curStart.ch + actionArgs.repeat;
2822
if (replaceTo > line.length) {
2823
replaceTo=line.length;
2825
curEnd = new Pos(curStart.line, replaceTo);
2827
if (replaceWith=='\n') {
2828
if (!vim.visualMode) cm.replaceRange('', curStart, curEnd);
2830
(CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
2832
var replaceWithStr = cm.getRange(curStart, curEnd);
2834
replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith);
2835
if (vim.visualBlock) {
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);
2842
cm.replaceRange(replaceWithStr, curStart, curEnd);
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);
2850
cm.setCursor(offsetCursor(curEnd, 0, -1));
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;
2862
while ((match = re.exec(lineStr)) !== null) {
2863
start = match.index;
2864
end = start + match[0].length;
2865
if (cur.ch < end)break;
2867
if (!actionArgs.backtrack && (end <= cur.ch))return;
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);
2879
numberStr = baseStr + zeroPadding + numberStr;
2881
var from = new Pos(cur.line, start);
2882
var to = new Pos(cur.line, end);
2883
cm.replaceRange(numberStr, from, to);
2887
cm.setCursor(new Pos(cur.line, start + numberStr.length - 1));
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;
2896
repeat = vim.lastEditInputState.repeatOverride || repeat;
2898
repeatLastEdit(cm, vim, repeat, false );
2900
indent: function(cm, actionArgs) {
2901
cm.indentLine(cm.getCursor().line, actionArgs.indentRight);
2903
exitInsertMode: exitInsertMode
2906
function defineAction(name, fn) {
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);
2926
function copyArgs(args) {
2928
for (var prop in args) {
2929
if (args.hasOwnProperty(prop)) {
2930
ret[prop] = args[prop];
2935
function offsetCursor(cur, offsetLine, offsetCh) {
2936
if (typeof offsetLine === 'object') {
2937
offsetCh = offsetLine.ch;
2938
offsetLine = offsetLine.line;
2940
return new Pos(cur.line + offsetLine, cur.ch + offsetCh);
2942
function commandMatches(keys, keyMap, context, inputState) {
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); }
2957
partial: partial.length && partial,
2958
full: full.length && full
2961
function commandMatch(pressed, mapped) {
2962
if (mapped.slice(-11) == '<character>') {
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;
2970
return pressed == mapped ? 'full' :
2971
mapped.indexOf(pressed) == 0 ? 'partial' : false;
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){
2980
selectedCharacter='\n';
2983
selectedCharacter=' ';
2986
selectedCharacter='';
2990
return selectedCharacter;
2992
function repeatFn(cm, fn, repeat) {
2994
for (var i = 0; i < repeat; i++) {
2999
function copyCursor(cur) {
3000
return new Pos(cur.line, cur.ch);
3002
function cursorEqual(cur1, cur2) {
3003
return cur1.ch == cur2.ch && cur1.line == cur2.line;
3005
function cursorIsBefore(cur1, cur2) {
3006
if (cur1.line < cur2.line) {
3009
if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
3014
function cursorMin(cur1, cur2) {
3015
if (arguments.length > 2) {
3016
cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));
3018
return cursorIsBefore(cur1, cur2) ? cur1 : cur2;
3020
function cursorMax(cur1, cur2) {
3021
if (arguments.length > 2) {
3022
cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));
3024
return cursorIsBefore(cur1, cur2) ? cur2 : cur1;
3026
function cursorIsBetween(cur1, cur2, cur3) {
3028
var cur1before2 = cursorIsBefore(cur1, cur2);
3029
var cur2before3 = cursorIsBefore(cur2, cur3);
3030
return cur1before2 && cur2before3;
3032
function lineLength(cm, lineNum) {
3033
return cm.getLine(lineNum).length;
3039
return s.replace(/^\s+|\s+$/g, '');
3041
function escapeRegex(s) {
3042
return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
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());
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;
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;
3071
var dir = ranges[index].head.ch - baseCh;
3072
var newDir = headCh - baseCh;
3073
if (dir > 0 && newDir <= 0) {
3075
if (!isClipped) { headCh--; }
3076
} else if (dir < 0 && newDir >= 0) {
3078
if (!wasClipped) { headCh++; }
3079
} else if (dir < 0 && newDir == -1) {
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);
3087
cm.setSelections(selections);
3088
selectionEnd.ch = headCh;
3092
function selectForInsert(cm, head, height) {
3094
for (var i = 0; i < height; i++) {
3095
var lineHead = offsetCursor(head, i, 0);
3096
sel.push({anchor: lineHead, head: lineHead});
3098
cm.setSelections(sel, 0);
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) {
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];
3121
var getLastSelectedAreaRange = function() {
3122
var selectionStart = cm.getCursor();
3123
var selectionEnd = cm.getCursor();
3124
var block = lastSelection.visualBlock;
3126
var width = block.width;
3127
var height = block.height;
3128
selectionEnd = new Pos(selectionStart.line + height, selectionStart.ch + width);
3129
var 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);
3138
cm.setSelections(selections);
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));
3149
cm.setSelection(selectionStart, selectionEnd);
3151
return [selectionStart, selectionEnd];
3153
if (!vim.visualMode) {
3155
return getLastSelectedAreaRange();
3157
return getCurrentSelectedAreaRange();
3162
function updateLastSelection(cm, vim) {
3163
var anchor = vim.sel.anchor;
3164
var head = vim.sel.head;
3166
if (vim.lastPastedText) {
3167
head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);
3168
vim.lastPastedText = null;
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};
3178
function expandSelection(cm, start, end) {
3179
var sel = cm.state.vim.sel;
3180
var head = sel.head;
3181
var anchor = sel.anchor;
3183
if (cursorIsBefore(end, start)) {
3188
if (cursorIsBefore(head, anchor)) {
3189
head = cursorMin(start, head);
3190
anchor = cursorMax(anchor, end);
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));
3199
return [anchor, head];
3205
function updateCmSelection(cm, sel, mode) {
3206
var vim = cm.state.vim;
3207
sel = sel || vim.sel;
3209
vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';
3210
var cmSel = makeCmSelection(cm, sel, mode);
3211
cm.setSelections(cmSel.ranges, cmSel.primary);
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);
3222
ranges: [{anchor: anchor, head: head}],
3225
} else if (mode == 'line') {
3226
if (!cursorIsBefore(sel.head, sel.anchor)) {
3229
var lastLine = cm.lastLine();
3230
if (head.line > lastLine) {
3231
head.line = lastLine;
3233
head.ch = lineLength(cm, head.line);
3236
anchor.ch = lineLength(cm, anchor.line);
3239
ranges: [{anchor: anchor, head: head}],
3242
} else if (mode == 'block') {
3243
var top = Math.min(anchor.line, head.line),
3245
bottom = Math.max(anchor.line, head.line),
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;
3252
for (var i = 0; i < height; i++) {
3254
anchor: new Pos(top + i, fromCh),
3255
head: new Pos(top + i, toCh)
3264
function getHead(cm) {
3265
var cur = cm.getCursor('head');
3266
if (cm.getSelection().length == 1) {
3269
cur = cursorMin(cur, cm.getCursor('anchor'));
3279
function exitVisualMode(cm, moveHead) {
3280
var vim = cm.state.vim;
3281
if (moveHead !== false) {
3282
cm.setCursor(clipCursorToContent(cm, vim.sel.head));
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"});
3295
function clipToLine(cm, curStart, curEnd) {
3296
var selection = cm.getRange(curStart, curEnd);
3298
if (/\n\s*$/.test(selection)) {
3299
var lines = selection.split('\n');
3309
for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
3316
curEnd.ch = lineLength(cm, curEnd.line);
3324
function expandSelectionToLine(_cm, curStart, curEnd) {
3330
function findFirstNonWhiteSpaceCharacter(text) {
3334
var firstNonWS = text.search(/\S/);
3335
return firstNonWS == -1 ? text.length : firstNonWS;
3338
function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
3339
var cur = getHead(cm);
3340
var line = cm.getLine(cur.line);
3345
var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0];
3346
while (!test(line.charAt(idx))) {
3348
if (idx >= line.length) { return null; }
3352
test = bigWordCharTest[0];
3354
test = wordCharTest[0];
3355
if (!test(line.charAt(idx))) {
3356
test = wordCharTest[1];
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--; }
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; }
3376
return { start: new Pos(cur.line, start), end: new Pos(cur.line, end) };
3405
function expandTagUnderCursor(cm, head, inclusive) {
3407
if (!CodeMirror.findMatchingTag || !CodeMirror.findEnclosingTag) {
3408
return { start: cur, end: cur };
3411
var tags = CodeMirror.findMatchingTag(cm, head) || CodeMirror.findEnclosingTag(cm, head);
3412
if (!tags || !tags.open || !tags.close) {
3413
return { start: cur, end: cur };
3417
return { start: tags.open.from, end: tags.close.to };
3419
return { start: tags.open.to, end: tags.close.from };
3422
function recordJumpPosition(cm, oldCur, newCur) {
3423
if (!cursorEqual(oldCur, newCur)) {
3424
vimGlobalState.jumpList.add(cm, oldCur, newCur);
3428
function recordLastCharacterSearch(increment, args) {
3429
vimGlobalState.lastCharacterSearch.increment = increment;
3430
vimGlobalState.lastCharacterSearch.forward = args.forward;
3431
vimGlobalState.lastCharacterSearch.selectedCharacter = args.selectedCharacter;
3434
var symbolToMode = {
3435
'(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
3436
'[': 'section', ']': 'section',
3437
'*': 'comment', '/': 'comment',
3438
'm': 'method', 'M': 'method',
3441
var findSymbolModes = {
3443
isComplete: function(state) {
3444
if (state.nextCh === state.symb) {
3446
if (state.depth >= 1)return true;
3447
} else if (state.nextCh === state.reverseSymb) {
3454
init: function(state) {
3455
state.curMoveThrough = true;
3456
state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
3458
isComplete: function(state) {
3459
return state.index === 0 && state.nextCh === state.symb;
3463
isComplete: function(state) {
3464
var found = state.lastCh === '*' && state.nextCh === '/';
3465
state.lastCh = state.nextCh;
3473
init: function(state) {
3474
state.symb = (state.symb === 'm' ? '{' : '}');
3475
state.reverseSymb = state.symb === '{' ? '}' : '{';
3477
isComplete: function(state) {
3478
if (state.nextCh === state.symb)return true;
3483
init: function(state) {
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) {
3494
} else if (token === 'if') {
3495
if (!state.forward && state.depth === 0) {
3500
if (token === 'else' && state.depth === 0)return true;
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;
3511
var line = cur.line;
3512
var lineText = cm.getLine(line);
3515
nextCh: lineText.charAt(curCh),
3519
reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
3522
curMoveThrough: false
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) {
3534
state.lineText = cm.getLine(line) || '';
3535
if (increment > 0) {
3538
var lineLen = state.lineText.length;
3539
state.index = (lineLen > 0) ? (lineLen-1) : 0;
3541
state.nextCh = state.lineText.charAt(state.index);
3543
if (isComplete(state)) {
3545
cur.ch = state.index;
3549
if (state.nextCh || state.curMoveThrough) {
3550
return new Pos(line, state.index);
3572
function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
3573
var lineNum = cur.line;
3575
var line = cm.getLine(lineNum);
3576
var dir = forward ? 1 : -1;
3577
var charTests = bigWord ? bigWordCharTest: wordCharTest;
3579
if (emptyLineIsWord && line == '') {
3581
line = cm.getLine(lineNum);
3582
if (!isLine(cm, lineNum)) {
3585
pos = (forward) ? 0 : line.length;
3589
if (emptyLineIsWord && line == '') {
3590
return { from: 0, to: 0, line: lineNum };
3592
var stop = (dir > 0) ? line.length : -1;
3593
var wordStart = stop, wordEnd = stop;
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))) {
3601
while (pos != stop && charTests[i](line.charAt(pos))) {
3605
foundWord = wordStart != wordEnd;
3606
if (wordStart == cur.ch && lineNum == cur.line &&
3607
wordEnd == wordStart + dir) {
3612
from: Math.min(wordStart, wordEnd + 1),
3613
to: Math.max(wordStart, wordEnd),
3624
if (!isLine(cm, lineNum)) {
3627
line = cm.getLine(lineNum);
3628
pos = (dir > 0) ? 0 : line.length;
3644
function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {
3645
var curStart = copyCursor(cur);
3647
if (forward && !wordEnd || !forward && wordEnd) {
3651
var emptyLineIsWord = !(forward && wordEnd);
3652
for (var i = 0; i < repeat; i++) {
3653
var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
3655
var eodCh = lineLength(cm, cm.lastLine());
3657
? {line: cm.lastLine(), from: eodCh, to: eodCh}
3658
: {line: 0, from: 0, to: 0});
3662
cur = new Pos(word.line, forward ? (word.to - 1) : word.from);
3664
var shortCircuit = words.length != repeat;
3665
var firstWord = words[0];
3666
var lastWord = words.pop();
3667
if (forward && !wordEnd) {
3669
if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
3671
lastWord = words.pop();
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) {
3678
if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
3680
lastWord = words.pop();
3682
return new Pos(lastWord.line, lastWord.to);
3685
return new Pos(lastWord.line, lastWord.from);
3689
function moveToEol(cm, head, motionArgs, vim, keepHPos) {
3691
var retval= new Pos(cur.line + motionArgs.repeat - 1, Infinity);
3692
var end=cm.clipPos(retval);
3695
vim.lastHPos = Infinity;
3696
vim.lastHSPos = cm.charCoords(end,'div').left;
3701
function moveToCharacter(cm, repeat, forward, character) {
3702
var cur = cm.getCursor();
3705
for (var i = 0; i < repeat; i ++) {
3706
var line = cm.getLine(cur.line);
3707
idx = charIdxInLine(start, line, character, forward, true);
3713
return new Pos(cm.getCursor().line, idx);
3716
function moveToColumn(cm, repeat) {
3719
var line = cm.getCursor().line;
3720
return clipCursorToContent(cm, new Pos(line, repeat - 1));
3723
function updateMark(cm, vim, markName, pos) {
3724
if (!inArray(markName, validMarks)) {
3727
if (vim.marks[markName]) {
3728
vim.marks[markName].clear();
3730
vim.marks[markName] = cm.setBookmark(pos);
3733
function charIdxInLine(start, line, character, forward, includeChar) {
3741
idx = line.indexOf(character, start + 1);
3742
if (idx != -1 && !includeChar) {
3746
idx = line.lastIndexOf(character, start - 1);
3747
if (idx != -1 && !includeChar) {
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);
3765
while (min <= i && i <= max && repeat > 0) {
3766
if (isBoundary(i, dir)) { repeat--; }
3769
return new Pos(i, 0);
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) {
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) {
3789
end = new Pos(i, 0);
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; }
3798
start = new Pos(i, 0);
3799
return { start: start, end: end };
3802
function findSentence(cm, cur, repeat, dir) {
3816
function nextChar(cm, idx) {
3817
if (idx.pos + idx.dir < 0 || idx.pos + idx.dir >= idx.line.length) {
3819
if (!isLine(cm, idx.ln)) {
3825
idx.line = cm.getLine(idx.ln);
3826
idx.pos = (idx.dir > 0) ? 0 : idx.line.length - 1;
3837
function forward(cm, ln, pos, dir) {
3838
var line = cm.getLine(ln);
3839
var stop = (line === "");
3853
var skip_empty_lines = (curr.line === "");
3858
while (curr.line !== null) {
3859
last_valid.ln = curr.ln;
3860
last_valid.pos = curr.pos;
3862
if (curr.line === "" && !skip_empty_lines) {
3863
return { ln: curr.ln, pos: curr.pos, };
3865
else if (stop && curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
3866
return { ln: curr.ln, pos: curr.pos, };
3868
else if (isEndOfSentenceSymbol(curr.line[curr.pos])
3870
&& (curr.pos === curr.line.length - 1
3871
|| isWhiteSpaceString(curr.line[curr.pos + 1]))) {
3882
var line = cm.getLine(last_valid.ln);
3884
for(var i = line.length - 1; i >= 0; --i) {
3885
if (!isWhiteSpaceString(line[i])) {
3899
function reverse(cm, ln, pos, dir) {
3900
var line = cm.getLine(ln);
3914
var skip_empty_lines = (curr.line === "");
3919
while (curr.line !== null) {
3921
if (curr.line === "" && !skip_empty_lines) {
3922
if (last_valid.pos !== null) {
3926
return { ln: curr.ln, pos: curr.pos };
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)) {
3934
else if (curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
3935
skip_empty_lines = false;
3936
last_valid = { ln: curr.ln, pos: curr.pos }
3946
var line = cm.getLine(last_valid.ln);
3948
for(var i = 0; i < line.length; ++i) {
3949
if (!isWhiteSpaceString(line[i])) {
3962
while (repeat > 0) {
3964
curr_index = reverse(cm, curr_index.ln, curr_index.pos, dir);
3967
curr_index = forward(cm, curr_index.ln, curr_index.pos, dir);
3972
return new Pos(curr_index.ln, curr_index.pos);
3977
function selectCompanionObject(cm, head, symb, inclusive) {
3978
var cur = head, start, end;
3980
var bracketRegexp = ({
3981
'(': /[()]/, ')': /[()]/,
3982
'[': /[[\]]/, ']': /[[\]]/,
3983
'{': /[{}]/, '}': /[{}]/,
3984
'<': /[<>]/, '>': /[<>]/})[symb];
3989
'<': '<', '>': '<'})[symb];
3990
var curChar = cm.getLine(cur.line).charAt(cur.ch);
3993
var offset = curChar === openSym ? 1 : 0;
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});
3998
if (!start || !end) {
3999
return { start: cur, end: cur };
4005
if ((start.line == end.line && start.ch > end.ch)
4006
|| (start.line > end.line)) {
4018
return { start: start, end: end };
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);
4034
if (cur.ch < firstIndex) {
4035
cur.ch = firstIndex;
4040
else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
4046
if (chars[cur.ch] == symb && !end) {
4050
for (i = cur.ch; i > -1 && !start; i--) {
4051
if (chars[i] == symb) {
4058
if (start && !end) {
4059
for (i = start, len = chars.length; i < len && !end; i++) {
4060
if (chars[i] == symb) {
4067
if (!start || !end) {
4068
return { start: cur, end: cur };
4077
start: new Pos(cur.line, start),
4078
end: new Pos(cur.line, end)
4083
defineOption('pcre', true, 'boolean');
4084
function SearchState() {}
4085
SearchState.prototype = {
4086
getQuery: function() {
4087
return vimGlobalState.query;
4089
setQuery: function(query) {
4090
vimGlobalState.query = query;
4092
getOverlay: function() {
4093
return this.searchOverlay;
4095
setOverlay: function(overlay) {
4096
this.searchOverlay = overlay;
4098
isReversed: function() {
4099
return vimGlobalState.isReversed;
4101
setReversed: function(reversed) {
4102
vimGlobalState.isReversed = reversed;
4104
getScrollbarAnnotate: function() {
4105
return this.annotate;
4107
setScrollbarAnnotate: function(annotate) {
4108
this.annotate = annotate;
4111
function getSearchState(cm) {
4112
var vim = cm.state.vim;
4113
return vim.searchState_ || (vim.searchState_ = new SearchState());
4115
function splitBySlash(argString) {
4116
return splitBySeparator(argString, '/');
4119
function findUnescapedSlashes(argString) {
4120
return findUnescapedSeparators(argString, '/');
4123
function splitBySeparator(argString, separator) {
4124
var slashes = findUnescapedSeparators(argString, separator) || [];
4125
if (!slashes.length) return [];
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]));
4136
function findUnescapedSeparators(str, separator) {
4140
var escapeNextChar = false;
4142
for (var i = 0; i < str.length; i++) {
4143
var c = str.charAt(i);
4144
if (!escapeNextChar && c == separator) {
4147
escapeNextChar = !escapeNextChar && (c == '\\');
4153
function translateRegex(str) {
4155
var specials = '|(){';
4158
var escapeNextChar = false;
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) {
4168
escapeNextChar = false;
4171
escapeNextChar = true;
4173
if (n && unescape.indexOf(n) != -1) {
4174
specialComesNext = true;
4177
if (!specialComesNext || n === '\\') {
4182
if (specialComesNext && n !== '\\') {
4188
return out.join('');
4194
var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'};
4195
function translateRegexReplace(str) {
4196
var escapeNextChar = false;
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]);
4204
} else if (escapeNextChar) {
4208
escapeNextChar = false;
4211
escapeNextChar = true;
4212
if ((isNumber(n) || n === '$')) {
4214
} else if (n !== '/' && n !== '\\') {
4228
return out.join('');
4232
var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t', '\\&':'&'};
4233
function unescapeRegexReplace(str) {
4234
var stream = new CodeMirror.StringStream(str);
4236
while (!stream.eol()) {
4238
while (stream.peek() && stream.peek() != '\\') {
4239
output.push(stream.next());
4241
var matched = false;
4242
for (var matcher in unescapes) {
4243
if (stream.match(matcher, true)) {
4245
output.push(unescapes[matcher]);
4251
output.push(stream.next());
4254
return output.join('');
4267
function parseQuery(query, ignoreCase, smartCase) {
4269
var lastSearchRegister = vimGlobalState.registerController.getRegister('/');
4270
lastSearchRegister.setText(query);
4272
if (query instanceof RegExp) { return query; }
4276
var slashes = findUnescapedSlashes(query);
4278
var forceIgnoreCase;
4279
if (!slashes.length) {
4284
regexPart = query.substring(0, slashes[0]);
4285
var flagsPart = query.substring(slashes[0]);
4286
forceIgnoreCase = (flagsPart.indexOf('i') != -1);
4291
if (!getOption('pcre')) {
4292
regexPart = translateRegex(regexPart);
4295
ignoreCase = (/^[^A-Z]*$/).test(regexPart);
4297
var regexp = new RegExp(regexPart,
4298
(ignoreCase || forceIgnoreCase) ? 'im' : 'm');
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]);
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});
4332
alert(pre.innerText);
4336
function makePrompt(prefix, desc) {
4337
return dom(document.createDocumentFragment(),
4338
dom('span', {$fontFamily: 'monospace', $whiteSpace: 'pre'},
4340
dom('input', {type: 'text', autocorrect: 'off',
4341
autocapitalize: 'off', spellcheck: 'false'})),
4342
desc && dom('span', {$color: '#888'}, desc));
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
4355
if (typeof options.prefix != "string" && options.prefix) shortText += options.prefix.textContent;
4356
if (options.desc) shortText += " " + options.desc;
4357
options.onClose(prompt(shortText, ''));
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]) {
4375
function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
4379
var state = getSearchState(cm);
4380
var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
4384
highlightSearchMatches(cm, query);
4385
if (regexEqual(query, state.getQuery())) {
4388
state.setQuery(query);
4391
function searchOverlay(query) {
4392
if (query.source.charAt(0) == '^') {
4393
var matchSol = true;
4396
token: function(stream) {
4397
if (matchSol && !stream.sol()) {
4401
var match = stream.match(query, false);
4403
if (match[0].length == 0) {
4408
if (!stream.sol()) {
4411
if (!query.exec(stream.next() + match[0])) {
4416
stream.match(query);
4419
while (!stream.eol()) {
4421
if (stream.match(query, false)) break;
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) {
4436
cm.removeOverlay(overlay);
4438
overlay = searchOverlay(query);
4439
cm.addOverlay(overlay);
4440
if (cm.showMatchesOnScrollbar) {
4441
if (searchState.getScrollbarAnnotate()) {
4442
searchState.getScrollbarAnnotate().clear();
4444
searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query));
4446
searchState.setOverlay(overlay);
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);
4468
cursor = cm.getSearchCursor(query,
4469
(prev) ? new Pos(cm.lastLine()) : new Pos(cm.firstLine(), 0) );
4470
if (!cursor.find(prev)) {
4475
return cursor.from();
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);
4492
var found = cursor.find(!prev);
4495
if (!vim.visualMode && found && cursorEqual(cursor.from(), pos)) {
4499
for (var i = 0; i < repeat; i++) {
4500
found = cursor.find(prev);
4504
cursor = cm.getSearchCursor(query,
4505
(prev) ? new Pos(cm.lastLine()) : new Pos(cm.firstLine(), 0) );
4506
if (!cursor.find(prev)) {
4511
return [cursor.from(), cursor.to()];
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);
4534
function isInRange(pos, start, end) {
4535
if (typeof pos != 'number') {
4539
if (start instanceof Array) {
4540
return inArray(pos, start);
4542
if (typeof end == 'number') {
4543
return (pos >= start && pos <= end);
4545
return pos == start;
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};
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);
4566
var mark = vim.marks[markName];
4567
return mark && mark.find();
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);
4579
var ExCommandDispatcher = function() {
4580
this.buildCommandMap_();
4582
ExCommandDispatcher.prototype = {
4583
processCommand: function(cm, input, opt_params) {
4585
cm.operation(function () {
4586
cm.curOp.isVimOp = true;
4587
that._processCommand(cm, input, opt_params);
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) {
4597
var inputStream = new CodeMirror.StringStream(input);
4599
commandHistoryRegister.setText(input);
4600
var params = opt_params || {};
4601
params.input = input;
4603
this.parseInput_(cm, inputStream, params);
4605
showConfirm(cm, e.toString());
4610
if (!params.commandName) {
4612
if (params.line !== undefined) {
4613
commandName = 'move';
4616
command = this.matchCommand_(params.commandName);
4618
commandName = command.name;
4619
if (command.excludeFromCommandHistory) {
4620
commandHistoryRegister.setText(previousCommand);
4622
this.parseCommandArgs_(inputStream, params, command);
4623
if (command.type == 'exToKey') {
4625
for (var i = 0; i < command.toKeys.length; i++) {
4626
vimApi.handleKey(cm, command.toKeys[i], 'mapping');
4629
} else if (command.type == 'exToEx') {
4631
this.processCommand(cm, command.toInput);
4637
showConfirm(cm, 'Not an editor command ":' + input + '"');
4641
exCommands[commandName](cm, params);
4645
if ((!command || !command.possiblyAsync) && params.callback) {
4649
showConfirm(cm, e.toString());
4653
parseInput_: function(cm, inputStream, result) {
4654
inputStream.eatWhile(':');
4656
if (inputStream.eat('%')) {
4657
result.line = cm.firstLine();
4658
result.lineEnd = cm.lastLine();
4660
result.line = this.parseLineSpec_(cm, inputStream);
4661
if (result.line !== undefined && inputStream.eat(',')) {
4662
result.lineEnd = this.parseLineSpec_(cm, inputStream);
4667
var commandMatch = inputStream.match(/^(\w+|!!|@@|[!#&*<=>@~])/);
4669
result.commandName = commandMatch[1];
4671
result.commandName = inputStream.match(/.*/)[0];
4676
parseLineSpec_: function(cm, inputStream) {
4677
var numberMatch = inputStream.match(/^(\d+)/);
4681
return parseInt(numberMatch[1], 10) - 1;
4683
switch (inputStream.next()) {
4685
return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
4687
return this.parseLineSpecOffset_(inputStream, cm.lastLine());
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);
4695
inputStream.backUp(1);
4697
return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
4699
inputStream.backUp(1);
4703
parseLineSpecOffset_: function(inputStream, line) {
4704
var offsetMatch = inputStream.match(/^([+-])?(\d+)/);
4706
var offset = parseInt(offsetMatch[2], 10);
4707
if (offsetMatch[1] == "-") {
4715
parseCommandArgs_: function(inputStream, params, command) {
4716
if (inputStream.eol()) {
4719
params.argString = inputStream.match(/.*/)[0];
4721
var delim = command.argDelimiter || /\s+/;
4722
var args = trim(params.argString).split(delim);
4723
if (args.length && args[0]) {
4727
matchCommand_: function(commandName) {
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) {
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;
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) == ':') {
4757
this.commandMap_[commandName] = {
4760
toInput: rhs.substring(1),
4765
this.commandMap_[commandName] = {
4773
if (rhs != ':' && rhs.charAt(0) == ':') {
4778
exArgs: { input: rhs.substring(1) }
4780
if (ctx) { mapping.context = ctx; }
4781
defaultKeymap.unshift(mapping);
4789
if (ctx) { mapping.context = ctx; }
4790
defaultKeymap.unshift(mapping);
4794
unmap: function(lhs, ctx) {
4795
if (lhs != ':' && lhs.charAt(0) == ':') {
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];
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);
4818
colorscheme: function(cm, params) {
4819
if (!params.args || params.args.length < 1) {
4820
showConfirm(cm, cm.getOption('theme'));
4823
cm.setOption('theme', params.args[0]);
4825
map: function(cm, params, ctx) {
4826
var mapArgs = params.args;
4827
if (!mapArgs || mapArgs.length < 2) {
4829
showConfirm(cm, 'Invalid mapping: ' + params.input);
4833
exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
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)) {
4842
showConfirm(cm, 'No such mapping: ' + params.input);
4846
move: function(cm, params) {
4847
commandDispatcher.processCommand(cm, cm.state.vim, {
4849
motion: 'moveToLineOrEdgeOfDocument',
4850
motionArgs: { forward: false, explicitRepeat: true,
4852
repeatOverride: params.line+1});
4854
set: function(cm, params) {
4855
var setArgs = params.args;
4858
var setCfg = params.setCfg || {};
4859
if (!setArgs || setArgs.length < 1) {
4861
showConfirm(cm, 'Invalid mapping: ' + params.input);
4865
var expr = setArgs[0].split('=');
4866
var optionName = expr[0];
4867
var value = expr[1];
4868
var forceGet = false;
4870
if (optionName.charAt(optionName.length - 1) == '?') {
4872
if (value) { throw Error('Trailing characters: ' + params.argString); }
4873
optionName = optionName.substring(0, optionName.length - 1);
4876
if (value === undefined && optionName.substring(0, 2) == 'no') {
4879
optionName = optionName.substring(2);
4883
var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';
4884
if (optionIsBoolean && value == undefined) {
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);
4896
showConfirm(cm, ' ' + optionName + '=' + oldValue);
4899
var setOptionReturn = setOption(optionName, value, cm, setCfg);
4900
if (setOptionReturn instanceof Error) {
4901
showConfirm(cm, setOptionReturn.message);
4905
setlocal: function (cm, params) {
4907
params.setCfg = {scope: 'local'};
4908
this.set(cm, params);
4910
setglobal: function (cm, params) {
4912
params.setCfg = {scope: 'global'};
4913
this.set(cm, params);
4915
registers: function(cm, params) {
4916
var regArgs = params.args;
4917
var registers = vimGlobalState.registerController.registers;
4918
var regInfo = '----------Registers----------\n\n';
4920
for (var registerName in registers) {
4921
var text = registers[registerName].toString();
4923
regInfo += '"' + registerName + ' ' + text + '\n'
4928
regArgs = regArgs.join('');
4929
for (var i = 0; i < regArgs.length; i++) {
4930
registerName = regArgs.charAt(i);
4931
if (!vimGlobalState.registerController.isValidRegister(registerName)) {
4934
var register = registers[registerName] || new Register();
4935
regInfo += '"' + registerName + ' ' + register.toString() + '\n'
4938
showConfirm(cm, regInfo);
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'; }
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';
4960
pattern = new RegExp(opts[2].substr(1, opts[2].length - 2), ignoreCase ? 'i' : '');
4964
var err = parseArgs();
4966
showConfirm(cm, err + ': ' + params.argString);
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]);
4989
textPart.push(text[i]);
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);
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;
5010
numPart.sort(pattern ? comparePatternFn : compareFn);
5012
for (var i = 0; i < numPart.length; i++) {
5013
numPart[i] = numPart[i].input;
5015
} else if (!number) { textPart.sort(compareFn); }
5016
text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
5021
for (var i = 0; i < textOld.length; i++) {
5022
if (textOld[i] != lastLine) {
5023
text.push(textOld[i]);
5025
lastLine = textOld[i];
5028
cm.replaceRange(text.join('\n'), curStart, curEnd);
5030
vglobal: function(cm, params) {
5032
this.global(cm, params);
5034
global: function(cm, params) {
5038
var argString = params.argString;
5040
showConfirm(cm, 'Regular Expression missing from global');
5043
var inverted = params.commandName[0] === 'v';
5045
var lineStart = (params.line !== undefined) ? params.line : cm.firstLine();
5046
var lineEnd = params.lineEnd || params.line || cm.lastLine();
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('/');
5058
updateSearchQuery(cm, regexPart, true ,
5061
showConfirm(cm, 'Invalid regex: ' + regexPart);
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);
5078
showConfirm(cm, matchedLines.join('\n'));
5082
var nextCommand = function() {
5083
if (index < matchedLines.length) {
5084
var line = matchedLines[index++];
5085
var lineNum = cm.getLineNumber(line);
5086
if (lineNum == null) {
5090
var command = (lineNum + 1) + cmd;
5091
exCommandDispatcher.processCommand(cm, command, {
5092
callback: nextCommand
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.');
5103
var argString = params.argString;
5104
var tokens = argString ? splitBySeparator(argString, argString[0]) : [];
5105
var regexPart, replacePart = '', trailing, flagsPart, count;
5106
var confirm = false;
5108
if (tokens.length) {
5109
regexPart = tokens[0];
5110
if (getOption('pcre') && regexPart !== '') {
5111
regexPart = new RegExp(regexPart).source;
5113
replacePart = tokens[1];
5114
if (replacePart !== undefined) {
5115
if (getOption('pcre')) {
5116
replacePart = unescapeRegexReplace(replacePart.replace(/([^\\])&/g,"$1$$&"));
5118
replacePart = translateRegexReplace(replacePart);
5120
vimGlobalState.lastSubstituteReplacePart = replacePart;
5122
trailing = tokens[2] ? tokens[2].split(' ') : [];
5127
if (argString && argString.length) {
5128
showConfirm(cm, 'Substitutions should be of the form ' +
5129
':s/pattern/replace/');
5136
flagsPart = trailing[0];
5137
count = parseInt(trailing[1]);
5139
if (flagsPart.indexOf('c') != -1) {
5142
if (flagsPart.indexOf('g') != -1) {
5145
if (getOption('pcre')) {
5146
regexPart = regexPart + '/' + flagsPart;
5148
regexPart = regexPart.replace(/\//g, "\\/") + '/' + flagsPart;
5156
updateSearchQuery(cm, regexPart, true ,
5159
showConfirm(cm, 'Invalid regex: ' + regexPart);
5163
replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart;
5164
if (replacePart === undefined) {
5165
showConfirm(cm, 'No previous substitute regular expression');
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()) {
5176
lineStart = lineEnd;
5177
lineEnd = lineStart + count - 1;
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);
5183
redo: CodeMirror.commands.redo,
5184
undo: CodeMirror.commands.undo,
5185
write: function(cm) {
5186
if (CodeMirror.commands.save) {
5188
CodeMirror.commands.save(cm);
5189
} else if (cm.save) {
5194
nohlsearch: function(cm) {
5195
clearSearchHighlight(cm);
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);
5204
delmarks: function(cm, params) {
5205
if (!params.argString || !trim(params.argString)) {
5206
showConfirm(cm, 'Argument required');
5210
var state = cm.state.vim;
5211
var stream = new CodeMirror.StringStream(trim(params.argString));
5212
while (!stream.eol()) {
5217
var count = stream.pos;
5219
if (!stream.match(/[a-zA-Z]/, false)) {
5220
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
5224
var sym = stream.next();
5226
if (stream.match('-', true)) {
5230
if (!stream.match(/[a-zA-Z]/, false)) {
5231
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
5235
var startMark = sym;
5236
var finishMark = stream.next();
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));
5251
for (var j = 0; j <= finish - start; j++) {
5252
var mark = String.fromCharCode(start + j);
5253
delete state.marks[mark];
5256
showConfirm(cm, 'Invalid argument: ' + startMark + '-');
5261
delete state.marks[sym];
5267
var exCommandDispatcher = new ExCommandDispatcher();
5279
function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query,
5280
replaceWith, callback) {
5282
cm.state.vim.exMode = true;
5284
var lastPos, modifiedLineNumber, joined;
5285
function replaceAll() {
5286
cm.operation(function() {
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;
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();
5314
while(findNextValidMatch() &&
5315
isInRange(searchCursor.from(), lineStart, lineEnd)) {
5316
if (!global && searchCursor.from().line == modifiedLineNumber && !joined) {
5319
cm.scrollIntoView(searchCursor.from(), 30);
5320
cm.setSelection(searchCursor.from(), searchCursor.to());
5321
lastPos = searchCursor.from();
5327
function stop(close) {
5328
if (close) { close(); }
5331
cm.setCursor(lastPos);
5332
var vim = cm.state.vim;
5334
vim.lastHPos = vim.lastHSPos = lastPos.ch;
5336
if (callback) { callback(); }
5338
function onPromptKeyDown(e, _value, close) {
5340
CodeMirror.e_stop(e);
5341
var keyName = CodeMirror.keyName(e);
5344
replace(); next(); break;
5350
var savedCallback = callback;
5351
callback = undefined;
5352
cm.operation(replaceAll);
5353
callback = savedCallback;
5365
if (done) { stop(close); }
5372
showConfirm(cm, 'No matches for ' + query.source);
5377
if (callback) { callback(); }
5381
prefix: dom('span', 'replace with ', dom('strong', replaceWith), ' (y/n/a/q/l)'),
5382
onKeyDown: onPromptKeyDown
5386
CodeMirror.keyMap.vim = {
5387
attach: attachVimMap,
5388
detach: detachVimMap,
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;
5399
cm.off('change', onChange);
5400
CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
5402
if (!isPlaying && vim.insertModeRepeat > 1) {
5404
repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
5406
vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
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);
5415
insertModeChangeRegister.setText(lastChange.changes.join(''));
5416
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
5417
if (macroModeState.isRecording) {
5418
logInsertModeChange(macroModeState);
5422
function _mapCommand(command) {
5423
defaultKeymap.unshift(command);
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);
5437
defineOption('insertModeEscKeysTimeout', 200, 'number');
5439
CodeMirror.keyMap['vim-insert'] = {
5442
fallthrough: ['default'],
5443
attach: attachVimMap,
5444
detach: detachVimMap,
5448
CodeMirror.keyMap['vim-replace'] = {
5449
'Backspace': 'goCharLeft',
5450
fallthrough: ['vim-insert'],
5451
attach: attachVimMap,
5452
detach: detachVimMap,
5456
function executeMacroRegister(cm, vim, macroModeState, registerName) {
5457
var register = vimGlobalState.registerController.getRegister(registerName);
5458
if (registerName == ':') {
5460
if (register.keyBuffer[0]) {
5461
exCommandDispatcher.processCommand(cm, register.keyBuffer[0]);
5463
macroModeState.isPlaying = false;
5466
var keyBuffer = register.keyBuffer;
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];
5476
match = (/<\w+-.+?>|<\w+>|./).exec(text);
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 =
5484
repeatInsertModeChanges(cm, changes, 1);
5489
macroModeState.isPlaying = false;
5492
function logKey(macroModeState, key) {
5493
if (macroModeState.isPlaying) { return; }
5494
var registerName = macroModeState.latestRegister;
5495
var register = vimGlobalState.registerController.getRegister(registerName);
5497
register.pushText(key);
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);
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);
5523
function onChange(cm, changeObj) {
5524
var macroModeState = vimGlobalState.macroModeState;
5525
var lastChange = macroModeState.lastInsertModeChanges;
5526
if (!macroModeState.isPlaying) {
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 ) {
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;
5542
if (cm.state.overwrite && !/\n/.test(text)) {
5543
lastChange.changes.push([text]);
5545
lastChange.changes.push(text);
5550
changeObj = changeObj.next;
5558
function onCursorActivity(cm) {
5559
var vim = cm.state.vim;
5560
if (vim.insertMode) {
5562
var macroModeState = vimGlobalState.macroModeState;
5563
if (macroModeState.isPlaying) { return; }
5564
var lastChange = macroModeState.lastInsertModeChanges;
5565
if (lastChange.expectCursorActivityForChange) {
5566
lastChange.expectCursorActivityForChange = false;
5569
lastChange.maybeReset = true;
5571
} else if (!cm.curOp.isVimOp) {
5572
handleExternalSelection(cm, vim);
5575
function handleExternalSelection(cm, vim) {
5576
var anchor = cm.getCursor('anchor');
5577
var head = cm.getCursor('head');
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"});
5586
if (vim.visualMode) {
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);
5597
updateMark(cm, vim, '<', cursorMin(head, anchor));
5598
updateMark(cm, vim, '>', cursorMax(head, anchor));
5599
} else if (!vim.insertMode) {
5601
vim.lastHPos = cm.getCursor().ch;
5606
function InsertModeKey(keyName) {
5607
this.keyName = keyName;
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;
5625
lastChange.changes.push(new InsertModeKey(keyName));
5628
if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
5629
CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound);
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() {
5649
commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
5651
commandDispatcher.evalInput(cm, vim);
5654
function repeatInsert(repeat) {
5655
if (macroModeState.lastInsertModeChanges.changes.length > 0) {
5658
repeat = !vim.lastEditActionCommand ? 1 : repeat;
5659
var changeObject = macroModeState.lastInsertModeChanges;
5660
repeatInsertModeChanges(cm, changeObject.changes, repeat);
5663
vim.inputState = vim.lastEditInputState;
5664
if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
5667
for (var i = 0; i < repeat; i++) {
5672
if (!repeatForInsert) {
5678
repeatInsert(repeat);
5680
vim.inputState = cachedInputState;
5681
if (vim.insertMode && !repeatForInsert) {
5686
macroModeState.isPlaying = false;
5689
function repeatInsertModeChanges(cm, changes, repeat) {
5690
function keyHandler(binding) {
5691
if (typeof binding == 'string') {
5692
CodeMirror.commands[binding](cm);
5698
var head = cm.getCursor('head');
5699
var visualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.visualBlock;
5702
selectForInsert(cm, head, visualBlock + 1);
5703
repeat = cm.listSelections().length;
5706
for (var i = 0; i < repeat; i++) {
5708
cm.setCursor(offsetCursor(head, i, 0));
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);
5717
var start = cm.getCursor();
5718
var end = offsetCursor(start, 0, change[0].length);
5719
cm.replaceRange(change[0], start, end);
5725
cm.setCursor(offsetCursor(head, 0, 1));
5729
resetVimGlobalState();
5733
CodeMirror.Vim = Vim();