Debian Codegraph @

extensions/CodeEditor/modules/lib/ace/keybinding-vim.js

raw symbols SCIP
1 ace.define("ace/ext/hardwrap",["require","exports","module","ace/range","ace/editor","ace/config"], function(require, exports, module){"use strict";
2 var Range = require("../range").Range;
3 function hardWrap(editor, options) {
4 var max = options.column || editor.getOption("printMarginColumn");
5 var allowMerge = options.allowMerge != false;
6 var row = Math.min(options.startRow, options.endRow);
7 var endRow = Math.max(options.startRow, options.endRow);
8 var session = editor.session;
9 while (row <= endRow) {
10 var line = session.getLine(row);
11 if (line.length > max) {
12 var space = findSpace(line, max, 5);
13 if (space) {
14 var indentation = /^\s*/.exec(line)[0];
15 session.replace(new Range(row, space.start, row, space.end), "\n" + indentation);
16 }
17 endRow++;
18 }
19 else if (allowMerge && /\S/.test(line) && row != endRow) {
20 var nextLine = session.getLine(row + 1);
21 if (nextLine && /\S/.test(nextLine)) {
22 var trimmedLine = line.replace(/\s+$/, "");
23 var trimmedNextLine = nextLine.replace(/^\s+/, "");
24 var mergedLine = trimmedLine + " " + trimmedNextLine;
25 var space = findSpace(mergedLine, max, 5);
26 if (space && space.start > trimmedLine.length || mergedLine.length < max) {
27 var replaceRange = new Range(row, trimmedLine.length, row + 1, nextLine.length - trimmedNextLine.length);
28 session.replace(replaceRange, " ");
29 row--;
30 endRow--;
31 }
32 else if (trimmedLine.length < line.length) {
33 session.remove(new Range(row, trimmedLine.length, row, line.length));
34 }
35 }
36 }
37 row++;
38 }
39 function findSpace(line, max, min) {
40 if (line.length < max)
41 return;
42 var before = line.slice(0, max);
43 var after = line.slice(max);
44 var spaceAfter = /^(?:(\s+)|(\S+)(\s+))/.exec(after);
45 var spaceBefore = /(?:(\s+)|(\s+)(\S+))$/.exec(before);
46 var start = 0;
47 var end = 0;
48 if (spaceBefore && !spaceBefore[2]) {
49 start = max - spaceBefore[1].length;
50 end = max;
51 }
52 if (spaceAfter && !spaceAfter[2]) {
53 if (!start)
54 start = max;
55 end = max + spaceAfter[1].length;
56 }
57 if (start) {
58 return {
59 start: start,
60 end: end
61 };
62 }
63 if (spaceBefore && spaceBefore[2] && spaceBefore.index > min) {
64 return {
65 start: spaceBefore.index,
66 end: spaceBefore.index + spaceBefore[2].length
67 };
68 }
69 if (spaceAfter && spaceAfter[2]) {
70 start = max + spaceAfter[2].length;
71 return {
72 start: start,
73 end: start + spaceAfter[3].length
74 };
75 }
76 }
77 }
78 function wrapAfterInput(e) {
79 if (e.command.name == "insertstring" && /\S/.test(e.args)) {
80 var editor = e.editor;
81 var cursor = editor.selection.cursor;
82 if (cursor.column <= editor.renderer.$printMarginColumn)
83 return;
84 var lastDelta = editor.session.$undoManager.$lastDelta;
85 hardWrap(editor, {
86 startRow: cursor.row, endRow: cursor.row,
87 allowMerge: false
88 });
89 if (lastDelta != editor.session.$undoManager.$lastDelta)
90 editor.session.markUndoGroup();
91 }
92 }
93 var Editor = require("../editor").Editor;
94 require("../config").defineOptions(Editor.prototype, "editor", {
95 hardWrap: {
96 set: function (val) {
97 if (val) {
98 this.commands.on("afterExec", wrapAfterInput);
99 }
100 else {
101 this.commands.off("afterExec", wrapAfterInput);
102 }
103 },
104 value: false
105 }
106 });
107 exports.hardWrap = hardWrap;
108
109 });
110
111 ace.define("ace/keyboard/vim",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/dom","ace/lib/oop","ace/lib/keys","ace/lib/event","ace/search","ace/lib/useragent","ace/search_highlight","ace/commands/multi_select_commands","ace/mode/text","ace/ext/hardwrap","ace/multi_select"], function(require, exports, module){// CodeMirror, copyright (c) by Marijn Haverbeke and others
112 'use strict';
113 function log() {
114 var d = "";
115 function format(p) {
116 if (typeof p != "object")
117 return p + "";
118 if ("line" in p) {
119 return p.line + ":" + p.ch;
120 }
121 if ("anchor" in p) {
122 return format(p.anchor) + "->" + format(p.head);
123 }
124 if (Array.isArray(p))
125 return "[" + p.map(function (x) {
126 return format(x);
127 }) + "]";
128 return JSON.stringify(p);
129 }
130 for (var i = 0; i < arguments.length; i++) {
131 var p = arguments[i];
132 var f = format(p);
133 d += f + " ";
134 }
135 console.log(d);
136 }
137 var Range = require("../range").Range;
138 var EventEmitter = require("../lib/event_emitter").EventEmitter;
139 var domLib = require("../lib/dom");
140 var oop = require("../lib/oop");
141 var KEYS = require("../lib/keys");
142 var event = require("../lib/event");
143 var Search = require("../search").Search;
144 var useragent = require("../lib/useragent");
145 var SearchHighlight = require("../search_highlight").SearchHighlight;
146 var multiSelectCommands = require("../commands/multi_select_commands");
147 var TextModeTokenRe = require("../mode/text").Mode.prototype.tokenRe;
148 var hardWrap = require("../ext/hardwrap").hardWrap;
149 require("../multi_select");
150 var CodeMirror = function (ace) {
151 this.ace = ace;
152 this.state = {};
153 this.marks = {};
154 this.options = {};
155 this.$uid = 0;
156 this.onChange = this.onChange.bind(this);
157 this.onSelectionChange = this.onSelectionChange.bind(this);
158 this.onBeforeEndOperation = this.onBeforeEndOperation.bind(this);
159 this.ace.on('change', this.onChange);
160 this.ace.on('changeSelection', this.onSelectionChange);
161 this.ace.on('beforeEndOperation', this.onBeforeEndOperation);
162 };
163 CodeMirror.Pos = function (line, ch) {
164 if (!(this instanceof Pos))
165 return new Pos(line, ch);
166 this.line = line;
167 this.ch = ch;
168 };
169 CodeMirror.defineOption = function (name, val, setter) { };
170 CodeMirror.commands = {
171 redo: function (cm) { cm.ace.redo(); },
172 undo: function (cm) { cm.ace.undo(); },
173 newlineAndIndent: function (cm) { cm.ace.insert("\n"); },
174 goLineLeft: function (cm) { cm.ace.selection.moveCursorLineStart(); },
175 goLineRight: function (cm) { cm.ace.selection.moveCursorLineEnd(); }
176 };
177 CodeMirror.keyMap = {};
178 CodeMirror.addClass = CodeMirror.rmClass = function () { };
179 CodeMirror.e_stop = CodeMirror.e_preventDefault = event.stopEvent;
180 CodeMirror.keyName = function (e) {
181 var key = (KEYS[e.keyCode] || e.key || "");
182 if (key.length == 1)
183 key = key.toUpperCase();
184 key = event.getModifierString(e).replace(/(^|-)\w/g, function (m) {
185 return m.toUpperCase();
186 }) + key;
187 return key;
188 };
189 CodeMirror.keyMap['default'] = function (key) {
190 return function (cm) {
191 var cmd = cm.ace.commands.commandKeyBinding[key.toLowerCase()];
192 return cmd && cm.ace.execCommand(cmd) !== false;
193 };
194 };
195 CodeMirror.lookupKey = function lookupKey(key, map, handle) {
196 if (!map)
197 map = "default";
198 if (typeof map == "string")
199 map = CodeMirror.keyMap[map] || CodeMirror.keyMap['default'];
200 var found = typeof map == "function" ? map(key) : map[key];
201 if (found === false)
202 return "nothing";
203 if (found === "...")
204 return "multi";
205 if (found != null && handle(found))
206 return "handled";
207 if (map.fallthrough) {
208 if (!Array.isArray(map.fallthrough))
209 return lookupKey(key, map.fallthrough, handle);
210 for (var i = 0; i < map.fallthrough.length; i++) {
211 var result = lookupKey(key, map.fallthrough[i], handle);
212 if (result)
213 return result;
214 }
215 }
216 };
217 CodeMirror.findMatchingTag = function (cm, head) {
218 return cm.findMatchingTag(head);
219 };
220 CodeMirror.findEnclosingTag = function (cm, head) {
221 };
222 CodeMirror.signal = function (o, name, e) { return o._signal(name, e); };
223 CodeMirror.on = event.addListener;
224 CodeMirror.off = event.removeListener;
225 CodeMirror.isWordChar = function (ch) {
226 if (ch < "\x7f")
227 return /^\w$/.test(ch);
228 TextModeTokenRe.lastIndex = 0;
229 return TextModeTokenRe.test(ch);
230 };
231 (function () {
232 oop.implement(CodeMirror.prototype, EventEmitter);
233 this.destroy = function () {
234 this.ace.off('change', this.onChange);
235 this.ace.off('changeSelection', this.onSelectionChange);
236 this.ace.off('beforeEndOperation', this.onBeforeEndOperation);
237 this.removeOverlay();
238 };
239 this.virtualSelectionMode = function () {
240 return this.ace.inVirtualSelectionMode && this.ace.selection.index;
241 };
242 this.onChange = function (delta) {
243 if (this.$lineHandleChanges) {
244 this.$lineHandleChanges.push(delta);
245 }
246 var change = { text: delta.action[0] == 'i' ? delta.lines : [] };
247 var curOp = this.curOp = this.curOp || {};
248 if (!curOp.changeHandlers)
249 curOp.changeHandlers = this._eventRegistry["change"] && this._eventRegistry["change"].slice();
250 if (!curOp.lastChange) {
251 curOp.lastChange = curOp.change = change;
252 }
253 else {
254 curOp.lastChange.next = curOp.lastChange = change;
255 }
256 this.$updateMarkers(delta);
257 };
258 this.onSelectionChange = function () {
259 var curOp = this.curOp = this.curOp || {};
260 if (!curOp.cursorActivityHandlers)
261 curOp.cursorActivityHandlers = this._eventRegistry["cursorActivity"] && this._eventRegistry["cursorActivity"].slice();
262 this.curOp.cursorActivity = true;
263 if (this.ace.inMultiSelectMode) {
264 this.ace.keyBinding.removeKeyboardHandler(multiSelectCommands.keyboardHandler);
265 }
266 };
267 this.operation = function (fn, force) {
268 if (!force && this.curOp || force && this.curOp && this.curOp.force) {
269 return fn();
270 }
271 if (force || !this.ace.curOp) {
272 if (this.curOp)
273 this.onBeforeEndOperation();
274 }
275 if (!this.ace.curOp) {
276 var prevOp = this.ace.prevOp;
277 this.ace.startOperation({
278 command: { name: "vim", scrollIntoView: "cursor" }
279 });
280 }
281 var curOp = this.curOp = this.curOp || {};
282 this.curOp.force = force;
283 var result = fn();
284 if (this.ace.curOp && this.ace.curOp.command.name == "vim") {
285 if (this.state.dialog)
286 this.ace.curOp.command.scrollIntoView = this.ace.curOp.vimDialogScroll;
287 this.ace.endOperation();
288 if (!curOp.cursorActivity && !curOp.lastChange && prevOp)
289 this.ace.prevOp = prevOp;
290 }
291 if (force || !this.ace.curOp) {
292 if (this.curOp)
293 this.onBeforeEndOperation();
294 }
295 return result;
296 };
297 this.onBeforeEndOperation = function () {
298 var op = this.curOp;
299 if (op) {
300 if (op.change) {
301 this.signal("change", op.change, op);
302 }
303 if (op && op.cursorActivity) {
304 this.signal("cursorActivity", null, op);
305 }
306 this.curOp = null;
307 }
308 };
309 this.signal = function (eventName, e, handlers) {
310 var listeners = handlers ? handlers[eventName + "Handlers"]
311 : (this._eventRegistry || {})[eventName];
312 if (!listeners)
313 return;
314 listeners = listeners.slice();
315 for (var i = 0; i < listeners.length; i++)
316 listeners[i](this, e);
317 };
318 this.firstLine = function () { return 0; };
319 this.lastLine = function () { return this.ace.session.getLength() - 1; };
320 this.lineCount = function () { return this.ace.session.getLength(); };
321 this.setCursor = function (line, ch) {
322 if (typeof line === 'object') {
323 ch = line.ch;
324 line = line.line;
325 }
326 var shouldScroll = !this.curOp && !this.ace.inVirtualSelectionMode;
327 if (!this.ace.inVirtualSelectionMode)
328 this.ace.exitMultiSelectMode();
329 this.ace.session.unfold({ row: line, column: ch });
330 this.ace.selection.moveTo(line, ch);
331 if (shouldScroll) {
332 this.ace.renderer.scrollCursorIntoView();
333 this.ace.endOperation();
334 }
335 };
336 this.getCursor = function (p) {
337 var sel = this.ace.selection;
338 var pos = p == 'anchor' ? (sel.isEmpty() ? sel.lead : sel.anchor) :
339 p == 'head' || !p ? sel.lead : sel.getRange()[p];
340 return toCmPos(pos);
341 };
342 this.listSelections = function (p) {
343 var ranges = this.ace.multiSelect.rangeList.ranges;
344 if (!ranges.length || this.ace.inVirtualSelectionMode)
345 return [{ anchor: this.getCursor('anchor'), head: this.getCursor('head') }];
346 return ranges.map(function (r) {
347 return {
348 anchor: this.clipPos(toCmPos(r.cursor == r.end ? r.start : r.end)),
349 head: this.clipPos(toCmPos(r.cursor))
350 };
351 }, this);
352 };
353 this.setSelections = function (p, primIndex) {
354 var sel = this.ace.multiSelect;
355 var ranges = p.map(function (x) {
356 var anchor = toAcePos(x.anchor);
357 var head = toAcePos(x.head);
358 var r = Range.comparePoints(anchor, head) < 0
359 ? new Range.fromPoints(anchor, head)
360 : new Range.fromPoints(head, anchor);
361 r.cursor = Range.comparePoints(r.start, head) ? r.end : r.start;
362 return r;
363 });
364 if (this.ace.inVirtualSelectionMode) {
365 this.ace.selection.fromOrientedRange(ranges[0]);
366 return;
367 }
368 if (!primIndex) {
369 ranges = ranges.reverse();
370 }
371 else if (ranges[primIndex]) {
372 ranges.push(ranges.splice(primIndex, 1)[0]);
373 }
374 sel.toSingleRange(ranges[0].clone());
375 var session = this.ace.session;
376 for (var i = 0; i < ranges.length; i++) {
377 var range = session.$clipRangeToDocument(ranges[i]); // todo why ace doesn't do this?
378 sel.addRange(range);
379 }
380 };
381 this.setSelection = function (a, h, options) {
382 var sel = this.ace.selection;
383 sel.moveTo(a.line, a.ch);
384 sel.selectTo(h.line, h.ch);
385 if (options && options.origin == '*mouse') {
386 this.onBeforeEndOperation();
387 }
388 };
389 this.somethingSelected = function (p) {
390 return !this.ace.selection.isEmpty();
391 };
392 this.clipPos = function (p) {
393 var pos = this.ace.session.$clipPositionToDocument(p.line, p.ch);
394 return toCmPos(pos);
395 };
396 this.foldCode = function (pos) {
397 this.ace.session.$toggleFoldWidget(pos.line, {});
398 };
399 this.markText = function (cursor) {
400 return { clear: function () { }, find: function () { } };
401 };
402 this.$updateMarkers = function (delta) {
403 var isInsert = delta.action == "insert";
404 var start = delta.start;
405 var end = delta.end;
406 var rowShift = (end.row - start.row) * (isInsert ? 1 : -1);
407 var colShift = (end.column - start.column) * (isInsert ? 1 : -1);
408 if (isInsert)
409 end = start;
410 for (var i in this.marks) {
411 var point = this.marks[i];
412 var cmp = Range.comparePoints(point, start);
413 if (cmp < 0) {
414 continue; // delta starts after the range
415 }
416 if (cmp === 0) {
417 if (isInsert) {
418 if (!point.$insertRight) {
419 cmp = 1;
420 }
421 else if (point.bias == 1) {
422 cmp = 1;
423 }
424 else {
425 point.bias = -1;
426 continue;
427 }
428 }
429 }
430 var cmp2 = isInsert ? cmp : Range.comparePoints(point, end);
431 if (cmp2 > 0) {
432 point.row += rowShift;
433 point.column += point.row == end.row ? colShift : 0;
434 continue;
435 }
436 if (!isInsert && cmp2 <= 0) {
437 point.row = start.row;
438 point.column = start.column;
439 if (cmp2 === 0)
440 point.bias = 1;
441 }
442 }
443 };
444 var Marker = function (cm, id, row, column) {
445 this.cm = cm;
446 this.id = id;
447 this.row = row;
448 this.column = column;
449 cm.marks[this.id] = this;
450 };
451 Marker.prototype.clear = function () { delete this.cm.marks[this.id]; };
452 Marker.prototype.find = function () { return toCmPos(this); };
453 this.setBookmark = function (cursor, options) {
454 var bm = new Marker(this, this.$uid++, cursor.line, cursor.ch);
455 if (!options || !options.insertLeft)
456 bm.$insertRight = true;
457 this.marks[bm.id] = bm;
458 return bm;
459 };
460 this.moveH = function (increment, unit) {
461 if (unit == 'char') {
462 var sel = this.ace.selection;
463 sel.clearSelection();
464 sel.moveCursorBy(0, increment);
465 }
466 };
467 this.findPosV = function (start, amount, unit, goalColumn) {
468 if (unit == 'page') {
469 var renderer = this.ace.renderer;
470 var config = renderer.layerConfig;
471 amount = amount * Math.floor(config.height / config.lineHeight);
472 unit = 'line';
473 }
474 if (unit == 'line') {
475 var screenPos = this.ace.session.documentToScreenPosition(start.line, start.ch);
476 if (goalColumn != null)
477 screenPos.column = goalColumn;
478 screenPos.row += amount;
479 screenPos.row = Math.min(Math.max(0, screenPos.row), this.ace.session.getScreenLength() - 1);
480 var pos = this.ace.session.screenToDocumentPosition(screenPos.row, screenPos.column);
481 return toCmPos(pos);
482 }
483 else {
484 debugger;
485 }
486 };
487 this.charCoords = function (pos, mode) {
488 if (mode == 'div' || !mode) {
489 var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch);
490 return { left: sc.column, top: sc.row };
491 }
492 if (mode == 'local') {
493 var renderer = this.ace.renderer;
494 var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch);
495 var lh = renderer.layerConfig.lineHeight;
496 var cw = renderer.layerConfig.characterWidth;
497 var top = lh * sc.row;
498 return { left: sc.column * cw, top: top, bottom: top + lh };
499 }
500 };
501 this.coordsChar = function (pos, mode) {
502 var renderer = this.ace.renderer;
503 if (mode == 'local') {
504 var row = Math.max(0, Math.floor(pos.top / renderer.lineHeight));
505 var col = Math.max(0, Math.floor(pos.left / renderer.characterWidth));
506 var ch = renderer.session.screenToDocumentPosition(row, col);
507 return toCmPos(ch);
508 }
509 else if (mode == 'div') {
510 throw "not implemented";
511 }
512 };
513 this.getSearchCursor = function (query, pos, caseFold) {
514 var caseSensitive = false;
515 var isRegexp = false;
516 if (query instanceof RegExp && !query.global) {
517 caseSensitive = !query.ignoreCase;
518 query = query.source;
519 isRegexp = true;
520 }
521 if (query == "\\n") {
522 query = "\n";
523 isRegexp = false;
524 }
525 var search = new Search();
526 if (pos.ch == undefined)
527 pos.ch = Number.MAX_VALUE;
528 var acePos = { row: pos.line, column: pos.ch };
529 var cm = this;
530 var last = null;
531 return {
532 findNext: function () { return this.find(false); },
533 findPrevious: function () { return this.find(true); },
534 find: function (back) {
535 search.setOptions({
536 needle: query,
537 caseSensitive: caseSensitive,
538 wrap: false,
539 backwards: back,
540 regExp: isRegexp,
541 start: last || acePos
542 });
543 var range = search.find(cm.ace.session);
544 last = range;
545 return last && [!last.isEmpty()];
546 },
547 from: function () { return last && toCmPos(last.start); },
548 to: function () { return last && toCmPos(last.end); },
549 replace: function (text) {
550 if (last) {
551 last.end = cm.ace.session.doc.replace(last, text);
552 }
553 }
554 };
555 };
556 this.scrollTo = function (x, y) {
557 var renderer = this.ace.renderer;
558 var config = renderer.layerConfig;
559 var maxHeight = config.maxHeight;
560 maxHeight -= (renderer.$size.scrollerHeight - renderer.lineHeight) * renderer.$scrollPastEnd;
561 if (y != null)
562 this.ace.session.setScrollTop(Math.max(0, Math.min(y, maxHeight)));
563 if (x != null)
564 this.ace.session.setScrollLeft(Math.max(0, Math.min(x, config.width)));
565 };
566 this.scrollInfo = function () { return 0; };
567 this.scrollIntoView = function (pos, margin) {
568 if (pos) {
569 var renderer = this.ace.renderer;
570 var viewMargin = { "top": 0, "bottom": margin };
571 renderer.scrollCursorIntoView(toAcePos(pos), (renderer.lineHeight * 2) / renderer.$size.scrollerHeight, viewMargin);
572 }
573 };
574 this.getLine = function (row) { return this.ace.session.getLine(row); };
575 this.getRange = function (s, e) {
576 return this.ace.session.getTextRange(new Range(s.line, s.ch, e.line, e.ch));
577 };
578 this.replaceRange = function (text, s, e) {
579 if (!e)
580 e = s;
581 var range = new Range(s.line, s.ch, e.line, e.ch);
582 this.ace.session.$clipRangeToDocument(range);
583 return this.ace.session.replace(range, text);
584 };
585 this.replaceSelection =
586 this.replaceSelections = function (p) {
587 var strings = Array.isArray(p) && p;
588 var sel = this.ace.selection;
589 if (this.ace.inVirtualSelectionMode) {
590 this.ace.session.replace(sel.getRange(), strings ? p[0] || "" : p);
591 return;
592 }
593 sel.inVirtualSelectionMode = true;
594 var ranges = sel.rangeList.ranges;
595 if (!ranges.length)
596 ranges = [this.ace.multiSelect.getRange()];
597 for (var i = ranges.length; i--;)
598 this.ace.session.replace(ranges[i], strings ? p[i] || "" : p);
599 sel.inVirtualSelectionMode = false;
600 };
601 this.getSelection = function () {
602 return this.ace.getSelectedText();
603 };
604 this.getSelections = function () {
605 return this.listSelections().map(function (x) {
606 return this.getRange(x.anchor, x.head);
607 }, this);
608 };
609 this.getInputField = function () {
610 return this.ace.textInput.getElement();
611 };
612 this.getWrapperElement = function () {
613 return this.ace.container;
614 };
615 var optMap = {
616 indentWithTabs: "useSoftTabs",
617 indentUnit: "tabSize",
618 tabSize: "tabSize",
619 firstLineNumber: "firstLineNumber",
620 readOnly: "readOnly"
621 };
622 this.setOption = function (name, val) {
623 this.state[name] = val;
624 switch (name) {
625 case 'indentWithTabs':
626 name = optMap[name];
627 val = !val;
628 break;
629 case 'keyMap':
630 this.state.$keyMap = val;
631 return;
632 break;
633 default:
634 name = optMap[name];
635 }
636 if (name)
637 this.ace.setOption(name, val);
638 };
639 this.getOption = function (name) {
640 var val;
641 var aceOpt = optMap[name];
642 if (aceOpt)
643 val = this.ace.getOption(aceOpt);
644 switch (name) {
645 case 'indentWithTabs':
646 name = optMap[name];
647 return !val;
648 case 'keyMap':
649 return this.state.$keyMap || 'vim';
650 }
651 return aceOpt ? val : this.state[name];
652 };
653 this.toggleOverwrite = function (on) {
654 this.state.overwrite = on;
655 return this.ace.setOverwrite(on);
656 };
657 this.addOverlay = function (o) {
658 if (!this.$searchHighlight || !this.$searchHighlight.session) {
659 var highlight = new SearchHighlight(null, "ace_highlight-marker", "text");
660 var marker = this.ace.session.addDynamicMarker(highlight);
661 highlight.id = marker.id;
662 highlight.session = this.ace.session;
663 highlight.destroy = function (o) {
664 highlight.session.off("change", highlight.updateOnChange);
665 highlight.session.off("changeEditor", highlight.destroy);
666 highlight.session.removeMarker(highlight.id);
667 highlight.session = null;
668 };
669 highlight.updateOnChange = function (delta) {
670 var row = delta.start.row;
671 if (row == delta.end.row)
672 highlight.cache[row] = undefined;
673 else
674 highlight.cache.splice(row, highlight.cache.length);
675 };
676 highlight.session.on("changeEditor", highlight.destroy);
677 highlight.session.on("change", highlight.updateOnChange);
678 }
679 var re = new RegExp(o.query.source, "gmi");
680 this.$searchHighlight = o.highlight = highlight;
681 this.$searchHighlight.setRegexp(re);
682 this.ace.renderer.updateBackMarkers();
683 };
684 this.removeOverlay = function (o) {
685 if (this.$searchHighlight && this.$searchHighlight.session) {
686 this.$searchHighlight.destroy();
687 }
688 };
689 this.getScrollInfo = function () {
690 var renderer = this.ace.renderer;
691 var config = renderer.layerConfig;
692 return {
693 left: renderer.scrollLeft,
694 top: renderer.scrollTop,
695 height: config.maxHeight,
696 width: config.width,
697 clientHeight: config.height,
698 clientWidth: config.width
699 };
700 };
701 this.getValue = function () {
702 return this.ace.getValue();
703 };
704 this.setValue = function (v) {
705 return this.ace.setValue(v, -1);
706 };
707 this.getTokenTypeAt = function (pos) {
708 var token = this.ace.session.getTokenAt(pos.line, pos.ch);
709 return token && /comment|string/.test(token.type) ? "string" : "";
710 };
711 this.findMatchingBracket = function (pos) {
712 var m = this.ace.session.findMatchingBracket(toAcePos(pos));
713 return { to: m && toCmPos(m) };
714 };
715 this.findMatchingTag = function (pos) {
716 var m = this.ace.session.getMatchingTags(toAcePos(pos));
717 if (!m)
718 return;
719 return {
720 open: {
721 from: toCmPos(m.openTag.start),
722 to: toCmPos(m.openTag.end)
723 },
724 close: {
725 from: toCmPos(m.closeTag.start),
726 to: toCmPos(m.closeTag.end)
727 }
728 };
729 };
730 this.indentLine = function (line, method) {
731 if (method === true)
732 this.ace.session.indentRows(line, line, "\t");
733 else if (method === false)
734 this.ace.session.outdentRows(new Range(line, 0, line, 0));
735 };
736 this.indexFromPos = function (pos) {
737 return this.ace.session.doc.positionToIndex(toAcePos(pos));
738 };
739 this.posFromIndex = function (index) {
740 return toCmPos(this.ace.session.doc.indexToPosition(index));
741 };
742 this.focus = function (index) {
743 return this.ace.textInput.focus();
744 };
745 this.blur = function (index) {
746 return this.ace.blur();
747 };
748 this.defaultTextHeight = function (index) {
749 return this.ace.renderer.layerConfig.lineHeight;
750 };
751 this.scanForBracket = function (pos, dir, _, options) {
752 var re = options.bracketRegex.source;
753 var tokenRe = /paren|text|operator|tag/;
754 if (dir == 1) {
755 var m = this.ace.session.$findClosingBracket(re.slice(1, 2), toAcePos(pos), tokenRe);
756 }
757 else {
758 var m = this.ace.session.$findOpeningBracket(re.slice(-2, -1), { row: pos.line, column: pos.ch + 1 }, tokenRe);
759 if (!m && options.bracketRegex && options.bracketRegex.test(this.getLine(pos.line)[pos.ch - 1])) {
760 m = { row: pos.line, column: pos.ch - 1 };
761 }
762 }
763 return m && { pos: toCmPos(m) };
764 };
765 this.refresh = function () {
766 return this.ace.resize(true);
767 };
768 this.getMode = function () {
769 return { name: this.getOption("mode") };
770 };
771 this.execCommand = function (name) {
772 if (CodeMirror.commands.hasOwnProperty(name))
773 return CodeMirror.commands[name](this);
774 if (name == "indentAuto")
775 return this.ace.execCommand("autoindent");
776 console.log(name + " is not implemented");
777 };
778 this.getLineNumber = function (handle) {
779 var deltas = this.$lineHandleChanges;
780 if (!deltas)
781 return null;
782 var row = handle.row;
783 for (var i = 0; i < deltas.length; i++) {
784 var delta = deltas[i];
785 if (delta.start.row != delta.end.row) {
786 if (delta.action[0] == "i") {
787 if (delta.start.row < row)
788 row += delta.end.row - delta.start.row;
789 }
790 else {
791 if (delta.start.row < row) {
792 if (row < delta.end.row || row == delta.end.row && delta.start.column > 0) {
793 return null;
794 }
795 row -= delta.end.row - delta.start.row;
796 }
797 }
798 }
799 }
800 return row;
801 };
802 this.getLineHandle = function (row) {
803 if (!this.$lineHandleChanges)
804 this.$lineHandleChanges = [];
805 return { text: this.ace.session.getLine(row), row: row };
806 };
807 this.releaseLineHandles = function () {
808 this.$lineHandleChanges = undefined;
809 };
810 this.getLastEditEnd = function () {
811 var undoManager = this.ace.session.$undoManager;
812 if (undoManager && undoManager.$lastDelta)
813 return toCmPos(undoManager.$lastDelta.end);
814 };
815 }).call(CodeMirror.prototype);
816 function toAcePos(cmPos) {
817 return { row: cmPos.line, column: cmPos.ch };
818 }
819 function toCmPos(acePos) {
820 return new Pos(acePos.row, acePos.column);
821 }
822 var StringStream = CodeMirror.StringStream = function (string, tabSize) {
823 this.pos = this.start = 0;
824 this.string = string;
825 this.tabSize = tabSize || 8;
826 this.lastColumnPos = this.lastColumnValue = 0;
827 this.lineStart = 0;
828 };
829 StringStream.prototype = {
830 eol: function () { return this.pos >= this.string.length; },
831 sol: function () { return this.pos == this.lineStart; },
832 peek: function () { return this.string.charAt(this.pos) || undefined; },
833 next: function () {
834 if (this.pos < this.string.length)
835 return this.string.charAt(this.pos++);
836 },
837 eat: function (match) {
838 var ch = this.string.charAt(this.pos);
839 if (typeof match == "string")
840 var ok = ch == match;
841 else
842 var ok = ch && (match.test ? match.test(ch) : match(ch));
843 if (ok) {
844 ++this.pos;
845 return ch;
846 }
847 },
848 eatWhile: function (match) {
849 var start = this.pos;
850 while (this.eat(match)) { }
851 return this.pos > start;
852 },
853 eatSpace: function () {
854 var start = this.pos;
855 while (/[\s\u00a0]/.test(this.string.charAt(this.pos)))
856 ++this.pos;
857 return this.pos > start;
858 },
859 skipToEnd: function () { this.pos = this.string.length; },
860 skipTo: function (ch) {
861 var found = this.string.indexOf(ch, this.pos);
862 if (found > -1) {
863 this.pos = found;
864 return true;
865 }
866 },
867 backUp: function (n) { this.pos -= n; },
868 column: function () {
869 throw "not implemented";
870 },
871 indentation: function () {
872 throw "not implemented";
873 },
874 match: function (pattern, consume, caseInsensitive) {
875 if (typeof pattern == "string") {
876 var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
877 var substr = this.string.substr(this.pos, pattern.length);
878 if (cased(substr) == cased(pattern)) {
879 if (consume !== false)
880 this.pos += pattern.length;
881 return true;
882 }
883 }
884 else {
885 var match = this.string.slice(this.pos).match(pattern);
886 if (match && match.index > 0)
887 return null;
888 if (match && consume !== false)
889 this.pos += match[0].length;
890 return match;
891 }
892 },
893 current: function () { return this.string.slice(this.start, this.pos); },
894 hideFirstChars: function (n, inner) {
895 this.lineStart += n;
896 try {
897 return inner();
898 }
899 finally {
900 this.lineStart -= n;
901 }
902 }
903 };
904 CodeMirror.defineExtension = function (name, fn) {
905 CodeMirror.prototype[name] = fn;
906 };
907 domLib.importCssString(".normal-mode .ace_cursor{\n border: none;\n background-color: rgba(255,0,0,0.5);\n}\n.normal-mode .ace_hidden-cursors .ace_cursor{\n background-color: transparent;\n border: 1px solid red;\n opacity: 0.7\n}\n.ace_dialog {\n position: absolute;\n left: 0; right: 0;\n background: inherit;\n z-index: 15;\n padding: .1em .8em;\n overflow: hidden;\n color: inherit;\n}\n.ace_dialog-top {\n border-bottom: 1px solid #444;\n top: 0;\n}\n.ace_dialog-bottom {\n border-top: 1px solid #444;\n bottom: 0;\n}\n.ace_dialog input {\n border: none;\n outline: none;\n background: transparent;\n width: 20em;\n color: inherit;\n font-family: monospace;\n}", "vimMode", false);
908 (function () {
909 function dialogDiv(cm, template, bottom) {
910 var wrap = cm.ace.container;
911 var dialog;
912 dialog = wrap.appendChild(document.createElement("div"));
913 if (bottom)
914 dialog.className = "ace_dialog ace_dialog-bottom";
915 else
916 dialog.className = "ace_dialog ace_dialog-top";
917 if (typeof template == "string") {
918 dialog.innerHTML = template;
919 }
920 else { // Assuming it's a detached DOM element.
921 dialog.appendChild(template);
922 }
923 return dialog;
924 }
925 function closeNotification(cm, newVal) {
926 if (cm.state.currentNotificationClose)
927 cm.state.currentNotificationClose();
928 cm.state.currentNotificationClose = newVal;
929 }
930 CodeMirror.defineExtension("openDialog", function (template, callback, options) {
931 if (this.virtualSelectionMode())
932 return;
933 if (!options)
934 options = {};
935 closeNotification(this, null);
936 var dialog = dialogDiv(this, template, options.bottom);
937 var closed = false, me = this;
938 this.state.dialog = dialog;
939 function close(newVal) {
940 if (typeof newVal == 'string') {
941 inp.value = newVal;
942 }
943 else {
944 if (closed)
945 return;
946 if (newVal && newVal.type == "blur") {
947 if (document.activeElement === inp)
948 return;
949 }
950 if (me.state.dialog == dialog) {
951 me.state.dialog = null;
952 me.focus();
953 }
954 closed = true;
955 dialog.remove();
956 if (options.onClose)
957 options.onClose(dialog);
958 var cm = me;
959 if (cm.state.vim) {
960 cm.state.vim.status = null;
961 cm.ace._signal("changeStatus");
962 cm.ace.renderer.$loop.schedule(cm.ace.renderer.CHANGE_CURSOR);
963 }
964 }
965 }
966 var inp = dialog.getElementsByTagName("input")[0], button;
967 if (inp) {
968 if (options.value) {
969 inp.value = options.value;
970 if (options.selectValueOnOpen !== false)
971 inp.select();
972 }
973 if (options.onInput)
974 CodeMirror.on(inp, "input", function (e) { options.onInput(e, inp.value, close); });
975 if (options.onKeyUp)
976 CodeMirror.on(inp, "keyup", function (e) { options.onKeyUp(e, inp.value, close); });
977 CodeMirror.on(inp, "keydown", function (e) {
978 if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) {
979 return;
980 }
981 if (e.keyCode == 13)
982 callback(inp.value);
983 if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) {
984 CodeMirror.e_stop(e);
985 close();
986 }
987 });
988 if (options.closeOnBlur !== false)
989 CodeMirror.on(inp, "blur", close);
990 inp.focus();
991 }
992 else if (button = dialog.getElementsByTagName("button")[0]) {
993 CodeMirror.on(button, "click", function () {
994 close();
995 me.focus();
996 });
997 if (options.closeOnBlur !== false)
998 CodeMirror.on(button, "blur", close);
999 button.focus();
1000 }
1001 return close;
1002 });
1003 CodeMirror.defineExtension("openNotification", function (template, options) {
1004 if (this.virtualSelectionMode())
1005 return;
1006 closeNotification(this, close);
1007 var dialog = dialogDiv(this, template, options && options.bottom);
1008 var closed = false, doneTimer;
1009 var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000;
1010 function close() {
1011 if (closed)
1012 return;
1013 closed = true;
1014 clearTimeout(doneTimer);
1015 dialog.remove();
1016 }
1017 CodeMirror.on(dialog, 'click', function (e) {
1018 CodeMirror.e_preventDefault(e);
1019 close();
1020 });
1021 if (duration)
1022 doneTimer = setTimeout(close, duration);
1023 return close;
1024 });
1025 })();
1026 var Pos = CodeMirror.Pos;
1027 function updateSelectionForSurrogateCharacters(cm, curStart, curEnd) {
1028 if (curStart.line === curEnd.line && curStart.ch >= curEnd.ch - 1) {
1029 var text = cm.getLine(curStart.line);
1030 var charCode = text.charCodeAt(curStart.ch);
1031 if (0xD800 <= charCode && charCode <= 0xD8FF) {
1032 curEnd.ch += 1;
1033 }
1034 }
1035 return { start: curStart, end: curEnd };
1036 }
1037 var defaultKeymap = [
1038 { keys: '<Left>', type: 'keyToKey', toKeys: 'h' },
1039 { keys: '<Right>', type: 'keyToKey', toKeys: 'l' },
1040 { keys: '<Up>', type: 'keyToKey', toKeys: 'k' },
1041 { keys: '<Down>', type: 'keyToKey', toKeys: 'j' },
1042 { keys: 'g<Up>', type: 'keyToKey', toKeys: 'gk' },
1043 { keys: 'g<Down>', type: 'keyToKey', toKeys: 'gj' },
1044 { keys: '<Space>', type: 'keyToKey', toKeys: 'l' },
1045 { keys: '<BS>', type: 'keyToKey', toKeys: 'h' },
1046 { keys: '<Del>', type: 'keyToKey', toKeys: 'x' },
1047 { keys: '<C-Space>', type: 'keyToKey', toKeys: 'W' },
1048 { keys: '<C-BS>', type: 'keyToKey', toKeys: 'B' },
1049 { keys: '<S-Space>', type: 'keyToKey', toKeys: 'w' },
1050 { keys: '<S-BS>', type: 'keyToKey', toKeys: 'b' },
1051 { keys: '<C-n>', type: 'keyToKey', toKeys: 'j' },
1052 { keys: '<C-p>', type: 'keyToKey', toKeys: 'k' },
1053 { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>' },
1054 { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>' },
1055 { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
1056 { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
1057 { keys: '<C-Esc>', type: 'keyToKey', toKeys: '<Esc>' }, // ipad keyboard sends C-Esc instead of C-[
1058 { keys: '<C-Esc>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
1059 { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' },
1060 { keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual' },
1061 { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' },
1062 { keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' },
1063 { keys: '<Home>', type: 'keyToKey', toKeys: '0' },
1064 { keys: '<End>', type: 'keyToKey', toKeys: '$' },
1065 { keys: '<PageUp>', type: 'keyToKey', toKeys: '<C-b>' },
1066 { keys: '<PageDown>', type: 'keyToKey', toKeys: '<C-f>' },
1067 { keys: '<CR>', type: 'keyToKey', toKeys: 'j^', context: 'normal' },
1068 { keys: '<Ins>', type: 'keyToKey', toKeys: 'i', context: 'normal' },
1069 { keys: '<Ins>', type: 'action', action: 'toggleOverwrite', context: 'insert' },
1070 { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true } },
1071 { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true } },
1072 { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true } },
1073 { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false } },
1074 { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true } },
1075 { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true } },
1076 { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true } },
1077 { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true } },
1078 { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false } },
1079 { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false } },
1080 { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true } },
1081 { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true } },
1082 { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true } },
1083 { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false } },
1084 { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true } },
1085 { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true } },
1086 { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true } },
1087 { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true } },
1088 { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true } },
1089 { keys: '(', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: false } },
1090 { keys: ')', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: true } },
1091 { keys: '<C-f>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true } },
1092 { keys: '<C-b>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false } },
1093 { keys: '<C-d>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true } },
1094 { keys: '<C-u>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true } },
1095 { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true } },
1096 { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true } },
1097 { keys: "g$", type: "motion", motion: "moveToEndOfDisplayLine" },
1098 { keys: "g^", type: "motion", motion: "moveToStartOfDisplayLine" },
1099 { keys: "g0", type: "motion", motion: "moveToStartOfDisplayLine" },
1100 { keys: '0', type: 'motion', motion: 'moveToStartOfLine' },
1101 { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' },
1102 { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar: true } },
1103 { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar: true } },
1104 { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar: true, repeatOffset: -1 } },
1105 { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true } },
1106 { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true } },
1107 { keys: 'f<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true, inclusive: true } },
1108 { keys: 'F<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false } },
1109 { keys: 't<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true } },
1110 { keys: 'T<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false } },
1111 { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true } },
1112 { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false } },
1113 { keys: '\'<register>', type: 'motion', motion: 'goToMark', motionArgs: { toJumplist: true, linewise: true } },
1114 { keys: '`<register>', type: 'motion', motion: 'goToMark', motionArgs: { toJumplist: true } },
1115 { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
1116 { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
1117 { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
1118 { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
1119 { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true } },
1120 { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true } },
1121 { keys: ']<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true } },
1122 { keys: '[<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true } },
1123 { keys: '|', type: 'motion', motion: 'moveToColumn' },
1124 { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context: 'visual' },
1125 { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: { sameLine: true }, context: 'visual' },
1126 { keys: 'd', type: 'operator', operator: 'delete' },
1127 { keys: 'y', type: 'operator', operator: 'yank' },
1128 { keys: 'c', type: 'operator', operator: 'change' },
1129 { keys: '=', type: 'operator', operator: 'indentAuto' },
1130 { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true } },
1131 { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false } },
1132 { keys: 'g~', type: 'operator', operator: 'changeCase' },
1133 { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: { toLower: true }, isEdit: true },
1134 { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: { toLower: false }, isEdit: true },
1135 { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true } },
1136 { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true } },
1137 { keys: 'gn', type: 'motion', motion: 'findAndSelectNextInclusive', motionArgs: { forward: true } },
1138 { keys: 'gN', type: 'motion', motion: 'findAndSelectNextInclusive', motionArgs: { forward: false } },
1139 { keys: 'gq', type: 'operator', operator: 'hardWrap' },
1140 { keys: 'gw', type: 'operator', operator: 'hardWrap', operatorArgs: { keepCursor: true } },
1141 { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false } },
1142 { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true } },
1143 { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal' },
1144 { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual' },
1145 { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'expandToLine', motionArgs: { linewise: true }, context: 'normal' },
1146 { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual' },
1147 { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal' },
1148 { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual' },
1149 { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal' },
1150 { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual' },
1151 { keys: '<C-u>', type: 'operatorMotion', operator: 'delete', motion: 'moveToStartOfLine', context: 'insert' },
1152 { keys: '<C-w>', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' },
1153 { keys: '<C-w>', type: 'idle', context: 'normal' },
1154 { keys: '<C-i>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true } },
1155 { keys: '<C-o>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false } },
1156 { keys: '<C-e>', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true } },
1157 { keys: '<C-y>', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true } },
1158 { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' },
1159 { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' },
1160 { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
1161 { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' },
1162 { keys: 'gi', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'lastEdit' }, context: 'normal' },
1163 { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank' }, context: 'normal' },
1164 { keys: 'gI', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'bol' }, context: 'normal' },
1165 { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' },
1166 { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' },
1167 { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' },
1168 { keys: 'v', type: 'action', action: 'toggleVisualMode' },
1169 { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true } },
1170 { keys: '<C-v>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true } },
1171 { keys: '<C-q>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true } },
1172 { keys: 'gv', type: 'action', action: 'reselectLastSelection' },
1173 { keys: 'J', type: 'action', action: 'joinLines', isEdit: true },
1174 { keys: 'gJ', type: 'action', action: 'joinLines', actionArgs: { keepSpaces: true }, isEdit: true },
1175 { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true } },
1176 { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true } },
1177 { keys: 'r<character>', type: 'action', action: 'replace', isEdit: true },
1178 { keys: '@<register>', type: 'action', action: 'replayMacro' },
1179 { keys: 'q<register>', type: 'action', action: 'enterMacroRecordMode' },
1180 { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }, context: 'normal' },
1181 { keys: 'R', type: 'operator', operator: 'change', operatorArgs: { linewise: true, fullLine: true }, context: 'visual', exitVisualBlock: true },
1182 { keys: 'u', type: 'action', action: 'undo', context: 'normal' },
1183 { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: { toLower: true }, context: 'visual', isEdit: true },
1184 { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: { toLower: false }, context: 'visual', isEdit: true },
1185 { keys: '<C-r>', type: 'action', action: 'redo' },
1186 { keys: 'm<register>', type: 'action', action: 'setMark' },
1187 { keys: '"<register>', type: 'action', action: 'setRegister' },
1188 { keys: '<C-r><register>', type: 'action', action: 'insertRegister', context: 'insert', isEdit: true },
1189 { keys: '<C-o>', type: 'action', action: 'oneNormalCommand', context: 'insert' },
1190 { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' } },
1191 { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
1192 { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' } },
1193 { keys: 'z<CR>', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
1194 { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' } },
1195 { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
1196 { keys: '.', type: 'action', action: 'repeatLastEdit' },
1197 { keys: '<C-a>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: { increase: true, backtrack: false } },
1198 { keys: '<C-x>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: { increase: false, backtrack: false } },
1199 { keys: '<C-t>', type: 'action', action: 'indent', actionArgs: { indentRight: true }, context: 'insert' },
1200 { keys: '<C-d>', type: 'action', action: 'indent', actionArgs: { indentRight: false }, context: 'insert' },
1201 { keys: 'a<register>', type: 'motion', motion: 'textObjectManipulation' },
1202 { keys: 'i<register>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true } },
1203 { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true } },
1204 { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true } },
1205 { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true } },
1206 { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true } },
1207 { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true } },
1208 { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true } },
1209 { keys: ':', type: 'ex' }
1210 ];
1211 var defaultKeymapLength = defaultKeymap.length;
1212 var defaultExCommandMap = [
1213 { name: 'colorscheme', shortName: 'colo' },
1214 { name: 'map' },
1215 { name: 'imap', shortName: 'im' },
1216 { name: 'nmap', shortName: 'nm' },
1217 { name: 'vmap', shortName: 'vm' },
1218 { name: 'omap', shortName: 'om' },
1219 { name: 'noremap', shortName: 'no' },
1220 { name: 'nnoremap', shortName: 'nn' },
1221 { name: 'vnoremap', shortName: 'vn' },
1222 { name: 'inoremap', shortName: 'ino' },
1223 { name: 'onoremap', shortName: 'ono' },
1224 { name: 'unmap' },
1225 { name: 'mapclear', shortName: 'mapc' },
1226 { name: 'nmapclear', shortName: 'nmapc' },
1227 { name: 'vmapclear', shortName: 'vmapc' },
1228 { name: 'imapclear', shortName: 'imapc' },
1229 { name: 'omapclear', shortName: 'omapc' },
1230 { name: 'write', shortName: 'w' },
1231 { name: 'undo', shortName: 'u' },
1232 { name: 'redo', shortName: 'red' },
1233 { name: 'set', shortName: 'se' },
1234 { name: 'setlocal', shortName: 'setl' },
1235 { name: 'setglobal', shortName: 'setg' },
1236 { name: 'sort', shortName: 'sor' },
1237 { name: 'substitute', shortName: 's', possiblyAsync: true },
1238 { name: 'startinsert', shortName: 'start' },
1239 { name: 'nohlsearch', shortName: 'noh' },
1240 { name: 'yank', shortName: 'y' },
1241 { name: 'delmarks', shortName: 'delm' },
1242 { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true },
1243 { name: 'vglobal', shortName: 'v' },
1244 { name: 'delete', shortName: 'd' },
1245 { name: 'join', shortName: 'j' },
1246 { name: 'normal', shortName: 'norm' },
1247 { name: 'global', shortName: 'g' }
1248 ];
1249 var langmap = parseLangmap('');
1250 function enterVimMode(cm) {
1251 cm.setOption('disableInput', true);
1252 cm.setOption('showCursorWhenSelecting', false);
1253 CodeMirror.signal(cm, "vim-mode-change", { mode: "normal" });
1254 cm.on('cursorActivity', onCursorActivity);
1255 maybeInitVimState(cm);
1256 CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
1257 }
1258 function leaveVimMode(cm) {
1259 cm.setOption('disableInput', false);
1260 cm.off('cursorActivity', onCursorActivity);
1261 CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
1262 cm.state.vim = null;
1263 if (highlightTimeout)
1264 clearTimeout(highlightTimeout);
1265 }
1266 function getOnPasteFn(cm) {
1267 var vim = cm.state.vim;
1268 if (!vim.onPasteFn) {
1269 vim.onPasteFn = function () {
1270 if (!vim.insertMode) {
1271 cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
1272 actions.enterInsertMode(cm, {}, vim);
1273 }
1274 };
1275 }
1276 return vim.onPasteFn;
1277 }
1278 var numberRegex = /[\d]/;
1279 var wordCharTest = [CodeMirror.isWordChar, function (ch) {
1280 return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch);
1281 }], bigWordCharTest = [function (ch) {
1282 return /\S/.test(ch);
1283 }];
1284 var validMarks = ['<', '>'];
1285 var validRegisters = ['-', '"', '.', ':', '_', '/', '+'];
1286 var latinCharRegex = /^\w$/;
1287 var upperCaseChars;
1288 try {
1289 upperCaseChars = new RegExp("^[\\p{Lu}]$", "u");
1290 }
1291 catch (_) {
1292 upperCaseChars = /^[A-Z]$/;
1293 }
1294 function isLine(cm, line) {
1295 return line >= cm.firstLine() && line <= cm.lastLine();
1296 }
1297 function isLowerCase(k) {
1298 return (/^[a-z]$/).test(k);
1299 }
1300 function isMatchableSymbol(k) {
1301 return '()[]{}'.indexOf(k) != -1;
1302 }
1303 function isNumber(k) {
1304 return numberRegex.test(k);
1305 }
1306 function isUpperCase(k) {
1307 return upperCaseChars.test(k);
1308 }
1309 function isWhiteSpaceString(k) {
1310 return (/^\s*$/).test(k);
1311 }
1312 function isEndOfSentenceSymbol(k) {
1313 return '.?!'.indexOf(k) != -1;
1314 }
1315 function inArray(val, arr) {
1316 for (var i = 0; i < arr.length; i++) {
1317 if (arr[i] == val) {
1318 return true;
1319 }
1320 }
1321 return false;
1322 }
1323 var options = {};
1324 function defineOption(name, defaultValue, type, aliases, callback) {
1325 if (defaultValue === undefined && !callback) {
1326 throw Error('defaultValue is required unless callback is provided');
1327 }
1328 if (!type) {
1329 type = 'string';
1330 }
1331 options[name] = {
1332 type: type,
1333 defaultValue: defaultValue,
1334 callback: callback
1335 };
1336 if (aliases) {
1337 for (var i = 0; i < aliases.length; i++) {
1338 options[aliases[i]] = options[name];
1339 }
1340 }
1341 if (defaultValue) {
1342 setOption(name, defaultValue);
1343 }
1344 }
1345 function setOption(name, value, cm, cfg) {
1346 var option = options[name];
1347 cfg = cfg || {};
1348 var scope = cfg.scope;
1349 if (!option) {
1350 return new Error('Unknown option: ' + name);
1351 }
1352 if (option.type == 'boolean') {
1353 if (value && value !== true) {
1354 return new Error('Invalid argument: ' + name + '=' + value);
1355 }
1356 else if (value !== false) {
1357 value = true;
1358 }
1359 }
1360 if (option.callback) {
1361 if (scope !== 'local') {
1362 option.callback(value, undefined);
1363 }
1364 if (scope !== 'global' && cm) {
1365 option.callback(value, cm);
1366 }
1367 }
1368 else {
1369 if (scope !== 'local') {
1370 option.value = option.type == 'boolean' ? !!value : value;
1371 }
1372 if (scope !== 'global' && cm) {
1373 cm.state.vim.options[name] = { value: value };
1374 }
1375 }
1376 }
1377 function getOption(name, cm, cfg) {
1378 var option = options[name];
1379 cfg = cfg || {};
1380 var scope = cfg.scope;
1381 if (!option) {
1382 return new Error('Unknown option: ' + name);
1383 }
1384 if (option.callback) {
1385 var local = cm && option.callback(undefined, cm);
1386 if (scope !== 'global' && local !== undefined) {
1387 return local;
1388 }
1389 if (scope !== 'local') {
1390 return option.callback();
1391 }
1392 return;
1393 }
1394 else {
1395 var local = (scope !== 'global') && (cm && cm.state.vim.options[name]);
1396 return (local || (scope !== 'local') && option || {}).value;
1397 }
1398 }
1399 defineOption('filetype', undefined, 'string', ['ft'], function (name, cm) {
1400 if (cm === undefined) {
1401 return;
1402 }
1403 if (name === undefined) {
1404 var mode = cm.getOption('mode');
1405 return mode == 'null' ? '' : mode;
1406 }
1407 else {
1408 var mode = name == '' ? 'null' : name;
1409 cm.setOption('mode', mode);
1410 }
1411 });
1412 defineOption('textwidth', 80, 'number', ['tw'], function (width, cm) {
1413 if (cm === undefined) {
1414 return;
1415 }
1416 if (width === undefined) {
1417 var value = cm.getOption('textwidth');
1418 return value;
1419 }
1420 else {
1421 var column = Math.round(width);
1422 if (column > 1) {
1423 cm.setOption('textwidth', column);
1424 }
1425 }
1426 });
1427 var createCircularJumpList = function () {
1428 var size = 100;
1429 var pointer = -1;
1430 var head = 0;
1431 var tail = 0;
1432 var buffer = new Array(size);
1433 function add(cm, oldCur, newCur) {
1434 var current = pointer % size;
1435 var curMark = buffer[current];
1436 function useNextSlot(cursor) {
1437 var next = ++pointer % size;
1438 var trashMark = buffer[next];
1439 if (trashMark) {
1440 trashMark.clear();
1441 }
1442 buffer[next] = cm.setBookmark(cursor);
1443 }
1444 if (curMark) {
1445 var markPos = curMark.find();
1446 if (markPos && !cursorEqual(markPos, oldCur)) {
1447 useNextSlot(oldCur);
1448 }
1449 }
1450 else {
1451 useNextSlot(oldCur);
1452 }
1453 useNextSlot(newCur);
1454 head = pointer;
1455 tail = pointer - size + 1;
1456 if (tail < 0) {
1457 tail = 0;
1458 }
1459 }
1460 function move(cm, offset) {
1461 pointer += offset;
1462 if (pointer > head) {
1463 pointer = head;
1464 }
1465 else if (pointer < tail) {
1466 pointer = tail;
1467 }
1468 var mark = buffer[(size + pointer) % size];
1469 if (mark && !mark.find()) {
1470 var inc = offset > 0 ? 1 : -1;
1471 var newCur;
1472 var oldCur = cm.getCursor();
1473 do {
1474 pointer += inc;
1475 mark = buffer[(size + pointer) % size];
1476 if (mark &&
1477 (newCur = mark.find()) &&
1478 !cursorEqual(oldCur, newCur)) {
1479 break;
1480 }
1481 } while (pointer < head && pointer > tail);
1482 }
1483 return mark;
1484 }
1485 function find(cm, offset) {
1486 var oldPointer = pointer;
1487 var mark = move(cm, offset);
1488 pointer = oldPointer;
1489 return mark && mark.find();
1490 }
1491 return {
1492 cachedCursor: undefined, //used for # and * jumps
1493 add: add,
1494 find: find,
1495 move: move
1496 };
1497 };
1498 var createInsertModeChanges = function (c) {
1499 if (c) {
1500 return {
1501 changes: c.changes,
1502 expectCursorActivityForChange: c.expectCursorActivityForChange
1503 };
1504 }
1505 return {
1506 changes: [],
1507 expectCursorActivityForChange: false
1508 };
1509 };
1510 function MacroModeState() {
1511 this.latestRegister = undefined;
1512 this.isPlaying = false;
1513 this.isRecording = false;
1514 this.replaySearchQueries = [];
1515 this.onRecordingDone = undefined;
1516 this.lastInsertModeChanges = createInsertModeChanges();
1517 }
1518 MacroModeState.prototype = {
1519 exitMacroRecordMode: function () {
1520 var macroModeState = vimGlobalState.macroModeState;
1521 if (macroModeState.onRecordingDone) {
1522 macroModeState.onRecordingDone(); // close dialog
1523 }
1524 macroModeState.onRecordingDone = undefined;
1525 macroModeState.isRecording = false;
1526 },
1527 enterMacroRecordMode: function (cm, registerName) {
1528 var register = vimGlobalState.registerController.getRegister(registerName);
1529 if (register) {
1530 register.clear();
1531 this.latestRegister = registerName;
1532 if (cm.openDialog) {
1533 var template = dom('span', { class: 'cm-vim-message' }, 'recording @' + registerName);
1534 this.onRecordingDone = cm.openDialog(template, null, { bottom: true });
1535 }
1536 this.isRecording = true;
1537 }
1538 }
1539 };
1540 function maybeInitVimState(cm) {
1541 if (!cm.state.vim) {
1542 cm.state.vim = {
1543 inputState: new InputState(),
1544 lastEditInputState: undefined,
1545 lastEditActionCommand: undefined,
1546 lastHPos: -1,
1547 lastHSPos: -1,
1548 lastMotion: null,
1549 marks: {},
1550 insertMode: false,
1551 insertModeReturn: false,
1552 insertModeRepeat: undefined,
1553 visualMode: false,
1554 visualLine: false,
1555 visualBlock: false,
1556 lastSelection: null,
1557 lastPastedText: null,
1558 sel: {},
1559 options: {},
1560 expectLiteralNext: false
1561 };
1562 }
1563 return cm.state.vim;
1564 }
1565 var vimGlobalState;
1566 function resetVimGlobalState() {
1567 vimGlobalState = {
1568 searchQuery: null,
1569 searchIsReversed: false,
1570 lastSubstituteReplacePart: undefined,
1571 jumpList: createCircularJumpList(),
1572 macroModeState: new MacroModeState,
1573 lastCharacterSearch: { increment: 0, forward: true, selectedCharacter: '' },
1574 registerController: new RegisterController({}),
1575 searchHistoryController: new HistoryController(),
1576 exCommandHistoryController: new HistoryController()
1577 };
1578 for (var optionName in options) {
1579 var option = options[optionName];
1580 option.value = option.defaultValue;
1581 }
1582 }
1583 var lastInsertModeKeyTimer;
1584 var vimApi = {
1585 enterVimMode: enterVimMode,
1586 leaveVimMode: leaveVimMode,
1587 buildKeyMap: function () {
1588 },
1589 getRegisterController: function () {
1590 return vimGlobalState.registerController;
1591 },
1592 resetVimGlobalState_: resetVimGlobalState,
1593 getVimGlobalState_: function () {
1594 return vimGlobalState;
1595 },
1596 maybeInitVimState_: maybeInitVimState,
1597 suppressErrorLogging: false,
1598 InsertModeKey: InsertModeKey,
1599 map: function (lhs, rhs, ctx) {
1600 exCommandDispatcher.map(lhs, rhs, ctx);
1601 },
1602 unmap: function (lhs, ctx) {
1603 return exCommandDispatcher.unmap(lhs, ctx);
1604 },
1605 noremap: function (lhs, rhs, ctx) {
1606 exCommandDispatcher.map(lhs, rhs, ctx, true);
1607 },
1608 mapclear: function (ctx) {
1609 var actualLength = defaultKeymap.length, origLength = defaultKeymapLength;
1610 var userKeymap = defaultKeymap.slice(0, actualLength - origLength);
1611 defaultKeymap = defaultKeymap.slice(actualLength - origLength);
1612 if (ctx) {
1613 for (var i = userKeymap.length - 1; i >= 0; i--) {
1614 var mapping = userKeymap[i];
1615 if (ctx !== mapping.context) {
1616 if (mapping.context) {
1617 this._mapCommand(mapping);
1618 }
1619 else {
1620 var contexts = ['normal', 'insert', 'visual'];
1621 for (var j in contexts) {
1622 if (contexts[j] !== ctx) {
1623 var newMapping = {};
1624 for (var key in mapping) {
1625 newMapping[key] = mapping[key];
1626 }
1627 newMapping.context = contexts[j];
1628 this._mapCommand(newMapping);
1629 }
1630 }
1631 }
1632 }
1633 }
1634 }
1635 },
1636 langmap: updateLangmap,
1637 vimKeyFromEvent: vimKeyFromEvent,
1638 setOption: setOption,
1639 getOption: getOption,
1640 defineOption: defineOption,
1641 defineEx: function (name, prefix, func) {
1642 if (!prefix) {
1643 prefix = name;
1644 }
1645 else if (name.indexOf(prefix) !== 0) {
1646 throw new Error('(Vim.defineEx) "' + prefix + '" is not a prefix of "' + name + '", command not registered');
1647 }
1648 exCommands[name] = func;
1649 exCommandDispatcher.commandMap_[prefix] = { name: name, shortName: prefix, type: 'api' };
1650 },
1651 handleKey: function (cm, key, origin) {
1652 var command = this.findKey(cm, key, origin);
1653 if (typeof command === 'function') {
1654 return command();
1655 }
1656 },
1657 multiSelectHandleKey: multiSelectHandleKey,
1658 findKey: function (cm, key, origin) {
1659 var vim = maybeInitVimState(cm);
1660 function handleMacroRecording() {
1661 var macroModeState = vimGlobalState.macroModeState;
1662 if (macroModeState.isRecording) {
1663 if (key == 'q') {
1664 macroModeState.exitMacroRecordMode();
1665 clearInputState(cm);
1666 return true;
1667 }
1668 if (origin != 'mapping') {
1669 logKey(macroModeState, key);
1670 }
1671 }
1672 }
1673 function handleEsc() {
1674 if (key == '<Esc>') {
1675 if (vim.visualMode) {
1676 exitVisualMode(cm);
1677 }
1678 else if (vim.insertMode) {
1679 exitInsertMode(cm);
1680 }
1681 else {
1682 return;
1683 }
1684 clearInputState(cm);
1685 return true;
1686 }
1687 }
1688 function handleKeyInsertMode() {
1689 if (handleEsc()) {
1690 return true;
1691 }
1692 vim.inputState.keyBuffer.push(key);
1693 var keys = vim.inputState.keyBuffer.join("");
1694 var keysAreChars = key.length == 1;
1695 var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
1696 var changeQueue = vim.inputState.changeQueue;
1697 if (match.type == 'none') {
1698 clearInputState(cm);
1699 return false;
1700 }
1701 else if (match.type == 'partial') {
1702 if (match.expectLiteralNext)
1703 vim.expectLiteralNext = true;
1704 if (lastInsertModeKeyTimer) {
1705 window.clearTimeout(lastInsertModeKeyTimer);
1706 }
1707 lastInsertModeKeyTimer = keysAreChars && window.setTimeout(function () { if (vim.insertMode && vim.inputState.keyBuffer.length) {
1708 clearInputState(cm);
1709 } }, getOption('insertModeEscKeysTimeout'));
1710 if (keysAreChars) {
1711 var selections = cm.listSelections();
1712 if (!changeQueue || changeQueue.removed.length != selections.length)
1713 changeQueue = vim.inputState.changeQueue = new ChangeQueue;
1714 changeQueue.inserted += key;
1715 for (var i = 0; i < selections.length; i++) {
1716 var from = cursorMin(selections[i].anchor, selections[i].head);
1717 var to = cursorMax(selections[i].anchor, selections[i].head);
1718 var text = cm.getRange(from, cm.state.overwrite ? offsetCursor(to, 0, 1) : to);
1719 changeQueue.removed[i] = (changeQueue.removed[i] || "") + text;
1720 }
1721 }
1722 return !keysAreChars;
1723 }
1724 vim.expectLiteralNext = false;
1725 if (lastInsertModeKeyTimer) {
1726 window.clearTimeout(lastInsertModeKeyTimer);
1727 }
1728 if (match.command && changeQueue) {
1729 var selections = cm.listSelections();
1730 for (var i = 0; i < selections.length; i++) {
1731 var here = selections[i].head;
1732 cm.replaceRange(changeQueue.removed[i] || "", offsetCursor(here, 0, -changeQueue.inserted.length), here, '+input');
1733 }
1734 vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop();
1735 }
1736 if (!match.command)
1737 clearInputState(cm);
1738 return match.command;
1739 }
1740 function handleKeyNonInsertMode() {
1741 if (handleMacroRecording() || handleEsc()) {
1742 return true;
1743 }
1744 vim.inputState.keyBuffer.push(key);
1745 var keys = vim.inputState.keyBuffer.join("");
1746 if (/^[1-9]\d*$/.test(keys)) {
1747 return true;
1748 }
1749 var keysMatcher = /^(\d*)(.*)$/.exec(keys);
1750 if (!keysMatcher) {
1751 clearInputState(cm);
1752 return false;
1753 }
1754 var context = vim.visualMode ? 'visual' :
1755 'normal';
1756 var mainKey = keysMatcher[2] || keysMatcher[1];
1757 if (vim.inputState.operatorShortcut && vim.inputState.operatorShortcut.slice(-1) == mainKey) {
1758 mainKey = vim.inputState.operatorShortcut;
1759 }
1760 var match = commandDispatcher.matchCommand(mainKey, defaultKeymap, vim.inputState, context);
1761 if (match.type == 'none') {
1762 clearInputState(cm);
1763 return false;
1764 }
1765 else if (match.type == 'partial') {
1766 if (match.expectLiteralNext)
1767 vim.expectLiteralNext = true;
1768 return true;
1769 }
1770 else if (match.type == 'clear') {
1771 clearInputState(cm);
1772 return true;
1773 }
1774 vim.expectLiteralNext = false;
1775 vim.inputState.keyBuffer.length = 0;
1776 keysMatcher = /^(\d*)(.*)$/.exec(keys);
1777 if (keysMatcher[1] && keysMatcher[1] != '0') {
1778 vim.inputState.pushRepeatDigit(keysMatcher[1]);
1779 }
1780 return match.command;
1781 }
1782 var command;
1783 if (vim.insertMode) {
1784 command = handleKeyInsertMode();
1785 }
1786 else {
1787 command = handleKeyNonInsertMode();
1788 }
1789 if (command === false) {
1790 return !vim.insertMode && key.length === 1 ? function () { return true; } : undefined;
1791 }
1792 else if (command === true) {
1793 return function () { return true; };
1794 }
1795 else {
1796 return function () {
1797 if ((command.operator || command.isEdit) && cm.getOption('readOnly'))
1798 return; // ace_patch
1799 return cm.operation(function () {
1800 cm.curOp.isVimOp = true;
1801 try {
1802 if (command.type == 'keyToKey') {
1803 doKeyToKey(cm, command.toKeys, command);
1804 }
1805 else {
1806 commandDispatcher.processCommand(cm, vim, command);
1807 }
1808 }
1809 catch (e) {
1810 cm.state.vim = undefined;
1811 maybeInitVimState(cm);
1812 if (!vimApi.suppressErrorLogging) {
1813 console['log'](e);
1814 }
1815 throw e;
1816 }
1817 return true;
1818 });
1819 };
1820 }
1821 },
1822 handleEx: function (cm, input) {
1823 exCommandDispatcher.processCommand(cm, input);
1824 },
1825 defineMotion: defineMotion,
1826 defineAction: defineAction,
1827 defineOperator: defineOperator,
1828 mapCommand: mapCommand,
1829 _mapCommand: _mapCommand,
1830 defineRegister: defineRegister,
1831 exitVisualMode: exitVisualMode,
1832 exitInsertMode: exitInsertMode
1833 };
1834 var keyToKeyStack = [];
1835 var noremap = false;
1836 var virtualPrompt;
1837 function sendKeyToPrompt(key) {
1838 if (key[0] == "<") {
1839 var lowerKey = key.toLowerCase().slice(1, -1);
1840 var parts = lowerKey.split('-');
1841 lowerKey = parts.pop() || '';
1842 if (lowerKey == 'lt')
1843 key = '<';
1844 else if (lowerKey == 'space')
1845 key = ' ';
1846 else if (lowerKey == 'cr')
1847 key = '\n';
1848 else if (vimToCmKeyMap[lowerKey]) {
1849 var value = virtualPrompt.value;
1850 var event = {
1851 key: vimToCmKeyMap[lowerKey],
1852 target: {
1853 value: value,
1854 selectionEnd: value.length,
1855 selectionStart: value.length
1856 }
1857 };
1858 if (virtualPrompt.onKeyDown) {
1859 virtualPrompt.onKeyDown(event, virtualPrompt.value, close);
1860 }
1861 if (virtualPrompt && virtualPrompt.onKeyUp) {
1862 virtualPrompt.onKeyUp(event, virtualPrompt.value, close);
1863 }
1864 return;
1865 }
1866 }
1867 if (key == '\n') {
1868 var prompt = virtualPrompt;
1869 virtualPrompt = null;
1870 prompt.onClose && prompt.onClose(prompt.value);
1871 }
1872 else {
1873 virtualPrompt.value = (virtualPrompt.value || '') + key;
1874 }
1875 function close(value) {
1876 if (typeof value == 'string') {
1877 virtualPrompt.value = value;
1878 }
1879 else {
1880 virtualPrompt = null;
1881 }
1882 }
1883 }
1884 function doKeyToKey(cm, keys, fromKey) {
1885 var noremapBefore = noremap;
1886 if (fromKey) {
1887 if (keyToKeyStack.indexOf(fromKey) != -1)
1888 return;
1889 keyToKeyStack.push(fromKey);
1890 noremap = fromKey.noremap != false;
1891 }
1892 try {
1893 var vim = maybeInitVimState(cm);
1894 var keyRe = /<(?:[CSMA]-)*\w+>|./gi;
1895 var match;
1896 while ((match = keyRe.exec(keys))) {
1897 var key = match[0];
1898 var wasInsert = vim.insertMode;
1899 if (virtualPrompt) {
1900 sendKeyToPrompt(key);
1901 continue;
1902 }
1903 var result = vimApi.handleKey(cm, key, 'mapping');
1904 if (!result && wasInsert && vim.insertMode) {
1905 if (key[0] == "<") {
1906 var lowerKey = key.toLowerCase().slice(1, -1);
1907 var parts = lowerKey.split('-');
1908 lowerKey = parts.pop() || '';
1909 if (lowerKey == 'lt')
1910 key = '<';
1911 else if (lowerKey == 'space')
1912 key = ' ';
1913 else if (lowerKey == 'cr')
1914 key = '\n';
1915 else if (vimToCmKeyMap.hasOwnProperty(lowerKey)) {
1916 key = vimToCmKeyMap[lowerKey];
1917 sendCmKey(cm, key);
1918 continue;
1919 }
1920 else {
1921 key = key[0];
1922 keyRe.lastIndex = match.index + 1;
1923 }
1924 }
1925 cm.replaceSelection(key);
1926 }
1927 }
1928 }
1929 finally {
1930 keyToKeyStack.pop();
1931 noremap = keyToKeyStack.length ? noremapBefore : false;
1932 if (!keyToKeyStack.length && virtualPrompt) {
1933 var promptOptions = virtualPrompt;
1934 virtualPrompt = null;
1935 showPrompt(cm, promptOptions);
1936 }
1937 }
1938 }
1939 var specialKey = {
1940 Return: 'CR', Backspace: 'BS', 'Delete': 'Del', Escape: 'Esc', Insert: 'Ins',
1941 ArrowLeft: 'Left', ArrowRight: 'Right', ArrowUp: 'Up', ArrowDown: 'Down',
1942 Enter: 'CR', ' ': 'Space'
1943 };
1944 var ignoredKeys = { Shift: 1, Alt: 1, Command: 1, Control: 1,
1945 CapsLock: 1, AltGraph: 1, Dead: 1, Unidentified: 1 };
1946 var vimToCmKeyMap = {};
1947 'Left|Right|Up|Down|End|Home'.split('|').concat(Object.keys(specialKey)).forEach(function (x) {
1948 vimToCmKeyMap[(specialKey[x] || '').toLowerCase()]
1949 = vimToCmKeyMap[x.toLowerCase()] = x;
1950 });
1951 function vimKeyFromEvent(e, vim) {
1952 var key = e.key;
1953 if (ignoredKeys[key])
1954 return;
1955 if (key.length > 1 && key[0] == "n") {
1956 key = key.replace("Numpad", "");
1957 }
1958 key = specialKey[key] || key;
1959 var name = '';
1960 if (e.ctrlKey) {
1961 name += 'C-';
1962 }
1963 if (e.altKey) {
1964 name += 'A-';
1965 }
1966 if (e.metaKey) {
1967 name += 'M-';
1968 }
1969 if (CodeMirror.isMac && e.altKey && !e.metaKey && !e.ctrlKey) {
1970 name = name.slice(2);
1971 }
1972 if ((name || key.length > 1) && e.shiftKey) {
1973 name += 'S-';
1974 }
1975 if (vim && !vim.expectLiteralNext && key.length == 1) {
1976 if (langmap.keymap && key in langmap.keymap) {
1977 if (langmap.remapCtrl != false || !name)
1978 key = langmap.keymap[key];
1979 }
1980 else if (key.charCodeAt(0) > 255) {
1981 var code = e.code && e.code.slice(-1) || "";
1982 if (!e.shiftKey)
1983 code = code.toLowerCase();
1984 if (code)
1985 key = code;
1986 }
1987 }
1988 name += key;
1989 if (name.length > 1) {
1990 name = '<' + name + '>';
1991 }
1992 return name;
1993 }
1994 ;
1995 function updateLangmap(langmapString, remapCtrl) {
1996 if (langmap.string !== langmapString) {
1997 langmap = parseLangmap(langmapString);
1998 }
1999 langmap.remapCtrl = remapCtrl;
2000 }
2001 function parseLangmap(langmapString) {
2002 var keymap = {};
2003 if (!langmapString)
2004 return { keymap: keymap, string: '' };
2005 function getEscaped(list) {
2006 return list.split(/\\?(.)/).filter(Boolean);
2007 }
2008 langmapString.split(/((?:[^\\,]|\\.)+),/).map(function (part) {
2009 if (!part)
2010 return;
2011 var semicolon = part.split(/((?:[^\\;]|\\.)+);/);
2012 if (semicolon.length == 3) {
2013 var from = getEscaped(semicolon[1]);
2014 var to = getEscaped(semicolon[2]);
2015 if (from.length !== to.length)
2016 return; // skip over malformed part
2017 for (var i = 0; i < from.length; ++i)
2018 keymap[from[i]] = to[i];
2019 }
2020 else if (semicolon.length == 1) {
2021 var pairs = getEscaped(part);
2022 if (pairs.length % 2 !== 0)
2023 return; // skip over malformed part
2024 for (var i = 0; i < pairs.length; i += 2)
2025 keymap[pairs[i]] = pairs[i + 1];
2026 }
2027 });
2028 return { keymap: keymap, string: langmapString };
2029 }
2030 defineOption('langmap', undefined, 'string', ['lmap'], function (name, cm) {
2031 if (name === undefined) {
2032 return langmap.string;
2033 }
2034 else {
2035 updateLangmap(name);
2036 }
2037 });
2038 function InputState() {
2039 this.prefixRepeat = [];
2040 this.motionRepeat = [];
2041 this.operator = null;
2042 this.operatorArgs = null;
2043 this.motion = null;
2044 this.motionArgs = null;
2045 this.keyBuffer = []; // For matching multi-key commands.
2046 this.registerName = null; // Defaults to the unnamed register.
2047 this.changeQueue = null; // For restoring text used by insert mode keybindings
2048 }
2049 InputState.prototype.pushRepeatDigit = function (n) {
2050 if (!this.operator) {
2051 this.prefixRepeat = this.prefixRepeat.concat(n);
2052 }
2053 else {
2054 this.motionRepeat = this.motionRepeat.concat(n);
2055 }
2056 };
2057 InputState.prototype.getRepeat = function () {
2058 var repeat = 0;
2059 if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
2060 repeat = 1;
2061 if (this.prefixRepeat.length > 0) {
2062 repeat *= parseInt(this.prefixRepeat.join(''), 10);
2063 }
2064 if (this.motionRepeat.length > 0) {
2065 repeat *= parseInt(this.motionRepeat.join(''), 10);
2066 }
2067 }
2068 return repeat;
2069 };
2070 function clearInputState(cm, reason) {
2071 cm.state.vim.inputState = new InputState();
2072 cm.state.vim.expectLiteralNext = false;
2073 CodeMirror.signal(cm, 'vim-command-done', reason);
2074 }
2075 function ChangeQueue() {
2076 this.removed = [];
2077 this.inserted = "";
2078 }
2079 function Register(text, linewise, blockwise) {
2080 this.clear();
2081 this.keyBuffer = [text || ''];
2082 this.insertModeChanges = [];
2083 this.searchQueries = [];
2084 this.linewise = !!linewise;
2085 this.blockwise = !!blockwise;
2086 }
2087 Register.prototype = {
2088 setText: function (text, linewise, blockwise) {
2089 this.keyBuffer = [text || ''];
2090 this.linewise = !!linewise;
2091 this.blockwise = !!blockwise;
2092 },
2093 pushText: function (text, linewise) {
2094 if (linewise) {
2095 if (!this.linewise) {
2096 this.keyBuffer.push('\n');
2097 }
2098 this.linewise = true;
2099 }
2100 this.keyBuffer.push(text);
2101 },
2102 pushInsertModeChanges: function (changes) {
2103 this.insertModeChanges.push(createInsertModeChanges(changes));
2104 },
2105 pushSearchQuery: function (query) {
2106 this.searchQueries.push(query);
2107 },
2108 clear: function () {
2109 this.keyBuffer = [];
2110 this.insertModeChanges = [];
2111 this.searchQueries = [];
2112 this.linewise = false;
2113 },
2114 toString: function () {
2115 return this.keyBuffer.join('');
2116 }
2117 };
2118 function defineRegister(name, register) {
2119 var registers = vimGlobalState.registerController.registers;
2120 if (!name || name.length != 1) {
2121 throw Error('Register name must be 1 character');
2122 }
2123 registers[name] = register;
2124 validRegisters.push(name);
2125 }
2126 function RegisterController(registers) {
2127 this.registers = registers;
2128 this.unnamedRegister = registers['"'] = new Register();
2129 registers['.'] = new Register();
2130 registers[':'] = new Register();
2131 registers['/'] = new Register();
2132 registers['+'] = new Register();
2133 }
2134 RegisterController.prototype = {
2135 pushText: function (registerName, operator, text, linewise, blockwise) {
2136 if (registerName === '_')
2137 return;
2138 if (linewise && text.charAt(text.length - 1) !== '\n') {
2139 text += '\n';
2140 }
2141 var register = this.isValidRegister(registerName) ?
2142 this.getRegister(registerName) : null;
2143 if (!register) {
2144 switch (operator) {
2145 case 'yank':
2146 this.registers['0'] = new Register(text, linewise, blockwise);
2147 break;
2148 case 'delete':
2149 case 'change':
2150 if (text.indexOf('\n') == -1) {
2151 this.registers['-'] = new Register(text, linewise);
2152 }
2153 else {
2154 this.shiftNumericRegisters_();
2155 this.registers['1'] = new Register(text, linewise);
2156 }
2157 break;
2158 }
2159 this.unnamedRegister.setText(text, linewise, blockwise);
2160 return;
2161 }
2162 var append = isUpperCase(registerName);
2163 if (append) {
2164 register.pushText(text, linewise);
2165 }
2166 else {
2167 register.setText(text, linewise, blockwise);
2168 }
2169 if (registerName === '+' && typeof navigator !== 'undefined' &&
2170 typeof navigator.clipboard !== 'undefined' &&
2171 typeof navigator.clipboard.readText === 'function') {
2172 navigator.clipboard.writeText(text);
2173 }
2174 this.unnamedRegister.setText(register.toString(), linewise);
2175 },
2176 getRegister: function (name) {
2177 if (!this.isValidRegister(name)) {
2178 return this.unnamedRegister;
2179 }
2180 name = name.toLowerCase();
2181 if (!this.registers[name]) {
2182 this.registers[name] = new Register();
2183 }
2184 return this.registers[name];
2185 },
2186 isValidRegister: function (name) {
2187 return name && (inArray(name, validRegisters) || latinCharRegex.test(name));
2188 },
2189 shiftNumericRegisters_: function () {
2190 for (var i = 9; i >= 2; i--) {
2191 this.registers[i] = this.getRegister('' + (i - 1));
2192 }
2193 }
2194 };
2195 function HistoryController() {
2196 this.historyBuffer = [];
2197 this.iterator = 0;
2198 this.initialPrefix = null;
2199 }
2200 HistoryController.prototype = {
2201 nextMatch: function (input, up) {
2202 var historyBuffer = this.historyBuffer;
2203 var dir = up ? -1 : 1;
2204 if (this.initialPrefix === null)
2205 this.initialPrefix = input;
2206 for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i += dir) {
2207 var element = historyBuffer[i];
2208 for (var j = 0; j <= element.length; j++) {
2209 if (this.initialPrefix == element.substring(0, j)) {
2210 this.iterator = i;
2211 return element;
2212 }
2213 }
2214 }
2215 if (i >= historyBuffer.length) {
2216 this.iterator = historyBuffer.length;
2217 return this.initialPrefix;
2218 }
2219 if (i < 0)
2220 return input;
2221 },
2222 pushInput: function (input) {
2223 var index = this.historyBuffer.indexOf(input);
2224 if (index > -1)
2225 this.historyBuffer.splice(index, 1);
2226 if (input.length)
2227 this.historyBuffer.push(input);
2228 },
2229 reset: function () {
2230 this.initialPrefix = null;
2231 this.iterator = this.historyBuffer.length;
2232 }
2233 };
2234 var commandDispatcher = {
2235 matchCommand: function (keys, keyMap, inputState, context) {
2236 var matches = commandMatches(keys, keyMap, context, inputState);
2237 if (!matches.full && !matches.partial) {
2238 return { type: 'none' };
2239 }
2240 else if (!matches.full && matches.partial) {
2241 return {
2242 type: 'partial',
2243 expectLiteralNext: matches.partial.length == 1 && matches.partial[0].keys.slice(-11) == '<character>' // langmap literal logic
2244 };
2245 }
2246 var bestMatch;
2247 for (var i = 0; i < matches.full.length; i++) {
2248 var match = matches.full[i];
2249 if (!bestMatch) {
2250 bestMatch = match;
2251 }
2252 }
2253 if (bestMatch.keys.slice(-11) == '<character>' || bestMatch.keys.slice(-10) == '<register>') {
2254 var character = lastChar(keys);
2255 if (!character || character.length > 1)
2256 return { type: 'clear' };
2257 inputState.selectedCharacter = character;
2258 }
2259 return { type: 'full', command: bestMatch };
2260 },
2261 processCommand: function (cm, vim, command) {
2262 vim.inputState.repeatOverride = command.repeatOverride;
2263 switch (command.type) {
2264 case 'motion':
2265 this.processMotion(cm, vim, command);
2266 break;
2267 case 'operator':
2268 this.processOperator(cm, vim, command);
2269 break;
2270 case 'operatorMotion':
2271 this.processOperatorMotion(cm, vim, command);
2272 break;
2273 case 'action':
2274 this.processAction(cm, vim, command);
2275 break;
2276 case 'search':
2277 this.processSearch(cm, vim, command);
2278 break;
2279 case 'ex':
2280 case 'keyToEx':
2281 this.processEx(cm, vim, command);
2282 break;
2283 default:
2284 break;
2285 }
2286 },
2287 processMotion: function (cm, vim, command) {
2288 vim.inputState.motion = command.motion;
2289 vim.inputState.motionArgs = copyArgs(command.motionArgs);
2290 this.evalInput(cm, vim);
2291 },
2292 processOperator: function (cm, vim, command) {
2293 var inputState = vim.inputState;
2294 if (inputState.operator) {
2295 if (inputState.operator == command.operator) {
2296 inputState.motion = 'expandToLine';
2297 inputState.motionArgs = { linewise: true };
2298 this.evalInput(cm, vim);
2299 return;
2300 }
2301 else {
2302 clearInputState(cm);
2303 }
2304 }
2305 inputState.operator = command.operator;
2306 inputState.operatorArgs = copyArgs(command.operatorArgs);
2307 if (command.keys.length > 1) {
2308 inputState.operatorShortcut = command.keys;
2309 }
2310 if (command.exitVisualBlock) {
2311 vim.visualBlock = false;
2312 updateCmSelection(cm);
2313 }
2314 if (vim.visualMode) {
2315 this.evalInput(cm, vim);
2316 }
2317 },
2318 processOperatorMotion: function (cm, vim, command) {
2319 var visualMode = vim.visualMode;
2320 var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
2321 if (operatorMotionArgs) {
2322 if (visualMode && operatorMotionArgs.visualLine) {
2323 vim.visualLine = true;
2324 }
2325 }
2326 this.processOperator(cm, vim, command);
2327 if (!visualMode) {
2328 this.processMotion(cm, vim, command);
2329 }
2330 },
2331 processAction: function (cm, vim, command) {
2332 var inputState = vim.inputState;
2333 var repeat = inputState.getRepeat();
2334 var repeatIsExplicit = !!repeat;
2335 var actionArgs = copyArgs(command.actionArgs) || {};
2336 if (inputState.selectedCharacter) {
2337 actionArgs.selectedCharacter = inputState.selectedCharacter;
2338 }
2339 if (command.operator) {
2340 this.processOperator(cm, vim, command);
2341 }
2342 if (command.motion) {
2343 this.processMotion(cm, vim, command);
2344 }
2345 if (command.motion || command.operator) {
2346 this.evalInput(cm, vim);
2347 }
2348 actionArgs.repeat = repeat || 1;
2349 actionArgs.repeatIsExplicit = repeatIsExplicit;
2350 actionArgs.registerName = inputState.registerName;
2351 clearInputState(cm);
2352 vim.lastMotion = null;
2353 if (command.isEdit) {
2354 this.recordLastEdit(vim, inputState, command);
2355 }
2356 actions[command.action](cm, actionArgs, vim);
2357 },
2358 processSearch: function (cm, vim, command) {
2359 if (!cm.getSearchCursor) {
2360 return;
2361 }
2362 var forward = command.searchArgs.forward;
2363 var wholeWordOnly = command.searchArgs.wholeWordOnly;
2364 getSearchState(cm).setReversed(!forward);
2365 var promptPrefix = (forward) ? '/' : '?';
2366 var originalQuery = getSearchState(cm).getQuery();
2367 var originalScrollPos = cm.getScrollInfo();
2368 function handleQuery(query, ignoreCase, smartCase) {
2369 vimGlobalState.searchHistoryController.pushInput(query);
2370 vimGlobalState.searchHistoryController.reset();
2371 try {
2372 updateSearchQuery(cm, query, ignoreCase, smartCase);
2373 }
2374 catch (e) {
2375 showConfirm(cm, 'Invalid regex: ' + query);
2376 clearInputState(cm);
2377 return;
2378 }
2379 commandDispatcher.processMotion(cm, vim, {
2380 type: 'motion',
2381 motion: 'findNext',
2382 motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
2383 });
2384 }
2385 function onPromptClose(query) {
2386 handleQuery(query, true /** ignoreCase */, true /** smartCase */);
2387 var macroModeState = vimGlobalState.macroModeState;
2388 if (macroModeState.isRecording) {
2389 logSearchQuery(macroModeState, query);
2390 }
2391 }
2392 function onPromptKeyUp(e, query, close) {
2393 var keyName = vimKeyFromEvent(e), up, offset;
2394 if (keyName == '<Up>' || keyName == '<Down>') {
2395 up = keyName == '<Up>' ? true : false;
2396 offset = e.target ? e.target.selectionEnd : 0;
2397 query = vimGlobalState.searchHistoryController.nextMatch(query, up) || '';
2398 close(query);
2399 if (offset && e.target)
2400 e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
2401 }
2402 else if (keyName && keyName != '<Left>' && keyName != '<Right>') {
2403 vimGlobalState.searchHistoryController.reset();
2404 }
2405 var parsedQuery;
2406 try {
2407 parsedQuery = updateSearchQuery(cm, query, true /** ignoreCase */, true /** smartCase */);
2408 }
2409 catch (e) {
2410 }
2411 if (parsedQuery) {
2412 cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
2413 }
2414 else {
2415 clearSearchHighlight(cm);
2416 cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
2417 }
2418 }
2419 function onPromptKeyDown(e, query, close) {
2420 var keyName = vimKeyFromEvent(e);
2421 if (keyName == '<Esc>' || keyName == '<C-c>' || keyName == '<C-[>' ||
2422 (keyName == '<BS>' && query == '')) {
2423 vimGlobalState.searchHistoryController.pushInput(query);
2424 vimGlobalState.searchHistoryController.reset();
2425 updateSearchQuery(cm, originalQuery);
2426 clearSearchHighlight(cm);
2427 cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
2428 CodeMirror.e_stop(e);
2429 clearInputState(cm);
2430 close();
2431 cm.focus();
2432 }
2433 else if (keyName == '<Up>' || keyName == '<Down>') {
2434 CodeMirror.e_stop(e);
2435 }
2436 else if (keyName == '<C-u>') {
2437 CodeMirror.e_stop(e);
2438 close('');
2439 }
2440 }
2441 switch (command.searchArgs.querySrc) {
2442 case 'prompt':
2443 var macroModeState = vimGlobalState.macroModeState;
2444 if (macroModeState.isPlaying) {
2445 var query = macroModeState.replaySearchQueries.shift();
2446 handleQuery(query, true /** ignoreCase */, false /** smartCase */);
2447 }
2448 else {
2449 showPrompt(cm, {
2450 onClose: onPromptClose,
2451 prefix: promptPrefix,
2452 desc: '(JavaScript regexp)',
2453 onKeyUp: onPromptKeyUp,
2454 onKeyDown: onPromptKeyDown
2455 });
2456 }
2457 break;
2458 case 'wordUnderCursor':
2459 var word = expandWordUnderCursor(cm, { noSymbol: true });
2460 var isKeyword = true;
2461 if (!word) {
2462 word = expandWordUnderCursor(cm, { noSymbol: false });
2463 isKeyword = false;
2464 }
2465 if (!word) {
2466 showConfirm(cm, 'No word under cursor');
2467 clearInputState(cm);
2468 return;
2469 }
2470 var query = cm.getLine(word.start.line).substring(word.start.ch, word.end.ch);
2471 if (isKeyword && wholeWordOnly) {
2472 query = '\\b' + query + '\\b';
2473 }
2474 else {
2475 query = escapeRegex(query);
2476 }
2477 vimGlobalState.jumpList.cachedCursor = cm.getCursor();
2478 cm.setCursor(word.start);
2479 handleQuery(query, true /** ignoreCase */, false /** smartCase */);
2480 break;
2481 }
2482 },
2483 processEx: function (cm, vim, command) {
2484 function onPromptClose(input) {
2485 vimGlobalState.exCommandHistoryController.pushInput(input);
2486 vimGlobalState.exCommandHistoryController.reset();
2487 exCommandDispatcher.processCommand(cm, input);
2488 if (cm.state.vim)
2489 clearInputState(cm);
2490 }
2491 function onPromptKeyDown(e, input, close) {
2492 var keyName = vimKeyFromEvent(e), up, offset;
2493 if (keyName == '<Esc>' || keyName == '<C-c>' || keyName == '<C-[>' ||
2494 (keyName == '<BS>' && input == '')) {
2495 vimGlobalState.exCommandHistoryController.pushInput(input);
2496 vimGlobalState.exCommandHistoryController.reset();
2497 CodeMirror.e_stop(e);
2498 clearInputState(cm);
2499 close();
2500 cm.focus();
2501 }
2502 if (keyName == '<Up>' || keyName == '<Down>') {
2503 CodeMirror.e_stop(e);
2504 up = keyName == '<Up>' ? true : false;
2505 offset = e.target ? e.target.selectionEnd : 0;
2506 input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || '';
2507 close(input);
2508 if (offset && e.target)
2509 e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
2510 }
2511 else if (keyName == '<C-u>') {
2512 CodeMirror.e_stop(e);
2513 close('');
2514 }
2515 else if (keyName && keyName != '<Left>' && keyName != '<Right>') {
2516 vimGlobalState.exCommandHistoryController.reset();
2517 }
2518 }
2519 if (command.type == 'keyToEx') {
2520 exCommandDispatcher.processCommand(cm, command.exArgs.input);
2521 }
2522 else {
2523 if (vim.visualMode) {
2524 showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
2525 onKeyDown: onPromptKeyDown, selectValueOnOpen: false });
2526 }
2527 else {
2528 showPrompt(cm, { onClose: onPromptClose, prefix: ':',
2529 onKeyDown: onPromptKeyDown });
2530 }
2531 }
2532 },
2533 evalInput: function (cm, vim) {
2534 var inputState = vim.inputState;
2535 var motion = inputState.motion;
2536 var motionArgs = inputState.motionArgs || {};
2537 var operator = inputState.operator;
2538 var operatorArgs = inputState.operatorArgs || {};
2539 var registerName = inputState.registerName;
2540 var sel = vim.sel;
2541 var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head) : cm.getCursor('head'));
2542 var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor'));
2543 var oldHead = copyCursor(origHead);
2544 var oldAnchor = copyCursor(origAnchor);
2545 var newHead, newAnchor;
2546 var repeat;
2547 if (operator) {
2548 this.recordLastEdit(vim, inputState);
2549 }
2550 if (inputState.repeatOverride !== undefined) {
2551 repeat = inputState.repeatOverride;
2552 }
2553 else {
2554 repeat = inputState.getRepeat();
2555 }
2556 if (repeat > 0 && motionArgs.explicitRepeat) {
2557 motionArgs.repeatIsExplicit = true;
2558 }
2559 else if (motionArgs.noRepeat ||
2560 (!motionArgs.explicitRepeat && repeat === 0)) {
2561 repeat = 1;
2562 motionArgs.repeatIsExplicit = false;
2563 }
2564 if (inputState.selectedCharacter) {
2565 motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
2566 inputState.selectedCharacter;
2567 }
2568 motionArgs.repeat = repeat;
2569 clearInputState(cm);
2570 if (motion) {
2571 var motionResult = motions[motion](cm, origHead, motionArgs, vim, inputState);
2572 vim.lastMotion = motions[motion];
2573 if (!motionResult) {
2574 return;
2575 }
2576 if (motionArgs.toJumplist) {
2577 if (!operator && cm.ace.curOp != null)
2578 cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch
2579 var jumpList = vimGlobalState.jumpList;
2580 var cachedCursor = jumpList.cachedCursor;
2581 if (cachedCursor) {
2582 recordJumpPosition(cm, cachedCursor, motionResult);
2583 delete jumpList.cachedCursor;
2584 }
2585 else {
2586 recordJumpPosition(cm, origHead, motionResult);
2587 }
2588 }
2589 if (motionResult instanceof Array) {
2590 newAnchor = motionResult[0];
2591 newHead = motionResult[1];
2592 }
2593 else {
2594 newHead = motionResult;
2595 }
2596 if (!newHead) {
2597 newHead = copyCursor(origHead);
2598 }
2599 if (vim.visualMode) {
2600 if (!(vim.visualBlock && newHead.ch === Infinity)) {
2601 newHead = clipCursorToContent(cm, newHead, oldHead);
2602 }
2603 if (newAnchor) {
2604 newAnchor = clipCursorToContent(cm, newAnchor);
2605 }
2606 newAnchor = newAnchor || oldAnchor;
2607 sel.anchor = newAnchor;
2608 sel.head = newHead;
2609 updateCmSelection(cm);
2610 updateMark(cm, vim, '<', cursorIsBefore(newAnchor, newHead) ? newAnchor
2611 : newHead);
2612 updateMark(cm, vim, '>', cursorIsBefore(newAnchor, newHead) ? newHead
2613 : newAnchor);
2614 }
2615 else if (!operator) {
2616 if (cm.ace.curOp)
2617 cm.ace.curOp.vimDialogScroll = "center-animate"; // ace_patch
2618 newHead = clipCursorToContent(cm, newHead, oldHead);
2619 cm.setCursor(newHead.line, newHead.ch);
2620 }
2621 }
2622 if (operator) {
2623 if (operatorArgs.lastSel) {
2624 newAnchor = oldAnchor;
2625 var lastSel = operatorArgs.lastSel;
2626 var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line);
2627 var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch);
2628 if (lastSel.visualLine) {
2629 newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
2630 }
2631 else if (lastSel.visualBlock) {
2632 newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);
2633 }
2634 else if (lastSel.head.line == lastSel.anchor.line) {
2635 newHead = new Pos(oldAnchor.line, oldAnchor.ch + chOffset);
2636 }
2637 else {
2638 newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
2639 }
2640 vim.visualMode = true;
2641 vim.visualLine = lastSel.visualLine;
2642 vim.visualBlock = lastSel.visualBlock;
2643 sel = vim.sel = {
2644 anchor: newAnchor,
2645 head: newHead
2646 };
2647 updateCmSelection(cm);
2648 }
2649 else if (vim.visualMode) {
2650 operatorArgs.lastSel = {
2651 anchor: copyCursor(sel.anchor),
2652 head: copyCursor(sel.head),
2653 visualBlock: vim.visualBlock,
2654 visualLine: vim.visualLine
2655 };
2656 }
2657 var curStart, curEnd, linewise, mode;
2658 var cmSel;
2659 if (vim.visualMode) {
2660 curStart = cursorMin(sel.head, sel.anchor);
2661 curEnd = cursorMax(sel.head, sel.anchor);
2662 linewise = vim.visualLine || operatorArgs.linewise;
2663 mode = vim.visualBlock ? 'block' :
2664 linewise ? 'line' :
2665 'char';
2666 var newPositions = updateSelectionForSurrogateCharacters(cm, curStart, curEnd);
2667 cmSel = makeCmSelection(cm, {
2668 anchor: newPositions.start,
2669 head: newPositions.end
2670 }, mode);
2671 if (linewise) {
2672 var ranges = cmSel.ranges;
2673 if (mode == 'block') {
2674 for (var i = 0; i < ranges.length; i++) {
2675 ranges[i].head.ch = lineLength(cm, ranges[i].head.line);
2676 }
2677 }
2678 else if (mode == 'line') {
2679 ranges[0].head = new Pos(ranges[0].head.line + 1, 0);
2680 }
2681 }
2682 }
2683 else {
2684 curStart = copyCursor(newAnchor || oldAnchor);
2685 curEnd = copyCursor(newHead || oldHead);
2686 if (cursorIsBefore(curEnd, curStart)) {
2687 var tmp = curStart;
2688 curStart = curEnd;
2689 curEnd = tmp;
2690 }
2691 linewise = motionArgs.linewise || operatorArgs.linewise;
2692 if (linewise) {
2693 expandSelectionToLine(cm, curStart, curEnd);
2694 }
2695 else if (motionArgs.forward) {
2696 clipToLine(cm, curStart, curEnd);
2697 }
2698 mode = 'char';
2699 var exclusive = !motionArgs.inclusive || linewise;
2700 var newPositions = updateSelectionForSurrogateCharacters(cm, curStart, curEnd);
2701 cmSel = makeCmSelection(cm, {
2702 anchor: newPositions.start,
2703 head: newPositions.end
2704 }, mode, exclusive);
2705 }
2706 cm.setSelections(cmSel.ranges, cmSel.primary);
2707 vim.lastMotion = null;
2708 operatorArgs.repeat = repeat; // For indent in visual mode.
2709 operatorArgs.registerName = registerName;
2710 operatorArgs.linewise = linewise;
2711 var operatorMoveTo = operators[operator](cm, operatorArgs, cmSel.ranges, oldAnchor, newHead);
2712 if (vim.visualMode) {
2713 exitVisualMode(cm, operatorMoveTo != null);
2714 }
2715 if (operatorMoveTo) {
2716 cm.setCursor(operatorMoveTo);
2717 }
2718 }
2719 },
2720 recordLastEdit: function (vim, inputState, actionCommand) {
2721 var macroModeState = vimGlobalState.macroModeState;
2722 if (macroModeState.isPlaying) {
2723 return;
2724 }
2725 vim.lastEditInputState = inputState;
2726 vim.lastEditActionCommand = actionCommand;
2727 macroModeState.lastInsertModeChanges.changes = [];
2728 macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
2729 macroModeState.lastInsertModeChanges.visualBlock = vim.visualBlock ? vim.sel.head.line - vim.sel.anchor.line : 0;
2730 }
2731 };
2732 var motions = {
2733 moveToTopLine: function (cm, _head, motionArgs) {
2734 var line = getUserVisibleLines(cm).top + motionArgs.repeat - 1;
2735 return new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
2736 },
2737 moveToMiddleLine: function (cm) {
2738 var range = getUserVisibleLines(cm);
2739 var line = Math.floor((range.top + range.bottom) * 0.5);
2740 return new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
2741 },
2742 moveToBottomLine: function (cm, _head, motionArgs) {
2743 var line = getUserVisibleLines(cm).bottom - motionArgs.repeat + 1;
2744 return new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
2745 },
2746 expandToLine: function (_cm, head, motionArgs) {
2747 var cur = head;
2748 return new Pos(cur.line + motionArgs.repeat - 1, Infinity);
2749 },
2750 findNext: function (cm, _head, motionArgs) {
2751 var state = getSearchState(cm);
2752 var query = state.getQuery();
2753 if (!query) {
2754 return;
2755 }
2756 var prev = !motionArgs.forward;
2757 prev = (state.isReversed()) ? !prev : prev;
2758 highlightSearchMatches(cm, query);
2759 return findNext(cm, prev /** prev */, query, motionArgs.repeat);
2760 },
2761 findAndSelectNextInclusive: function (cm, _head, motionArgs, vim, prevInputState) {
2762 var state = getSearchState(cm);
2763 var query = state.getQuery();
2764 if (!query) {
2765 return;
2766 }
2767 var prev = !motionArgs.forward;
2768 prev = (state.isReversed()) ? !prev : prev;
2769 var next = findNextFromAndToInclusive(cm, prev, query, motionArgs.repeat, vim);
2770 if (!next) {
2771 return;
2772 }
2773 if (prevInputState.operator) {
2774 return next;
2775 }
2776 var from = next[0];
2777 var to = new Pos(next[1].line, next[1].ch - 1);
2778 if (vim.visualMode) {
2779 if (vim.visualLine || vim.visualBlock) {
2780 vim.visualLine = false;
2781 vim.visualBlock = false;
2782 CodeMirror.signal(cm, "vim-mode-change", { mode: "visual", subMode: "" });
2783 }
2784 var anchor = vim.sel.anchor;
2785 if (anchor) {
2786 if (state.isReversed()) {
2787 if (motionArgs.forward) {
2788 return [anchor, from];
2789 }
2790 return [anchor, to];
2791 }
2792 else {
2793 if (motionArgs.forward) {
2794 return [anchor, to];
2795 }
2796 return [anchor, from];
2797 }
2798 }
2799 }
2800 else {
2801 vim.visualMode = true;
2802 vim.visualLine = false;
2803 vim.visualBlock = false;
2804 CodeMirror.signal(cm, "vim-mode-change", { mode: "visual", subMode: "" });
2805 }
2806 return prev ? [to, from] : [from, to];
2807 },
2808 goToMark: function (cm, _head, motionArgs, vim) {
2809 var pos = getMarkPos(cm, vim, motionArgs.selectedCharacter);
2810 if (pos) {
2811 return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos;
2812 }
2813 return null;
2814 },
2815 moveToOtherHighlightedEnd: function (cm, _head, motionArgs, vim) {
2816 if (vim.visualBlock && motionArgs.sameLine) {
2817 var sel = vim.sel;
2818 return [
2819 clipCursorToContent(cm, new Pos(sel.anchor.line, sel.head.ch)),
2820 clipCursorToContent(cm, new Pos(sel.head.line, sel.anchor.ch))
2821 ];
2822 }
2823 else {
2824 return ([vim.sel.head, vim.sel.anchor]);
2825 }
2826 },
2827 jumpToMark: function (cm, head, motionArgs, vim) {
2828 var best = head;
2829 for (var i = 0; i < motionArgs.repeat; i++) {
2830 var cursor = best;
2831 for (var key in vim.marks) {
2832 if (!isLowerCase(key)) {
2833 continue;
2834 }
2835 var mark = vim.marks[key].find();
2836 var isWrongDirection = (motionArgs.forward) ?
2837 cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
2838 if (isWrongDirection) {
2839 continue;
2840 }
2841 if (motionArgs.linewise && (mark.line == cursor.line)) {
2842 continue;
2843 }
2844 var equal = cursorEqual(cursor, best);
2845 var between = (motionArgs.forward) ?
2846 cursorIsBetween(cursor, mark, best) :
2847 cursorIsBetween(best, mark, cursor);
2848 if (equal || between) {
2849 best = mark;
2850 }
2851 }
2852 }
2853 if (motionArgs.linewise) {
2854 best = new Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));
2855 }
2856 return best;
2857 },
2858 moveByCharacters: function (_cm, head, motionArgs) {
2859 var cur = head;
2860 var repeat = motionArgs.repeat;
2861 var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
2862 return new Pos(cur.line, ch);
2863 },
2864 moveByLines: function (cm, head, motionArgs, vim) {
2865 var cur = head;
2866 var endCh = cur.ch;
2867 switch (vim.lastMotion) {
2868 case this.moveByLines:
2869 case this.moveByDisplayLines:
2870 case this.moveByScroll:
2871 case this.moveToColumn:
2872 case this.moveToEol:
2873 endCh = vim.lastHPos;
2874 break;
2875 default:
2876 vim.lastHPos = endCh;
2877 }
2878 var repeat = motionArgs.repeat + (motionArgs.repeatOffset || 0);
2879 var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
2880 var first = cm.firstLine();
2881 var last = cm.lastLine();
2882 if (line < first && cur.line == first) {
2883 return this.moveToStartOfLine(cm, head, motionArgs, vim);
2884 }
2885 else if (line > last && cur.line == last) {
2886 return moveToEol(cm, head, motionArgs, vim, true);
2887 }
2888 var fold = cm.ace.session.getFoldLine(line);
2889 if (fold) {
2890 if (motionArgs.forward) {
2891 if (line > fold.start.row)
2892 line = fold.end.row + 1;
2893 }
2894 else {
2895 line = fold.start.row;
2896 }
2897 }
2898 if (motionArgs.toFirstChar) {
2899 endCh = findFirstNonWhiteSpaceCharacter(cm.getLine(line));
2900 vim.lastHPos = endCh;
2901 }
2902 vim.lastHSPos = cm.charCoords(new Pos(line, endCh), 'div').left;
2903 return new Pos(line, endCh);
2904 },
2905 moveByDisplayLines: function (cm, head, motionArgs, vim) {
2906 var cur = head;
2907 switch (vim.lastMotion) {
2908 case this.moveByDisplayLines:
2909 case this.moveByScroll:
2910 case this.moveByLines:
2911 case this.moveToColumn:
2912 case this.moveToEol:
2913 break;
2914 default:
2915 vim.lastHSPos = cm.charCoords(cur, 'div').left;
2916 }
2917 var repeat = motionArgs.repeat;
2918 var res = cm.findPosV(cur, (motionArgs.forward ? repeat : -repeat), 'line', vim.lastHSPos);
2919 if (res.hitSide) {
2920 if (motionArgs.forward) {
2921 var lastCharCoords = cm.charCoords(res, 'div');
2922 var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
2923 var res = cm.coordsChar(goalCoords, 'div');
2924 }
2925 else {
2926 var resCoords = cm.charCoords(new Pos(cm.firstLine(), 0), 'div');
2927 resCoords.left = vim.lastHSPos;
2928 res = cm.coordsChar(resCoords, 'div');
2929 }
2930 }
2931 vim.lastHPos = res.ch;
2932 return res;
2933 },
2934 moveByPage: function (cm, head, motionArgs) {
2935 var curStart = head;
2936 var repeat = motionArgs.repeat;
2937 return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
2938 },
2939 moveByParagraph: function (cm, head, motionArgs) {
2940 var dir = motionArgs.forward ? 1 : -1;
2941 return findParagraph(cm, head, motionArgs.repeat, dir);
2942 },
2943 moveBySentence: function (cm, head, motionArgs) {
2944 var dir = motionArgs.forward ? 1 : -1;
2945 return findSentence(cm, head, motionArgs.repeat, dir);
2946 },
2947 moveByScroll: function (cm, head, motionArgs, vim) {
2948 var scrollbox = cm.getScrollInfo();
2949 var curEnd = null;
2950 var repeat = motionArgs.repeat;
2951 if (!repeat) {
2952 repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
2953 }
2954 var orig = cm.charCoords(head, 'local');
2955 motionArgs.repeat = repeat;
2956 curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);
2957 if (!curEnd) {
2958 return null;
2959 }
2960 var dest = cm.charCoords(curEnd, 'local');
2961 cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
2962 return curEnd;
2963 },
2964 moveByWords: function (cm, head, motionArgs) {
2965 return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward, !!motionArgs.wordEnd, !!motionArgs.bigWord);
2966 },
2967 moveTillCharacter: function (cm, head, motionArgs) {
2968 var repeat = motionArgs.repeat;
2969 var curEnd = moveToCharacter(cm, repeat, motionArgs.forward, motionArgs.selectedCharacter, head);
2970 var increment = motionArgs.forward ? -1 : 1;
2971 recordLastCharacterSearch(increment, motionArgs);
2972 if (!curEnd)
2973 return null;
2974 curEnd.ch += increment;
2975 return curEnd;
2976 },
2977 moveToCharacter: function (cm, head, motionArgs) {
2978 var repeat = motionArgs.repeat;
2979 recordLastCharacterSearch(0, motionArgs);
2980 return moveToCharacter(cm, repeat, motionArgs.forward, motionArgs.selectedCharacter, head) || head;
2981 },
2982 moveToSymbol: function (cm, head, motionArgs) {
2983 var repeat = motionArgs.repeat;
2984 return findSymbol(cm, repeat, motionArgs.forward, motionArgs.selectedCharacter) || head;
2985 },
2986 moveToColumn: function (cm, head, motionArgs, vim) {
2987 var repeat = motionArgs.repeat;
2988 vim.lastHPos = repeat - 1;
2989 vim.lastHSPos = cm.charCoords(head, 'div').left;
2990 return moveToColumn(cm, repeat);
2991 },
2992 moveToEol: function (cm, head, motionArgs, vim) {
2993 return moveToEol(cm, head, motionArgs, vim, false);
2994 },
2995 moveToFirstNonWhiteSpaceCharacter: function (cm, head) {
2996 var cursor = head;
2997 return new Pos(cursor.line, findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
2998 },
2999 moveToMatchedSymbol: function (cm, head) {
3000 var cursor = head;
3001 var line = cursor.line;
3002 var ch = cursor.ch;
3003 var lineText = cm.getLine(line);
3004 var symbol;
3005 for (; ch < lineText.length; ch++) {
3006 symbol = lineText.charAt(ch);
3007 if (symbol && isMatchableSymbol(symbol)) {
3008 var style = cm.getTokenTypeAt(new Pos(line, ch + 1));
3009 if (style !== "string" && style !== "comment") {
3010 break;
3011 }
3012 }
3013 }
3014 if (ch < lineText.length) {
3015 var re = /[<>]/.test(lineText[ch]) ? /[(){}[\]<>]/ : /[(){}[\]]/; //ace_patch?
3016 var matched = cm.findMatchingBracket(new Pos(line, ch + 1), { bracketRegex: re });
3017 return matched.to;
3018 }
3019 else {
3020 return cursor;
3021 }
3022 },
3023 moveToStartOfLine: function (_cm, head) {
3024 return new Pos(head.line, 0);
3025 },
3026 moveToLineOrEdgeOfDocument: function (cm, _head, motionArgs) {
3027 var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
3028 if (motionArgs.repeatIsExplicit) {
3029 lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
3030 }
3031 return new Pos(lineNum, findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
3032 },
3033 moveToStartOfDisplayLine: function (cm) {
3034 cm.execCommand("goLineLeft");
3035 return cm.getCursor();
3036 },
3037 moveToEndOfDisplayLine: function (cm) {
3038 cm.execCommand("goLineRight");
3039 var head = cm.getCursor();
3040 if (head.sticky == "before")
3041 head.ch--;
3042 return head;
3043 },
3044 textObjectManipulation: function (cm, head, motionArgs, vim) {
3045 var mirroredPairs = { '(': ')', ')': '(',
3046 '{': '}', '}': '{',
3047 '[': ']', ']': '[',
3048 '<': '>', '>': '<' };
3049 var selfPaired = { '\'': true, '"': true, '`': true };
3050 var character = motionArgs.selectedCharacter;
3051 if (character == 'b') {
3052 character = '(';
3053 }
3054 else if (character == 'B') {
3055 character = '{';
3056 }
3057 var inclusive = !motionArgs.textObjectInner;
3058 var tmp, move;
3059 if (mirroredPairs[character]) {
3060 move = true;
3061 tmp = selectCompanionObject(cm, head, character, inclusive);
3062 if (!tmp) {
3063 var sc = cm.getSearchCursor(new RegExp("\\" + character, "g"), head);
3064 if (sc.find()) {
3065 tmp = selectCompanionObject(cm, sc.from(), character, inclusive);
3066 }
3067 }
3068 }
3069 else if (selfPaired[character]) {
3070 move = true;
3071 tmp = findBeginningAndEnd(cm, head, character, inclusive);
3072 }
3073 else if (character === 'W' || character === 'w') {
3074 var repeat = motionArgs.repeat || 1;
3075 while (repeat-- > 0) {
3076 var repeated = expandWordUnderCursor(cm, {
3077 inclusive: inclusive,
3078 innerWord: !inclusive,
3079 bigWord: character === 'W',
3080 noSymbol: character === 'W',
3081 multiline: true
3082 }, tmp && tmp.end);
3083 if (repeated) {
3084 if (!tmp)
3085 tmp = repeated;
3086 tmp.end = repeated.end;
3087 }
3088 }
3089 }
3090 else if (character === 'p') {
3091 tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive);
3092 motionArgs.linewise = true;
3093 if (vim.visualMode) {
3094 if (!vim.visualLine) {
3095 vim.visualLine = true;
3096 }
3097 }
3098 else {
3099 var operatorArgs = vim.inputState.operatorArgs;
3100 if (operatorArgs) {
3101 operatorArgs.linewise = true;
3102 }
3103 tmp.end.line--;
3104 }
3105 }
3106 else if (character === 't') {
3107 tmp = expandTagUnderCursor(cm, head, inclusive);
3108 }
3109 else if (character === 's') {
3110 var content = cm.getLine(head.line);
3111 if (head.ch > 0 && isEndOfSentenceSymbol(content[head.ch])) {
3112 head.ch -= 1;
3113 }
3114 var end = getSentence(cm, head, motionArgs.repeat, 1, inclusive);
3115 var start = getSentence(cm, head, motionArgs.repeat, -1, inclusive);
3116 if (isWhiteSpaceString(cm.getLine(start.line)[start.ch])
3117 && isWhiteSpaceString(cm.getLine(end.line)[end.ch - 1])) {
3118 start = { line: start.line, ch: start.ch + 1 };
3119 }
3120 tmp = { start: start, end: end };
3121 }
3122 if (!tmp) {
3123 return null;
3124 }
3125 if (!cm.state.vim.visualMode) {
3126 return [tmp.start, tmp.end];
3127 }
3128 else {
3129 return expandSelection(cm, tmp.start, tmp.end, move);
3130 }
3131 },
3132 repeatLastCharacterSearch: function (cm, head, motionArgs) {
3133 var lastSearch = vimGlobalState.lastCharacterSearch;
3134 var repeat = motionArgs.repeat;
3135 var forward = motionArgs.forward === lastSearch.forward;
3136 var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
3137 cm.moveH(-increment, 'char');
3138 motionArgs.inclusive = forward ? true : false;
3139 var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
3140 if (!curEnd) {
3141 cm.moveH(increment, 'char');
3142 return head;
3143 }
3144 curEnd.ch += increment;
3145 return curEnd;
3146 }
3147 };
3148 function defineMotion(name, fn) {
3149 motions[name] = fn;
3150 }
3151 function fillArray(val, times) {
3152 var arr = [];
3153 for (var i = 0; i < times; i++) {
3154 arr.push(val);
3155 }
3156 return arr;
3157 }
3158 var operators = {
3159 change: function (cm, args, ranges) {
3160 var finalHead, text;
3161 var vim = cm.state.vim;
3162 var anchor = ranges[0].anchor, head = ranges[0].head;
3163 if (!vim.visualMode) {
3164 text = cm.getRange(anchor, head);
3165 var lastState = vim.lastEditInputState || {};
3166 if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) {
3167 var match = (/\s+$/).exec(text);
3168 if (match && lastState.motionArgs && lastState.motionArgs.forward) {
3169 head = offsetCursor(head, 0, -match[0].length);
3170 text = text.slice(0, -match[0].length);
3171 }
3172 }
3173 if (args.linewise) {
3174 anchor = new Pos(anchor.line, findFirstNonWhiteSpaceCharacter(cm.getLine(anchor.line)));
3175 if (head.line > anchor.line) {
3176 head = new Pos(head.line - 1, Number.MAX_VALUE);
3177 }
3178 }
3179 cm.replaceRange('', anchor, head);
3180 finalHead = anchor;
3181 }
3182 else if (args.fullLine) {
3183 head.ch = Number.MAX_VALUE;
3184 head.line--;
3185 cm.setSelection(anchor, head);
3186 text = cm.getSelection();
3187 cm.replaceSelection("");
3188 finalHead = anchor;
3189 }
3190 else {
3191 text = cm.getSelection();
3192 var replacement = fillArray('', ranges.length);
3193 cm.replaceSelections(replacement);
3194 finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
3195 }
3196 vimGlobalState.registerController.pushText(args.registerName, 'change', text, args.linewise, ranges.length > 1);
3197 actions.enterInsertMode(cm, { head: finalHead }, cm.state.vim);
3198 },
3199 'delete': function (cm, args, ranges) {
3200 var finalHead, text;
3201 var vim = cm.state.vim;
3202 if (!vim.visualBlock) {
3203 var anchor = ranges[0].anchor, head = ranges[0].head;
3204 if (args.linewise &&
3205 head.line != cm.firstLine() &&
3206 anchor.line == cm.lastLine() &&
3207 anchor.line == head.line - 1) {
3208 if (anchor.line == cm.firstLine()) {
3209 anchor.ch = 0;
3210 }
3211 else {
3212 anchor = new Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));
3213 }
3214 }
3215 text = cm.getRange(anchor, head);
3216 cm.replaceRange('', anchor, head);
3217 finalHead = anchor;
3218 if (args.linewise) {
3219 finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);
3220 }
3221 }
3222 else {
3223 text = cm.getSelection();
3224 var replacement = fillArray('', ranges.length);
3225 cm.replaceSelections(replacement);
3226 finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
3227 }
3228 vimGlobalState.registerController.pushText(args.registerName, 'delete', text, args.linewise, vim.visualBlock);
3229 return clipCursorToContent(cm, finalHead);
3230 },
3231 indent: function (cm, args, ranges) {
3232 var vim = cm.state.vim;
3233 if (cm.indentMore) {
3234 var repeat = (vim.visualMode) ? args.repeat : 1;
3235 for (var j = 0; j < repeat; j++) {
3236 if (args.indentRight)
3237 cm.indentMore();
3238 else
3239 cm.indentLess();
3240 }
3241 }
3242 else {
3243 var startLine = ranges[0].anchor.line;
3244 var endLine = vim.visualBlock ?
3245 ranges[ranges.length - 1].anchor.line :
3246 ranges[0].head.line;
3247 var repeat = (vim.visualMode) ? args.repeat : 1;
3248 if (args.linewise) {
3249 endLine--;
3250 }
3251 for (var i = startLine; i <= endLine; i++) {
3252 for (var j = 0; j < repeat; j++) {
3253 cm.indentLine(i, args.indentRight);
3254 }
3255 }
3256 }
3257 return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
3258 },
3259 indentAuto: function (cm, _args, ranges) {
3260 cm.execCommand("indentAuto");
3261 return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
3262 },
3263 hardWrap: function (cm, operatorArgs, ranges, oldAnchor, newHead) {
3264 if (!cm.hardWrap)
3265 return;
3266 var from = ranges[0].anchor.line;
3267 var to = ranges[0].head.line;
3268 if (operatorArgs.linewise)
3269 to--;
3270 var endRow = cm.hardWrap({ from: from, to: to });
3271 if (endRow > from && operatorArgs.linewise)
3272 endRow--;
3273 return operatorArgs.keepCursor ? oldAnchor : new Pos(endRow, 0);
3274 },
3275 changeCase: function (cm, args, ranges, oldAnchor, newHead) {
3276 var selections = cm.getSelections();
3277 var swapped = [];
3278 var toLower = args.toLower;
3279 for (var j = 0; j < selections.length; j++) {
3280 var toSwap = selections[j];
3281 var text = '';
3282 if (toLower === true) {
3283 text = toSwap.toLowerCase();
3284 }
3285 else if (toLower === false) {
3286 text = toSwap.toUpperCase();
3287 }
3288 else {
3289 for (var i = 0; i < toSwap.length; i++) {
3290 var character = toSwap.charAt(i);
3291 text += isUpperCase(character) ? character.toLowerCase() :
3292 character.toUpperCase();
3293 }
3294 }
3295 swapped.push(text);
3296 }
3297 cm.replaceSelections(swapped);
3298 if (args.shouldMoveCursor) {
3299 return newHead;
3300 }
3301 else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) {
3302 return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor);
3303 }
3304 else if (args.linewise) {
3305 return oldAnchor;
3306 }
3307 else {
3308 return cursorMin(ranges[0].anchor, ranges[0].head);
3309 }
3310 },
3311 yank: function (cm, args, ranges, oldAnchor) {
3312 var vim = cm.state.vim;
3313 var text = cm.getSelection();
3314 var endPos = vim.visualMode
3315 ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)
3316 : oldAnchor;
3317 vimGlobalState.registerController.pushText(args.registerName, 'yank', text, args.linewise, vim.visualBlock);
3318 return endPos;
3319 }
3320 };
3321 function defineOperator(name, fn) {
3322 operators[name] = fn;
3323 }
3324 var actions = {
3325 jumpListWalk: function (cm, actionArgs, vim) {
3326 if (vim.visualMode) {
3327 return;
3328 }
3329 var repeat = actionArgs.repeat;
3330 var forward = actionArgs.forward;
3331 var jumpList = vimGlobalState.jumpList;
3332 var mark = jumpList.move(cm, forward ? repeat : -repeat);
3333 var markPos = mark ? mark.find() : undefined;
3334 markPos = markPos ? markPos : cm.getCursor();
3335 cm.setCursor(markPos);
3336 cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch
3337 },
3338 scroll: function (cm, actionArgs, vim) {
3339 if (vim.visualMode) {
3340 return;
3341 }
3342 var repeat = actionArgs.repeat || 1;
3343 var lineHeight = cm.defaultTextHeight();
3344 var top = cm.getScrollInfo().top;
3345 var delta = lineHeight * repeat;
3346 var newPos = actionArgs.forward ? top + delta : top - delta;
3347 var cursor = copyCursor(cm.getCursor());
3348 var cursorCoords = cm.charCoords(cursor, 'local');
3349 if (actionArgs.forward) {
3350 if (newPos > cursorCoords.top) {
3351 cursor.line += (newPos - cursorCoords.top) / lineHeight;
3352 cursor.line = Math.ceil(cursor.line);
3353 cm.setCursor(cursor);
3354 cursorCoords = cm.charCoords(cursor, 'local');
3355 cm.scrollTo(null, cursorCoords.top);
3356 }
3357 else {
3358 cm.scrollTo(null, newPos);
3359 }
3360 }
3361 else {
3362 var newBottom = newPos + cm.getScrollInfo().clientHeight;
3363 if (newBottom < cursorCoords.bottom) {
3364 cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
3365 cursor.line = Math.floor(cursor.line);
3366 cm.setCursor(cursor);
3367 cursorCoords = cm.charCoords(cursor, 'local');
3368 cm.scrollTo(null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
3369 }
3370 else {
3371 cm.scrollTo(null, newPos);
3372 }
3373 }
3374 },
3375 scrollToCursor: function (cm, actionArgs) {
3376 var lineNum = cm.getCursor().line;
3377 var charCoords = cm.charCoords(new Pos(lineNum, 0), 'local');
3378 var height = cm.getScrollInfo().clientHeight;
3379 var y = charCoords.top;
3380 switch (actionArgs.position) {
3381 case 'center':
3382 y = charCoords.bottom - height / 2;
3383 break;
3384 case 'bottom':
3385 var lineLastCharPos = new Pos(lineNum, cm.getLine(lineNum).length - 1);
3386 var lineLastCharCoords = cm.charCoords(lineLastCharPos, 'local');
3387 var lineHeight = lineLastCharCoords.bottom - y;
3388 y = y - height + lineHeight;
3389 break;
3390 }
3391 cm.scrollTo(null, y);
3392 },
3393 replayMacro: function (cm, actionArgs, vim) {
3394 var registerName = actionArgs.selectedCharacter;
3395 var repeat = actionArgs.repeat;
3396 var macroModeState = vimGlobalState.macroModeState;
3397 if (registerName == '@') {
3398 registerName = macroModeState.latestRegister;
3399 }
3400 else {
3401 macroModeState.latestRegister = registerName;
3402 }
3403 while (repeat--) {
3404 executeMacroRegister(cm, vim, macroModeState, registerName);
3405 }
3406 },
3407 enterMacroRecordMode: function (cm, actionArgs) {
3408 var macroModeState = vimGlobalState.macroModeState;
3409 var registerName = actionArgs.selectedCharacter;
3410 if (vimGlobalState.registerController.isValidRegister(registerName)) {
3411 macroModeState.enterMacroRecordMode(cm, registerName);
3412 }
3413 },
3414 toggleOverwrite: function (cm) {
3415 if (!cm.state.overwrite) {
3416 cm.toggleOverwrite(true);
3417 cm.setOption('keyMap', 'vim-replace');
3418 CodeMirror.signal(cm, "vim-mode-change", { mode: "replace" });
3419 }
3420 else {
3421 cm.toggleOverwrite(false);
3422 cm.setOption('keyMap', 'vim-insert');
3423 CodeMirror.signal(cm, "vim-mode-change", { mode: "insert" });
3424 }
3425 },
3426 enterInsertMode: function (cm, actionArgs, vim) {
3427 if (cm.getOption('readOnly')) {
3428 return;
3429 }
3430 vim.insertMode = true;
3431 vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
3432 var insertAt = (actionArgs) ? actionArgs.insertAt : null;
3433 var sel = vim.sel;
3434 var head = actionArgs.head || cm.getCursor('head');
3435 var height = cm.listSelections().length;
3436 if (insertAt == 'eol') {
3437 head = new Pos(head.line, lineLength(cm, head.line));
3438 }
3439 else if (insertAt == 'bol') {
3440 head = new Pos(head.line, 0);
3441 }
3442 else if (insertAt == 'charAfter') {
3443 var newPosition = updateSelectionForSurrogateCharacters(cm, head, offsetCursor(head, 0, 1));
3444 head = newPosition.end;
3445 }
3446 else if (insertAt == 'firstNonBlank') {
3447 var newPosition = updateSelectionForSurrogateCharacters(cm, head, motions.moveToFirstNonWhiteSpaceCharacter(cm, head));
3448 head = newPosition.end;
3449 }
3450 else if (insertAt == 'startOfSelectedArea') {
3451 if (!vim.visualMode)
3452 return;
3453 if (!vim.visualBlock) {
3454 if (sel.head.line < sel.anchor.line) {
3455 head = sel.head;
3456 }
3457 else {
3458 head = new Pos(sel.anchor.line, 0);
3459 }
3460 }
3461 else {
3462 head = new Pos(Math.min(sel.head.line, sel.anchor.line), Math.min(sel.head.ch, sel.anchor.ch));
3463 height = Math.abs(sel.head.line - sel.anchor.line) + 1;
3464 }
3465 }
3466 else if (insertAt == 'endOfSelectedArea') {
3467 if (!vim.visualMode)
3468 return;
3469 if (!vim.visualBlock) {
3470 if (sel.head.line >= sel.anchor.line) {
3471 head = offsetCursor(sel.head, 0, 1);
3472 }
3473 else {
3474 head = new Pos(sel.anchor.line, 0);
3475 }
3476 }
3477 else {
3478 head = new Pos(Math.min(sel.head.line, sel.anchor.line), Math.max(sel.head.ch, sel.anchor.ch) + 1);
3479 height = Math.abs(sel.head.line - sel.anchor.line) + 1;
3480 }
3481 }
3482 else if (insertAt == 'inplace') {
3483 if (vim.visualMode) {
3484 return;
3485 }
3486 }
3487 else if (insertAt == 'lastEdit') {
3488 head = getLastEditPos(cm) || head;
3489 }
3490 cm.setOption('disableInput', false);
3491 if (actionArgs && actionArgs.replace) {
3492 cm.toggleOverwrite(true);
3493 cm.setOption('keyMap', 'vim-replace');
3494 CodeMirror.signal(cm, "vim-mode-change", { mode: "replace" });
3495 }
3496 else {
3497 cm.toggleOverwrite(false);
3498 cm.setOption('keyMap', 'vim-insert');
3499 CodeMirror.signal(cm, "vim-mode-change", { mode: "insert" });
3500 }
3501 if (!vimGlobalState.macroModeState.isPlaying) {
3502 cm.on('change', onChange);
3503 if (vim.insertEnd)
3504 vim.insertEnd.clear();
3505 vim.insertEnd = cm.setBookmark(head, { insertLeft: true });
3506 CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
3507 }
3508 if (vim.visualMode) {
3509 exitVisualMode(cm);
3510 }
3511 selectForInsert(cm, head, height);
3512 },
3513 toggleVisualMode: function (cm, actionArgs, vim) {
3514 var repeat = actionArgs.repeat;
3515 var anchor = cm.getCursor();
3516 var head;
3517 if (!vim.visualMode) {
3518 vim.visualMode = true;
3519 vim.visualLine = !!actionArgs.linewise;
3520 vim.visualBlock = !!actionArgs.blockwise;
3521 head = clipCursorToContent(cm, new Pos(anchor.line, anchor.ch + repeat - 1));
3522 var newPosition = updateSelectionForSurrogateCharacters(cm, anchor, head);
3523 vim.sel = {
3524 anchor: newPosition.start,
3525 head: newPosition.end
3526 };
3527 CodeMirror.signal(cm, "vim-mode-change", { mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : "" });
3528 updateCmSelection(cm);
3529 updateMark(cm, vim, '<', cursorMin(anchor, head));
3530 updateMark(cm, vim, '>', cursorMax(anchor, head));
3531 }
3532 else if (vim.visualLine ^ actionArgs.linewise ||
3533 vim.visualBlock ^ actionArgs.blockwise) {
3534 vim.visualLine = !!actionArgs.linewise;
3535 vim.visualBlock = !!actionArgs.blockwise;
3536 CodeMirror.signal(cm, "vim-mode-change", { mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : "" });
3537 updateCmSelection(cm);
3538 }
3539 else {
3540 exitVisualMode(cm);
3541 }
3542 },
3543 reselectLastSelection: function (cm, _actionArgs, vim) {
3544 var lastSelection = vim.lastSelection;
3545 if (vim.visualMode) {
3546 updateLastSelection(cm, vim);
3547 }
3548 if (lastSelection) {
3549 var anchor = lastSelection.anchorMark.find();
3550 var head = lastSelection.headMark.find();
3551 if (!anchor || !head) {
3552 return;
3553 }
3554 vim.sel = {
3555 anchor: anchor,
3556 head: head
3557 };
3558 vim.visualMode = true;
3559 vim.visualLine = lastSelection.visualLine;
3560 vim.visualBlock = lastSelection.visualBlock;
3561 updateCmSelection(cm);
3562 updateMark(cm, vim, '<', cursorMin(anchor, head));
3563 updateMark(cm, vim, '>', cursorMax(anchor, head));
3564 CodeMirror.signal(cm, 'vim-mode-change', {
3565 mode: 'visual',
3566 subMode: vim.visualLine ? 'linewise' :
3567 vim.visualBlock ? 'blockwise' : ''
3568 });
3569 }
3570 },
3571 joinLines: function (cm, actionArgs, vim) {
3572 var curStart, curEnd;
3573 if (vim.visualMode) {
3574 curStart = cm.getCursor('anchor');
3575 curEnd = cm.getCursor('head');
3576 if (cursorIsBefore(curEnd, curStart)) {
3577 var tmp = curEnd;
3578 curEnd = curStart;
3579 curStart = tmp;
3580 }
3581 curEnd.ch = lineLength(cm, curEnd.line) - 1;
3582 }
3583 else {
3584 var repeat = Math.max(actionArgs.repeat, 2);
3585 curStart = cm.getCursor();
3586 curEnd = clipCursorToContent(cm, new Pos(curStart.line + repeat - 1, Infinity));
3587 }
3588 var finalCh = 0;
3589 for (var i = curStart.line; i < curEnd.line; i++) {
3590 finalCh = lineLength(cm, curStart.line);
3591 var text = '';
3592 var nextStartCh = 0;
3593 if (!actionArgs.keepSpaces) {
3594 var nextLine = cm.getLine(curStart.line + 1);
3595 nextStartCh = nextLine.search(/\S/);
3596 if (nextStartCh == -1) {
3597 nextStartCh = nextLine.length;
3598 }
3599 else {
3600 text = " ";
3601 }
3602 }
3603 cm.replaceRange(text, new Pos(curStart.line, finalCh), new Pos(curStart.line + 1, nextStartCh));
3604 }
3605 var curFinalPos = clipCursorToContent(cm, new Pos(curStart.line, finalCh));
3606 if (vim.visualMode) {
3607 exitVisualMode(cm, false);
3608 }
3609 cm.setCursor(curFinalPos);
3610 },
3611 newLineAndEnterInsertMode: function (cm, actionArgs, vim) {
3612 vim.insertMode = true;
3613 var insertAt = copyCursor(cm.getCursor());
3614 if (insertAt.line === cm.firstLine() && !actionArgs.after) {
3615 cm.replaceRange('\n', new Pos(cm.firstLine(), 0));
3616 cm.setCursor(cm.firstLine(), 0);
3617 }
3618 else {
3619 insertAt.line = (actionArgs.after) ? insertAt.line :
3620 insertAt.line - 1;
3621 insertAt.ch = lineLength(cm, insertAt.line);
3622 cm.setCursor(insertAt);
3623 var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
3624 CodeMirror.commands.newlineAndIndent;
3625 newlineFn(cm);
3626 }
3627 this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
3628 },
3629 paste: function (cm, actionArgs, vim) {
3630 var _this = this;
3631 var register = vimGlobalState.registerController.getRegister(actionArgs.registerName);
3632 var fallback = function () {
3633 var text = register.toString();
3634 _this.continuePaste(cm, actionArgs, vim, text, register);
3635 };
3636 if (actionArgs.registerName === '+' &&
3637 typeof navigator !== 'undefined' &&
3638 typeof navigator.clipboard !== 'undefined' &&
3639 typeof navigator.clipboard.readText === 'function') {
3640 navigator.clipboard.readText().then(function (value) {
3641 _this.continuePaste(cm, actionArgs, vim, value, register);
3642 }, function () { fallback(); });
3643 }
3644 else {
3645 fallback();
3646 }
3647 },
3648 continuePaste: function (cm, actionArgs, vim, text, register) {
3649 var cur = copyCursor(cm.getCursor());
3650 if (!text) {
3651 return;
3652 }
3653 if (actionArgs.matchIndent) {
3654 var tabSize = cm.getOption("tabSize");
3655 var whitespaceLength = function (str) {
3656 var tabs = (str.split("\t").length - 1);
3657 var spaces = (str.split(" ").length - 1);
3658 return tabs * tabSize + spaces * 1;
3659 };
3660 var currentLine = cm.getLine(cm.getCursor().line);
3661 var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
3662 var chompedText = text.replace(/\n$/, '');
3663 var wasChomped = text !== chompedText;
3664 var firstIndent = whitespaceLength(text.match(/^\s*/)[0]);
3665 var text = chompedText.replace(/^\s*/gm, function (wspace) {
3666 var newIndent = indent + (whitespaceLength(wspace) - firstIndent);
3667 if (newIndent < 0) {
3668 return "";
3669 }
3670 else if (cm.getOption("indentWithTabs")) {
3671 var quotient = Math.floor(newIndent / tabSize);
3672 return Array(quotient + 1).join('\t');
3673 }
3674 else {
3675 return Array(newIndent + 1).join(' ');
3676 }
3677 });
3678 text += wasChomped ? "\n" : "";
3679 }
3680 if (actionArgs.repeat > 1) {
3681 var text = Array(actionArgs.repeat + 1).join(text);
3682 }
3683 var linewise = register.linewise;
3684 var blockwise = register.blockwise;
3685 if (blockwise) {
3686 text = text.split('\n');
3687 if (linewise) {
3688 text.pop();
3689 }
3690 for (var i = 0; i < text.length; i++) {
3691 text[i] = (text[i] == '') ? ' ' : text[i];
3692 }
3693 cur.ch += actionArgs.after ? 1 : 0;
3694 cur.ch = Math.min(lineLength(cm, cur.line), cur.ch);
3695 }
3696 else if (linewise) {
3697 if (vim.visualMode) {
3698 text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n';
3699 }
3700 else if (actionArgs.after) {
3701 text = '\n' + text.slice(0, text.length - 1);
3702 cur.ch = lineLength(cm, cur.line);
3703 }
3704 else {
3705 cur.ch = 0;
3706 }
3707 }
3708 else {
3709 cur.ch += actionArgs.after ? 1 : 0;
3710 }
3711 var curPosFinal;
3712 if (vim.visualMode) {
3713 vim.lastPastedText = text;
3714 var lastSelectionCurEnd;
3715 var selectedArea = getSelectedAreaRange(cm, vim);
3716 var selectionStart = selectedArea[0];
3717 var selectionEnd = selectedArea[1];
3718 var selectedText = cm.getSelection();
3719 var selections = cm.listSelections();
3720 var emptyStrings = new Array(selections.length).join('1').split('1');
3721 if (vim.lastSelection) {
3722 lastSelectionCurEnd = vim.lastSelection.headMark.find();
3723 }
3724 vimGlobalState.registerController.unnamedRegister.setText(selectedText);
3725 if (blockwise) {
3726 cm.replaceSelections(emptyStrings);
3727 selectionEnd = new Pos(selectionStart.line + text.length - 1, selectionStart.ch);
3728 cm.setCursor(selectionStart);
3729 selectBlock(cm, selectionEnd);
3730 cm.replaceSelections(text);
3731 curPosFinal = selectionStart;
3732 }
3733 else if (vim.visualBlock) {
3734 cm.replaceSelections(emptyStrings);
3735 cm.setCursor(selectionStart);
3736 cm.replaceRange(text, selectionStart, selectionStart);
3737 curPosFinal = selectionStart;
3738 }
3739 else {
3740 cm.replaceRange(text, selectionStart, selectionEnd);
3741 curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1);
3742 }
3743 if (lastSelectionCurEnd) {
3744 vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);
3745 }
3746 if (linewise) {
3747 curPosFinal.ch = 0;
3748 }
3749 }
3750 else {
3751 if (blockwise) {
3752 cm.setCursor(cur);
3753 for (var i = 0; i < text.length; i++) {
3754 var line = cur.line + i;
3755 if (line > cm.lastLine()) {
3756 cm.replaceRange('\n', new Pos(line, 0));
3757 }
3758 var lastCh = lineLength(cm, line);
3759 if (lastCh < cur.ch) {
3760 extendLineToColumn(cm, line, cur.ch);
3761 }
3762 }
3763 cm.setCursor(cur);
3764 selectBlock(cm, new Pos(cur.line + text.length - 1, cur.ch));
3765 cm.replaceSelections(text);
3766 curPosFinal = cur;
3767 }
3768 else {
3769 cm.replaceRange(text, cur);
3770 if (linewise) {
3771 var line = actionArgs.after ? cur.line + 1 : cur.line;
3772 curPosFinal = new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
3773 }
3774 else {
3775 curPosFinal = copyCursor(cur);
3776 if (!/\n/.test(text)) {
3777 curPosFinal.ch += text.length - (actionArgs.after ? 1 : 0);
3778 }
3779 }
3780 }
3781 }
3782 if (vim.visualMode) {
3783 exitVisualMode(cm, false);
3784 }
3785 cm.setCursor(curPosFinal);
3786 },
3787 undo: function (cm, actionArgs) {
3788 cm.operation(function () {
3789 repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
3790 cm.setCursor(clipCursorToContent(cm, cm.getCursor('start')));
3791 });
3792 },
3793 redo: function (cm, actionArgs) {
3794 repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
3795 },
3796 setRegister: function (_cm, actionArgs, vim) {
3797 vim.inputState.registerName = actionArgs.selectedCharacter;
3798 },
3799 insertRegister: function (cm, actionArgs, vim) {
3800 var registerName = actionArgs.selectedCharacter;
3801 var register = vimGlobalState.registerController.getRegister(registerName);
3802 var text = register && register.toString();
3803 if (text) {
3804 cm.replaceSelection(text);
3805 }
3806 },
3807 oneNormalCommand: function (cm, actionArgs, vim) {
3808 exitInsertMode(cm, true);
3809 vim.insertModeReturn = true;
3810 CodeMirror.on(cm, 'vim-command-done', function handler() {
3811 if (vim.visualMode)
3812 return;
3813 if (vim.insertModeReturn) {
3814 vim.insertModeReturn = false;
3815 if (!vim.insertMode) {
3816 actions.enterInsertMode(cm, {}, vim);
3817 }
3818 }
3819 CodeMirror.off(cm, 'vim-command-done', handler);
3820 });
3821 },
3822 setMark: function (cm, actionArgs, vim) {
3823 var markName = actionArgs.selectedCharacter;
3824 updateMark(cm, vim, markName, cm.getCursor());
3825 },
3826 replace: function (cm, actionArgs, vim) {
3827 var replaceWith = actionArgs.selectedCharacter;
3828 var curStart = cm.getCursor();
3829 var replaceTo;
3830 var curEnd;
3831 var selections = cm.listSelections();
3832 if (vim.visualMode) {
3833 curStart = cm.getCursor('start');
3834 curEnd = cm.getCursor('end');
3835 }
3836 else {
3837 var line = cm.getLine(curStart.line);
3838 replaceTo = curStart.ch + actionArgs.repeat;
3839 if (replaceTo > line.length) {
3840 replaceTo = line.length;
3841 }
3842 curEnd = new Pos(curStart.line, replaceTo);
3843 }
3844 var newPositions = updateSelectionForSurrogateCharacters(cm, curStart, curEnd);
3845 curStart = newPositions.start;
3846 curEnd = newPositions.end;
3847 if (replaceWith == '\n') {
3848 if (!vim.visualMode)
3849 cm.replaceRange('', curStart, curEnd);
3850 (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
3851 }
3852 else {
3853 var replaceWithStr = cm.getRange(curStart, curEnd);
3854 replaceWithStr = replaceWithStr.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, replaceWith);
3855 replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith);
3856 if (vim.visualBlock) {
3857 var spaces = new Array(cm.getOption("tabSize") + 1).join(' ');
3858 replaceWithStr = cm.getSelection();
3859 replaceWithStr = replaceWithStr.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, replaceWith);
3860 replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n');
3861 cm.replaceSelections(replaceWithStr);
3862 }
3863 else {
3864 cm.replaceRange(replaceWithStr, curStart, curEnd);
3865 }
3866 if (vim.visualMode) {
3867 curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ?
3868 selections[0].anchor : selections[0].head;
3869 cm.setCursor(curStart);
3870 exitVisualMode(cm, false);
3871 }
3872 else {
3873 cm.setCursor(offsetCursor(curEnd, 0, -1));
3874 }
3875 }
3876 },
3877 incrementNumberToken: function (cm, actionArgs) {
3878 var cur = cm.getCursor();
3879 var lineStr = cm.getLine(cur.line);
3880 var re = /(-?)(?:(0x)([\da-f]+)|(0b|0|)(\d+))/gi;
3881 var match;
3882 var start;
3883 var end;
3884 var numberStr;
3885 while ((match = re.exec(lineStr)) !== null) {
3886 start = match.index;
3887 end = start + match[0].length;
3888 if (cur.ch < end)
3889 break;
3890 }
3891 if (!actionArgs.backtrack && (end <= cur.ch))
3892 return;
3893 if (match) {
3894 var baseStr = match[2] || match[4];
3895 var digits = match[3] || match[5];
3896 var increment = actionArgs.increase ? 1 : -1;
3897 var base = { '0b': 2, '0': 8, '': 10, '0x': 16 }[baseStr.toLowerCase()];
3898 var number = parseInt(match[1] + digits, base) + (increment * actionArgs.repeat);
3899 numberStr = number.toString(base);
3900 var zeroPadding = baseStr ? new Array(digits.length - numberStr.length + 1 + match[1].length).join('0') : '';
3901 if (numberStr.charAt(0) === '-') {
3902 numberStr = '-' + baseStr + zeroPadding + numberStr.substr(1);
3903 }
3904 else {
3905 numberStr = baseStr + zeroPadding + numberStr;
3906 }
3907 var from = new Pos(cur.line, start);
3908 var to = new Pos(cur.line, end);
3909 cm.replaceRange(numberStr, from, to);
3910 }
3911 else {
3912 return;
3913 }
3914 cm.setCursor(new Pos(cur.line, start + numberStr.length - 1));
3915 },
3916 repeatLastEdit: function (cm, actionArgs, vim) {
3917 var lastEditInputState = vim.lastEditInputState;
3918 if (!lastEditInputState) {
3919 return;
3920 }
3921 var repeat = actionArgs.repeat;
3922 if (repeat && actionArgs.repeatIsExplicit) {
3923 vim.lastEditInputState.repeatOverride = repeat;
3924 }
3925 else {
3926 repeat = vim.lastEditInputState.repeatOverride || repeat;
3927 }
3928 repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
3929 },
3930 indent: function (cm, actionArgs) {
3931 cm.indentLine(cm.getCursor().line, actionArgs.indentRight);
3932 },
3933 exitInsertMode: exitInsertMode
3934 };
3935 function defineAction(name, fn) {
3936 actions[name] = fn;
3937 }
3938 function clipCursorToContent(cm, cur, oldCur) {
3939 var vim = cm.state.vim;
3940 var includeLineBreak = vim.insertMode || vim.visualMode;
3941 var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine());
3942 var text = cm.getLine(line);
3943 var maxCh = text.length - 1 + Number(!!includeLineBreak);
3944 var ch = Math.min(Math.max(0, cur.ch), maxCh);
3945 var charCode = text.charCodeAt(ch);
3946 if (0xDC00 <= charCode && charCode <= 0xDFFF) {
3947 var direction = 1;
3948 if (oldCur && oldCur.line == line && oldCur.ch > ch) {
3949 direction = -1;
3950 }
3951 ch += direction;
3952 if (ch > maxCh)
3953 ch -= 2;
3954 }
3955 return new Pos(line, ch);
3956 }
3957 function copyArgs(args) {
3958 var ret = {};
3959 for (var prop in args) {
3960 if (args.hasOwnProperty(prop)) {
3961 ret[prop] = args[prop];
3962 }
3963 }
3964 return ret;
3965 }
3966 function offsetCursor(cur, offsetLine, offsetCh) {
3967 if (typeof offsetLine === 'object') {
3968 offsetCh = offsetLine.ch;
3969 offsetLine = offsetLine.line;
3970 }
3971 return new Pos(cur.line + offsetLine, cur.ch + offsetCh);
3972 }
3973 function commandMatches(keys, keyMap, context, inputState) {
3974 if (inputState.operator)
3975 context = "operatorPending";
3976 var match, partial = [], full = [];
3977 var startIndex = noremap ? keyMap.length - defaultKeymapLength : 0;
3978 for (var i = startIndex; i < keyMap.length; i++) {
3979 var command = keyMap[i];
3980 if (context == 'insert' && command.context != 'insert' ||
3981 (command.context && command.context != context) ||
3982 inputState.operator && command.type == 'action' ||
3983 !(match = commandMatch(keys, command.keys))) {
3984 continue;
3985 }
3986 if (match == 'partial') {
3987 partial.push(command);
3988 }
3989 if (match == 'full') {
3990 full.push(command);
3991 }
3992 }
3993 return {
3994 partial: partial.length && partial,
3995 full: full.length && full
3996 };
3997 }
3998 function commandMatch(pressed, mapped) {
3999 var isLastCharacter = mapped.slice(-11) == '<character>';
4000 var isLastRegister = mapped.slice(-10) == '<register>';
4001 if (isLastCharacter || isLastRegister) {
4002 var prefixLen = mapped.length - (isLastCharacter ? 11 : 10);
4003 var pressedPrefix = pressed.slice(0, prefixLen);
4004 var mappedPrefix = mapped.slice(0, prefixLen);
4005 return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' :
4006 mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false;
4007 }
4008 else {
4009 return pressed == mapped ? 'full' :
4010 mapped.indexOf(pressed) == 0 ? 'partial' : false;
4011 }
4012 }
4013 function lastChar(keys) {
4014 var match = /^.*(<[^>]+>)$/.exec(keys);
4015 var selectedCharacter = match ? match[1] : keys.slice(-1);
4016 if (selectedCharacter.length > 1) {
4017 switch (selectedCharacter) {
4018 case '<CR>':
4019 selectedCharacter = '\n';
4020 break;
4021 case '<Space>':
4022 selectedCharacter = ' ';
4023 break;
4024 default:
4025 selectedCharacter = '';
4026 break;
4027 }
4028 }
4029 return selectedCharacter;
4030 }
4031 function repeatFn(cm, fn, repeat) {
4032 return function () {
4033 for (var i = 0; i < repeat; i++) {
4034 fn(cm);
4035 }
4036 };
4037 }
4038 function copyCursor(cur) {
4039 return new Pos(cur.line, cur.ch);
4040 }
4041 function cursorEqual(cur1, cur2) {
4042 return cur1.ch == cur2.ch && cur1.line == cur2.line;
4043 }
4044 function cursorIsBefore(cur1, cur2) {
4045 if (cur1.line < cur2.line) {
4046 return true;
4047 }
4048 if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
4049 return true;
4050 }
4051 return false;
4052 }
4053 function cursorMin(cur1, cur2) {
4054 if (arguments.length > 2) {
4055 cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));
4056 }
4057 return cursorIsBefore(cur1, cur2) ? cur1 : cur2;
4058 }
4059 function cursorMax(cur1, cur2) {
4060 if (arguments.length > 2) {
4061 cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));
4062 }
4063 return cursorIsBefore(cur1, cur2) ? cur2 : cur1;
4064 }
4065 function cursorIsBetween(cur1, cur2, cur3) {
4066 var cur1before2 = cursorIsBefore(cur1, cur2);
4067 var cur2before3 = cursorIsBefore(cur2, cur3);
4068 return cur1before2 && cur2before3;
4069 }
4070 function lineLength(cm, lineNum) {
4071 return cm.getLine(lineNum).length;
4072 }
4073 function trim(s) {
4074 if (s.trim) {
4075 return s.trim();
4076 }
4077 return s.replace(/^\s+|\s+$/g, '');
4078 }
4079 function escapeRegex(s) {
4080 return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
4081 }
4082 function extendLineToColumn(cm, lineNum, column) {
4083 var endCh = lineLength(cm, lineNum);
4084 var spaces = new Array(column - endCh + 1).join(' ');
4085 cm.setCursor(new Pos(lineNum, endCh));
4086 cm.replaceRange(spaces, cm.getCursor());
4087 }
4088 function selectBlock(cm, selectionEnd) {
4089 var selections = [], ranges = cm.listSelections();
4090 var head = copyCursor(cm.clipPos(selectionEnd));
4091 var isClipped = !cursorEqual(selectionEnd, head);
4092 var curHead = cm.getCursor('head');
4093 var primIndex = getIndex(ranges, curHead);
4094 var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor);
4095 var max = ranges.length - 1;
4096 var index = max - primIndex > primIndex ? max : 0;
4097 var base = ranges[index].anchor;
4098 var firstLine = Math.min(base.line, head.line);
4099 var lastLine = Math.max(base.line, head.line);
4100 var baseCh = base.ch, headCh = head.ch;
4101 var dir = ranges[index].head.ch - baseCh;
4102 var newDir = headCh - baseCh;
4103 if (dir > 0 && newDir <= 0) {
4104 baseCh++;
4105 if (!isClipped) {
4106 headCh--;
4107 }
4108 }
4109 else if (dir < 0 && newDir >= 0) {
4110 baseCh--;
4111 if (!wasClipped) {
4112 headCh++;
4113 }
4114 }
4115 else if (dir < 0 && newDir == -1) {
4116 baseCh--;
4117 headCh++;
4118 }
4119 for (var line = firstLine; line <= lastLine; line++) {
4120 var range = { anchor: new Pos(line, baseCh), head: new Pos(line, headCh) };
4121 selections.push(range);
4122 }
4123 cm.setSelections(selections);
4124 selectionEnd.ch = headCh;
4125 base.ch = baseCh;
4126 return base;
4127 }
4128 function selectForInsert(cm, head, height) {
4129 var sel = [];
4130 for (var i = 0; i < height; i++) {
4131 var lineHead = offsetCursor(head, i, 0);
4132 sel.push({ anchor: lineHead, head: lineHead });
4133 }
4134 cm.setSelections(sel, 0);
4135 }
4136 function getIndex(ranges, cursor, end) {
4137 for (var i = 0; i < ranges.length; i++) {
4138 var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor);
4139 var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor);
4140 if (atAnchor || atHead) {
4141 return i;
4142 }
4143 }
4144 return -1;
4145 }
4146 function getSelectedAreaRange(cm, vim) {
4147 var lastSelection = vim.lastSelection;
4148 var getCurrentSelectedAreaRange = function () {
4149 var selections = cm.listSelections();
4150 var start = selections[0];
4151 var end = selections[selections.length - 1];
4152 var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
4153 var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
4154 return [selectionStart, selectionEnd];
4155 };
4156 var getLastSelectedAreaRange = function () {
4157 var selectionStart = cm.getCursor();
4158 var selectionEnd = cm.getCursor();
4159 var block = lastSelection.visualBlock;
4160 if (block) {
4161 var width = block.width;
4162 var height = block.height;
4163 selectionEnd = new Pos(selectionStart.line + height, selectionStart.ch + width);
4164 var selections = [];
4165 for (var i = selectionStart.line; i < selectionEnd.line; i++) {
4166 var anchor = new Pos(i, selectionStart.ch);
4167 var head = new Pos(i, selectionEnd.ch);
4168 var range = { anchor: anchor, head: head };
4169 selections.push(range);
4170 }
4171 cm.setSelections(selections);
4172 }
4173 else {
4174 var start = lastSelection.anchorMark.find();
4175 var end = lastSelection.headMark.find();
4176 var line = end.line - start.line;
4177 var ch = end.ch - start.ch;
4178 selectionEnd = { line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch };
4179 if (lastSelection.visualLine) {
4180 selectionStart = new Pos(selectionStart.line, 0);
4181 selectionEnd = new Pos(selectionEnd.line, lineLength(cm, selectionEnd.line));
4182 }
4183 cm.setSelection(selectionStart, selectionEnd);
4184 }
4185 return [selectionStart, selectionEnd];
4186 };
4187 if (!vim.visualMode) {
4188 return getLastSelectedAreaRange();
4189 }
4190 else {
4191 return getCurrentSelectedAreaRange();
4192 }
4193 }
4194 function updateLastSelection(cm, vim) {
4195 var anchor = vim.sel.anchor;
4196 var head = vim.sel.head;
4197 if (vim.lastPastedText) {
4198 head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);
4199 vim.lastPastedText = null;
4200 }
4201 vim.lastSelection = { 'anchorMark': cm.setBookmark(anchor),
4202 'headMark': cm.setBookmark(head),
4203 'anchor': copyCursor(anchor),
4204 'head': copyCursor(head),
4205 'visualMode': vim.visualMode,
4206 'visualLine': vim.visualLine,
4207 'visualBlock': vim.visualBlock };
4208 }
4209 function expandSelection(cm, start, end, move) {
4210 var sel = cm.state.vim.sel;
4211 var head = move ? start : sel.head;
4212 var anchor = move ? start : sel.anchor;
4213 var tmp;
4214 if (cursorIsBefore(end, start)) {
4215 tmp = end;
4216 end = start;
4217 start = tmp;
4218 }
4219 if (cursorIsBefore(head, anchor)) {
4220 head = cursorMin(start, head);
4221 anchor = cursorMax(anchor, end);
4222 }
4223 else {
4224 anchor = cursorMin(start, anchor);
4225 head = cursorMax(head, end);
4226 head = offsetCursor(head, 0, -1);
4227 if (head.ch == -1 && head.line != cm.firstLine()) {
4228 head = new Pos(head.line - 1, lineLength(cm, head.line - 1));
4229 }
4230 }
4231 return [anchor, head];
4232 }
4233 function updateCmSelection(cm, sel, mode) {
4234 var vim = cm.state.vim;
4235 sel = sel || vim.sel;
4236 var mode = mode ||
4237 vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';
4238 var cmSel = makeCmSelection(cm, sel, mode);
4239 cm.setSelections(cmSel.ranges, cmSel.primary);
4240 }
4241 function makeCmSelection(cm, sel, mode, exclusive) {
4242 var head = copyCursor(sel.head);
4243 var anchor = copyCursor(sel.anchor);
4244 if (mode == 'char') {
4245 var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
4246 var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
4247 head = offsetCursor(sel.head, 0, headOffset);
4248 anchor = offsetCursor(sel.anchor, 0, anchorOffset);
4249 return {
4250 ranges: [{ anchor: anchor, head: head }],
4251 primary: 0
4252 };
4253 }
4254 else if (mode == 'line') {
4255 if (!cursorIsBefore(sel.head, sel.anchor)) {
4256 anchor.ch = 0;
4257 var lastLine = cm.lastLine();
4258 if (head.line > lastLine) {
4259 head.line = lastLine;
4260 }
4261 head.ch = lineLength(cm, head.line);
4262 }
4263 else {
4264 head.ch = 0;
4265 anchor.ch = lineLength(cm, anchor.line);
4266 }
4267 return {
4268 ranges: [{ anchor: anchor, head: head }],
4269 primary: 0
4270 };
4271 }
4272 else if (mode == 'block') {
4273 var top = Math.min(anchor.line, head.line), fromCh = anchor.ch, bottom = Math.max(anchor.line, head.line), toCh = head.ch;
4274 if (fromCh < toCh) {
4275 toCh += 1;
4276 }
4277 else {
4278 fromCh += 1;
4279 }
4280 ;
4281 var height = bottom - top + 1;
4282 var primary = head.line == top ? 0 : height - 1;
4283 var ranges = [];
4284 for (var i = 0; i < height; i++) {
4285 ranges.push({
4286 anchor: new Pos(top + i, fromCh),
4287 head: new Pos(top + i, toCh)
4288 });
4289 }
4290 return {
4291 ranges: ranges,
4292 primary: primary
4293 };
4294 }
4295 }
4296 function getHead(cm) {
4297 var cur = cm.getCursor('head');
4298 if (cm.getSelection().length == 1) {
4299 cur = cursorMin(cur, cm.getCursor('anchor'));
4300 }
4301 return cur;
4302 }
4303 function exitVisualMode(cm, moveHead) {
4304 var vim = cm.state.vim;
4305 if (moveHead !== false) {
4306 cm.setCursor(clipCursorToContent(cm, vim.sel.head));
4307 }
4308 updateLastSelection(cm, vim);
4309 vim.visualMode = false;
4310 vim.visualLine = false;
4311 vim.visualBlock = false;
4312 if (!vim.insertMode)
4313 CodeMirror.signal(cm, "vim-mode-change", { mode: "normal" });
4314 }
4315 function clipToLine(cm, curStart, curEnd) {
4316 var selection = cm.getRange(curStart, curEnd);
4317 if (/\n\s*$/.test(selection)) {
4318 var lines = selection.split('\n');
4319 lines.pop();
4320 var line;
4321 for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
4322 curEnd.line--;
4323 curEnd.ch = 0;
4324 }
4325 if (line) {
4326 curEnd.line--;
4327 curEnd.ch = lineLength(cm, curEnd.line);
4328 }
4329 else {
4330 curEnd.ch = 0;
4331 }
4332 }
4333 }
4334 function expandSelectionToLine(_cm, curStart, curEnd) {
4335 curStart.ch = 0;
4336 curEnd.ch = 0;
4337 curEnd.line++;
4338 }
4339 function findFirstNonWhiteSpaceCharacter(text) {
4340 if (!text) {
4341 return 0;
4342 }
4343 var firstNonWS = text.search(/\S/);
4344 return firstNonWS == -1 ? text.length : firstNonWS;
4345 }
4346 function expandWordUnderCursor(cm, _a, cursor) {
4347 var inclusive = _a.inclusive, innerWord = _a.innerWord, bigWord = _a.bigWord, noSymbol = _a.noSymbol, multiline = _a.multiline;
4348 var cur = cursor || getHead(cm);
4349 var line = cm.getLine(cur.line);
4350 var endLine = line;
4351 var startLineNumber = cur.line;
4352 var endLineNumber = startLineNumber;
4353 var idx = cur.ch;
4354 var wordOnNextLine;
4355 var test = noSymbol ? wordCharTest[0] : bigWordCharTest[0];
4356 if (innerWord && /\s/.test(line.charAt(idx))) {
4357 test = function (ch) { return /\s/.test(ch); };
4358 }
4359 else {
4360 while (!test(line.charAt(idx))) {
4361 idx++;
4362 if (idx >= line.length) {
4363 if (!multiline)
4364 return null;
4365 idx--;
4366 wordOnNextLine = findWord(cm, cur, true, bigWord, true);
4367 break;
4368 }
4369 }
4370 if (bigWord) {
4371 test = bigWordCharTest[0];
4372 }
4373 else {
4374 test = wordCharTest[0];
4375 if (!test(line.charAt(idx))) {
4376 test = wordCharTest[1];
4377 }
4378 }
4379 }
4380 var end = idx, start = idx;
4381 while (test(line.charAt(start)) && start >= 0) {
4382 start--;
4383 }
4384 start++;
4385 if (wordOnNextLine) {
4386 end = wordOnNextLine.to;
4387 endLineNumber = wordOnNextLine.line;
4388 endLine = cm.getLine(endLineNumber);
4389 if (!endLine && end == 0)
4390 end++;
4391 }
4392 else {
4393 while (test(line.charAt(end)) && end < line.length) {
4394 end++;
4395 }
4396 }
4397 if (inclusive) {
4398 var wordEnd = end;
4399 var startsWithSpace = cur.ch <= start && /\s/.test(line.charAt(cur.ch));
4400 if (!startsWithSpace) {
4401 while (/\s/.test(endLine.charAt(end)) && end < endLine.length) {
4402 end++;
4403 }
4404 }
4405 if (wordEnd == end || startsWithSpace) {
4406 var wordStart = start;
4407 while (/\s/.test(line.charAt(start - 1)) && start > 0) {
4408 start--;
4409 }
4410 if (!start && !startsWithSpace) {
4411 start = wordStart;
4412 }
4413 }
4414 }
4415 return { start: new Pos(startLineNumber, start), end: new Pos(endLineNumber, end) };
4416 }
4417 function expandTagUnderCursor(cm, head, inclusive) {
4418 var cur = head;
4419 if (!CodeMirror.findMatchingTag || !CodeMirror.findEnclosingTag) {
4420 return { start: cur, end: cur };
4421 }
4422 var tags = CodeMirror.findMatchingTag(cm, head) || CodeMirror.findEnclosingTag(cm, head);
4423 if (!tags || !tags.open || !tags.close) {
4424 return { start: cur, end: cur };
4425 }
4426 if (inclusive) {
4427 return { start: tags.open.from, end: tags.close.to };
4428 }
4429 return { start: tags.open.to, end: tags.close.from };
4430 }
4431 function recordJumpPosition(cm, oldCur, newCur) {
4432 if (!cursorEqual(oldCur, newCur)) {
4433 vimGlobalState.jumpList.add(cm, oldCur, newCur);
4434 }
4435 }
4436 function recordLastCharacterSearch(increment, args) {
4437 vimGlobalState.lastCharacterSearch.increment = increment;
4438 vimGlobalState.lastCharacterSearch.forward = args.forward;
4439 vimGlobalState.lastCharacterSearch.selectedCharacter = args.selectedCharacter;
4440 }
4441 var symbolToMode = {
4442 '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
4443 '[': 'section', ']': 'section',
4444 '*': 'comment', '/': 'comment',
4445 'm': 'method', 'M': 'method',
4446 '#': 'preprocess'
4447 };
4448 var findSymbolModes = {
4449 bracket: {
4450 isComplete: function (state) {
4451 if (state.nextCh === state.symb) {
4452 state.depth++;
4453 if (state.depth >= 1)
4454 return true;
4455 }
4456 else if (state.nextCh === state.reverseSymb) {
4457 state.depth--;
4458 }
4459 return false;
4460 }
4461 },
4462 section: {
4463 init: function (state) {
4464 state.curMoveThrough = true;
4465 state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
4466 },
4467 isComplete: function (state) {
4468 return state.index === 0 && state.nextCh === state.symb;
4469 }
4470 },
4471 comment: {
4472 isComplete: function (state) {
4473 var found = state.lastCh === '*' && state.nextCh === '/';
4474 state.lastCh = state.nextCh;
4475 return found;
4476 }
4477 },
4478 method: {
4479 init: function (state) {
4480 state.symb = (state.symb === 'm' ? '{' : '}');
4481 state.reverseSymb = state.symb === '{' ? '}' : '{';
4482 },
4483 isComplete: function (state) {
4484 if (state.nextCh === state.symb)
4485 return true;
4486 return false;
4487 }
4488 },
4489 preprocess: {
4490 init: function (state) {
4491 state.index = 0;
4492 },
4493 isComplete: function (state) {
4494 if (state.nextCh === '#') {
4495 var token = state.lineText.match(/^#(\w+)/)[1];
4496 if (token === 'endif') {
4497 if (state.forward && state.depth === 0) {
4498 return true;
4499 }
4500 state.depth++;
4501 }
4502 else if (token === 'if') {
4503 if (!state.forward && state.depth === 0) {
4504 return true;
4505 }
4506 state.depth--;
4507 }
4508 if (token === 'else' && state.depth === 0)
4509 return true;
4510 }
4511 return false;
4512 }
4513 }
4514 };
4515 function findSymbol(cm, repeat, forward, symb) {
4516 var cur = copyCursor(cm.getCursor());
4517 var increment = forward ? 1 : -1;
4518 var endLine = forward ? cm.lineCount() : -1;
4519 var curCh = cur.ch;
4520 var line = cur.line;
4521 var lineText = cm.getLine(line);
4522 var state = {
4523 lineText: lineText,
4524 nextCh: lineText.charAt(curCh),
4525 lastCh: null,
4526 index: curCh,
4527 symb: symb,
4528 reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
4529 forward: forward,
4530 depth: 0,
4531 curMoveThrough: false
4532 };
4533 var mode = symbolToMode[symb];
4534 if (!mode)
4535 return cur;
4536 var init = findSymbolModes[mode].init;
4537 var isComplete = findSymbolModes[mode].isComplete;
4538 if (init) {
4539 init(state);
4540 }
4541 while (line !== endLine && repeat) {
4542 state.index += increment;
4543 state.nextCh = state.lineText.charAt(state.index);
4544 if (!state.nextCh) {
4545 line += increment;
4546 state.lineText = cm.getLine(line) || '';
4547 if (increment > 0) {
4548 state.index = 0;
4549 }
4550 else {
4551 var lineLen = state.lineText.length;
4552 state.index = (lineLen > 0) ? (lineLen - 1) : 0;
4553 }
4554 state.nextCh = state.lineText.charAt(state.index);
4555 }
4556 if (isComplete(state)) {
4557 cur.line = line;
4558 cur.ch = state.index;
4559 repeat--;
4560 }
4561 }
4562 if (state.nextCh || state.curMoveThrough) {
4563 return new Pos(line, state.index);
4564 }
4565 return cur;
4566 }
4567 function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
4568 var lineNum = cur.line;
4569 var pos = cur.ch;
4570 var line = cm.getLine(lineNum);
4571 var dir = forward ? 1 : -1;
4572 var charTests = bigWord ? bigWordCharTest : wordCharTest;
4573 if (emptyLineIsWord && line == '') {
4574 lineNum += dir;
4575 line = cm.getLine(lineNum);
4576 if (!isLine(cm, lineNum)) {
4577 return null;
4578 }
4579 pos = (forward) ? 0 : line.length;
4580 }
4581 while (true) {
4582 if (emptyLineIsWord && line == '') {
4583 return { from: 0, to: 0, line: lineNum };
4584 }
4585 var stop = (dir > 0) ? line.length : -1;
4586 var wordStart = stop, wordEnd = stop;
4587 while (pos != stop) {
4588 var foundWord = false;
4589 for (var i = 0; i < charTests.length && !foundWord; ++i) {
4590 if (charTests[i](line.charAt(pos))) {
4591 wordStart = pos;
4592 while (pos != stop && charTests[i](line.charAt(pos))) {
4593 pos += dir;
4594 }
4595 wordEnd = pos;
4596 foundWord = wordStart != wordEnd;
4597 if (wordStart == cur.ch && lineNum == cur.line &&
4598 wordEnd == wordStart + dir) {
4599 continue;
4600 }
4601 else {
4602 return {
4603 from: Math.min(wordStart, wordEnd + 1),
4604 to: Math.max(wordStart, wordEnd),
4605 line: lineNum
4606 };
4607 }
4608 }
4609 }
4610 if (!foundWord) {
4611 pos += dir;
4612 }
4613 }
4614 lineNum += dir;
4615 if (!isLine(cm, lineNum)) {
4616 return null;
4617 }
4618 line = cm.getLine(lineNum);
4619 pos = (dir > 0) ? 0 : line.length;
4620 }
4621 }
4622 function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {
4623 var curStart = copyCursor(cur);
4624 var words = [];
4625 if (forward && !wordEnd || !forward && wordEnd) {
4626 repeat++;
4627 }
4628 var emptyLineIsWord = !(forward && wordEnd);
4629 for (var i = 0; i < repeat; i++) {
4630 var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
4631 if (!word) {
4632 var eodCh = lineLength(cm, cm.lastLine());
4633 words.push(forward
4634 ? { line: cm.lastLine(), from: eodCh, to: eodCh }
4635 : { line: 0, from: 0, to: 0 });
4636 break;
4637 }
4638 words.push(word);
4639 cur = new Pos(word.line, forward ? (word.to - 1) : word.from);
4640 }
4641 var shortCircuit = words.length != repeat;
4642 var firstWord = words[0];
4643 var lastWord = words.pop();
4644 if (forward && !wordEnd) {
4645 if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
4646 lastWord = words.pop();
4647 }
4648 return new Pos(lastWord.line, lastWord.from);
4649 }
4650 else if (forward && wordEnd) {
4651 return new Pos(lastWord.line, lastWord.to - 1);
4652 }
4653 else if (!forward && wordEnd) {
4654 if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
4655 lastWord = words.pop();
4656 }
4657 return new Pos(lastWord.line, lastWord.to);
4658 }
4659 else {
4660 return new Pos(lastWord.line, lastWord.from);
4661 }
4662 }
4663 function moveToEol(cm, head, motionArgs, vim, keepHPos) {
4664 var cur = head;
4665 var retval = new Pos(cur.line + motionArgs.repeat - 1, Infinity);
4666 var end = cm.clipPos(retval);
4667 end.ch--;
4668 if (!keepHPos) {
4669 vim.lastHPos = Infinity;
4670 vim.lastHSPos = cm.charCoords(end, 'div').left;
4671 }
4672 return retval;
4673 }
4674 function moveToCharacter(cm, repeat, forward, character, head) {
4675 var cur = head || cm.getCursor();
4676 var start = cur.ch;
4677 var idx;
4678 for (var i = 0; i < repeat; i++) {
4679 var line = cm.getLine(cur.line);
4680 idx = charIdxInLine(start, line, character, forward, true);
4681 if (idx == -1) {
4682 return null;
4683 }
4684 start = idx;
4685 }
4686 return new Pos(cm.getCursor().line, idx);
4687 }
4688 function moveToColumn(cm, repeat) {
4689 var line = cm.getCursor().line;
4690 return clipCursorToContent(cm, new Pos(line, repeat - 1));
4691 }
4692 function updateMark(cm, vim, markName, pos) {
4693 if (!inArray(markName, validMarks) && !latinCharRegex.test(markName)) {
4694 return;
4695 }
4696 if (vim.marks[markName]) {
4697 vim.marks[markName].clear();
4698 }
4699 vim.marks[markName] = cm.setBookmark(pos);
4700 }
4701 function charIdxInLine(start, line, character, forward, includeChar) {
4702 var idx;
4703 if (forward) {
4704 idx = line.indexOf(character, start + 1);
4705 if (idx != -1 && !includeChar) {
4706 idx -= 1;
4707 }
4708 }
4709 else {
4710 idx = line.lastIndexOf(character, start - 1);
4711 if (idx != -1 && !includeChar) {
4712 idx += 1;
4713 }
4714 }
4715 return idx;
4716 }
4717 function findParagraph(cm, head, repeat, dir, inclusive) {
4718 var line = head.line;
4719 var min = cm.firstLine();
4720 var max = cm.lastLine();
4721 var start, end, i = line;
4722 function isEmpty(i) { return !/\S/.test(cm.getLine(i)); } // ace_patch
4723 function isBoundary(i, dir, any) {
4724 if (any) {
4725 return isEmpty(i) != isEmpty(i + dir);
4726 }
4727 return !isEmpty(i) && isEmpty(i + dir);
4728 }
4729 function skipFold(i) {
4730 dir = dir > 0 ? 1 : -1;
4731 var foldLine = cm.ace.session.getFoldLine(i);
4732 if (foldLine) {
4733 if (i + dir > foldLine.start.row && i + dir < foldLine.end.row)
4734 dir = (dir > 0 ? foldLine.end.row : foldLine.start.row) - i;
4735 }
4736 }
4737 if (dir) {
4738 while (min <= i && i <= max && repeat > 0) {
4739 skipFold(i);
4740 if (isBoundary(i, dir)) {
4741 repeat--;
4742 }
4743 i += dir;
4744 }
4745 return new Pos(i, 0);
4746 }
4747 var vim = cm.state.vim;
4748 if (vim.visualLine && isBoundary(line, 1, true)) {
4749 var anchor = vim.sel.anchor;
4750 if (isBoundary(anchor.line, -1, true)) {
4751 if (!inclusive || anchor.line != line) {
4752 line += 1;
4753 }
4754 }
4755 }
4756 var startState = isEmpty(line);
4757 for (i = line; i <= max && repeat; i++) {
4758 if (isBoundary(i, 1, true)) {
4759 if (!inclusive || isEmpty(i) != startState) {
4760 repeat--;
4761 }
4762 }
4763 }
4764 end = new Pos(i, 0);
4765 if (i > max && !startState) {
4766 startState = true;
4767 }
4768 else {
4769 inclusive = false;
4770 }
4771 for (i = line; i > min; i--) {
4772 if (!inclusive || isEmpty(i) == startState || i == line) {
4773 if (isBoundary(i, -1, true)) {
4774 break;
4775 }
4776 }
4777 }
4778 start = new Pos(i, 0);
4779 return { start: start, end: end };
4780 }
4781 function getSentence(cm, cur, repeat, dir, inclusive /*includes whitespace*/) {
4782 function nextChar(curr) {
4783 if (curr.pos + curr.dir < 0 || curr.pos + curr.dir >= curr.line.length) {
4784 curr.line = null;
4785 }
4786 else {
4787 curr.pos += curr.dir;
4788 }
4789 }
4790 function forward(cm, ln, pos, dir) {
4791 var line = cm.getLine(ln);
4792 var curr = {
4793 line: line,
4794 ln: ln,
4795 pos: pos,
4796 dir: dir,
4797 };
4798 if (curr.line === "") {
4799 return { ln: curr.ln, pos: curr.pos };
4800 }
4801 var lastSentencePos = curr.pos;
4802 nextChar(curr);
4803 while (curr.line !== null) {
4804 lastSentencePos = curr.pos;
4805 if (isEndOfSentenceSymbol(curr.line[curr.pos])) {
4806 if (!inclusive) {
4807 return { ln: curr.ln, pos: curr.pos + 1 };
4808 }
4809 else {
4810 nextChar(curr);
4811 while (curr.line !== null) {
4812 if (isWhiteSpaceString(curr.line[curr.pos])) {
4813 lastSentencePos = curr.pos;
4814 nextChar(curr);
4815 }
4816 else {
4817 break;
4818 }
4819 }
4820 return { ln: curr.ln, pos: lastSentencePos + 1 };
4821 }
4822 }
4823 nextChar(curr);
4824 }
4825 return { ln: curr.ln, pos: lastSentencePos + 1 };
4826 }
4827 function reverse(cm, ln, pos, dir) {
4828 var line = cm.getLine(ln);
4829 var curr = {
4830 line: line,
4831 ln: ln,
4832 pos: pos,
4833 dir: dir,
4834 };
4835 if (curr.line === "") {
4836 return { ln: curr.ln, pos: curr.pos };
4837 }
4838 var lastSentencePos = curr.pos;
4839 nextChar(curr);
4840 while (curr.line !== null) {
4841 if (!isWhiteSpaceString(curr.line[curr.pos]) && !isEndOfSentenceSymbol(curr.line[curr.pos])) {
4842 lastSentencePos = curr.pos;
4843 }
4844 else if (isEndOfSentenceSymbol(curr.line[curr.pos])) {
4845 if (!inclusive) {
4846 return { ln: curr.ln, pos: lastSentencePos };
4847 }
4848 else {
4849 if (isWhiteSpaceString(curr.line[curr.pos + 1])) {
4850 return { ln: curr.ln, pos: curr.pos + 1 };
4851 }
4852 else {
4853 return { ln: curr.ln, pos: lastSentencePos };
4854 }
4855 }
4856 }
4857 nextChar(curr);
4858 }
4859 curr.line = line;
4860 if (inclusive && isWhiteSpaceString(curr.line[curr.pos])) {
4861 return { ln: curr.ln, pos: curr.pos };
4862 }
4863 else {
4864 return { ln: curr.ln, pos: lastSentencePos };
4865 }
4866 }
4867 var curr_index = {
4868 ln: cur.line,
4869 pos: cur.ch,
4870 };
4871 while (repeat > 0) {
4872 if (dir < 0) {
4873 curr_index = reverse(cm, curr_index.ln, curr_index.pos, dir);
4874 }
4875 else {
4876 curr_index = forward(cm, curr_index.ln, curr_index.pos, dir);
4877 }
4878 repeat--;
4879 }
4880 return new Pos(curr_index.ln, curr_index.pos);
4881 }
4882 function findSentence(cm, cur, repeat, dir) {
4883 function nextChar(cm, idx) {
4884 if (idx.pos + idx.dir < 0 || idx.pos + idx.dir >= idx.line.length) {
4885 idx.ln += idx.dir;
4886 if (!isLine(cm, idx.ln)) {
4887 idx.line = null;
4888 idx.ln = null;
4889 idx.pos = null;
4890 return;
4891 }
4892 idx.line = cm.getLine(idx.ln);
4893 idx.pos = (idx.dir > 0) ? 0 : idx.line.length - 1;
4894 }
4895 else {
4896 idx.pos += idx.dir;
4897 }
4898 }
4899 function forward(cm, ln, pos, dir) {
4900 var line = cm.getLine(ln);
4901 var stop = (line === "");
4902 var curr = {
4903 line: line,
4904 ln: ln,
4905 pos: pos,
4906 dir: dir,
4907 };
4908 var last_valid = {
4909 ln: curr.ln,
4910 pos: curr.pos,
4911 };
4912 var skip_empty_lines = (curr.line === "");
4913 nextChar(cm, curr);
4914 while (curr.line !== null) {
4915 last_valid.ln = curr.ln;
4916 last_valid.pos = curr.pos;
4917 if (curr.line === "" && !skip_empty_lines) {
4918 return { ln: curr.ln, pos: curr.pos, };
4919 }
4920 else if (stop && curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
4921 return { ln: curr.ln, pos: curr.pos, };
4922 }
4923 else if (isEndOfSentenceSymbol(curr.line[curr.pos])
4924 && !stop
4925 && (curr.pos === curr.line.length - 1
4926 || isWhiteSpaceString(curr.line[curr.pos + 1]))) {
4927 stop = true;
4928 }
4929 nextChar(cm, curr);
4930 }
4931 var line = cm.getLine(last_valid.ln);
4932 last_valid.pos = 0;
4933 for (var i = line.length - 1; i >= 0; --i) {
4934 if (!isWhiteSpaceString(line[i])) {
4935 last_valid.pos = i;
4936 break;
4937 }
4938 }
4939 return last_valid;
4940 }
4941 function reverse(cm, ln, pos, dir) {
4942 var line = cm.getLine(ln);
4943 var curr = {
4944 line: line,
4945 ln: ln,
4946 pos: pos,
4947 dir: dir,
4948 };
4949 var last_valid = {
4950 ln: curr.ln,
4951 pos: null,
4952 };
4953 var skip_empty_lines = (curr.line === "");
4954 nextChar(cm, curr);
4955 while (curr.line !== null) {
4956 if (curr.line === "" && !skip_empty_lines) {
4957 if (last_valid.pos !== null) {
4958 return last_valid;
4959 }
4960 else {
4961 return { ln: curr.ln, pos: curr.pos };
4962 }
4963 }
4964 else if (isEndOfSentenceSymbol(curr.line[curr.pos])
4965 && last_valid.pos !== null
4966 && !(curr.ln === last_valid.ln && curr.pos + 1 === last_valid.pos)) {
4967 return last_valid;
4968 }
4969 else if (curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
4970 skip_empty_lines = false;
4971 last_valid = { ln: curr.ln, pos: curr.pos };
4972 }
4973 nextChar(cm, curr);
4974 }
4975 var line = cm.getLine(last_valid.ln);
4976 last_valid.pos = 0;
4977 for (var i = 0; i < line.length; ++i) {
4978 if (!isWhiteSpaceString(line[i])) {
4979 last_valid.pos = i;
4980 break;
4981 }
4982 }
4983 return last_valid;
4984 }
4985 var curr_index = {
4986 ln: cur.line,
4987 pos: cur.ch,
4988 };
4989 while (repeat > 0) {
4990 if (dir < 0) {
4991 curr_index = reverse(cm, curr_index.ln, curr_index.pos, dir);
4992 }
4993 else {
4994 curr_index = forward(cm, curr_index.ln, curr_index.pos, dir);
4995 }
4996 repeat--;
4997 }
4998 return new Pos(curr_index.ln, curr_index.pos);
4999 }
5000 function selectCompanionObject(cm, head, symb, inclusive) {
5001 var cur = head, start, end;
5002 var bracketRegexp = ({
5003 '(': /[()]/, ')': /[()]/,
5004 '[': /[[\]]/, ']': /[[\]]/,
5005 '{': /[{}]/, '}': /[{}]/,
5006 '<': /[<>]/, '>': /[<>]/
5007 })[symb];
5008 var openSym = ({
5009 '(': '(', ')': '(',
5010 '[': '[', ']': '[',
5011 '{': '{', '}': '{',
5012 '<': '<', '>': '<'
5013 })[symb];
5014 var curChar = cm.getLine(cur.line).charAt(cur.ch);
5015 var offset = curChar === openSym ? 1 : 0;
5016 start = cm.scanForBracket(new Pos(cur.line, cur.ch + offset), -1, undefined, { 'bracketRegex': bracketRegexp });
5017 end = cm.scanForBracket(new Pos(cur.line, cur.ch + offset), 1, undefined, { 'bracketRegex': bracketRegexp });
5018 if (!start || !end)
5019 return null;
5020 start = start.pos;
5021 end = end.pos;
5022 if ((start.line == end.line && start.ch > end.ch)
5023 || (start.line > end.line)) {
5024 var tmp = start;
5025 start = end;
5026 end = tmp;
5027 }
5028 if (inclusive) {
5029 end.ch += 1;
5030 }
5031 else {
5032 start.ch += 1;
5033 }
5034 return { start: start, end: end };
5035 }
5036 function findBeginningAndEnd(cm, head, symb, inclusive) {
5037 var cur = copyCursor(head);
5038 var line = cm.getLine(cur.line);
5039 var chars = line.split('');
5040 var start, end, i, len;
5041 var firstIndex = chars.indexOf(symb);
5042 if (cur.ch < firstIndex) {
5043 cur.ch = firstIndex;
5044 }
5045 else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
5046 var stringAfter = /string/.test(cm.getTokenTypeAt(offsetCursor(head, 0, 1)));
5047 var stringBefore = /string/.test(cm.getTokenTypeAt(head));
5048 var isStringStart = stringAfter && !stringBefore;
5049 if (!isStringStart) {
5050 end = cur.ch; // assign end to the current cursor
5051 --cur.ch; // make sure to look backwards
5052 }
5053 }
5054 if (chars[cur.ch] == symb && !end) {
5055 start = cur.ch + 1; // assign start to ahead of the cursor
5056 }
5057 else {
5058 for (i = cur.ch; i > -1 && !start; i--) {
5059 if (chars[i] == symb) {
5060 start = i + 1;
5061 }
5062 }
5063 }
5064 if (start && !end) {
5065 for (i = start, len = chars.length; i < len && !end; i++) {
5066 if (chars[i] == symb) {
5067 end = i;
5068 }
5069 }
5070 }
5071 if (!start || !end) {
5072 return { start: cur, end: cur };
5073 }
5074 if (inclusive) {
5075 --start;
5076 ++end;
5077 }
5078 return {
5079 start: new Pos(cur.line, start),
5080 end: new Pos(cur.line, end)
5081 };
5082 }
5083 defineOption('pcre', true, 'boolean');
5084 function SearchState() { }
5085 SearchState.prototype = {
5086 getQuery: function () {
5087 return vimGlobalState.query;
5088 },
5089 setQuery: function (query) {
5090 vimGlobalState.query = query;
5091 },
5092 getOverlay: function () {
5093 return this.searchOverlay;
5094 },
5095 setOverlay: function (overlay) {
5096 this.searchOverlay = overlay;
5097 },
5098 isReversed: function () {
5099 return vimGlobalState.isReversed;
5100 },
5101 setReversed: function (reversed) {
5102 vimGlobalState.isReversed = reversed;
5103 },
5104 getScrollbarAnnotate: function () {
5105 return this.annotate;
5106 },
5107 setScrollbarAnnotate: function (annotate) {
5108 this.annotate = annotate;
5109 }
5110 };
5111 function getSearchState(cm) {
5112 var vim = cm.state.vim;
5113 return vim.searchState_ || (vim.searchState_ = new SearchState());
5114 }
5115 function splitBySlash(argString) {
5116 return splitBySeparator(argString, '/');
5117 }
5118 function findUnescapedSlashes(argString) {
5119 return findUnescapedSeparators(argString, '/');
5120 }
5121 function splitBySeparator(argString, separator) {
5122 var slashes = findUnescapedSeparators(argString, separator) || [];
5123 if (!slashes.length)
5124 return [];
5125 var tokens = [];
5126 if (slashes[0] !== 0)
5127 return;
5128 for (var i = 0; i < slashes.length; i++) {
5129 if (typeof slashes[i] == 'number')
5130 tokens.push(argString.substring(slashes[i] + 1, slashes[i + 1]));
5131 }
5132 return tokens;
5133 }
5134 function findUnescapedSeparators(str, separator) {
5135 if (!separator)
5136 separator = '/';
5137 var escapeNextChar = false;
5138 var slashes = [];
5139 for (var i = 0; i < str.length; i++) {
5140 var c = str.charAt(i);
5141 if (!escapeNextChar && c == separator) {
5142 slashes.push(i);
5143 }
5144 escapeNextChar = !escapeNextChar && (c == '\\');
5145 }
5146 return slashes;
5147 }
5148 function translateRegex(str) {
5149 var specials = '|(){';
5150 var unescape = '}';
5151 var escapeNextChar = false;
5152 var out = [];
5153 for (var i = -1; i < str.length; i++) {
5154 var c = str.charAt(i) || '';
5155 var n = str.charAt(i + 1) || '';
5156 var specialComesNext = (n && specials.indexOf(n) != -1);
5157 if (escapeNextChar) {
5158 if (c !== '\\' || !specialComesNext) {
5159 out.push(c);
5160 }
5161 escapeNextChar = false;
5162 }
5163 else {
5164 if (c === '\\') {
5165 escapeNextChar = true;
5166 if (n && unescape.indexOf(n) != -1) {
5167 specialComesNext = true;
5168 }
5169 if (!specialComesNext || n === '\\') {
5170 out.push(c);
5171 }
5172 }
5173 else {
5174 out.push(c);
5175 if (specialComesNext && n !== '\\') {
5176 out.push('\\');
5177 }
5178 }
5179 }
5180 }
5181 return out.join('');
5182 }
5183 var charUnescapes = { '\\n': '\n', '\\r': '\r', '\\t': '\t' };
5184 function translateRegexReplace(str) {
5185 var escapeNextChar = false;
5186 var out = [];
5187 for (var i = -1; i < str.length; i++) {
5188 var c = str.charAt(i) || '';
5189 var n = str.charAt(i + 1) || '';
5190 if (charUnescapes[c + n]) {
5191 out.push(charUnescapes[c + n]);
5192 i++;
5193 }
5194 else if (escapeNextChar) {
5195 out.push(c);
5196 escapeNextChar = false;
5197 }
5198 else {
5199 if (c === '\\') {
5200 escapeNextChar = true;
5201 if ((isNumber(n) || n === '$')) {
5202 out.push('$');
5203 }
5204 else if (n !== '/' && n !== '\\') {
5205 out.push('\\');
5206 }
5207 }
5208 else {
5209 if (c === '$') {
5210 out.push('$');
5211 }
5212 out.push(c);
5213 if (n === '/') {
5214 out.push('\\');
5215 }
5216 }
5217 }
5218 }
5219 return out.join('');
5220 }
5221 var unescapes = { '\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t', '\\&': '&' };
5222 function unescapeRegexReplace(str) {
5223 var stream = new CodeMirror.StringStream(str);
5224 var output = [];
5225 while (!stream.eol()) {
5226 while (stream.peek() && stream.peek() != '\\') {
5227 output.push(stream.next());
5228 }
5229 var matched = false;
5230 for (var matcher in unescapes) {
5231 if (stream.match(matcher, true)) {
5232 matched = true;
5233 output.push(unescapes[matcher]);
5234 break;
5235 }
5236 }
5237 if (!matched) {
5238 output.push(stream.next());
5239 }
5240 }
5241 return output.join('');
5242 }
5243 function parseQuery(query, ignoreCase, smartCase) {
5244 var lastSearchRegister = vimGlobalState.registerController.getRegister('/');
5245 lastSearchRegister.setText(query);
5246 if (query instanceof RegExp) {
5247 return query;
5248 }
5249 var slashes = findUnescapedSlashes(query);
5250 var regexPart;
5251 var forceIgnoreCase;
5252 if (!slashes.length) {
5253 regexPart = query;
5254 }
5255 else {
5256 regexPart = query.substring(0, slashes[0]);
5257 var flagsPart = query.substring(slashes[0]);
5258 forceIgnoreCase = (flagsPart.indexOf('i') != -1);
5259 }
5260 if (!regexPart) {
5261 return null;
5262 }
5263 if (!getOption('pcre')) {
5264 regexPart = translateRegex(regexPart);
5265 }
5266 if (smartCase) {
5267 ignoreCase = (/^[^A-Z]*$/).test(regexPart);
5268 }
5269 var regexp = new RegExp(regexPart, (ignoreCase || forceIgnoreCase) ? 'im' : 'm');
5270 return regexp;
5271 }
5272 function dom(n) {
5273 if (typeof n === 'string')
5274 n = document.createElement(n);
5275 for (var a, i = 1; i < arguments.length; i++) {
5276 if (!(a = arguments[i]))
5277 continue;
5278 if (typeof a !== 'object')
5279 a = document.createTextNode(a);
5280 if (a.nodeType)
5281 n.appendChild(a);
5282 else
5283 for (var key in a) {
5284 if (!Object.prototype.hasOwnProperty.call(a, key))
5285 continue;
5286 if (key[0] === '$')
5287 n.style[key.slice(1)] = a[key];
5288 else
5289 n.setAttribute(key, a[key]);
5290 }
5291 }
5292 return n;
5293 }
5294 function showConfirm(cm, template) {
5295 var pre = dom('div', { $color: 'red', $whiteSpace: 'pre', class: 'cm-vim-message' }, template);
5296 if (cm.openNotification) {
5297 cm.openNotification(pre, { bottom: true, duration: 5000 });
5298 }
5299 else {
5300 alert(pre.innerText);
5301 }
5302 }
5303 function makePrompt(prefix, desc) {
5304 return dom('div', { $display: 'flex' }, dom('span', { $fontFamily: 'monospace', $whiteSpace: 'pre', $flex: 1 }, prefix, dom('input', { type: 'text', autocorrect: 'off',
5305 autocapitalize: 'off', spellcheck: 'false', $width: '100%' })), desc && dom('span', { $color: '#888' }, desc));
5306 }
5307 function showPrompt(cm, options) {
5308 if (keyToKeyStack.length) {
5309 if (!options.value)
5310 options.value = '';
5311 virtualPrompt = options;
5312 return;
5313 }
5314 var template = makePrompt(options.prefix, options.desc);
5315 if (cm.openDialog) {
5316 cm.openDialog(template, options.onClose, {
5317 onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp,
5318 bottom: true, selectValueOnOpen: false, value: options.value
5319 });
5320 }
5321 else {
5322 var shortText = '';
5323 if (typeof options.prefix != "string" && options.prefix)
5324 shortText += options.prefix.textContent;
5325 if (options.desc)
5326 shortText += " " + options.desc;
5327 options.onClose(prompt(shortText, ''));
5328 }
5329 }
5330 function regexEqual(r1, r2) {
5331 if (r1 instanceof RegExp && r2 instanceof RegExp) {
5332 var props = ['global', 'multiline', 'ignoreCase', 'source'];
5333 for (var i = 0; i < props.length; i++) {
5334 var prop = props[i];
5335 if (r1[prop] !== r2[prop]) {
5336 return false;
5337 }
5338 }
5339 return true;
5340 }
5341 return false;
5342 }
5343 function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
5344 if (!rawQuery) {
5345 return;
5346 }
5347 var state = getSearchState(cm);
5348 var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
5349 if (!query) {
5350 return;
5351 }
5352 highlightSearchMatches(cm, query);
5353 if (regexEqual(query, state.getQuery())) {
5354 return query;
5355 }
5356 state.setQuery(query);
5357 return query;
5358 }
5359 function searchOverlay(query) {
5360 if (query.source.charAt(0) == '^') {
5361 var matchSol = true;
5362 }
5363 return {
5364 token: function (stream) {
5365 if (matchSol && !stream.sol()) {
5366 stream.skipToEnd();
5367 return;
5368 }
5369 var match = stream.match(query, false);
5370 if (match) {
5371 if (match[0].length == 0) {
5372 stream.next();
5373 return 'searching';
5374 }
5375 if (!stream.sol()) {
5376 stream.backUp(1);
5377 if (!query.exec(stream.next() + match[0])) {
5378 stream.next();
5379 return null;
5380 }
5381 }
5382 stream.match(query);
5383 return 'searching';
5384 }
5385 while (!stream.eol()) {
5386 stream.next();
5387 if (stream.match(query, false))
5388 break;
5389 }
5390 },
5391 query: query
5392 };
5393 }
5394 var highlightTimeout = 0;
5395 function highlightSearchMatches(cm, query) {
5396 clearTimeout(highlightTimeout);
5397 var searchState = getSearchState(cm);
5398 searchState.highlightTimeout = highlightTimeout;
5399 highlightTimeout = setTimeout(function () {
5400 if (!cm.state.vim)
5401 return;
5402 var searchState = getSearchState(cm);
5403 searchState.highlightTimeout = null;
5404 var overlay = searchState.getOverlay();
5405 if (!overlay || query != overlay.query) {
5406 if (overlay) {
5407 cm.removeOverlay(overlay);
5408 }
5409 overlay = searchOverlay(query);
5410 cm.addOverlay(overlay);
5411 if (cm.showMatchesOnScrollbar) {
5412 if (searchState.getScrollbarAnnotate()) {
5413 searchState.getScrollbarAnnotate().clear();
5414 }
5415 searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query));
5416 }
5417 searchState.setOverlay(overlay);
5418 }
5419 }, 50);
5420 }
5421 function findNext(cm, prev, query, repeat) {
5422 if (repeat === undefined) {
5423 repeat = 1;
5424 }
5425 return cm.operation(function () {
5426 var pos = cm.getCursor();
5427 var cursor = cm.getSearchCursor(query, pos);
5428 for (var i = 0; i < repeat; i++) {
5429 var found = cursor.find(prev);
5430 if (i == 0 && found && cursorEqual(cursor.from(), pos)) {
5431 var lastEndPos = prev ? cursor.from() : cursor.to();
5432 found = cursor.find(prev);
5433 if (found && !found[0] && cursorEqual(cursor.from(), lastEndPos)) {
5434 if (cm.getLine(lastEndPos.line).length == lastEndPos.ch)
5435 found = cursor.find(prev);
5436 }
5437 }
5438 if (!found) {
5439 cursor = cm.getSearchCursor(query, (prev) ? new Pos(cm.lastLine()) : new Pos(cm.firstLine(), 0));
5440 if (!cursor.find(prev)) {
5441 return;
5442 }
5443 }
5444 }
5445 return cursor.from();
5446 });
5447 }
5448 function findNextFromAndToInclusive(cm, prev, query, repeat, vim) {
5449 if (repeat === undefined) {
5450 repeat = 1;
5451 }
5452 return cm.operation(function () {
5453 var pos = cm.getCursor();
5454 var cursor = cm.getSearchCursor(query, pos);
5455 var found = cursor.find(!prev);
5456 if (!vim.visualMode && found && cursorEqual(cursor.from(), pos)) {
5457 cursor.find(!prev);
5458 }
5459 for (var i = 0; i < repeat; i++) {
5460 found = cursor.find(prev);
5461 if (!found) {
5462 cursor = cm.getSearchCursor(query, (prev) ? new Pos(cm.lastLine()) : new Pos(cm.firstLine(), 0));
5463 if (!cursor.find(prev)) {
5464 return;
5465 }
5466 }
5467 }
5468 return [cursor.from(), cursor.to()];
5469 });
5470 }
5471 function clearSearchHighlight(cm) {
5472 var state = getSearchState(cm);
5473 if (state.highlightTimeout) {
5474 clearTimeout(state.highlightTimeout);
5475 state.highlightTimeout = null;
5476 }
5477 cm.removeOverlay(getSearchState(cm).getOverlay());
5478 state.setOverlay(null);
5479 if (state.getScrollbarAnnotate()) {
5480 state.getScrollbarAnnotate().clear();
5481 state.setScrollbarAnnotate(null);
5482 }
5483 }
5484 function isInRange(pos, start, end) {
5485 if (typeof pos != 'number') {
5486 pos = pos.line;
5487 }
5488 if (start instanceof Array) {
5489 return inArray(pos, start);
5490 }
5491 else {
5492 if (typeof end == 'number') {
5493 return (pos >= start && pos <= end);
5494 }
5495 else {
5496 return pos == start;
5497 }
5498 }
5499 }
5500 function getUserVisibleLines(cm) {
5501 var renderer = cm.ace.renderer;
5502 return {
5503 top: renderer.getFirstFullyVisibleRow(),
5504 bottom: renderer.getLastFullyVisibleRow()
5505 };
5506 }
5507 function getMarkPos(cm, vim, markName) {
5508 if (markName == '\'' || markName == '`') {
5509 return vimGlobalState.jumpList.find(cm, -1) || new Pos(0, 0);
5510 }
5511 else if (markName == '.') {
5512 return getLastEditPos(cm);
5513 }
5514 var mark = vim.marks[markName];
5515 return mark && mark.find();
5516 }
5517 function getLastEditPos(cm) {
5518 if (cm.getLastEditEnd) {
5519 return cm.getLastEditEnd();
5520 }
5521 var done = cm.doc.history.done;
5522 for (var i = done.length; i--;) {
5523 if (done[i].changes) {
5524 return copyCursor(done[i].changes[0].to);
5525 }
5526 }
5527 }
5528 var ExCommandDispatcher = function () {
5529 this.buildCommandMap_();
5530 };
5531 ExCommandDispatcher.prototype = {
5532 processCommand: function (cm, input, opt_params) {
5533 var that = this;
5534 cm.operation(function () {
5535 cm.curOp.isVimOp = true;
5536 that._processCommand(cm, input, opt_params);
5537 });
5538 },
5539 _processCommand: function (cm, input, opt_params) {
5540 var vim = cm.state.vim;
5541 var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');
5542 var previousCommand = commandHistoryRegister.toString();
5543 var inputStream = new CodeMirror.StringStream(input);
5544 commandHistoryRegister.setText(input);
5545 var params = opt_params || {};
5546 params.input = input;
5547 try {
5548 this.parseInput_(cm, inputStream, params);
5549 }
5550 catch (e) {
5551 showConfirm(cm, e.toString());
5552 throw e;
5553 }
5554 if (vim.visualMode) {
5555 exitVisualMode(cm);
5556 }
5557 var command;
5558 var commandName;
5559 if (!params.commandName) {
5560 if (params.line !== undefined) {
5561 commandName = 'move';
5562 }
5563 }
5564 else {
5565 command = this.matchCommand_(params.commandName);
5566 if (command) {
5567 commandName = command.name;
5568 if (command.excludeFromCommandHistory) {
5569 commandHistoryRegister.setText(previousCommand);
5570 }
5571 this.parseCommandArgs_(inputStream, params, command);
5572 if (command.type == 'exToKey') {
5573 doKeyToKey(cm, command.toKeys, command);
5574 return;
5575 }
5576 else if (command.type == 'exToEx') {
5577 this.processCommand(cm, command.toInput);
5578 return;
5579 }
5580 }
5581 }
5582 if (!commandName) {
5583 showConfirm(cm, 'Not an editor command ":' + input + '"');
5584 return;
5585 }
5586 try {
5587 exCommands[commandName](cm, params);
5588 if ((!command || !command.possiblyAsync) && params.callback) {
5589 params.callback();
5590 }
5591 }
5592 catch (e) {
5593 showConfirm(cm, e.toString());
5594 throw e;
5595 }
5596 },
5597 parseInput_: function (cm, inputStream, result) {
5598 inputStream.eatWhile(':');
5599 if (inputStream.eat('%')) {
5600 result.line = cm.firstLine();
5601 result.lineEnd = cm.lastLine();
5602 }
5603 else {
5604 result.line = this.parseLineSpec_(cm, inputStream);
5605 if (result.line !== undefined && inputStream.eat(',')) {
5606 result.lineEnd = this.parseLineSpec_(cm, inputStream);
5607 }
5608 }
5609 if (result.line == undefined) {
5610 if (cm.state.vim.visualMode) {
5611 var pos = getMarkPos(cm, cm.state.vim, '<');
5612 result.selectionLine = pos && pos.line;
5613 pos = getMarkPos(cm, cm.state.vim, '>');
5614 result.selectionLineEnd = pos && pos.line;
5615 }
5616 else {
5617 result.selectionLine = cm.getCursor().line;
5618 }
5619 }
5620 else {
5621 result.selectionLine = result.line;
5622 result.selectionLineEnd = result.lineEnd;
5623 }
5624 var commandMatch = inputStream.match(/^(\w+|!!|@@|[!#&*<=>@~])/);
5625 if (commandMatch) {
5626 result.commandName = commandMatch[1];
5627 }
5628 else {
5629 result.commandName = inputStream.match(/.*/)[0];
5630 }
5631 return result;
5632 },
5633 parseLineSpec_: function (cm, inputStream) {
5634 var numberMatch = inputStream.match(/^(\d+)/);
5635 if (numberMatch) {
5636 return parseInt(numberMatch[1], 10) - 1;
5637 }
5638 switch (inputStream.next()) {
5639 case '.':
5640 return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
5641 case '$':
5642 return this.parseLineSpecOffset_(inputStream, cm.lastLine());
5643 case '\'':
5644 var markName = inputStream.next();
5645 var markPos = getMarkPos(cm, cm.state.vim, markName);
5646 if (!markPos)
5647 throw new Error('Mark not set');
5648 return this.parseLineSpecOffset_(inputStream, markPos.line);
5649 case '-':
5650 case '+':
5651 inputStream.backUp(1);
5652 return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
5653 default:
5654 inputStream.backUp(1);
5655 return undefined;
5656 }
5657 },
5658 parseLineSpecOffset_: function (inputStream, line) {
5659 var offsetMatch = inputStream.match(/^([+-])?(\d+)/);
5660 if (offsetMatch) {
5661 var offset = parseInt(offsetMatch[2], 10);
5662 if (offsetMatch[1] == "-") {
5663 line -= offset;
5664 }
5665 else {
5666 line += offset;
5667 }
5668 }
5669 return line;
5670 },
5671 parseCommandArgs_: function (inputStream, params, command) {
5672 if (inputStream.eol()) {
5673 return;
5674 }
5675 params.argString = inputStream.match(/.*/)[0];
5676 var delim = command.argDelimiter || /\s+/;
5677 var args = trim(params.argString).split(delim);
5678 if (args.length && args[0]) {
5679 params.args = args;
5680 }
5681 },
5682 matchCommand_: function (commandName) {
5683 for (var i = commandName.length; i > 0; i--) {
5684 var prefix = commandName.substring(0, i);
5685 if (this.commandMap_[prefix]) {
5686 var command = this.commandMap_[prefix];
5687 if (command.name.indexOf(commandName) === 0) {
5688 return command;
5689 }
5690 }
5691 }
5692 return null;
5693 },
5694 buildCommandMap_: function () {
5695 this.commandMap_ = {};
5696 for (var i = 0; i < defaultExCommandMap.length; i++) {
5697 var command = defaultExCommandMap[i];
5698 var key = command.shortName || command.name;
5699 this.commandMap_[key] = command;
5700 }
5701 },
5702 map: function (lhs, rhs, ctx, noremap) {
5703 if (lhs != ':' && lhs.charAt(0) == ':') {
5704 if (ctx) {
5705 throw Error('Mode not supported for ex mappings');
5706 }
5707 var commandName = lhs.substring(1);
5708 if (rhs != ':' && rhs.charAt(0) == ':') {
5709 this.commandMap_[commandName] = {
5710 name: commandName,
5711 type: 'exToEx',
5712 toInput: rhs.substring(1),
5713 user: true
5714 };
5715 }
5716 else {
5717 this.commandMap_[commandName] = {
5718 name: commandName,
5719 type: 'exToKey',
5720 toKeys: rhs,
5721 user: true
5722 };
5723 }
5724 }
5725 else {
5726 var mapping = {
5727 keys: lhs,
5728 type: 'keyToKey',
5729 toKeys: rhs,
5730 noremap: !!noremap
5731 };
5732 if (ctx) {
5733 mapping.context = ctx;
5734 }
5735 defaultKeymap.unshift(mapping);
5736 }
5737 },
5738 unmap: function (lhs, ctx) {
5739 if (lhs != ':' && lhs.charAt(0) == ':') {
5740 if (ctx) {
5741 throw Error('Mode not supported for ex mappings');
5742 }
5743 var commandName = lhs.substring(1);
5744 if (this.commandMap_[commandName] && this.commandMap_[commandName].user) {
5745 delete this.commandMap_[commandName];
5746 return true;
5747 }
5748 }
5749 else {
5750 var keys = lhs;
5751 for (var i = 0; i < defaultKeymap.length; i++) {
5752 if (keys == defaultKeymap[i].keys
5753 && defaultKeymap[i].context === ctx) {
5754 defaultKeymap.splice(i, 1);
5755 return true;
5756 }
5757 }
5758 }
5759 }
5760 };
5761 var exCommands = {
5762 colorscheme: function (cm, params) {
5763 if (!params.args || params.args.length < 1) {
5764 showConfirm(cm, cm.getOption('theme'));
5765 return;
5766 }
5767 cm.setOption('theme', params.args[0]);
5768 },
5769 map: function (cm, params, ctx, defaultOnly) {
5770 var mapArgs = params.args;
5771 if (!mapArgs || mapArgs.length < 2) {
5772 if (cm) {
5773 showConfirm(cm, 'Invalid mapping: ' + params.input);
5774 }
5775 return;
5776 }
5777 exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx, defaultOnly);
5778 },
5779 imap: function (cm, params) { this.map(cm, params, 'insert'); },
5780 nmap: function (cm, params) { this.map(cm, params, 'normal'); },
5781 vmap: function (cm, params) { this.map(cm, params, 'visual'); },
5782 omap: function (cm, params) { this.map(cm, params, 'operatorPending'); },
5783 noremap: function (cm, params) { this.map(cm, params, undefined, true); },
5784 inoremap: function (cm, params) { this.map(cm, params, 'insert', true); },
5785 nnoremap: function (cm, params) { this.map(cm, params, 'normal', true); },
5786 vnoremap: function (cm, params) { this.map(cm, params, 'visual', true); },
5787 onoremap: function (cm, params) { this.map(cm, params, 'operatorPending', true); },
5788 unmap: function (cm, params, ctx) {
5789 var mapArgs = params.args;
5790 if (!mapArgs || mapArgs.length < 1 || !exCommandDispatcher.unmap(mapArgs[0], ctx)) {
5791 if (cm) {
5792 showConfirm(cm, 'No such mapping: ' + params.input);
5793 }
5794 }
5795 },
5796 mapclear: function (cm, params) { vimApi.mapclear(); },
5797 imapclear: function (cm, params) { vimApi.mapclear('insert'); },
5798 nmapclear: function (cm, params) { vimApi.mapclear('normal'); },
5799 vmapclear: function (cm, params) { vimApi.mapclear('visual'); },
5800 omapclear: function (cm, params) { vimApi.mapclear('operatorPending'); },
5801 move: function (cm, params) {
5802 commandDispatcher.processCommand(cm, cm.state.vim, {
5803 type: 'motion',
5804 motion: 'moveToLineOrEdgeOfDocument',
5805 motionArgs: { forward: false, explicitRepeat: true,
5806 linewise: true },
5807 repeatOverride: params.line + 1
5808 });
5809 },
5810 set: function (cm, params) {
5811 var setArgs = params.args;
5812 var setCfg = params.setCfg || {};
5813 if (!setArgs || setArgs.length < 1) {
5814 if (cm) {
5815 showConfirm(cm, 'Invalid mapping: ' + params.input);
5816 }
5817 return;
5818 }
5819 var expr = setArgs[0].split('=');
5820 var optionName = expr[0];
5821 var value = expr[1];
5822 var forceGet = false;
5823 var forceToggle = false;
5824 if (optionName.charAt(optionName.length - 1) == '?') {
5825 if (value) {
5826 throw Error('Trailing characters: ' + params.argString);
5827 }
5828 optionName = optionName.substring(0, optionName.length - 1);
5829 forceGet = true;
5830 }
5831 else if (optionName.charAt(optionName.length - 1) == '!') {
5832 optionName = optionName.substring(0, optionName.length - 1);
5833 forceToggle = true;
5834 }
5835 if (value === undefined && optionName.substring(0, 2) == 'no') {
5836 optionName = optionName.substring(2);
5837 value = false;
5838 }
5839 var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';
5840 if (optionIsBoolean) {
5841 if (forceToggle) {
5842 value = !getOption(optionName, cm, setCfg);
5843 }
5844 else if (value == undefined) {
5845 value = true;
5846 }
5847 }
5848 if (!optionIsBoolean && value === undefined || forceGet) {
5849 var oldValue = getOption(optionName, cm, setCfg);
5850 if (oldValue instanceof Error) {
5851 showConfirm(cm, oldValue.message);
5852 }
5853 else if (oldValue === true || oldValue === false) {
5854 showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName);
5855 }
5856 else {
5857 showConfirm(cm, ' ' + optionName + '=' + oldValue);
5858 }
5859 }
5860 else {
5861 var setOptionReturn = setOption(optionName, value, cm, setCfg);
5862 if (setOptionReturn instanceof Error) {
5863 showConfirm(cm, setOptionReturn.message);
5864 }
5865 }
5866 },
5867 setlocal: function (cm, params) {
5868 params.setCfg = { scope: 'local' };
5869 this.set(cm, params);
5870 },
5871 setglobal: function (cm, params) {
5872 params.setCfg = { scope: 'global' };
5873 this.set(cm, params);
5874 },
5875 registers: function (cm, params) {
5876 var regArgs = params.args;
5877 var registers = vimGlobalState.registerController.registers;
5878 var regInfo = '----------Registers----------\n\n';
5879 if (!regArgs) {
5880 for (var registerName in registers) {
5881 var text = registers[registerName].toString();
5882 if (text.length) {
5883 regInfo += '"' + registerName + ' ' + text + '\n';
5884 }
5885 }
5886 }
5887 else {
5888 var registerName;
5889 regArgs = regArgs.join('');
5890 for (var i = 0; i < regArgs.length; i++) {
5891 registerName = regArgs.charAt(i);
5892 if (!vimGlobalState.registerController.isValidRegister(registerName)) {
5893 continue;
5894 }
5895 var register = registers[registerName] || new Register();
5896 regInfo += '"' + registerName + ' ' + register.toString() + '\n';
5897 }
5898 }
5899 showConfirm(cm, regInfo);
5900 },
5901 sort: function (cm, params) {
5902 var reverse, ignoreCase, unique, number, pattern;
5903 function parseArgs() {
5904 if (params.argString) {
5905 var args = new CodeMirror.StringStream(params.argString);
5906 if (args.eat('!')) {
5907 reverse = true;
5908 }
5909 if (args.eol()) {
5910 return;
5911 }
5912 if (!args.eatSpace()) {
5913 return 'Invalid arguments';
5914 }
5915 var opts = args.match(/([dinuox]+)?\s*(\/.+\/)?\s*/);
5916 if (!opts && !args.eol()) {
5917 return 'Invalid arguments';
5918 }
5919 if (opts[1]) {
5920 ignoreCase = opts[1].indexOf('i') != -1;
5921 unique = opts[1].indexOf('u') != -1;
5922 var decimal = opts[1].indexOf('d') != -1 || opts[1].indexOf('n') != -1 && 1;
5923 var hex = opts[1].indexOf('x') != -1 && 1;
5924 var octal = opts[1].indexOf('o') != -1 && 1;
5925 if (decimal + hex + octal > 1) {
5926 return 'Invalid arguments';
5927 }
5928 number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
5929 }
5930 if (opts[2]) {
5931 pattern = new RegExp(opts[2].substr(1, opts[2].length - 2), ignoreCase ? 'i' : '');
5932 }
5933 }
5934 }
5935 var err = parseArgs();
5936 if (err) {
5937 showConfirm(cm, err + ': ' + params.argString);
5938 return;
5939 }
5940 var lineStart = params.line || cm.firstLine();
5941 var lineEnd = params.lineEnd || params.line || cm.lastLine();
5942 if (lineStart == lineEnd) {
5943 return;
5944 }
5945 var curStart = new Pos(lineStart, 0);
5946 var curEnd = new Pos(lineEnd, lineLength(cm, lineEnd));
5947 var text = cm.getRange(curStart, curEnd).split('\n');
5948 var numberRegex = pattern ? pattern :
5949 (number == 'decimal') ? /(-?)([\d]+)/ :
5950 (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
5951 (number == 'octal') ? /([0-7]+)/ : null;
5952 var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
5953 var numPart = [], textPart = [];
5954 if (number || pattern) {
5955 for (var i = 0; i < text.length; i++) {
5956 var matchPart = pattern ? text[i].match(pattern) : null;
5957 if (matchPart && matchPart[0] != '') {
5958 numPart.push(matchPart);
5959 }
5960 else if (!pattern && numberRegex.exec(text[i])) {
5961 numPart.push(text[i]);
5962 }
5963 else {
5964 textPart.push(text[i]);
5965 }
5966 }
5967 }
5968 else {
5969 textPart = text;
5970 }
5971 function compareFn(a, b) {
5972 if (reverse) {
5973 var tmp;
5974 tmp = a;
5975 a = b;
5976 b = tmp;
5977 }
5978 if (ignoreCase) {
5979 a = a.toLowerCase();
5980 b = b.toLowerCase();
5981 }
5982 var anum = number && numberRegex.exec(a);
5983 var bnum = number && numberRegex.exec(b);
5984 if (!anum) {
5985 return a < b ? -1 : 1;
5986 }
5987 anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
5988 bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
5989 return anum - bnum;
5990 }
5991 function comparePatternFn(a, b) {
5992 if (reverse) {
5993 var tmp;
5994 tmp = a;
5995 a = b;
5996 b = tmp;
5997 }
5998 if (ignoreCase) {
5999 a[0] = a[0].toLowerCase();
6000 b[0] = b[0].toLowerCase();
6001 }
6002 return (a[0] < b[0]) ? -1 : 1;
6003 }
6004 numPart.sort(pattern ? comparePatternFn : compareFn);
6005 if (pattern) {
6006 for (var i = 0; i < numPart.length; i++) {
6007 numPart[i] = numPart[i].input;
6008 }
6009 }
6010 else if (!number) {
6011 textPart.sort(compareFn);
6012 }
6013 text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
6014 if (unique) { // Remove duplicate lines
6015 var textOld = text;
6016 var lastLine;
6017 text = [];
6018 for (var i = 0; i < textOld.length; i++) {
6019 if (textOld[i] != lastLine) {
6020 text.push(textOld[i]);
6021 }
6022 lastLine = textOld[i];
6023 }
6024 }
6025 cm.replaceRange(text.join('\n'), curStart, curEnd);
6026 },
6027 vglobal: function (cm, params) {
6028 this.global(cm, params);
6029 },
6030 normal: function (cm, params) {
6031 var argString = params.argString;
6032 if (argString && argString[0] == '!') {
6033 argString = argString.slice(1);
6034 noremap = true;
6035 }
6036 argString = argString.trimStart();
6037 if (!argString) {
6038 showConfirm(cm, 'Argument is required.');
6039 return;
6040 }
6041 var line = params.line;
6042 if (typeof line == 'number') {
6043 var lineEnd = isNaN(params.lineEnd) ? line : params.lineEnd;
6044 for (var i = line; i <= lineEnd; i++) {
6045 cm.setCursor(i, 0);
6046 doKeyToKey(cm, params.argString.trimStart());
6047 if (cm.state.vim.insertMode) {
6048 exitInsertMode(cm, true);
6049 }
6050 }
6051 }
6052 else {
6053 doKeyToKey(cm, params.argString.trimStart());
6054 if (cm.state.vim.insertMode) {
6055 exitInsertMode(cm, true);
6056 }
6057 }
6058 },
6059 global: function (cm, params) {
6060 var argString = params.argString;
6061 if (!argString) {
6062 showConfirm(cm, 'Regular Expression missing from global');
6063 return;
6064 }
6065 var inverted = params.commandName[0] === 'v';
6066 if (argString[0] === '!' && params.commandName[0] === 'g') {
6067 inverted = true;
6068 argString = argString.slice(1);
6069 }
6070 var lineStart = (params.line !== undefined) ? params.line : cm.firstLine();
6071 var lineEnd = params.lineEnd || params.line || cm.lastLine();
6072 var tokens = splitBySlash(argString);
6073 var regexPart = argString, cmd;
6074 if (tokens.length) {
6075 regexPart = tokens[0];
6076 cmd = tokens.slice(1, tokens.length).join('/');
6077 }
6078 if (regexPart) {
6079 try {
6080 updateSearchQuery(cm, regexPart, true /** ignoreCase */, true /** smartCase */);
6081 }
6082 catch (e) {
6083 showConfirm(cm, 'Invalid regex: ' + regexPart);
6084 return;
6085 }
6086 }
6087 var query = getSearchState(cm).getQuery();
6088 var matchedLines = [];
6089 for (var i = lineStart; i <= lineEnd; i++) {
6090 var line = cm.getLine(i);
6091 var matched = query.test(line);
6092 if (matched !== inverted) {
6093 matchedLines.push(cmd ? cm.getLineHandle(i) : line);
6094 }
6095 }
6096 if (!cmd) {
6097 showConfirm(cm, matchedLines.join('\n'));
6098 return;
6099 }
6100 var index = 0;
6101 var nextCommand = function () {
6102 if (index < matchedLines.length) {
6103 var lineHandle = matchedLines[index++];
6104 var lineNum = cm.getLineNumber(lineHandle);
6105 if (lineNum == null) {
6106 nextCommand();
6107 return;
6108 }
6109 var command = (lineNum + 1) + cmd;
6110 exCommandDispatcher.processCommand(cm, command, {
6111 callback: nextCommand
6112 });
6113 }
6114 else if (cm.releaseLineHandles) {
6115 cm.releaseLineHandles();
6116 }
6117 };
6118 nextCommand();
6119 },
6120 substitute: function (cm, params) {
6121 if (!cm.getSearchCursor) {
6122 throw new Error('Search feature not available. Requires searchcursor.js or ' +
6123 'any other getSearchCursor implementation.');
6124 }
6125 var argString = params.argString;
6126 var tokens = argString ? splitBySeparator(argString, argString[0]) : [];
6127 var regexPart, replacePart = '', trailing, flagsPart, count;
6128 var confirm = false; // Whether to confirm each replace.
6129 var global = false; // True to replace all instances on a line, false to replace only 1.
6130 if (tokens.length) {
6131 regexPart = tokens[0];
6132 if (getOption('pcre') && regexPart !== '') {
6133 regexPart = new RegExp(regexPart).source; //normalize not escaped characters
6134 }
6135 replacePart = tokens[1];
6136 if (replacePart !== undefined) {
6137 if (getOption('pcre')) {
6138 replacePart = unescapeRegexReplace(replacePart.replace(/([^\\])&/g, "$1$$&"));
6139 }
6140 else {
6141 replacePart = translateRegexReplace(replacePart);
6142 }
6143 vimGlobalState.lastSubstituteReplacePart = replacePart;
6144 }
6145 trailing = tokens[2] ? tokens[2].split(' ') : [];
6146 }
6147 else {
6148 if (argString && argString.length) {
6149 showConfirm(cm, 'Substitutions should be of the form ' +
6150 ':s/pattern/replace/');
6151 return;
6152 }
6153 }
6154 if (trailing) {
6155 flagsPart = trailing[0];
6156 count = parseInt(trailing[1]);
6157 if (flagsPart) {
6158 if (flagsPart.indexOf('c') != -1) {
6159 confirm = true;
6160 }
6161 if (flagsPart.indexOf('g') != -1) {
6162 global = true;
6163 }
6164 if (getOption('pcre')) {
6165 regexPart = regexPart + '/' + flagsPart;
6166 }
6167 else {
6168 regexPart = regexPart.replace(/\//g, "\\/") + '/' + flagsPart;
6169 }
6170 }
6171 }
6172 if (regexPart) {
6173 try {
6174 updateSearchQuery(cm, regexPart, true /** ignoreCase */, true /** smartCase */);
6175 }
6176 catch (e) {
6177 showConfirm(cm, 'Invalid regex: ' + regexPart);
6178 return;
6179 }
6180 }
6181 replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart;
6182 if (replacePart === undefined) {
6183 showConfirm(cm, 'No previous substitute regular expression');
6184 return;
6185 }
6186 var state = getSearchState(cm);
6187 var query = state.getQuery();
6188 var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
6189 var lineEnd = params.lineEnd || lineStart;
6190 if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) {
6191 lineEnd = Infinity;
6192 }
6193 if (count) {
6194 lineStart = lineEnd;
6195 lineEnd = lineStart + count - 1;
6196 }
6197 var startPos = clipCursorToContent(cm, new Pos(lineStart, 0));
6198 var cursor = cm.getSearchCursor(query, startPos);
6199 doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback);
6200 },
6201 startinsert: function (cm, params) {
6202 doKeyToKey(cm, params.argString == '!' ? 'A' : 'i', {});
6203 },
6204 redo: CodeMirror.commands.redo,
6205 undo: CodeMirror.commands.undo,
6206 write: function (cm) {
6207 if (CodeMirror.commands.save) {
6208 CodeMirror.commands.save(cm);
6209 }
6210 else if (cm.save) {
6211 cm.save();
6212 }
6213 },
6214 nohlsearch: function (cm) {
6215 clearSearchHighlight(cm);
6216 },
6217 yank: function (cm) {
6218 var cur = copyCursor(cm.getCursor());
6219 var line = cur.line;
6220 var lineText = cm.getLine(line);
6221 vimGlobalState.registerController.pushText('0', 'yank', lineText, true, true);
6222 },
6223 delete: function (cm, params) {
6224 var line = params.selectionLine;
6225 var lineEnd = isNaN(params.selectionLineEnd) ? line : params.selectionLineEnd;
6226 operators.delete(cm, { linewise: true }, [
6227 { anchor: new Pos(line, 0),
6228 head: new Pos(lineEnd + 1, 0) }
6229 ]);
6230 },
6231 join: function (cm, params) {
6232 var line = params.selectionLine;
6233 var lineEnd = isNaN(params.selectionLineEnd) ? line : params.selectionLineEnd;
6234 cm.setCursor(new Pos(line, 0));
6235 actions.joinLines(cm, { repeat: lineEnd - line }, cm.state.vim);
6236 },
6237 delmarks: function (cm, params) {
6238 if (!params.argString || !trim(params.argString)) {
6239 showConfirm(cm, 'Argument required');
6240 return;
6241 }
6242 var state = cm.state.vim;
6243 var stream = new CodeMirror.StringStream(trim(params.argString));
6244 while (!stream.eol()) {
6245 stream.eatSpace();
6246 var count = stream.pos;
6247 if (!stream.match(/[a-zA-Z]/, false)) {
6248 showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
6249 return;
6250 }
6251 var sym = stream.next();
6252 if (stream.match('-', true)) {
6253 if (!stream.match(/[a-zA-Z]/, false)) {
6254 showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
6255 return;
6256 }
6257 var startMark = sym;
6258 var finishMark = stream.next();
6259 if (isLowerCase(startMark) && isLowerCase(finishMark) ||
6260 isUpperCase(startMark) && isUpperCase(finishMark)) {
6261 var start = startMark.charCodeAt(0);
6262 var finish = finishMark.charCodeAt(0);
6263 if (start >= finish) {
6264 showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
6265 return;
6266 }
6267 for (var j = 0; j <= finish - start; j++) {
6268 var mark = String.fromCharCode(start + j);
6269 delete state.marks[mark];
6270 }
6271 }
6272 else {
6273 showConfirm(cm, 'Invalid argument: ' + startMark + '-');
6274 return;
6275 }
6276 }
6277 else {
6278 delete state.marks[sym];
6279 }
6280 }
6281 }
6282 };
6283 var exCommandDispatcher = new ExCommandDispatcher();
6284 function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query, replaceWith, callback) {
6285 cm.state.vim.exMode = true;
6286 var done = false;
6287 var lastPos, modifiedLineNumber, joined;
6288 function replaceAll() {
6289 cm.operation(function () {
6290 while (!done) {
6291 replace();
6292 next();
6293 }
6294 stop();
6295 });
6296 }
6297 function replace() {
6298 var text = cm.getRange(searchCursor.from(), searchCursor.to());
6299 var newText = text.replace(query, replaceWith);
6300 var unmodifiedLineNumber = searchCursor.to().line;
6301 searchCursor.replace(newText);
6302 modifiedLineNumber = searchCursor.to().line;
6303 lineEnd += modifiedLineNumber - unmodifiedLineNumber;
6304 joined = modifiedLineNumber < unmodifiedLineNumber;
6305 }
6306 function findNextValidMatch() {
6307 var lastMatchTo = lastPos && copyCursor(searchCursor.to());
6308 var match = searchCursor.findNext();
6309 if (match && !match[0] && lastMatchTo && cursorEqual(searchCursor.from(), lastMatchTo)) {
6310 match = searchCursor.findNext();
6311 }
6312 return match;
6313 }
6314 function next() {
6315 while (findNextValidMatch() &&
6316 isInRange(searchCursor.from(), lineStart, lineEnd)) {
6317 if (!global && searchCursor.from().line == modifiedLineNumber && !joined) {
6318 continue;
6319 }
6320 cm.scrollIntoView(searchCursor.from(), 30);
6321 cm.setSelection(searchCursor.from(), searchCursor.to());
6322 lastPos = searchCursor.from();
6323 done = false;
6324 return;
6325 }
6326 done = true;
6327 }
6328 function stop(close) {
6329 if (close) {
6330 close();
6331 }
6332 cm.focus();
6333 if (lastPos) {
6334 cm.setCursor(lastPos);
6335 var vim = cm.state.vim;
6336 vim.exMode = false;
6337 vim.lastHPos = vim.lastHSPos = lastPos.ch;
6338 }
6339 if (callback) {
6340 callback();
6341 }
6342 }
6343 function onPromptKeyDown(e, _value, close) {
6344 CodeMirror.e_stop(e);
6345 var keyName = vimKeyFromEvent(e);
6346 switch (keyName) {
6347 case 'y':
6348 replace();
6349 next();
6350 break;
6351 case 'n':
6352 next();
6353 break;
6354 case 'a':
6355 var savedCallback = callback;
6356 callback = undefined;
6357 cm.operation(replaceAll);
6358 callback = savedCallback;
6359 break;
6360 case 'l':
6361 replace();
6362 case 'q':
6363 case '<Esc>':
6364 case '<C-c>':
6365 case '<C-[>':
6366 stop(close);
6367 break;
6368 }
6369 if (done) {
6370 stop(close);
6371 }
6372 return true;
6373 }
6374 next();
6375 if (done) {
6376 showConfirm(cm, 'No matches for ' + query.source);
6377 return;
6378 }
6379 if (!confirm) {
6380 replaceAll();
6381 if (callback) {
6382 callback();
6383 }
6384 return;
6385 }
6386 showPrompt(cm, {
6387 prefix: dom('span', 'replace with ', dom('strong', replaceWith), ' (y/n/a/q/l)'),
6388 onKeyDown: onPromptKeyDown
6389 });
6390 }
6391 function exitInsertMode(cm, keepCursor) {
6392 var vim = cm.state.vim;
6393 var macroModeState = vimGlobalState.macroModeState;
6394 var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.');
6395 var isPlaying = macroModeState.isPlaying;
6396 var lastChange = macroModeState.lastInsertModeChanges;
6397 if (!isPlaying) {
6398 cm.off('change', onChange);
6399 if (vim.insertEnd)
6400 vim.insertEnd.clear();
6401 vim.insertEnd = null;
6402 CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
6403 }
6404 if (!isPlaying && vim.insertModeRepeat > 1) {
6405 repeatLastEdit(cm, vim, vim.insertModeRepeat - 1, true /** repeatForInsert */);
6406 vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
6407 }
6408 delete vim.insertModeRepeat;
6409 vim.insertMode = false;
6410 if (!keepCursor) {
6411 cm.setCursor(cm.getCursor().line, cm.getCursor().ch - 1);
6412 }
6413 cm.setOption('keyMap', 'vim');
6414 cm.setOption('disableInput', true);
6415 cm.toggleOverwrite(false); // exit replace mode if we were in it.
6416 insertModeChangeRegister.setText(lastChange.changes.join(''));
6417 CodeMirror.signal(cm, "vim-mode-change", { mode: "normal" });
6418 if (macroModeState.isRecording) {
6419 logInsertModeChange(macroModeState);
6420 }
6421 }
6422 function _mapCommand(command) {
6423 defaultKeymap.unshift(command);
6424 }
6425 function mapCommand(keys, type, name, args, extra) {
6426 var command = { keys: keys, type: type };
6427 command[type] = name;
6428 command[type + "Args"] = args;
6429 for (var key in extra)
6430 command[key] = extra[key];
6431 _mapCommand(command);
6432 }
6433 defineOption('insertModeEscKeysTimeout', 200, 'number');
6434 function executeMacroRegister(cm, vim, macroModeState, registerName) {
6435 var register = vimGlobalState.registerController.getRegister(registerName);
6436 if (registerName == ':') {
6437 if (register.keyBuffer[0]) {
6438 exCommandDispatcher.processCommand(cm, register.keyBuffer[0]);
6439 }
6440 macroModeState.isPlaying = false;
6441 return;
6442 }
6443 var keyBuffer = register.keyBuffer;
6444 var imc = 0;
6445 macroModeState.isPlaying = true;
6446 macroModeState.replaySearchQueries = register.searchQueries.slice(0);
6447 for (var i = 0; i < keyBuffer.length; i++) {
6448 var text = keyBuffer[i];
6449 var match, key;
6450 while (text) {
6451 match = (/<\w+-.+?>|<\w+>|./).exec(text);
6452 key = match[0];
6453 text = text.substring(match.index + key.length);
6454 vimApi.handleKey(cm, key, 'macro');
6455 if (vim.insertMode) {
6456 var changes = register.insertModeChanges[imc++].changes;
6457 vimGlobalState.macroModeState.lastInsertModeChanges.changes =
6458 changes;
6459 repeatInsertModeChanges(cm, changes, 1);
6460 exitInsertMode(cm);
6461 }
6462 }
6463 }
6464 macroModeState.isPlaying = false;
6465 }
6466 function logKey(macroModeState, key) {
6467 if (macroModeState.isPlaying) {
6468 return;
6469 }
6470 var registerName = macroModeState.latestRegister;
6471 var register = vimGlobalState.registerController.getRegister(registerName);
6472 if (register) {
6473 register.pushText(key);
6474 }
6475 }
6476 function logInsertModeChange(macroModeState) {
6477 if (macroModeState.isPlaying) {
6478 return;
6479 }
6480 var registerName = macroModeState.latestRegister;
6481 var register = vimGlobalState.registerController.getRegister(registerName);
6482 if (register && register.pushInsertModeChanges) {
6483 register.pushInsertModeChanges(macroModeState.lastInsertModeChanges);
6484 }
6485 }
6486 function logSearchQuery(macroModeState, query) {
6487 if (macroModeState.isPlaying) {
6488 return;
6489 }
6490 var registerName = macroModeState.latestRegister;
6491 var register = vimGlobalState.registerController.getRegister(registerName);
6492 if (register && register.pushSearchQuery) {
6493 register.pushSearchQuery(query);
6494 }
6495 }
6496 function onChange(cm, changeObj) {
6497 var macroModeState = vimGlobalState.macroModeState;
6498 var lastChange = macroModeState.lastInsertModeChanges;
6499 if (!macroModeState.isPlaying) {
6500 var vim = cm.state.vim;
6501 while (changeObj) {
6502 lastChange.expectCursorActivityForChange = true;
6503 if (lastChange.ignoreCount > 1) {
6504 lastChange.ignoreCount--;
6505 }
6506 else if (changeObj.origin == '+input' || changeObj.origin == 'paste'
6507 || changeObj.origin === undefined /* only in testing */) {
6508 var selectionCount = cm.listSelections().length;
6509 if (selectionCount > 1)
6510 lastChange.ignoreCount = selectionCount;
6511 var text = changeObj.text.join('\n');
6512 if (lastChange.maybeReset) {
6513 lastChange.changes = [];
6514 lastChange.maybeReset = false;
6515 }
6516 if (text) {
6517 if (cm.state.overwrite && !/\n/.test(text)) {
6518 lastChange.changes.push([text]);
6519 }
6520 else {
6521 if (text.length > 1) {
6522 var insertEnd = vim && vim.insertEnd && vim.insertEnd.find();
6523 var cursor = cm.getCursor();
6524 if (insertEnd && insertEnd.line == cursor.line) {
6525 var offset = insertEnd.ch - cursor.ch;
6526 if (offset > 0 && offset < text.length) {
6527 lastChange.changes.push([text, offset]);
6528 text = '';
6529 }
6530 }
6531 }
6532 if (text)
6533 lastChange.changes.push(text);
6534 }
6535 }
6536 }
6537 changeObj = changeObj.next;
6538 }
6539 }
6540 }
6541 function onCursorActivity(cm) {
6542 var vim = cm.state.vim;
6543 if (vim.insertMode) {
6544 var macroModeState = vimGlobalState.macroModeState;
6545 if (macroModeState.isPlaying) {
6546 return;
6547 }
6548 var lastChange = macroModeState.lastInsertModeChanges;
6549 if (lastChange.expectCursorActivityForChange) {
6550 lastChange.expectCursorActivityForChange = false;
6551 }
6552 else {
6553 lastChange.maybeReset = true;
6554 if (vim.insertEnd)
6555 vim.insertEnd.clear();
6556 vim.insertEnd = cm.setBookmark(cm.getCursor(), { insertLeft: true });
6557 }
6558 }
6559 else if (!cm.curOp.isVimOp) {
6560 handleExternalSelection(cm, vim);
6561 }
6562 }
6563 function handleExternalSelection(cm, vim, keepHPos) {
6564 var anchor = cm.getCursor('anchor');
6565 var head = cm.getCursor('head');
6566 if (vim.visualMode && !cm.somethingSelected()) {
6567 exitVisualMode(cm, false);
6568 }
6569 else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) {
6570 vim.visualMode = true;
6571 vim.visualLine = false;
6572 CodeMirror.signal(cm, "vim-mode-change", { mode: "visual" });
6573 }
6574 if (vim.visualMode) {
6575 var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
6576 var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
6577 head = offsetCursor(head, 0, headOffset);
6578 anchor = offsetCursor(anchor, 0, anchorOffset);
6579 vim.sel = {
6580 anchor: anchor,
6581 head: head
6582 };
6583 updateMark(cm, vim, '<', cursorMin(head, anchor));
6584 updateMark(cm, vim, '>', cursorMax(head, anchor));
6585 }
6586 else if (!vim.insertMode && !keepHPos) {
6587 vim.lastHPos = cm.getCursor().ch;
6588 }
6589 }
6590 function InsertModeKey(keyName, e) {
6591 this.keyName = keyName;
6592 this.key = e.key;
6593 this.ctrlKey = e.ctrlKey;
6594 this.altKey = e.altKey;
6595 this.metaKey = e.metaKey;
6596 this.shiftKey = e.shiftKey;
6597 }
6598 function onKeyEventTargetKeyDown(e) {
6599 var macroModeState = vimGlobalState.macroModeState;
6600 var lastChange = macroModeState.lastInsertModeChanges;
6601 var keyName = CodeMirror.keyName ? CodeMirror.keyName(e) : e.key;
6602 if (!keyName) {
6603 return;
6604 }
6605 if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
6606 if (lastChange.maybeReset) {
6607 lastChange.changes = [];
6608 lastChange.maybeReset = false;
6609 }
6610 lastChange.changes.push(new InsertModeKey(keyName, e));
6611 }
6612 }
6613 function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
6614 var macroModeState = vimGlobalState.macroModeState;
6615 macroModeState.isPlaying = true;
6616 var isAction = !!vim.lastEditActionCommand;
6617 var cachedInputState = vim.inputState;
6618 function repeatCommand() {
6619 if (isAction) {
6620 commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
6621 }
6622 else {
6623 commandDispatcher.evalInput(cm, vim);
6624 }
6625 }
6626 function repeatInsert(repeat) {
6627 if (macroModeState.lastInsertModeChanges.changes.length > 0) {
6628 repeat = !vim.lastEditActionCommand ? 1 : repeat;
6629 var changeObject = macroModeState.lastInsertModeChanges;
6630 repeatInsertModeChanges(cm, changeObject.changes, repeat);
6631 }
6632 }
6633 vim.inputState = vim.lastEditInputState;
6634 if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
6635 for (var i = 0; i < repeat; i++) {
6636 repeatCommand();
6637 repeatInsert(1);
6638 }
6639 }
6640 else {
6641 if (!repeatForInsert) {
6642 repeatCommand();
6643 }
6644 repeatInsert(repeat);
6645 }
6646 vim.inputState = cachedInputState;
6647 if (vim.insertMode && !repeatForInsert) {
6648 exitInsertMode(cm);
6649 }
6650 macroModeState.isPlaying = false;
6651 }
6652 function sendCmKey(cm, key) {
6653 CodeMirror.lookupKey(key, 'vim-insert', function keyHandler(binding) {
6654 if (typeof binding == 'string') {
6655 CodeMirror.commands[binding](cm);
6656 }
6657 else {
6658 binding(cm);
6659 }
6660 return true;
6661 });
6662 }
6663 function repeatInsertModeChanges(cm, changes, repeat) {
6664 var head = cm.getCursor('head');
6665 var visualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.visualBlock;
6666 if (visualBlock) {
6667 selectForInsert(cm, head, visualBlock + 1);
6668 repeat = cm.listSelections().length;
6669 cm.setCursor(head);
6670 }
6671 for (var i = 0; i < repeat; i++) {
6672 if (visualBlock) {
6673 cm.setCursor(offsetCursor(head, i, 0));
6674 }
6675 for (var j = 0; j < changes.length; j++) {
6676 var change = changes[j];
6677 if (change instanceof InsertModeKey) {
6678 sendCmKey(cm, change.keyName, change);
6679 }
6680 else if (typeof change == "string") {
6681 cm.replaceSelection(change);
6682 }
6683 else {
6684 var start = cm.getCursor();
6685 var end = offsetCursor(start, 0, change[0].length - (change[1] || 0));
6686 cm.replaceRange(change[0], start, change[1] ? start : end);
6687 cm.setCursor(end);
6688 }
6689 }
6690 }
6691 if (visualBlock) {
6692 cm.setCursor(offsetCursor(head, 0, 1));
6693 }
6694 }
6695 CodeMirror.Vim = vimApi;
6696 var specialKeyAce = { 'return': 'CR', backspace: 'BS', 'delete': 'Del', esc: 'Esc',
6697 left: 'Left', right: 'Right', up: 'Up', down: 'Down', space: 'Space', insert: 'Ins',
6698 home: 'Home', end: 'End', pageup: 'PageUp', pagedown: 'PageDown', enter: 'CR'
6699 };
6700 function lookupKey(hashId, key, e, vim) {
6701 if (key.length > 1 && key[0] == "n") {
6702 key = key.replace("numpad", "");
6703 }
6704 key = specialKeyAce[key] || key;
6705 var name = '';
6706 if (e.ctrlKey) {
6707 name += 'C-';
6708 }
6709 if (e.altKey) {
6710 name += 'A-';
6711 }
6712 if ((name || key.length > 1) && e.shiftKey) {
6713 name += 'S-';
6714 }
6715 if (vim && !vim.expectLiteralNext && key.length == 1) {
6716 if (langmap.keymap && key in langmap.keymap) {
6717 if (langmap.remapCtrl !== false || !name)
6718 key = langmap.keymap[key];
6719 }
6720 else if (key.charCodeAt(0) > 255) {
6721 var code = e.code && e.code.slice(-1) || "";
6722 if (!e.shiftKey)
6723 code = code.toLowerCase();
6724 if (code)
6725 key = code;
6726 }
6727 }
6728 name += key;
6729 if (name.length > 1) {
6730 name = '<' + name + '>';
6731 }
6732 return name;
6733 }
6734 var handleKey = vimApi.handleKey.bind(vimApi);
6735 vimApi.handleKey = function (cm, key, origin) {
6736 return cm.operation(function () {
6737 return handleKey(cm, key, origin);
6738 }, true);
6739 };
6740 function cloneVimState(state) {
6741 var n = new state.constructor();
6742 Object.keys(state).forEach(function (key) {
6743 if (key == "insertEnd")
6744 return;
6745 var o = state[key];
6746 if (Array.isArray(o))
6747 o = o.slice();
6748 else if (o && typeof o == "object" && o.constructor != Object)
6749 o = cloneVimState(o);
6750 n[key] = o;
6751 });
6752 if (state.sel) {
6753 n.sel = {
6754 head: state.sel.head && copyCursor(state.sel.head),
6755 anchor: state.sel.anchor && copyCursor(state.sel.anchor)
6756 };
6757 }
6758 return n;
6759 }
6760 function multiSelectHandleKey(cm, key, origin) {
6761 var isHandled = false;
6762 var vim = vimApi.maybeInitVimState_(cm);
6763 var visualBlock = vim.visualBlock || vim.wasInVisualBlock;
6764 var wasMultiselect = cm.ace.inMultiSelectMode;
6765 if (vim.wasInVisualBlock && !wasMultiselect) {
6766 vim.wasInVisualBlock = false;
6767 }
6768 else if (wasMultiselect && vim.visualBlock) {
6769 vim.wasInVisualBlock = true;
6770 }
6771 if (key == '<Esc>' && !vim.insertMode && !vim.visualMode && wasMultiselect) {
6772 cm.ace.exitMultiSelectMode();
6773 }
6774 else if (visualBlock || !wasMultiselect || cm.ace.inVirtualSelectionMode) {
6775 isHandled = vimApi.handleKey(cm, key, origin);
6776 }
6777 else {
6778 var old = cloneVimState(vim);
6779 var changeQueueList = vim.inputState.changeQueueList || [];
6780 cm.operation(function () {
6781 cm.curOp.isVimOp = true;
6782 var index = 0;
6783 cm.ace.forEachSelection(function () {
6784 var sel = cm.ace.selection;
6785 cm.state.vim.lastHPos = sel.$desiredColumn == null ? sel.lead.column : sel.$desiredColumn;
6786 cm.state.vim.inputState.changeQueue = changeQueueList[index];
6787 var head = cm.getCursor("head");
6788 var anchor = cm.getCursor("anchor");
6789 var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
6790 var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
6791 head = offsetCursor(head, 0, headOffset);
6792 anchor = offsetCursor(anchor, 0, anchorOffset);
6793 cm.state.vim.sel.head = head;
6794 cm.state.vim.sel.anchor = anchor;
6795 isHandled = handleKey(cm, key, origin);
6796 sel.$desiredColumn = cm.state.vim.lastHPos == -1 ? null : cm.state.vim.lastHPos;
6797 if (cm.ace.inVirtualSelectionMode) {
6798 changeQueueList[index] = cm.state.vim.inputState.changeQueue;
6799 }
6800 if (cm.virtualSelectionMode()) {
6801 cm.state.vim = cloneVimState(old);
6802 }
6803 index++;
6804 });
6805 if (cm.curOp.cursorActivity && !isHandled)
6806 cm.curOp.cursorActivity = false;
6807 vim.status = cm.state.vim.status;
6808 cm.state.vim = vim;
6809 vim.inputState.changeQueueList = changeQueueList;
6810 vim.inputState.changeQueue = null;
6811 }, true);
6812 }
6813 if (isHandled && !vim.visualMode && !vim.insert && vim.visualMode != cm.somethingSelected()) {
6814 handleExternalSelection(cm, vim, true);
6815 }
6816 return isHandled;
6817 }
6818 resetVimGlobalState();
6819 exports.CodeMirror = CodeMirror;
6820 var getVim = vimApi.maybeInitVimState_;
6821 exports.handler = {
6822 $id: "ace/keyboard/vim",
6823 drawCursor: function (element, pixelPos, config, sel, session) {
6824 var vim = this.state.vim || {};
6825 var w = config.characterWidth;
6826 var h = config.lineHeight;
6827 var top = pixelPos.top;
6828 var left = pixelPos.left;
6829 if (!vim.insertMode) {
6830 var isbackwards = !sel.cursor
6831 ? session.selection.isBackwards() || session.selection.isEmpty()
6832 : Range.comparePoints(sel.cursor, sel.start) <= 0;
6833 if (!isbackwards && left > w)
6834 left -= w;
6835 }
6836 if (!vim.insertMode && vim.status) {
6837 h = h / 2;
6838 top += h;
6839 }
6840 domLib.translate(element, left, top);
6841 domLib.setStyle(element.style, "width", w + "px");
6842 domLib.setStyle(element.style, "height", h + "px");
6843 },
6844 $getDirectionForHighlight: function (editor) {
6845 var cm = editor.state.cm;
6846 var vim = getVim(cm);
6847 if (!vim.insertMode) {
6848 return editor.session.selection.isBackwards() || editor.session.selection.isEmpty();
6849 }
6850 },
6851 handleKeyboard: function (data, hashId, key, keyCode, e) {
6852 var editor = data.editor;
6853 var cm = editor.state.cm;
6854 var vim = getVim(cm);
6855 if (keyCode == -1)
6856 return;
6857 if (!vim.insertMode) {
6858 if (hashId == -1) {
6859 if (key.charCodeAt(0) > 0xFF) {
6860 if (data.inputKey) {
6861 key = data.inputKey;
6862 if (key && data.inputHash == 4)
6863 key = key.toUpperCase();
6864 }
6865 }
6866 data.inputChar = key;
6867 }
6868 else if (hashId == 4 || hashId == 0) {
6869 if (data.inputKey == key && data.inputHash == hashId && data.inputChar) {
6870 key = data.inputChar;
6871 hashId = -1;
6872 }
6873 else {
6874 data.inputChar = null;
6875 data.inputKey = key;
6876 data.inputHash = hashId;
6877 }
6878 }
6879 else {
6880 data.inputChar = data.inputKey = null;
6881 }
6882 }
6883 if (cm.state.overwrite && vim.insertMode && key == "backspace" && hashId == 0) {
6884 return { command: "gotoleft" };
6885 }
6886 if (key == "c" && hashId == 1) { // key == "ctrl-c"
6887 if (!useragent.isMac && editor.getCopyText()) {
6888 editor.once("copy", function () {
6889 if (vim.insertMode)
6890 editor.selection.clearSelection();
6891 else
6892 cm.operation(function () { exitVisualMode(cm); });
6893 });
6894 return { command: "null", passEvent: true };
6895 }
6896 }
6897 if (key == "esc" && !vim.insertMode && !vim.visualMode && !cm.ace.inMultiSelectMode) {
6898 var searchState = getSearchState(cm);
6899 var overlay = searchState.getOverlay();
6900 if (overlay)
6901 cm.removeOverlay(overlay);
6902 }
6903 if (hashId == -1 || hashId & 1 || hashId === 0 && key.length > 1) {
6904 var insertMode = vim.insertMode;
6905 var name = lookupKey(hashId, key, e || {}, vim);
6906 if (vim.status == null)
6907 vim.status = "";
6908 var isHandled = multiSelectHandleKey(cm, name, 'user');
6909 vim = getVim(cm); // may be changed by multiSelectHandleKey
6910 if (isHandled && vim.status != null)
6911 vim.status += name;
6912 else if (vim.status == null)
6913 vim.status = "";
6914 cm._signal("changeStatus");
6915 if (!isHandled && (hashId != -1 || insertMode))
6916 return;
6917 return { command: "null", passEvent: !isHandled };
6918 }
6919 },
6920 attach: function (editor) {
6921 if (!editor.state)
6922 editor.state = {};
6923 var cm = new CodeMirror(editor);
6924 editor.state.cm = cm;
6925 editor.$vimModeHandler = this;
6926 enterVimMode(cm);
6927 getVim(cm).status = null;
6928 cm.on('vim-command-done', function () {
6929 if (cm.virtualSelectionMode())
6930 return;
6931 getVim(cm).status = null;
6932 cm.ace._signal("changeStatus");
6933 cm.ace.session.markUndoGroup();
6934 });
6935 cm.on("changeStatus", function () {
6936 cm.ace.renderer.updateCursor();
6937 cm.ace._signal("changeStatus");
6938 });
6939 cm.on("vim-mode-change", function () {
6940 if (cm.virtualSelectionMode())
6941 return;
6942 updateInputMode();
6943 cm._signal("changeStatus");
6944 });
6945 function updateInputMode() {
6946 var isIntsert = getVim(cm).insertMode;
6947 cm.ace.renderer.setStyle("normal-mode", !isIntsert);
6948 editor.textInput.setCommandMode(!isIntsert);
6949 editor.renderer.$keepTextAreaAtCursor = isIntsert;
6950 editor.renderer.$blockCursor = !isIntsert;
6951 }
6952 updateInputMode();
6953 editor.renderer.$cursorLayer.drawCursor = this.drawCursor.bind(cm);
6954 },
6955 detach: function (editor) {
6956 var cm = editor.state.cm;
6957 leaveVimMode(cm);
6958 cm.destroy();
6959 editor.state.cm = null;
6960 editor.$vimModeHandler = null;
6961 editor.renderer.$cursorLayer.drawCursor = null;
6962 editor.renderer.setStyle("normal-mode", false);
6963 editor.textInput.setCommandMode(false);
6964 editor.renderer.$keepTextAreaAtCursor = true;
6965 },
6966 getStatusText: function (editor) {
6967 var cm = editor.state.cm;
6968 var vim = getVim(cm);
6969 if (vim.insertMode)
6970 return "INSERT";
6971 var status = "";
6972 if (vim.visualMode) {
6973 status += "VISUAL";
6974 if (vim.visualLine)
6975 status += " LINE";
6976 if (vim.visualBlock)
6977 status += " BLOCK";
6978 }
6979 if (vim.status)
6980 status += (status ? " " : "") + vim.status;
6981 return status;
6982 }
6983 };
6984 vimApi.defineOption({
6985 name: "wrap",
6986 set: function (value, cm) {
6987 if (cm) {
6988 cm.ace.setOption("wrap", value);
6989 }
6990 },
6991 type: "boolean"
6992 }, false);
6993 vimApi.defineEx('write', 'w', function () {
6994 console.log(':write is not implemented');
6995 });
6996 defaultKeymap.push({ keys: 'zc', type: 'action', action: 'fold', actionArgs: { open: false } }, { keys: 'zC', type: 'action', action: 'fold', actionArgs: { open: false, all: true } }, { keys: 'zo', type: 'action', action: 'fold', actionArgs: { open: true } }, { keys: 'zO', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, { keys: 'za', type: 'action', action: 'fold', actionArgs: { toggle: true } }, { keys: 'zA', type: 'action', action: 'fold', actionArgs: { toggle: true, all: true } }, { keys: 'zf', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, { keys: 'zd', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, { keys: '<C-A-k>', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAbove" } }, { keys: '<C-A-j>', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelow" } }, { keys: '<C-A-S-k>', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAboveSkipCurrent" } }, { keys: '<C-A-S-j>', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelowSkipCurrent" } }, { keys: '<C-A-h>', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreBefore" } }, { keys: '<C-A-l>', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreAfter" } }, { keys: '<C-A-S-h>', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextBefore" } }, { keys: '<C-A-S-l>', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextAfter" } });
6997 defaultKeymap.push({
6998 keys: 'gq',
6999 type: 'operator',
7000 operator: 'hardWrap'
7001 });
7002 vimApi.defineOperator("hardWrap", function (cm, operatorArgs, ranges, oldAnchor, newHead) {
7003 var anchor = ranges[0].anchor.line;
7004 var head = ranges[0].head.line;
7005 if (operatorArgs.linewise)
7006 head--;
7007 hardWrap(cm.ace, { startRow: anchor, endRow: head });
7008 return Pos(head, 0);
7009 });
7010 defineOption('textwidth', undefined, 'number', ['tw'], function (width, cm) {
7011 if (cm === undefined) {
7012 return;
7013 }
7014 if (width === undefined) {
7015 var value = cm.ace.getOption('printMarginColumn');
7016 return value;
7017 }
7018 else {
7019 var column = Math.round(width);
7020 if (column > 1) {
7021 cm.ace.setOption('printMarginColumn', column);
7022 }
7023 }
7024 });
7025 actions.aceCommand = function (cm, actionArgs, vim) {
7026 cm.vimCmd = actionArgs;
7027 if (cm.ace.inVirtualSelectionMode)
7028 cm.ace.on("beforeEndOperation", delayedExecAceCommand);
7029 else
7030 delayedExecAceCommand(null, cm.ace);
7031 };
7032 function delayedExecAceCommand(op, ace) {
7033 ace.off("beforeEndOperation", delayedExecAceCommand);
7034 var cmd = ace.state.cm.vimCmd;
7035 if (cmd) {
7036 ace.execCommand(cmd.exec ? cmd : cmd.name, cmd.args);
7037 }
7038 ace.curOp = ace.prevOp;
7039 }
7040 actions.fold = function (cm, actionArgs, vim) {
7041 cm.ace.execCommand(['toggleFoldWidget', 'toggleFoldWidget', 'foldOther', 'unfoldall'
7042 ][(actionArgs.all ? 2 : 0) + (actionArgs.open ? 1 : 0)]);
7043 };
7044 defaultKeymapLength = defaultKeymap.length; // ace_patch
7045 exports.handler.defaultKeymap = defaultKeymap;
7046 exports.handler.actions = actions;
7047 exports.Vim = vimApi;
7048
7049 }); (function() {
7050 ace.require(["ace/keyboard/vim"], function(m) {
7051 if (typeof module == "object" && typeof exports == "object" && module) {
7052 module.exports = m;
7053 }
7054 });
7055 })();
7056