You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5598 lines
201 KiB

10 months ago
  1. 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/multi_select"], function(acequire, exports, module) {
  2. 'use strict';
  3. function log() {
  4. var d = "";
  5. function format(p) {
  6. if (typeof p != "object")
  7. return p + "";
  8. if ("line" in p) {
  9. return p.line + ":" + p.ch;
  10. }
  11. if ("anchor" in p) {
  12. return format(p.anchor) + "->" + format(p.head);
  13. }
  14. if (Array.isArray(p))
  15. return "[" + p.map(function(x) {
  16. return format(x);
  17. }) + "]";
  18. return JSON.stringify(p);
  19. }
  20. for (var i = 0; i < arguments.length; i++) {
  21. var p = arguments[i];
  22. var f = format(p);
  23. d += f + " ";
  24. }
  25. console.log(d);
  26. }
  27. var Range = acequire("../range").Range;
  28. var EventEmitter = acequire("../lib/event_emitter").EventEmitter;
  29. var dom = acequire("../lib/dom");
  30. var oop = acequire("../lib/oop");
  31. var KEYS = acequire("../lib/keys");
  32. var event = acequire("../lib/event");
  33. var Search = acequire("../search").Search;
  34. var useragent = acequire("../lib/useragent");
  35. var SearchHighlight = acequire("../search_highlight").SearchHighlight;
  36. var multiSelectCommands = acequire("../commands/multi_select_commands");
  37. var TextModeTokenRe = acequire("../mode/text").Mode.prototype.tokenRe;
  38. acequire("../multi_select");
  39. var CodeMirror = function(ace) {
  40. this.ace = ace;
  41. this.state = {};
  42. this.marks = {};
  43. this.$uid = 0;
  44. this.onChange = this.onChange.bind(this);
  45. this.onSelectionChange = this.onSelectionChange.bind(this);
  46. this.onBeforeEndOperation = this.onBeforeEndOperation.bind(this);
  47. this.ace.on('change', this.onChange);
  48. this.ace.on('changeSelection', this.onSelectionChange);
  49. this.ace.on('beforeEndOperation', this.onBeforeEndOperation);
  50. };
  51. CodeMirror.Pos = function(line, ch) {
  52. if (!(this instanceof Pos)) return new Pos(line, ch);
  53. this.line = line; this.ch = ch;
  54. };
  55. CodeMirror.defineOption = function(name, val, setter) {};
  56. CodeMirror.commands = {
  57. redo: function(cm) { cm.ace.redo(); },
  58. undo: function(cm) { cm.ace.undo(); },
  59. newlineAndIndent: function(cm) { cm.ace.insert("\n"); }
  60. };
  61. CodeMirror.keyMap = {};
  62. CodeMirror.addClass = CodeMirror.rmClass =
  63. CodeMirror.e_stop = function() {};
  64. CodeMirror.keyName = function(e) {
  65. if (e.key) return e.key;
  66. var key = (KEYS[e.keyCode] || "");
  67. if (key.length == 1) key = key.toUpperCase();
  68. key = event.getModifierString(e).replace(/(^|-)\w/g, function(m) {
  69. return m.toUpperCase();
  70. }) + key;
  71. return key;
  72. };
  73. CodeMirror.keyMap['default'] = function(key) {
  74. return function(cm) {
  75. var cmd = cm.ace.commands.commandKeyBinding[key.toLowerCase()];
  76. return cmd && cm.ace.execCommand(cmd) !== false;
  77. };
  78. };
  79. CodeMirror.lookupKey = function lookupKey(key, map, handle) {
  80. if (typeof map == "string")
  81. map = CodeMirror.keyMap[map];
  82. var found = typeof map == "function" ? map(key) : map[key];
  83. if (found === false) return "nothing";
  84. if (found === "...") return "multi";
  85. if (found != null && handle(found)) return "handled";
  86. if (map.fallthrough) {
  87. if (!Array.isArray(map.fallthrough))
  88. return lookupKey(key, map.fallthrough, handle);
  89. for (var i = 0; i < map.fallthrough.length; i++) {
  90. var result = lookupKey(key, map.fallthrough[i], handle);
  91. if (result) return result;
  92. }
  93. }
  94. };
  95. CodeMirror.signal = function(o, name, e) { return o._signal(name, e) };
  96. CodeMirror.on = event.addListener;
  97. CodeMirror.off = event.removeListener;
  98. CodeMirror.isWordChar = function(ch) {
  99. if (ch < "\x7f") return /^\w$/.test(ch);
  100. TextModeTokenRe.lastIndex = 0;
  101. return TextModeTokenRe.test(ch);
  102. };
  103. (function() {
  104. oop.implement(CodeMirror.prototype, EventEmitter);
  105. this.destroy = function() {
  106. this.ace.off('change', this.onChange);
  107. this.ace.off('changeSelection', this.onSelectionChange);
  108. this.ace.off('beforeEndOperation', this.onBeforeEndOperation);
  109. this.removeOverlay();
  110. };
  111. this.virtualSelectionMode = function() {
  112. return this.ace.inVirtualSelectionMode && this.ace.selection.index;
  113. };
  114. this.onChange = function(delta) {
  115. var change = { text: delta.action[0] == 'i' ? delta.lines : [] };
  116. var curOp = this.curOp = this.curOp || {};
  117. if (!curOp.changeHandlers)
  118. curOp.changeHandlers = this._eventRegistry["change"] && this._eventRegistry["change"].slice();
  119. if (this.virtualSelectionMode()) return;
  120. if (!curOp.lastChange) {
  121. curOp.lastChange = curOp.change = change;
  122. } else {
  123. curOp.lastChange.next = curOp.lastChange = change;
  124. }
  125. this.$updateMarkers(delta);
  126. };
  127. this.onSelectionChange = function() {
  128. var curOp = this.curOp = this.curOp || {};
  129. if (!curOp.cursorActivityHandlers)
  130. curOp.cursorActivityHandlers = this._eventRegistry["cursorActivity"] && this._eventRegistry["cursorActivity"].slice();
  131. this.curOp.cursorActivity = true;
  132. if (this.ace.inMultiSelectMode) {
  133. this.ace.keyBinding.removeKeyboardHandler(multiSelectCommands.keyboardHandler);
  134. }
  135. };
  136. this.operation = function(fn, force) {
  137. if (!force && this.curOp || force && this.curOp && this.curOp.force) {
  138. return fn();
  139. }
  140. if (force || !this.ace.curOp) {
  141. if (this.curOp)
  142. this.onBeforeEndOperation();
  143. }
  144. if (!this.ace.curOp) {
  145. var prevOp = this.ace.prevOp;
  146. this.ace.startOperation({
  147. command: { name: "vim", scrollIntoView: "cursor" }
  148. });
  149. }
  150. var curOp = this.curOp = this.curOp || {};
  151. this.curOp.force = force;
  152. var result = fn();
  153. if (this.ace.curOp && this.ace.curOp.command.name == "vim") {
  154. this.ace.endOperation();
  155. if (!curOp.cursorActivity && !curOp.lastChange && prevOp)
  156. this.ace.prevOp = prevOp;
  157. }
  158. if (force || !this.ace.curOp) {
  159. if (this.curOp)
  160. this.onBeforeEndOperation();
  161. }
  162. return result;
  163. };
  164. this.onBeforeEndOperation = function() {
  165. var op = this.curOp;
  166. if (op) {
  167. if (op.change) { this.signal("change", op.change, op); }
  168. if (op && op.cursorActivity) { this.signal("cursorActivity", null, op); }
  169. this.curOp = null;
  170. }
  171. };
  172. this.signal = function(eventName, e, handlers) {
  173. var listeners = handlers ? handlers[eventName + "Handlers"]
  174. : (this._eventRegistry || {})[eventName];
  175. if (!listeners)
  176. return;
  177. listeners = listeners.slice();
  178. for (var i=0; i<listeners.length; i++)
  179. listeners[i](this, e);
  180. };
  181. this.firstLine = function() { return 0; };
  182. this.lastLine = function() { return this.ace.session.getLength() - 1; };
  183. this.lineCount = function() { return this.ace.session.getLength(); };
  184. this.setCursor = function(line, ch) {
  185. if (typeof line === 'object') {
  186. ch = line.ch;
  187. line = line.line;
  188. }
  189. if (!this.ace.inVirtualSelectionMode)
  190. this.ace.exitMultiSelectMode();
  191. this.ace.session.unfold({row: line, column: ch});
  192. this.ace.selection.moveTo(line, ch);
  193. };
  194. this.getCursor = function(p) {
  195. var sel = this.ace.selection;
  196. var pos = p == 'anchor' ? (sel.isEmpty() ? sel.lead : sel.anchor) :
  197. p == 'head' || !p ? sel.lead : sel.getRange()[p];
  198. return toCmPos(pos);
  199. };
  200. this.listSelections = function(p) {
  201. var ranges = this.ace.multiSelect.rangeList.ranges;
  202. if (!ranges.length || this.ace.inVirtualSelectionMode)
  203. return [{anchor: this.getCursor('anchor'), head: this.getCursor('head')}];
  204. return ranges.map(function(r) {
  205. return {
  206. anchor: this.clipPos(toCmPos(r.cursor == r.end ? r.start : r.end)),
  207. head: this.clipPos(toCmPos(r.cursor))
  208. };
  209. }, this);
  210. };
  211. this.setSelections = function(p, primIndex) {
  212. var sel = this.ace.multiSelect;
  213. var ranges = p.map(function(x) {
  214. var anchor = toAcePos(x.anchor);
  215. var head = toAcePos(x.head);
  216. var r = Range.comparePoints(anchor, head) < 0
  217. ? new Range.fromPoints(anchor, head)
  218. : new Range.fromPoints(head, anchor);
  219. r.cursor = Range.comparePoints(r.start, head) ? r.end : r.start;
  220. return r;
  221. });
  222. if (this.ace.inVirtualSelectionMode) {
  223. this.ace.selection.fromOrientedRange(ranges[0]);
  224. return;
  225. }
  226. if (!primIndex) {
  227. ranges = ranges.reverse();
  228. } else if (ranges[primIndex]) {
  229. ranges.push(ranges.splice(primIndex, 1)[0]);
  230. }
  231. sel.toSingleRange(ranges[0].clone());
  232. var session = this.ace.session;
  233. for (var i = 0; i < ranges.length; i++) {
  234. var range = session.$clipRangeToDocument(ranges[i]); // todo why ace doesn't do this?
  235. sel.addRange(range);
  236. }
  237. };
  238. this.setSelection = function(a, h, options) {
  239. var sel = this.ace.selection;
  240. sel.moveTo(a.line, a.ch);
  241. sel.selectTo(h.line, h.ch);
  242. if (options && options.origin == '*mouse') {
  243. this.onBeforeEndOperation();
  244. }
  245. };
  246. this.somethingSelected = function(p) {
  247. return !this.ace.selection.isEmpty();
  248. };
  249. this.clipPos = function(p) {
  250. var pos = this.ace.session.$clipPositionToDocument(p.line, p.ch);
  251. return toCmPos(pos);
  252. };
  253. this.markText = function(cursor) {
  254. return {clear: function() {}, find: function() {}};
  255. };
  256. this.$updateMarkers = function(delta) {
  257. var isInsert = delta.action == "insert";
  258. var start = delta.start;
  259. var end = delta.end;
  260. var rowShift = (end.row - start.row) * (isInsert ? 1 : -1);
  261. var colShift = (end.column - start.column) * (isInsert ? 1 : -1);
  262. if (isInsert) end = start;
  263. for (var i in this.marks) {
  264. var point = this.marks[i];
  265. var cmp = Range.comparePoints(point, start);
  266. if (cmp < 0) {
  267. continue; // delta starts after the range
  268. }
  269. if (cmp === 0) {
  270. if (isInsert) {
  271. if (point.bias == 1) {
  272. cmp = 1;
  273. } else {
  274. point.bias == -1;
  275. continue;
  276. }
  277. }
  278. }
  279. var cmp2 = isInsert ? cmp : Range.comparePoints(point, end);
  280. if (cmp2 > 0) {
  281. point.row += rowShift;
  282. point.column += point.row == end.row ? colShift : 0;
  283. continue;
  284. }
  285. if (!isInsert && cmp2 <= 0) {
  286. point.row = start.row;
  287. point.column = start.column;
  288. if (cmp2 === 0)
  289. point.bias = 1;
  290. }
  291. }
  292. };
  293. var Marker = function(cm, id, row, column) {
  294. this.cm = cm;
  295. this.id = id;
  296. this.row = row;
  297. this.column = column;
  298. cm.marks[this.id] = this;
  299. };
  300. Marker.prototype.clear = function() { delete this.cm.marks[this.id] };
  301. Marker.prototype.find = function() { return toCmPos(this) };
  302. this.setBookmark = function(cursor, options) {
  303. var bm = new Marker(this, this.$uid++, cursor.line, cursor.ch);
  304. if (!options || !options.insertLeft)
  305. bm.$insertRight = true;
  306. this.marks[bm.id] = bm;
  307. return bm;
  308. };
  309. this.moveH = function(increment, unit) {
  310. if (unit == 'char') {
  311. var sel = this.ace.selection;
  312. sel.clearSelection();
  313. sel.moveCursorBy(0, increment);
  314. }
  315. };
  316. this.findPosV = function(start, amount, unit, goalColumn) {
  317. if (unit == 'page') {
  318. var renderer = this.ace.renderer;
  319. var config = renderer.layerConfig;
  320. amount = amount * Math.floor(config.height / config.lineHeight);
  321. unit = 'line';
  322. }
  323. if (unit == 'line') {
  324. var screenPos = this.ace.session.documentToScreenPosition(start.line, start.ch);
  325. if (goalColumn != null)
  326. screenPos.column = goalColumn;
  327. screenPos.row += amount;
  328. screenPos.row = Math.min(Math.max(0, screenPos.row), this.ace.session.getScreenLength() - 1);
  329. var pos = this.ace.session.screenToDocumentPosition(screenPos.row, screenPos.column);
  330. return toCmPos(pos);
  331. } else {
  332. debugger;
  333. }
  334. };
  335. this.charCoords = function(pos, mode) {
  336. if (mode == 'div' || !mode) {
  337. var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch);
  338. return {left: sc.column, top: sc.row};
  339. }if (mode == 'local') {
  340. var renderer = this.ace.renderer;
  341. var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch);
  342. var lh = renderer.layerConfig.lineHeight;
  343. var cw = renderer.layerConfig.characterWidth;
  344. var top = lh * sc.row;
  345. return {left: sc.column * cw, top: top, bottom: top + lh};
  346. }
  347. };
  348. this.coordsChar = function(pos, mode) {
  349. var renderer = this.ace.renderer;
  350. if (mode == 'local') {
  351. var row = Math.max(0, Math.floor(pos.top / renderer.lineHeight));
  352. var col = Math.max(0, Math.floor(pos.left / renderer.characterWidth));
  353. var ch = renderer.session.screenToDocumentPosition(row, col);
  354. return toCmPos(ch);
  355. } else if (mode == 'div') {
  356. throw "not implemented";
  357. }
  358. };
  359. this.getSearchCursor = function(query, pos, caseFold) {
  360. var caseSensitive = false;
  361. var isRegexp = false;
  362. if (query instanceof RegExp && !query.global) {
  363. caseSensitive = !query.ignoreCase;
  364. query = query.source;
  365. isRegexp = true;
  366. }
  367. var search = new Search();
  368. if (pos.ch == undefined) pos.ch = Number.MAX_VALUE;
  369. var acePos = {row: pos.line, column: pos.ch};
  370. var cm = this;
  371. var last = null;
  372. return {
  373. findNext: function() { return this.find(false) },
  374. findPrevious: function() {return this.find(true) },
  375. find: function(back) {
  376. search.setOptions({
  377. needle: query,
  378. caseSensitive: caseSensitive,
  379. wrap: false,
  380. backwards: back,
  381. regExp: isRegexp,
  382. start: last || acePos
  383. });
  384. var range = search.find(cm.ace.session);
  385. if (range && range.isEmpty()) {
  386. if (cm.getLine(range.start.row).length == range.start.column) {
  387. search.$options.start = range;
  388. range = search.find(cm.ace.session);
  389. }
  390. }
  391. last = range;
  392. return last;
  393. },
  394. from: function() { return last && toCmPos(last.start) },
  395. to: function() { return last && toCmPos(last.end) },
  396. replace: function(text) {
  397. if (last) {
  398. last.end = cm.ace.session.doc.replace(last, text);
  399. }
  400. }
  401. };
  402. };
  403. this.scrollTo = function(x, y) {
  404. var renderer = this.ace.renderer;
  405. var config = renderer.layerConfig;
  406. var maxHeight = config.maxHeight;
  407. maxHeight -= (renderer.$size.scrollerHeight - renderer.lineHeight) * renderer.$scrollPastEnd;
  408. if (y != null) this.ace.session.setScrollTop(Math.max(0, Math.min(y, maxHeight)));
  409. if (x != null) this.ace.session.setScrollLeft(Math.max(0, Math.min(x, config.width)));
  410. };
  411. this.scrollInfo = function() { return 0; };
  412. this.scrollIntoView = function(pos, margin) {
  413. if (pos) {
  414. var renderer = this.ace.renderer;
  415. var viewMargin = { "top": 0, "bottom": margin };
  416. renderer.scrollCursorIntoView(toAcePos(pos),
  417. (renderer.lineHeight * 2) / renderer.$size.scrollerHeight, viewMargin);
  418. }
  419. };
  420. this.getLine = function(row) { return this.ace.session.getLine(row) };
  421. this.getRange = function(s, e) {
  422. return this.ace.session.getTextRange(new Range(s.line, s.ch, e.line, e.ch));
  423. };
  424. this.replaceRange = function(text, s, e) {
  425. if (!e) e = s;
  426. return this.ace.session.replace(new Range(s.line, s.ch, e.line, e.ch), text);
  427. };
  428. this.replaceSelections = function(p) {
  429. var sel = this.ace.selection;
  430. if (this.ace.inVirtualSelectionMode) {
  431. this.ace.session.replace(sel.getRange(), p[0] || "");
  432. return;
  433. }
  434. sel.inVirtualSelectionMode = true;
  435. var ranges = sel.rangeList.ranges;
  436. if (!ranges.length) ranges = [this.ace.multiSelect.getRange()];
  437. for (var i = ranges.length; i--;)
  438. this.ace.session.replace(ranges[i], p[i] || "");
  439. sel.inVirtualSelectionMode = false;
  440. };
  441. this.getSelection = function() {
  442. return this.ace.getSelectedText();
  443. };
  444. this.getSelections = function() {
  445. return this.listSelections().map(function(x) {
  446. return this.getRange(x.anchor, x.head);
  447. }, this);
  448. };
  449. this.getInputField = function() {
  450. return this.ace.textInput.getElement();
  451. };
  452. this.getWrapperElement = function() {
  453. return this.ace.containter;
  454. };
  455. var optMap = {
  456. indentWithTabs: "useSoftTabs",
  457. indentUnit: "tabSize",
  458. tabSize: "tabSize",
  459. firstLineNumber: "firstLineNumber",
  460. readOnly: "readOnly"
  461. };
  462. this.setOption = function(name, val) {
  463. this.state[name] = val;
  464. switch (name) {
  465. case 'indentWithTabs':
  466. name = optMap[name];
  467. val = !val;
  468. break;
  469. default:
  470. name = optMap[name];
  471. }
  472. if (name)
  473. this.ace.setOption(name, val);
  474. };
  475. this.getOption = function(name, val) {
  476. var aceOpt = optMap[name];
  477. if (aceOpt)
  478. val = this.ace.getOption(aceOpt);
  479. switch (name) {
  480. case 'indentWithTabs':
  481. name = optMap[name];
  482. return !val;
  483. }
  484. return aceOpt ? val : this.state[name];
  485. };
  486. this.toggleOverwrite = function(on) {
  487. this.state.overwrite = on;
  488. return this.ace.setOverwrite(on);
  489. };
  490. this.addOverlay = function(o) {
  491. if (!this.$searchHighlight || !this.$searchHighlight.session) {
  492. var highlight = new SearchHighlight(null, "ace_highlight-marker", "text");
  493. var marker = this.ace.session.addDynamicMarker(highlight);
  494. highlight.id = marker.id;
  495. highlight.session = this.ace.session;
  496. highlight.destroy = function(o) {
  497. highlight.session.off("change", highlight.updateOnChange);
  498. highlight.session.off("changeEditor", highlight.destroy);
  499. highlight.session.removeMarker(highlight.id);
  500. highlight.session = null;
  501. };
  502. highlight.updateOnChange = function(delta) {
  503. var row = delta.start.row;
  504. if (row == delta.end.row) highlight.cache[row] = undefined;
  505. else highlight.cache.splice(row, highlight.cache.length);
  506. };
  507. highlight.session.on("changeEditor", highlight.destroy);
  508. highlight.session.on("change", highlight.updateOnChange);
  509. }
  510. var re = new RegExp(o.query.source, "gmi");
  511. this.$searchHighlight = o.highlight = highlight;
  512. this.$searchHighlight.setRegexp(re);
  513. this.ace.renderer.updateBackMarkers();
  514. };
  515. this.removeOverlay = function(o) {
  516. if (this.$searchHighlight && this.$searchHighlight.session) {
  517. this.$searchHighlight.destroy();
  518. }
  519. };
  520. this.getScrollInfo = function() {
  521. var renderer = this.ace.renderer;
  522. var config = renderer.layerConfig;
  523. return {
  524. left: renderer.scrollLeft,
  525. top: renderer.scrollTop,
  526. height: config.maxHeight,
  527. width: config.width,
  528. clientHeight: config.height,
  529. clientWidth: config.width
  530. };
  531. };
  532. this.getValue = function() {
  533. return this.ace.getValue();
  534. };
  535. this.setValue = function(v) {
  536. return this.ace.setValue(v);
  537. };
  538. this.getTokenTypeAt = function(pos) {
  539. var token = this.ace.session.getTokenAt(pos.line, pos.ch);
  540. return token && /comment|string/.test(token.type) ? "string" : "";
  541. };
  542. this.findMatchingBracket = function(pos) {
  543. var m = this.ace.session.findMatchingBracket(toAcePos(pos));
  544. return {to: m && toCmPos(m)};
  545. };
  546. this.indentLine = function(line, method) {
  547. if (method === true)
  548. this.ace.session.indentRows(line, line, "\t");
  549. else if (method === false)
  550. this.ace.session.outdentRows(new Range(line, 0, line, 0));
  551. };
  552. this.indexFromPos = function(pos) {
  553. return this.ace.session.doc.positionToIndex(toAcePos(pos));
  554. };
  555. this.posFromIndex = function(index) {
  556. return toCmPos(this.ace.session.doc.indexToPosition(index));
  557. };
  558. this.focus = function(index) {
  559. return this.ace.focus();
  560. };
  561. this.blur = function(index) {
  562. return this.ace.blur();
  563. };
  564. this.defaultTextHeight = function(index) {
  565. return this.ace.renderer.layerConfig.lineHeight;
  566. };
  567. this.scanForBracket = function(pos, dir, _, options) {
  568. var re = options.bracketRegex.source;
  569. if (dir == 1) {
  570. var m = this.ace.session.$findClosingBracket(re.slice(1, 2), toAcePos(pos), /paren|text/);
  571. } else {
  572. var m = this.ace.session.$findOpeningBracket(re.slice(-2, -1), {row: pos.line, column: pos.ch + 1}, /paren|text/);
  573. }
  574. return m && {pos: toCmPos(m)};
  575. };
  576. this.refresh = function() {
  577. return this.ace.resize(true);
  578. };
  579. this.getMode = function() {
  580. return { name : this.getOption("mode") };
  581. }
  582. }).call(CodeMirror.prototype);
  583. function toAcePos(cmPos) {
  584. return {row: cmPos.line, column: cmPos.ch};
  585. }
  586. function toCmPos(acePos) {
  587. return new Pos(acePos.row, acePos.column);
  588. }
  589. var StringStream = CodeMirror.StringStream = function(string, tabSize) {
  590. this.pos = this.start = 0;
  591. this.string = string;
  592. this.tabSize = tabSize || 8;
  593. this.lastColumnPos = this.lastColumnValue = 0;
  594. this.lineStart = 0;
  595. };
  596. StringStream.prototype = {
  597. eol: function() {return this.pos >= this.string.length;},
  598. sol: function() {return this.pos == this.lineStart;},
  599. peek: function() {return this.string.charAt(this.pos) || undefined;},
  600. next: function() {
  601. if (this.pos < this.string.length)
  602. return this.string.charAt(this.pos++);
  603. },
  604. eat: function(match) {
  605. var ch = this.string.charAt(this.pos);
  606. if (typeof match == "string") var ok = ch == match;
  607. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  608. if (ok) {++this.pos; return ch;}
  609. },
  610. eatWhile: function(match) {
  611. var start = this.pos;
  612. while (this.eat(match)){}
  613. return this.pos > start;
  614. },
  615. eatSpace: function() {
  616. var start = this.pos;
  617. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  618. return this.pos > start;
  619. },
  620. skipToEnd: function() {this.pos = this.string.length;},
  621. skipTo: function(ch) {
  622. var found = this.string.indexOf(ch, this.pos);
  623. if (found > -1) {this.pos = found; return true;}
  624. },
  625. backUp: function(n) {this.pos -= n;},
  626. column: function() {
  627. throw "not implemented";
  628. },
  629. indentation: function() {
  630. throw "not implemented";
  631. },
  632. match: function(pattern, consume, caseInsensitive) {
  633. if (typeof pattern == "string") {
  634. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  635. var substr = this.string.substr(this.pos, pattern.length);
  636. if (cased(substr) == cased(pattern)) {
  637. if (consume !== false) this.pos += pattern.length;
  638. return true;
  639. }
  640. } else {
  641. var match = this.string.slice(this.pos).match(pattern);
  642. if (match && match.index > 0) return null;
  643. if (match && consume !== false) this.pos += match[0].length;
  644. return match;
  645. }
  646. },
  647. current: function(){return this.string.slice(this.start, this.pos);},
  648. hideFirstChars: function(n, inner) {
  649. this.lineStart += n;
  650. try { return inner(); }
  651. finally { this.lineStart -= n; }
  652. }
  653. };
  654. CodeMirror.defineExtension = function(name, fn) {
  655. CodeMirror.prototype[name] = fn;
  656. };
  657. dom.importCssString(".normal-mode .ace_cursor{\
  658. border: 1px solid red;\
  659. background-color: red;\
  660. opacity: 0.5;\
  661. }\
  662. .normal-mode .ace_hidden-cursors .ace_cursor{\
  663. background-color: transparent;\
  664. }\
  665. .ace_dialog {\
  666. position: absolute;\
  667. left: 0; right: 0;\
  668. background: white;\
  669. z-index: 15;\
  670. padding: .1em .8em;\
  671. overflow: hidden;\
  672. color: #333;\
  673. }\
  674. .ace_dialog-top {\
  675. border-bottom: 1px solid #eee;\
  676. top: 0;\
  677. }\
  678. .ace_dialog-bottom {\
  679. border-top: 1px solid #eee;\
  680. bottom: 0;\
  681. }\
  682. .ace_dialog input {\
  683. border: none;\
  684. outline: none;\
  685. background: transparent;\
  686. width: 20em;\
  687. color: inherit;\
  688. font-family: monospace;\
  689. }", "vimMode");
  690. (function() {
  691. function dialogDiv(cm, template, bottom) {
  692. var wrap = cm.ace.container;
  693. var dialog;
  694. dialog = wrap.appendChild(document.createElement("div"));
  695. if (bottom)
  696. dialog.className = "ace_dialog ace_dialog-bottom";
  697. else
  698. dialog.className = "ace_dialog ace_dialog-top";
  699. if (typeof template == "string") {
  700. dialog.innerHTML = template;
  701. } else { // Assuming it's a detached DOM element.
  702. dialog.appendChild(template);
  703. }
  704. return dialog;
  705. }
  706. function closeNotification(cm, newVal) {
  707. if (cm.state.currentNotificationClose)
  708. cm.state.currentNotificationClose();
  709. cm.state.currentNotificationClose = newVal;
  710. }
  711. CodeMirror.defineExtension("openDialog", function(template, callback, options) {
  712. if (this.virtualSelectionMode()) return;
  713. if (!options) options = {};
  714. closeNotification(this, null);
  715. var dialog = dialogDiv(this, template, options.bottom);
  716. var closed = false, me = this;
  717. function close(newVal) {
  718. if (typeof newVal == 'string') {
  719. inp.value = newVal;
  720. } else {
  721. if (closed) return;
  722. closed = true;
  723. dialog.parentNode.removeChild(dialog);
  724. me.focus();
  725. if (options.onClose) options.onClose(dialog);
  726. }
  727. }
  728. var inp = dialog.getElementsByTagName("input")[0], button;
  729. if (inp) {
  730. if (options.value) {
  731. inp.value = options.value;
  732. if (options.select !== false) inp.select();
  733. }
  734. if (options.onInput)
  735. CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);});
  736. if (options.onKeyUp)
  737. CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
  738. CodeMirror.on(inp, "keydown", function(e) {
  739. if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
  740. if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) {
  741. inp.blur();
  742. CodeMirror.e_stop(e);
  743. close();
  744. }
  745. if (e.keyCode == 13) callback(inp.value);
  746. });
  747. if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close);
  748. inp.focus();
  749. } else if (button = dialog.getElementsByTagName("button")[0]) {
  750. CodeMirror.on(button, "click", function() {
  751. close();
  752. me.focus();
  753. });
  754. if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close);
  755. button.focus();
  756. }
  757. return close;
  758. });
  759. CodeMirror.defineExtension("openNotification", function(template, options) {
  760. if (this.virtualSelectionMode()) return;
  761. closeNotification(this, close);
  762. var dialog = dialogDiv(this, template, options && options.bottom);
  763. var closed = false, doneTimer;
  764. var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000;
  765. function close() {
  766. if (closed) return;
  767. closed = true;
  768. clearTimeout(doneTimer);
  769. dialog.parentNode.removeChild(dialog);
  770. }
  771. CodeMirror.on(dialog, 'click', function(e) {
  772. CodeMirror.e_preventDefault(e);
  773. close();
  774. });
  775. if (duration)
  776. doneTimer = setTimeout(close, duration);
  777. return close;
  778. });
  779. })();
  780. var defaultKeymap = [
  781. { keys: '<Left>', type: 'keyToKey', toKeys: 'h' },
  782. { keys: '<Right>', type: 'keyToKey', toKeys: 'l' },
  783. { keys: '<Up>', type: 'keyToKey', toKeys: 'k' },
  784. { keys: '<Down>', type: 'keyToKey', toKeys: 'j' },
  785. { keys: '<Space>', type: 'keyToKey', toKeys: 'l' },
  786. { keys: '<BS>', type: 'keyToKey', toKeys: 'h', context: 'normal'},
  787. { keys: '<C-Space>', type: 'keyToKey', toKeys: 'W' },
  788. { keys: '<C-BS>', type: 'keyToKey', toKeys: 'B', context: 'normal' },
  789. { keys: '<S-Space>', type: 'keyToKey', toKeys: 'w' },
  790. { keys: '<S-BS>', type: 'keyToKey', toKeys: 'b', context: 'normal' },
  791. { keys: '<C-n>', type: 'keyToKey', toKeys: 'j' },
  792. { keys: '<C-p>', type: 'keyToKey', toKeys: 'k' },
  793. { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>' },
  794. { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>' },
  795. { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
  796. { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
  797. { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' },
  798. { keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual'},
  799. { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' },
  800. { keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' },
  801. { keys: '<Home>', type: 'keyToKey', toKeys: '0' },
  802. { keys: '<End>', type: 'keyToKey', toKeys: '$' },
  803. { keys: '<PageUp>', type: 'keyToKey', toKeys: '<C-b>' },
  804. { keys: '<PageDown>', type: 'keyToKey', toKeys: '<C-f>' },
  805. { keys: '<CR>', type: 'keyToKey', toKeys: 'j^', context: 'normal' },
  806. { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }},
  807. { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }},
  808. { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }},
  809. { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }},
  810. { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }},
  811. { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }},
  812. { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }},
  813. { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }},
  814. { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }},
  815. { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }},
  816. { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }},
  817. { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }},
  818. { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }},
  819. { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }},
  820. { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }},
  821. { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }},
  822. { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }},
  823. { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }},
  824. { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }},
  825. { keys: '<C-f>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }},
  826. { keys: '<C-b>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }},
  827. { keys: '<C-d>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }},
  828. { keys: '<C-u>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }},
  829. { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
  830. { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
  831. { keys: '0', type: 'motion', motion: 'moveToStartOfLine' },
  832. { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' },
  833. { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }},
  834. { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }},
  835. { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
  836. { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }},
  837. { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }},
  838. { keys: 'f<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }},
  839. { keys: 'F<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }},
  840. { keys: 't<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }},
  841. { keys: 'T<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }},
  842. { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }},
  843. { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }},
  844. { keys: '\'<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}},
  845. { keys: '`<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}},
  846. { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
  847. { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
  848. { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
  849. { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
  850. { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}},
  851. { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}},
  852. { keys: ']<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}},
  853. { keys: '[<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}},
  854. { keys: '|', type: 'motion', motion: 'moveToColumn'},
  855. { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'},
  856. { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},
  857. { keys: 'd', type: 'operator', operator: 'delete' },
  858. { keys: 'y', type: 'operator', operator: 'yank' },
  859. { keys: 'c', type: 'operator', operator: 'change' },
  860. { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }},
  861. { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }},
  862. { keys: 'g~', type: 'operator', operator: 'changeCase' },
  863. { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true },
  864. { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true },
  865. { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }},
  866. { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }},
  867. { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }},
  868. { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }},
  869. { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
  870. { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'},
  871. { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
  872. { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'},
  873. { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
  874. { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'},
  875. { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'},
  876. { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'},
  877. { keys: '<C-w>', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' },
  878. { keys: '<C-i>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }},
  879. { keys: '<C-o>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }},
  880. { keys: '<C-e>', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }},
  881. { keys: '<C-y>', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }},
  882. { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' },
  883. { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' },
  884. { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
  885. { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' },
  886. { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' },
  887. { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' },
  888. { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' },
  889. { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' },
  890. { keys: 'v', type: 'action', action: 'toggleVisualMode' },
  891. { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }},
  892. { keys: '<C-v>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
  893. { keys: '<C-q>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
  894. { keys: 'gv', type: 'action', action: 'reselectLastSelection' },
  895. { keys: 'J', type: 'action', action: 'joinLines', isEdit: true },
  896. { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }},
  897. { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }},
  898. { keys: 'r<character>', type: 'action', action: 'replace', isEdit: true },
  899. { keys: '@<character>', type: 'action', action: 'replayMacro' },
  900. { keys: 'q<character>', type: 'action', action: 'enterMacroRecordMode' },
  901. { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }},
  902. { keys: 'u', type: 'action', action: 'undo', context: 'normal' },
  903. { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true },
  904. { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true },
  905. { keys: '<C-r>', type: 'action', action: 'redo' },
  906. { keys: 'm<character>', type: 'action', action: 'setMark' },
  907. { keys: '"<character>', type: 'action', action: 'setRegister' },
  908. { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},
  909. { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
  910. { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},
  911. { keys: 'z<CR>', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
  912. { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }},
  913. { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
  914. { keys: '.', type: 'action', action: 'repeatLastEdit' },
  915. { keys: '<C-a>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}},
  916. { keys: '<C-x>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}},
  917. { keys: 'a<character>', type: 'motion', motion: 'textObjectManipulation' },
  918. { keys: 'i<character>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
  919. { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
  920. { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
  921. { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
  922. { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
  923. { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
  924. { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
  925. { keys: ':', type: 'ex' }
  926. ];
  927. var defaultExCommandMap = [
  928. { name: 'colorscheme', shortName: 'colo' },
  929. { name: 'map' },
  930. { name: 'imap', shortName: 'im' },
  931. { name: 'nmap', shortName: 'nm' },
  932. { name: 'vmap', shortName: 'vm' },
  933. { name: 'unmap' },
  934. { name: 'write', shortName: 'w' },
  935. { name: 'undo', shortName: 'u' },
  936. { name: 'redo', shortName: 'red' },
  937. { name: 'set', shortName: 'se' },
  938. { name: 'set', shortName: 'se' },
  939. { name: 'setlocal', shortName: 'setl' },
  940. { name: 'setglobal', shortName: 'setg' },
  941. { name: 'sort', shortName: 'sor' },
  942. { name: 'substitute', shortName: 's', possiblyAsync: true },
  943. { name: 'nohlsearch', shortName: 'noh' },
  944. { name: 'delmarks', shortName: 'delm' },
  945. { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true },
  946. { name: 'global', shortName: 'g' }
  947. ];
  948. var Pos = CodeMirror.Pos;
  949. var Vim = function() { return vimApi; } //{
  950. function enterVimMode(cm) {
  951. cm.setOption('disableInput', true);
  952. cm.setOption('showCursorWhenSelecting', false);
  953. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  954. cm.on('cursorActivity', onCursorActivity);
  955. maybeInitVimState(cm);
  956. CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
  957. }
  958. function leaveVimMode(cm) {
  959. cm.setOption('disableInput', false);
  960. cm.off('cursorActivity', onCursorActivity);
  961. CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
  962. cm.state.vim = null;
  963. }
  964. function detachVimMap(cm, next) {
  965. if (this == CodeMirror.keyMap.vim)
  966. CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor");
  967. if (!next || next.attach != attachVimMap)
  968. leaveVimMode(cm, false);
  969. }
  970. function attachVimMap(cm, prev) {
  971. if (this == CodeMirror.keyMap.vim)
  972. CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor");
  973. if (!prev || prev.attach != attachVimMap)
  974. enterVimMode(cm);
  975. }
  976. CodeMirror.defineOption('vimMode', false, function(cm, val, prev) {
  977. if (val && cm.getOption("keyMap") != "vim")
  978. cm.setOption("keyMap", "vim");
  979. else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap")))
  980. cm.setOption("keyMap", "default");
  981. });
  982. function cmKey(key, cm) {
  983. if (!cm) { return undefined; }
  984. var vimKey = cmKeyToVimKey(key);
  985. if (!vimKey) {
  986. return false;
  987. }
  988. var cmd = CodeMirror.Vim.findKey(cm, vimKey);
  989. if (typeof cmd == 'function') {
  990. CodeMirror.signal(cm, 'vim-keypress', vimKey);
  991. }
  992. return cmd;
  993. }
  994. var modifiers = {'Shift': 'S', 'Ctrl': 'C', 'Alt': 'A', 'Cmd': 'D', 'Mod': 'A'};
  995. var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del'};
  996. function cmKeyToVimKey(key) {
  997. if (key.charAt(0) == '\'') {
  998. return key.charAt(1);
  999. }
  1000. var pieces = key.split(/-(?!$)/);
  1001. var lastPiece = pieces[pieces.length - 1];
  1002. if (pieces.length == 1 && pieces[0].length == 1) {
  1003. return false;
  1004. } else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) {
  1005. return false;
  1006. }
  1007. var hasCharacter = false;
  1008. for (var i = 0; i < pieces.length; i++) {
  1009. var piece = pieces[i];
  1010. if (piece in modifiers) { pieces[i] = modifiers[piece]; }
  1011. else { hasCharacter = true; }
  1012. if (piece in specialKeys) { pieces[i] = specialKeys[piece]; }
  1013. }
  1014. if (!hasCharacter) {
  1015. return false;
  1016. }
  1017. if (isUpperCase(lastPiece)) {
  1018. pieces[pieces.length - 1] = lastPiece.toLowerCase();
  1019. }
  1020. return '<' + pieces.join('-') + '>';
  1021. }
  1022. function getOnPasteFn(cm) {
  1023. var vim = cm.state.vim;
  1024. if (!vim.onPasteFn) {
  1025. vim.onPasteFn = function() {
  1026. if (!vim.insertMode) {
  1027. cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
  1028. actions.enterInsertMode(cm, {}, vim);
  1029. }
  1030. };
  1031. }
  1032. return vim.onPasteFn;
  1033. }
  1034. var numberRegex = /[\d]/;
  1035. var wordCharTest = [CodeMirror.isWordChar, function(ch) {
  1036. return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch);
  1037. }], bigWordCharTest = [function(ch) {
  1038. return /\S/.test(ch);
  1039. }];
  1040. function makeKeyRange(start, size) {
  1041. var keys = [];
  1042. for (var i = start; i < start + size; i++) {
  1043. keys.push(String.fromCharCode(i));
  1044. }
  1045. return keys;
  1046. }
  1047. var upperCaseAlphabet = makeKeyRange(65, 26);
  1048. var lowerCaseAlphabet = makeKeyRange(97, 26);
  1049. var numbers = makeKeyRange(48, 10);
  1050. var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
  1051. var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']);
  1052. function isLine(cm, line) {
  1053. return line >= cm.firstLine() && line <= cm.lastLine();
  1054. }
  1055. function isLowerCase(k) {
  1056. return (/^[a-z]$/).test(k);
  1057. }
  1058. function isMatchableSymbol(k) {
  1059. return '()[]{}'.indexOf(k) != -1;
  1060. }
  1061. function isNumber(k) {
  1062. return numberRegex.test(k);
  1063. }
  1064. function isUpperCase(k) {
  1065. return (/^[A-Z]$/).test(k);
  1066. }
  1067. function isWhiteSpaceString(k) {
  1068. return (/^\s*$/).test(k);
  1069. }
  1070. function inArray(val, arr) {
  1071. for (var i = 0; i < arr.length; i++) {
  1072. if (arr[i] == val) {
  1073. return true;
  1074. }
  1075. }
  1076. return false;
  1077. }
  1078. var options = {};
  1079. function defineOption(name, defaultValue, type, aliases, callback) {
  1080. if (defaultValue === undefined && !callback) {
  1081. throw Error('defaultValue is acequired unless callback is provided');
  1082. }
  1083. if (!type) { type = 'string'; }
  1084. options[name] = {
  1085. type: type,
  1086. defaultValue: defaultValue,
  1087. callback: callback
  1088. };
  1089. if (aliases) {
  1090. for (var i = 0; i < aliases.length; i++) {
  1091. options[aliases[i]] = options[name];
  1092. }
  1093. }
  1094. if (defaultValue) {
  1095. setOption(name, defaultValue);
  1096. }
  1097. }
  1098. function setOption(name, value, cm, cfg) {
  1099. var option = options[name];
  1100. cfg = cfg || {};
  1101. var scope = cfg.scope;
  1102. if (!option) {
  1103. throw Error('Unknown option: ' + name);
  1104. }
  1105. if (option.type == 'boolean') {
  1106. if (value && value !== true) {
  1107. throw Error('Invalid argument: ' + name + '=' + value);
  1108. } else if (value !== false) {
  1109. value = true;
  1110. }
  1111. }
  1112. if (option.callback) {
  1113. if (scope !== 'local') {
  1114. option.callback(value, undefined);
  1115. }
  1116. if (scope !== 'global' && cm) {
  1117. option.callback(value, cm);
  1118. }
  1119. } else {
  1120. if (scope !== 'local') {
  1121. option.value = option.type == 'boolean' ? !!value : value;
  1122. }
  1123. if (scope !== 'global' && cm) {
  1124. cm.state.vim.options[name] = {value: value};
  1125. }
  1126. }
  1127. }
  1128. function getOption(name, cm, cfg) {
  1129. var option = options[name];
  1130. cfg = cfg || {};
  1131. var scope = cfg.scope;
  1132. if (!option) {
  1133. throw Error('Unknown option: ' + name);
  1134. }
  1135. if (option.callback) {
  1136. var local = cm && option.callback(undefined, cm);
  1137. if (scope !== 'global' && local !== undefined) {
  1138. return local;
  1139. }
  1140. if (scope !== 'local') {
  1141. return option.callback();
  1142. }
  1143. return;
  1144. } else {
  1145. var local = (scope !== 'global') && (cm && cm.state.vim.options[name]);
  1146. return (local || (scope !== 'local') && option || {}).value;
  1147. }
  1148. }
  1149. defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) {
  1150. if (cm === undefined) {
  1151. return;
  1152. }
  1153. if (name === undefined) {
  1154. var mode = cm.getOption('mode');
  1155. return mode == 'null' ? '' : mode;
  1156. } else {
  1157. var mode = name == '' ? 'null' : name;
  1158. cm.setOption('mode', mode);
  1159. }
  1160. });
  1161. var createCircularJumpList = function() {
  1162. var size = 100;
  1163. var pointer = -1;
  1164. var head = 0;
  1165. var tail = 0;
  1166. var buffer = new Array(size);
  1167. function add(cm, oldCur, newCur) {
  1168. var current = pointer % size;
  1169. var curMark = buffer[current];
  1170. function useNextSlot(cursor) {
  1171. var next = ++pointer % size;
  1172. var trashMark = buffer[next];
  1173. if (trashMark) {
  1174. trashMark.clear();
  1175. }
  1176. buffer[next] = cm.setBookmark(cursor);
  1177. }
  1178. if (curMark) {
  1179. var markPos = curMark.find();
  1180. if (markPos && !cursorEqual(markPos, oldCur)) {
  1181. useNextSlot(oldCur);
  1182. }
  1183. } else {
  1184. useNextSlot(oldCur);
  1185. }
  1186. useNextSlot(newCur);
  1187. head = pointer;
  1188. tail = pointer - size + 1;
  1189. if (tail < 0) {
  1190. tail = 0;
  1191. }
  1192. }
  1193. function move(cm, offset) {
  1194. pointer += offset;
  1195. if (pointer > head) {
  1196. pointer = head;
  1197. } else if (pointer < tail) {
  1198. pointer = tail;
  1199. }
  1200. var mark = buffer[(size + pointer) % size];
  1201. if (mark && !mark.find()) {
  1202. var inc = offset > 0 ? 1 : -1;
  1203. var newCur;
  1204. var oldCur = cm.getCursor();
  1205. do {
  1206. pointer += inc;
  1207. mark = buffer[(size + pointer) % size];
  1208. if (mark &&
  1209. (newCur = mark.find()) &&
  1210. !cursorEqual(oldCur, newCur)) {
  1211. break;
  1212. }
  1213. } while (pointer < head && pointer > tail);
  1214. }
  1215. return mark;
  1216. }
  1217. return {
  1218. cachedCursor: undefined, //used for # and * jumps
  1219. add: add,
  1220. move: move
  1221. };
  1222. };
  1223. var createInsertModeChanges = function(c) {
  1224. if (c) {
  1225. return {
  1226. changes: c.changes,
  1227. expectCursorActivityForChange: c.expectCursorActivityForChange
  1228. };
  1229. }
  1230. return {
  1231. changes: [],
  1232. expectCursorActivityForChange: false
  1233. };
  1234. };
  1235. function MacroModeState() {
  1236. this.latestRegister = undefined;
  1237. this.isPlaying = false;
  1238. this.isRecording = false;
  1239. this.replaySearchQueries = [];
  1240. this.onRecordingDone = undefined;
  1241. this.lastInsertModeChanges = createInsertModeChanges();
  1242. }
  1243. MacroModeState.prototype = {
  1244. exitMacroRecordMode: function() {
  1245. var macroModeState = vimGlobalState.macroModeState;
  1246. if (macroModeState.onRecordingDone) {
  1247. macroModeState.onRecordingDone(); // close dialog
  1248. }
  1249. macroModeState.onRecordingDone = undefined;
  1250. macroModeState.isRecording = false;
  1251. },
  1252. enterMacroRecordMode: function(cm, registerName) {
  1253. var register =
  1254. vimGlobalState.registerController.getRegister(registerName);
  1255. if (register) {
  1256. register.clear();
  1257. this.latestRegister = registerName;
  1258. if (cm.openDialog) {
  1259. this.onRecordingDone = cm.openDialog(
  1260. '(recording)['+registerName+']', null, {bottom:true});
  1261. }
  1262. this.isRecording = true;
  1263. }
  1264. }
  1265. };
  1266. function maybeInitVimState(cm) {
  1267. if (!cm.state.vim) {
  1268. cm.state.vim = {
  1269. inputState: new InputState(),
  1270. lastEditInputState: undefined,
  1271. lastEditActionCommand: undefined,
  1272. lastHPos: -1,
  1273. lastHSPos: -1,
  1274. lastMotion: null,
  1275. marks: {},
  1276. fakeCursor: null,
  1277. insertMode: false,
  1278. insertModeRepeat: undefined,
  1279. visualMode: false,
  1280. visualLine: false,
  1281. visualBlock: false,
  1282. lastSelection: null,
  1283. lastPastedText: null,
  1284. sel: {},
  1285. options: {}
  1286. };
  1287. }
  1288. return cm.state.vim;
  1289. }
  1290. var vimGlobalState;
  1291. function resetVimGlobalState() {
  1292. vimGlobalState = {
  1293. searchQuery: null,
  1294. searchIsReversed: false,
  1295. lastSubstituteReplacePart: undefined,
  1296. jumpList: createCircularJumpList(),
  1297. macroModeState: new MacroModeState,
  1298. lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''},
  1299. registerController: new RegisterController({}),
  1300. searchHistoryController: new HistoryController({}),
  1301. exCommandHistoryController : new HistoryController({})
  1302. };
  1303. for (var optionName in options) {
  1304. var option = options[optionName];
  1305. option.value = option.defaultValue;
  1306. }
  1307. }
  1308. var lastInsertModeKeyTimer;
  1309. var vimApi= {
  1310. buildKeyMap: function() {
  1311. },
  1312. getRegisterController: function() {
  1313. return vimGlobalState.registerController;
  1314. },
  1315. resetVimGlobalState_: resetVimGlobalState,
  1316. getVimGlobalState_: function() {
  1317. return vimGlobalState;
  1318. },
  1319. maybeInitVimState_: maybeInitVimState,
  1320. suppressErrorLogging: false,
  1321. InsertModeKey: InsertModeKey,
  1322. map: function(lhs, rhs, ctx) {
  1323. exCommandDispatcher.map(lhs, rhs, ctx);
  1324. },
  1325. unmap: function(lhs, ctx) {
  1326. exCommandDispatcher.unmap(lhs, ctx);
  1327. },
  1328. setOption: setOption,
  1329. getOption: getOption,
  1330. defineOption: defineOption,
  1331. defineEx: function(name, prefix, func){
  1332. if (!prefix) {
  1333. prefix = name;
  1334. } else if (name.indexOf(prefix) !== 0) {
  1335. throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
  1336. }
  1337. exCommands[name]=func;
  1338. exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
  1339. },
  1340. handleKey: function (cm, key, origin) {
  1341. var command = this.findKey(cm, key, origin);
  1342. if (typeof command === 'function') {
  1343. return command();
  1344. }
  1345. },
  1346. findKey: function(cm, key, origin) {
  1347. var vim = maybeInitVimState(cm);
  1348. function handleMacroRecording() {
  1349. var macroModeState = vimGlobalState.macroModeState;
  1350. if (macroModeState.isRecording) {
  1351. if (key == 'q') {
  1352. macroModeState.exitMacroRecordMode();
  1353. clearInputState(cm);
  1354. return true;
  1355. }
  1356. if (origin != 'mapping') {
  1357. logKey(macroModeState, key);
  1358. }
  1359. }
  1360. }
  1361. function handleEsc() {
  1362. if (key == '<Esc>') {
  1363. clearInputState(cm);
  1364. if (vim.visualMode) {
  1365. exitVisualMode(cm);
  1366. } else if (vim.insertMode) {
  1367. exitInsertMode(cm);
  1368. }
  1369. return true;
  1370. }
  1371. }
  1372. function doKeyToKey(keys) {
  1373. var match;
  1374. while (keys) {
  1375. match = (/<\w+-.+?>|<\w+>|./).exec(keys);
  1376. key = match[0];
  1377. keys = keys.substring(match.index + key.length);
  1378. CodeMirror.Vim.handleKey(cm, key, 'mapping');
  1379. }
  1380. }
  1381. function handleKeyInsertMode() {
  1382. if (handleEsc()) { return true; }
  1383. var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
  1384. var keysAreChars = key.length == 1;
  1385. var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
  1386. while (keys.length > 1 && match.type != 'full') {
  1387. var keys = vim.inputState.keyBuffer = keys.slice(1);
  1388. var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
  1389. if (thisMatch.type != 'none') { match = thisMatch; }
  1390. }
  1391. if (match.type == 'none') { clearInputState(cm); return false; }
  1392. else if (match.type == 'partial') {
  1393. if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
  1394. lastInsertModeKeyTimer = window.setTimeout(
  1395. function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } },
  1396. getOption('insertModeEscKeysTimeout'));
  1397. return !keysAreChars;
  1398. }
  1399. if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
  1400. if (keysAreChars) {
  1401. var selections = cm.listSelections();
  1402. for (var i = 0; i < selections.length; i++) {
  1403. var here = selections[i].head;
  1404. cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input');
  1405. }
  1406. vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop();
  1407. }
  1408. clearInputState(cm);
  1409. return match.command;
  1410. }
  1411. function handleKeyNonInsertMode() {
  1412. if (handleMacroRecording() || handleEsc()) { return true; }
  1413. var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
  1414. if (/^[1-9]\d*$/.test(keys)) { return true; }
  1415. var keysMatcher = /^(\d*)(.*)$/.exec(keys);
  1416. if (!keysMatcher) { clearInputState(cm); return false; }
  1417. var context = vim.visualMode ? 'visual' :
  1418. 'normal';
  1419. var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context);
  1420. if (match.type == 'none') { clearInputState(cm); return false; }
  1421. else if (match.type == 'partial') { return true; }
  1422. vim.inputState.keyBuffer = '';
  1423. var keysMatcher = /^(\d*)(.*)$/.exec(keys);
  1424. if (keysMatcher[1] && keysMatcher[1] != '0') {
  1425. vim.inputState.pushRepeatDigit(keysMatcher[1]);
  1426. }
  1427. return match.command;
  1428. }
  1429. var command;
  1430. if (vim.insertMode) { command = handleKeyInsertMode(); }
  1431. else { command = handleKeyNonInsertMode(); }
  1432. if (command === false) {
  1433. return undefined;
  1434. } else if (command === true) {
  1435. return function() { return true; };
  1436. } else {
  1437. return function() {
  1438. if ((command.operator || command.isEdit) && cm.getOption('readOnly'))
  1439. return; // ace_patch
  1440. return cm.operation(function() {
  1441. cm.curOp.isVimOp = true;
  1442. try {
  1443. if (command.type == 'keyToKey') {
  1444. doKeyToKey(command.toKeys);
  1445. } else {
  1446. commandDispatcher.processCommand(cm, vim, command);
  1447. }
  1448. } catch (e) {
  1449. cm.state.vim = undefined;
  1450. maybeInitVimState(cm);
  1451. if (!CodeMirror.Vim.suppressErrorLogging) {
  1452. console['log'](e);
  1453. }
  1454. throw e;
  1455. }
  1456. return true;
  1457. });
  1458. };
  1459. }
  1460. },
  1461. handleEx: function(cm, input) {
  1462. exCommandDispatcher.processCommand(cm, input);
  1463. },
  1464. defineMotion: defineMotion,
  1465. defineAction: defineAction,
  1466. defineOperator: defineOperator,
  1467. mapCommand: mapCommand,
  1468. _mapCommand: _mapCommand,
  1469. defineRegister: defineRegister,
  1470. exitVisualMode: exitVisualMode,
  1471. exitInsertMode: exitInsertMode
  1472. };
  1473. function InputState() {
  1474. this.prefixRepeat = [];
  1475. this.motionRepeat = [];
  1476. this.operator = null;
  1477. this.operatorArgs = null;
  1478. this.motion = null;
  1479. this.motionArgs = null;
  1480. this.keyBuffer = []; // For matching multi-key commands.
  1481. this.registerName = null; // Defaults to the unnamed register.
  1482. }
  1483. InputState.prototype.pushRepeatDigit = function(n) {
  1484. if (!this.operator) {
  1485. this.prefixRepeat = this.prefixRepeat.concat(n);
  1486. } else {
  1487. this.motionRepeat = this.motionRepeat.concat(n);
  1488. }
  1489. };
  1490. InputState.prototype.getRepeat = function() {
  1491. var repeat = 0;
  1492. if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
  1493. repeat = 1;
  1494. if (this.prefixRepeat.length > 0) {
  1495. repeat *= parseInt(this.prefixRepeat.join(''), 10);
  1496. }
  1497. if (this.motionRepeat.length > 0) {
  1498. repeat *= parseInt(this.motionRepeat.join(''), 10);
  1499. }
  1500. }
  1501. return repeat;
  1502. };
  1503. function clearInputState(cm, reason) {
  1504. cm.state.vim.inputState = new InputState();
  1505. CodeMirror.signal(cm, 'vim-command-done', reason);
  1506. }
  1507. function Register(text, linewise, blockwise) {
  1508. this.clear();
  1509. this.keyBuffer = [text || ''];
  1510. this.insertModeChanges = [];
  1511. this.searchQueries = [];
  1512. this.linewise = !!linewise;
  1513. this.blockwise = !!blockwise;
  1514. }
  1515. Register.prototype = {
  1516. setText: function(text, linewise, blockwise) {
  1517. this.keyBuffer = [text || ''];
  1518. this.linewise = !!linewise;
  1519. this.blockwise = !!blockwise;
  1520. },
  1521. pushText: function(text, linewise) {
  1522. if (linewise) {
  1523. if (!this.linewise) {
  1524. this.keyBuffer.push('\n');
  1525. }
  1526. this.linewise = true;
  1527. }
  1528. this.keyBuffer.push(text);
  1529. },
  1530. pushInsertModeChanges: function(changes) {
  1531. this.insertModeChanges.push(createInsertModeChanges(changes));
  1532. },
  1533. pushSearchQuery: function(query) {
  1534. this.searchQueries.push(query);
  1535. },
  1536. clear: function() {
  1537. this.keyBuffer = [];
  1538. this.insertModeChanges = [];
  1539. this.searchQueries = [];
  1540. this.linewise = false;
  1541. },
  1542. toString: function() {
  1543. return this.keyBuffer.join('');
  1544. }
  1545. };
  1546. function defineRegister(name, register) {
  1547. var registers = vimGlobalState.registerController.registers[name];
  1548. if (!name || name.length != 1) {
  1549. throw Error('Register name must be 1 character');
  1550. }
  1551. registers[name] = register;
  1552. validRegisters.push(name);
  1553. }
  1554. function RegisterController(registers) {
  1555. this.registers = registers;
  1556. this.unnamedRegister = registers['"'] = new Register();
  1557. registers['.'] = new Register();
  1558. registers[':'] = new Register();
  1559. registers['/'] = new Register();
  1560. }
  1561. RegisterController.prototype = {
  1562. pushText: function(registerName, operator, text, linewise, blockwise) {
  1563. if (linewise && text.charAt(0) == '\n') {
  1564. text = text.slice(1) + '\n';
  1565. }
  1566. if (linewise && text.charAt(text.length - 1) !== '\n'){
  1567. text += '\n';
  1568. }
  1569. var register = this.isValidRegister(registerName) ?
  1570. this.getRegister(registerName) : null;
  1571. if (!register) {
  1572. switch (operator) {
  1573. case 'yank':
  1574. this.registers['0'] = new Register(text, linewise, blockwise);
  1575. break;
  1576. case 'delete':
  1577. case 'change':
  1578. if (text.indexOf('\n') == -1) {
  1579. this.registers['-'] = new Register(text, linewise);
  1580. } else {
  1581. this.shiftNumericRegisters_();
  1582. this.registers['1'] = new Register(text, linewise);
  1583. }
  1584. break;
  1585. }
  1586. this.unnamedRegister.setText(text, linewise, blockwise);
  1587. return;
  1588. }
  1589. var append = isUpperCase(registerName);
  1590. if (append) {
  1591. register.pushText(text, linewise);
  1592. } else {
  1593. register.setText(text, linewise, blockwise);
  1594. }
  1595. this.unnamedRegister.setText(register.toString(), linewise);
  1596. },
  1597. getRegister: function(name) {
  1598. if (!this.isValidRegister(name)) {
  1599. return this.unnamedRegister;
  1600. }
  1601. name = name.toLowerCase();
  1602. if (!this.registers[name]) {
  1603. this.registers[name] = new Register();
  1604. }
  1605. return this.registers[name];
  1606. },
  1607. isValidRegister: function(name) {
  1608. return name && inArray(name, validRegisters);
  1609. },
  1610. shiftNumericRegisters_: function() {
  1611. for (var i = 9; i >= 2; i--) {
  1612. this.registers[i] = this.getRegister('' + (i - 1));
  1613. }
  1614. }
  1615. };
  1616. function HistoryController() {
  1617. this.historyBuffer = [];
  1618. this.iterator;
  1619. this.initialPrefix = null;
  1620. }
  1621. HistoryController.prototype = {
  1622. nextMatch: function (input, up) {
  1623. var historyBuffer = this.historyBuffer;
  1624. var dir = up ? -1 : 1;
  1625. if (this.initialPrefix === null) this.initialPrefix = input;
  1626. for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) {
  1627. var element = historyBuffer[i];
  1628. for (var j = 0; j <= element.length; j++) {
  1629. if (this.initialPrefix == element.substring(0, j)) {
  1630. this.iterator = i;
  1631. return element;
  1632. }
  1633. }
  1634. }
  1635. if (i >= historyBuffer.length) {
  1636. this.iterator = historyBuffer.length;
  1637. return this.initialPrefix;
  1638. }
  1639. if (i < 0 ) return input;
  1640. },
  1641. pushInput: function(input) {
  1642. var index = this.historyBuffer.indexOf(input);
  1643. if (index > -1) this.historyBuffer.splice(index, 1);
  1644. if (input.length) this.historyBuffer.push(input);
  1645. },
  1646. reset: function() {
  1647. this.initialPrefix = null;
  1648. this.iterator = this.historyBuffer.length;
  1649. }
  1650. };
  1651. var commandDispatcher = {
  1652. matchCommand: function(keys, keyMap, inputState, context) {
  1653. var matches = commandMatches(keys, keyMap, context, inputState);
  1654. if (!matches.full && !matches.partial) {
  1655. return {type: 'none'};
  1656. } else if (!matches.full && matches.partial) {
  1657. return {type: 'partial'};
  1658. }
  1659. var bestMatch;
  1660. for (var i = 0; i < matches.full.length; i++) {
  1661. var match = matches.full[i];
  1662. if (!bestMatch) {
  1663. bestMatch = match;
  1664. }
  1665. }
  1666. if (bestMatch.keys.slice(-11) == '<character>') {
  1667. var character = lastChar(keys);
  1668. if (/<C-.>/.test(character)) return {type: 'none'};
  1669. inputState.selectedCharacter = character;
  1670. }
  1671. return {type: 'full', command: bestMatch};
  1672. },
  1673. processCommand: function(cm, vim, command) {
  1674. vim.inputState.repeatOverride = command.repeatOverride;
  1675. switch (command.type) {
  1676. case 'motion':
  1677. this.processMotion(cm, vim, command);
  1678. break;
  1679. case 'operator':
  1680. this.processOperator(cm, vim, command);
  1681. break;
  1682. case 'operatorMotion':
  1683. this.processOperatorMotion(cm, vim, command);
  1684. break;
  1685. case 'action':
  1686. this.processAction(cm, vim, command);
  1687. break;
  1688. case 'search':
  1689. this.processSearch(cm, vim, command);
  1690. break;
  1691. case 'ex':
  1692. case 'keyToEx':
  1693. this.processEx(cm, vim, command);
  1694. break;
  1695. default:
  1696. break;
  1697. }
  1698. },
  1699. processMotion: function(cm, vim, command) {
  1700. vim.inputState.motion = command.motion;
  1701. vim.inputState.motionArgs = copyArgs(command.motionArgs);
  1702. this.evalInput(cm, vim);
  1703. },
  1704. processOperator: function(cm, vim, command) {
  1705. var inputState = vim.inputState;
  1706. if (inputState.operator) {
  1707. if (inputState.operator == command.operator) {
  1708. inputState.motion = 'expandToLine';
  1709. inputState.motionArgs = { linewise: true };
  1710. this.evalInput(cm, vim);
  1711. return;
  1712. } else {
  1713. clearInputState(cm);
  1714. }
  1715. }
  1716. inputState.operator = command.operator;
  1717. inputState.operatorArgs = copyArgs(command.operatorArgs);
  1718. if (vim.visualMode) {
  1719. this.evalInput(cm, vim);
  1720. }
  1721. },
  1722. processOperatorMotion: function(cm, vim, command) {
  1723. var visualMode = vim.visualMode;
  1724. var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
  1725. if (operatorMotionArgs) {
  1726. if (visualMode && operatorMotionArgs.visualLine) {
  1727. vim.visualLine = true;
  1728. }
  1729. }
  1730. this.processOperator(cm, vim, command);
  1731. if (!visualMode) {
  1732. this.processMotion(cm, vim, command);
  1733. }
  1734. },
  1735. processAction: function(cm, vim, command) {
  1736. var inputState = vim.inputState;
  1737. var repeat = inputState.getRepeat();
  1738. var repeatIsExplicit = !!repeat;
  1739. var actionArgs = copyArgs(command.actionArgs) || {};
  1740. if (inputState.selectedCharacter) {
  1741. actionArgs.selectedCharacter = inputState.selectedCharacter;
  1742. }
  1743. if (command.operator) {
  1744. this.processOperator(cm, vim, command);
  1745. }
  1746. if (command.motion) {
  1747. this.processMotion(cm, vim, command);
  1748. }
  1749. if (command.motion || command.operator) {
  1750. this.evalInput(cm, vim);
  1751. }
  1752. actionArgs.repeat = repeat || 1;
  1753. actionArgs.repeatIsExplicit = repeatIsExplicit;
  1754. actionArgs.registerName = inputState.registerName;
  1755. clearInputState(cm);
  1756. vim.lastMotion = null;
  1757. if (command.isEdit) {
  1758. this.recordLastEdit(vim, inputState, command);
  1759. }
  1760. actions[command.action](cm, actionArgs, vim);
  1761. },
  1762. processSearch: function(cm, vim, command) {
  1763. if (!cm.getSearchCursor) {
  1764. return;
  1765. }
  1766. var forward = command.searchArgs.forward;
  1767. var wholeWordOnly = command.searchArgs.wholeWordOnly;
  1768. getSearchState(cm).setReversed(!forward);
  1769. var promptPrefix = (forward) ? '/' : '?';
  1770. var originalQuery = getSearchState(cm).getQuery();
  1771. var originalScrollPos = cm.getScrollInfo();
  1772. function handleQuery(query, ignoreCase, smartCase) {
  1773. vimGlobalState.searchHistoryController.pushInput(query);
  1774. vimGlobalState.searchHistoryController.reset();
  1775. try {
  1776. updateSearchQuery(cm, query, ignoreCase, smartCase);
  1777. } catch (e) {
  1778. showConfirm(cm, 'Invalid regex: ' + query);
  1779. clearInputState(cm);
  1780. return;
  1781. }
  1782. commandDispatcher.processMotion(cm, vim, {
  1783. type: 'motion',
  1784. motion: 'findNext',
  1785. motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
  1786. });
  1787. }
  1788. function onPromptClose(query) {
  1789. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1790. handleQuery(query, true /** ignoreCase */, true /** smartCase */);
  1791. var macroModeState = vimGlobalState.macroModeState;
  1792. if (macroModeState.isRecording) {
  1793. logSearchQuery(macroModeState, query);
  1794. }
  1795. }
  1796. function onPromptKeyUp(e, query, close) {
  1797. var keyName = CodeMirror.keyName(e), up;
  1798. if (keyName == 'Up' || keyName == 'Down') {
  1799. up = keyName == 'Up' ? true : false;
  1800. query = vimGlobalState.searchHistoryController.nextMatch(query, up) || '';
  1801. close(query);
  1802. } else {
  1803. if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
  1804. vimGlobalState.searchHistoryController.reset();
  1805. }
  1806. var parsedQuery;
  1807. try {
  1808. parsedQuery = updateSearchQuery(cm, query,
  1809. true /** ignoreCase */, true /** smartCase */);
  1810. } catch (e) {
  1811. }
  1812. if (parsedQuery) {
  1813. cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
  1814. } else {
  1815. clearSearchHighlight(cm);
  1816. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1817. }
  1818. }
  1819. function onPromptKeyDown(e, query, close) {
  1820. var keyName = CodeMirror.keyName(e);
  1821. if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
  1822. (keyName == 'Backspace' && query == '')) {
  1823. vimGlobalState.searchHistoryController.pushInput(query);
  1824. vimGlobalState.searchHistoryController.reset();
  1825. updateSearchQuery(cm, originalQuery);
  1826. clearSearchHighlight(cm);
  1827. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1828. CodeMirror.e_stop(e);
  1829. clearInputState(cm);
  1830. close();
  1831. cm.focus();
  1832. } else if (keyName == 'Ctrl-U') {
  1833. CodeMirror.e_stop(e);
  1834. close('');
  1835. }
  1836. }
  1837. switch (command.searchArgs.querySrc) {
  1838. case 'prompt':
  1839. var macroModeState = vimGlobalState.macroModeState;
  1840. if (macroModeState.isPlaying) {
  1841. var query = macroModeState.replaySearchQueries.shift();
  1842. handleQuery(query, true /** ignoreCase */, false /** smartCase */);
  1843. } else {
  1844. showPrompt(cm, {
  1845. onClose: onPromptClose,
  1846. prefix: promptPrefix,
  1847. desc: searchPromptDesc,
  1848. onKeyUp: onPromptKeyUp,
  1849. onKeyDown: onPromptKeyDown
  1850. });
  1851. }
  1852. break;
  1853. case 'wordUnderCursor':
  1854. var word = expandWordUnderCursor(cm, false /** inclusive */,
  1855. true /** forward */, false /** bigWord */,
  1856. true /** noSymbol */);
  1857. var isKeyword = true;
  1858. if (!word) {
  1859. word = expandWordUnderCursor(cm, false /** inclusive */,
  1860. true /** forward */, false /** bigWord */,
  1861. false /** noSymbol */);
  1862. isKeyword = false;
  1863. }
  1864. if (!word) {
  1865. return;
  1866. }
  1867. var query = cm.getLine(word.start.line).substring(word.start.ch,
  1868. word.end.ch);
  1869. if (isKeyword && wholeWordOnly) {
  1870. query = '\\b' + query + '\\b';
  1871. } else {
  1872. query = escapeRegex(query);
  1873. }
  1874. vimGlobalState.jumpList.cachedCursor = cm.getCursor();
  1875. cm.setCursor(word.start);
  1876. handleQuery(query, true /** ignoreCase */, false /** smartCase */);
  1877. break;
  1878. }
  1879. },
  1880. processEx: function(cm, vim, command) {
  1881. function onPromptClose(input) {
  1882. vimGlobalState.exCommandHistoryController.pushInput(input);
  1883. vimGlobalState.exCommandHistoryController.reset();
  1884. exCommandDispatcher.processCommand(cm, input);
  1885. }
  1886. function onPromptKeyDown(e, input, close) {
  1887. var keyName = CodeMirror.keyName(e), up;
  1888. if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
  1889. (keyName == 'Backspace' && input == '')) {
  1890. vimGlobalState.exCommandHistoryController.pushInput(input);
  1891. vimGlobalState.exCommandHistoryController.reset();
  1892. CodeMirror.e_stop(e);
  1893. clearInputState(cm);
  1894. close();
  1895. cm.focus();
  1896. }
  1897. if (keyName == 'Up' || keyName == 'Down') {
  1898. up = keyName == 'Up' ? true : false;
  1899. input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || '';
  1900. close(input);
  1901. } else if (keyName == 'Ctrl-U') {
  1902. CodeMirror.e_stop(e);
  1903. close('');
  1904. } else {
  1905. if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
  1906. vimGlobalState.exCommandHistoryController.reset();
  1907. }
  1908. }
  1909. if (command.type == 'keyToEx') {
  1910. exCommandDispatcher.processCommand(cm, command.exArgs.input);
  1911. } else {
  1912. if (vim.visualMode) {
  1913. showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
  1914. onKeyDown: onPromptKeyDown});
  1915. } else {
  1916. showPrompt(cm, { onClose: onPromptClose, prefix: ':',
  1917. onKeyDown: onPromptKeyDown});
  1918. }
  1919. }
  1920. },
  1921. evalInput: function(cm, vim) {
  1922. var inputState = vim.inputState;
  1923. var motion = inputState.motion;
  1924. var motionArgs = inputState.motionArgs || {};
  1925. var operator = inputState.operator;
  1926. var operatorArgs = inputState.operatorArgs || {};
  1927. var registerName = inputState.registerName;
  1928. var sel = vim.sel;
  1929. var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head'));
  1930. var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor'));
  1931. var oldHead = copyCursor(origHead);
  1932. var oldAnchor = copyCursor(origAnchor);
  1933. var newHead, newAnchor;
  1934. var repeat;
  1935. if (operator) {
  1936. this.recordLastEdit(vim, inputState);
  1937. }
  1938. if (inputState.repeatOverride !== undefined) {
  1939. repeat = inputState.repeatOverride;
  1940. } else {
  1941. repeat = inputState.getRepeat();
  1942. }
  1943. if (repeat > 0 && motionArgs.explicitRepeat) {
  1944. motionArgs.repeatIsExplicit = true;
  1945. } else if (motionArgs.noRepeat ||
  1946. (!motionArgs.explicitRepeat && repeat === 0)) {
  1947. repeat = 1;
  1948. motionArgs.repeatIsExplicit = false;
  1949. }
  1950. if (inputState.selectedCharacter) {
  1951. motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
  1952. inputState.selectedCharacter;
  1953. }
  1954. motionArgs.repeat = repeat;
  1955. clearInputState(cm);
  1956. if (motion) {
  1957. var motionResult = motions[motion](cm, origHead, motionArgs, vim);
  1958. vim.lastMotion = motions[motion];
  1959. if (!motionResult) {
  1960. return;
  1961. }
  1962. if (motionArgs.toJumplist) {
  1963. if (!operator && cm.ace.curOp != null)
  1964. cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch
  1965. var jumpList = vimGlobalState.jumpList;
  1966. var cachedCursor = jumpList.cachedCursor;
  1967. if (cachedCursor) {
  1968. recordJumpPosition(cm, cachedCursor, motionResult);
  1969. delete jumpList.cachedCursor;
  1970. } else {
  1971. recordJumpPosition(cm, origHead, motionResult);
  1972. }
  1973. }
  1974. if (motionResult instanceof Array) {
  1975. newAnchor = motionResult[0];
  1976. newHead = motionResult[1];
  1977. } else {
  1978. newHead = motionResult;
  1979. }
  1980. if (!newHead) {
  1981. newHead = copyCursor(origHead);
  1982. }
  1983. if (vim.visualMode) {
  1984. if (!(vim.visualBlock && newHead.ch === Infinity)) {
  1985. newHead = clipCursorToContent(cm, newHead, vim.visualBlock);
  1986. }
  1987. if (newAnchor) {
  1988. newAnchor = clipCursorToContent(cm, newAnchor, true);
  1989. }
  1990. newAnchor = newAnchor || oldAnchor;
  1991. sel.anchor = newAnchor;
  1992. sel.head = newHead;
  1993. updateCmSelection(cm);
  1994. updateMark(cm, vim, '<',
  1995. cursorIsBefore(newAnchor, newHead) ? newAnchor
  1996. : newHead);
  1997. updateMark(cm, vim, '>',
  1998. cursorIsBefore(newAnchor, newHead) ? newHead
  1999. : newAnchor);
  2000. } else if (!operator) {
  2001. newHead = clipCursorToContent(cm, newHead);
  2002. cm.setCursor(newHead.line, newHead.ch);
  2003. }
  2004. }
  2005. if (operator) {
  2006. if (operatorArgs.lastSel) {
  2007. newAnchor = oldAnchor;
  2008. var lastSel = operatorArgs.lastSel;
  2009. var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line);
  2010. var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch);
  2011. if (lastSel.visualLine) {
  2012. newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
  2013. } else if (lastSel.visualBlock) {
  2014. newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);
  2015. } else if (lastSel.head.line == lastSel.anchor.line) {
  2016. newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset);
  2017. } else {
  2018. newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
  2019. }
  2020. vim.visualMode = true;
  2021. vim.visualLine = lastSel.visualLine;
  2022. vim.visualBlock = lastSel.visualBlock;
  2023. sel = vim.sel = {
  2024. anchor: newAnchor,
  2025. head: newHead
  2026. };
  2027. updateCmSelection(cm);
  2028. } else if (vim.visualMode) {
  2029. operatorArgs.lastSel = {
  2030. anchor: copyCursor(sel.anchor),
  2031. head: copyCursor(sel.head),
  2032. visualBlock: vim.visualBlock,
  2033. visualLine: vim.visualLine
  2034. };
  2035. }
  2036. var curStart, curEnd, linewise, mode;
  2037. var cmSel;
  2038. if (vim.visualMode) {
  2039. curStart = cursorMin(sel.head, sel.anchor);
  2040. curEnd = cursorMax(sel.head, sel.anchor);
  2041. linewise = vim.visualLine || operatorArgs.linewise;
  2042. mode = vim.visualBlock ? 'block' :
  2043. linewise ? 'line' :
  2044. 'char';
  2045. cmSel = makeCmSelection(cm, {
  2046. anchor: curStart,
  2047. head: curEnd
  2048. }, mode);
  2049. if (linewise) {
  2050. var ranges = cmSel.ranges;
  2051. if (mode == 'block') {
  2052. for (var i = 0; i < ranges.length; i++) {
  2053. ranges[i].head.ch = lineLength(cm, ranges[i].head.line);
  2054. }
  2055. } else if (mode == 'line') {
  2056. ranges[0].head = Pos(ranges[0].head.line + 1, 0);
  2057. }
  2058. }
  2059. } else {
  2060. curStart = copyCursor(newAnchor || oldAnchor);
  2061. curEnd = copyCursor(newHead || oldHead);
  2062. if (cursorIsBefore(curEnd, curStart)) {
  2063. var tmp = curStart;
  2064. curStart = curEnd;
  2065. curEnd = tmp;
  2066. }
  2067. linewise = motionArgs.linewise || operatorArgs.linewise;
  2068. if (linewise) {
  2069. expandSelectionToLine(cm, curStart, curEnd);
  2070. } else if (motionArgs.forward) {
  2071. clipToLine(cm, curStart, curEnd);
  2072. }
  2073. mode = 'char';
  2074. var exclusive = !motionArgs.inclusive || linewise;
  2075. cmSel = makeCmSelection(cm, {
  2076. anchor: curStart,
  2077. head: curEnd
  2078. }, mode, exclusive);
  2079. }
  2080. cm.setSelections(cmSel.ranges, cmSel.primary);
  2081. vim.lastMotion = null;
  2082. operatorArgs.repeat = repeat; // For indent in visual mode.
  2083. operatorArgs.registerName = registerName;
  2084. operatorArgs.linewise = linewise;
  2085. var operatorMoveTo = operators[operator](
  2086. cm, operatorArgs, cmSel.ranges, oldAnchor, newHead);
  2087. if (vim.visualMode) {
  2088. exitVisualMode(cm, operatorMoveTo != null);
  2089. }
  2090. if (operatorMoveTo) {
  2091. cm.setCursor(operatorMoveTo);
  2092. }
  2093. }
  2094. },
  2095. recordLastEdit: function(vim, inputState, actionCommand) {
  2096. var macroModeState = vimGlobalState.macroModeState;
  2097. if (macroModeState.isPlaying) { return; }
  2098. vim.lastEditInputState = inputState;
  2099. vim.lastEditActionCommand = actionCommand;
  2100. macroModeState.lastInsertModeChanges.changes = [];
  2101. macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
  2102. }
  2103. };
  2104. var motions = {
  2105. moveToTopLine: function(cm, _head, motionArgs) {
  2106. var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
  2107. return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  2108. },
  2109. moveToMiddleLine: function(cm) {
  2110. var range = getUserVisibleLines(cm);
  2111. var line = Math.floor((range.top + range.bottom) * 0.5);
  2112. return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  2113. },
  2114. moveToBottomLine: function(cm, _head, motionArgs) {
  2115. var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
  2116. return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  2117. },
  2118. expandToLine: function(_cm, head, motionArgs) {
  2119. var cur = head;
  2120. return Pos(cur.line + motionArgs.repeat - 1, Infinity);
  2121. },
  2122. findNext: function(cm, _head, motionArgs) {
  2123. var state = getSearchState(cm);
  2124. var query = state.getQuery();
  2125. if (!query) {
  2126. return;
  2127. }
  2128. var prev = !motionArgs.forward;
  2129. prev = (state.isReversed()) ? !prev : prev;
  2130. highlightSearchMatches(cm, query);
  2131. return findNext(cm, prev/** prev */, query, motionArgs.repeat);
  2132. },
  2133. goToMark: function(cm, _head, motionArgs, vim) {
  2134. var mark = vim.marks[motionArgs.selectedCharacter];
  2135. if (mark) {
  2136. var pos = mark.find();
  2137. return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos;
  2138. }
  2139. return null;
  2140. },
  2141. moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) {
  2142. if (vim.visualBlock && motionArgs.sameLine) {
  2143. var sel = vim.sel;
  2144. return [
  2145. clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)),
  2146. clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch))
  2147. ];
  2148. } else {
  2149. return ([vim.sel.head, vim.sel.anchor]);
  2150. }
  2151. },
  2152. jumpToMark: function(cm, head, motionArgs, vim) {
  2153. var best = head;
  2154. for (var i = 0; i < motionArgs.repeat; i++) {
  2155. var cursor = best;
  2156. for (var key in vim.marks) {
  2157. if (!isLowerCase(key)) {
  2158. continue;
  2159. }
  2160. var mark = vim.marks[key].find();
  2161. var isWrongDirection = (motionArgs.forward) ?
  2162. cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
  2163. if (isWrongDirection) {
  2164. continue;
  2165. }
  2166. if (motionArgs.linewise && (mark.line == cursor.line)) {
  2167. continue;
  2168. }
  2169. var equal = cursorEqual(cursor, best);
  2170. var between = (motionArgs.forward) ?
  2171. cursorIsBetween(cursor, mark, best) :
  2172. cursorIsBetween(best, mark, cursor);
  2173. if (equal || between) {
  2174. best = mark;
  2175. }
  2176. }
  2177. }
  2178. if (motionArgs.linewise) {
  2179. best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));
  2180. }
  2181. return best;
  2182. },
  2183. moveByCharacters: function(_cm, head, motionArgs) {
  2184. var cur = head;
  2185. var repeat = motionArgs.repeat;
  2186. var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
  2187. return Pos(cur.line, ch);
  2188. },
  2189. moveByLines: function(cm, head, motionArgs, vim) {
  2190. var cur = head;
  2191. var endCh = cur.ch;
  2192. switch (vim.lastMotion) {
  2193. case this.moveByLines:
  2194. case this.moveByDisplayLines:
  2195. case this.moveByScroll:
  2196. case this.moveToColumn:
  2197. case this.moveToEol:
  2198. endCh = vim.lastHPos;
  2199. break;
  2200. default:
  2201. vim.lastHPos = endCh;
  2202. }
  2203. var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
  2204. var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
  2205. var first = cm.firstLine();
  2206. var last = cm.lastLine();
  2207. if ((line < first && cur.line == first) ||
  2208. (line > last && cur.line == last)) {
  2209. return;
  2210. }
  2211. var fold = cm.ace.session.getFoldLine(line);
  2212. if (fold) {
  2213. if (motionArgs.forward) {
  2214. if (line > fold.start.row)
  2215. line = fold.end.row + 1;
  2216. } else {
  2217. line = fold.start.row;
  2218. }
  2219. }
  2220. if (motionArgs.toFirstChar){
  2221. endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
  2222. vim.lastHPos = endCh;
  2223. }
  2224. vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left;
  2225. return Pos(line, endCh);
  2226. },
  2227. moveByDisplayLines: function(cm, head, motionArgs, vim) {
  2228. var cur = head;
  2229. switch (vim.lastMotion) {
  2230. case this.moveByDisplayLines:
  2231. case this.moveByScroll:
  2232. case this.moveByLines:
  2233. case this.moveToColumn:
  2234. case this.moveToEol:
  2235. break;
  2236. default:
  2237. vim.lastHSPos = cm.charCoords(cur,'div').left;
  2238. }
  2239. var repeat = motionArgs.repeat;
  2240. var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
  2241. if (res.hitSide) {
  2242. if (motionArgs.forward) {
  2243. var lastCharCoords = cm.charCoords(res, 'div');
  2244. var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
  2245. var res = cm.coordsChar(goalCoords, 'div');
  2246. } else {
  2247. var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div');
  2248. resCoords.left = vim.lastHSPos;
  2249. res = cm.coordsChar(resCoords, 'div');
  2250. }
  2251. }
  2252. vim.lastHPos = res.ch;
  2253. return res;
  2254. },
  2255. moveByPage: function(cm, head, motionArgs) {
  2256. var curStart = head;
  2257. var repeat = motionArgs.repeat;
  2258. return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
  2259. },
  2260. moveByParagraph: function(cm, head, motionArgs) {
  2261. var dir = motionArgs.forward ? 1 : -1;
  2262. return findParagraph(cm, head, motionArgs.repeat, dir);
  2263. },
  2264. moveByScroll: function(cm, head, motionArgs, vim) {
  2265. var scrollbox = cm.getScrollInfo();
  2266. var curEnd = null;
  2267. var repeat = motionArgs.repeat;
  2268. if (!repeat) {
  2269. repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
  2270. }
  2271. var orig = cm.charCoords(head, 'local');
  2272. motionArgs.repeat = repeat;
  2273. var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);
  2274. if (!curEnd) {
  2275. return null;
  2276. }
  2277. var dest = cm.charCoords(curEnd, 'local');
  2278. cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
  2279. return curEnd;
  2280. },
  2281. moveByWords: function(cm, head, motionArgs) {
  2282. return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward,
  2283. !!motionArgs.wordEnd, !!motionArgs.bigWord);
  2284. },
  2285. moveTillCharacter: function(cm, _head, motionArgs) {
  2286. var repeat = motionArgs.repeat;
  2287. var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
  2288. motionArgs.selectedCharacter);
  2289. var increment = motionArgs.forward ? -1 : 1;
  2290. recordLastCharacterSearch(increment, motionArgs);
  2291. if (!curEnd) return null;
  2292. curEnd.ch += increment;
  2293. return curEnd;
  2294. },
  2295. moveToCharacter: function(cm, head, motionArgs) {
  2296. var repeat = motionArgs.repeat;
  2297. recordLastCharacterSearch(0, motionArgs);
  2298. return moveToCharacter(cm, repeat, motionArgs.forward,
  2299. motionArgs.selectedCharacter) || head;
  2300. },
  2301. moveToSymbol: function(cm, head, motionArgs) {
  2302. var repeat = motionArgs.repeat;
  2303. return findSymbol(cm, repeat, motionArgs.forward,
  2304. motionArgs.selectedCharacter) || head;
  2305. },
  2306. moveToColumn: function(cm, head, motionArgs, vim) {
  2307. var repeat = motionArgs.repeat;
  2308. vim.lastHPos = repeat - 1;
  2309. vim.lastHSPos = cm.charCoords(head,'div').left;
  2310. return moveToColumn(cm, repeat);
  2311. },
  2312. moveToEol: function(cm, head, motionArgs, vim) {
  2313. var cur = head;
  2314. vim.lastHPos = Infinity;
  2315. var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity);
  2316. var end=cm.clipPos(retval);
  2317. end.ch--;
  2318. vim.lastHSPos = cm.charCoords(end,'div').left;
  2319. return retval;
  2320. },
  2321. moveToFirstNonWhiteSpaceCharacter: function(cm, head) {
  2322. var cursor = head;
  2323. return Pos(cursor.line,
  2324. findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
  2325. },
  2326. moveToMatchedSymbol: function(cm, head) {
  2327. var cursor = head;
  2328. var line = cursor.line;
  2329. var ch = cursor.ch;
  2330. var lineText = cm.getLine(line);
  2331. var symbol;
  2332. do {
  2333. symbol = lineText.charAt(ch++);
  2334. if (symbol && isMatchableSymbol(symbol)) {
  2335. var style = cm.getTokenTypeAt(Pos(line, ch));
  2336. if (style !== "string" && style !== "comment") {
  2337. break;
  2338. }
  2339. }
  2340. } while (symbol);
  2341. if (symbol) {
  2342. var matched = cm.findMatchingBracket(Pos(line, ch));
  2343. return matched.to;
  2344. } else {
  2345. return cursor;
  2346. }
  2347. },
  2348. moveToStartOfLine: function(_cm, head) {
  2349. return Pos(head.line, 0);
  2350. },
  2351. moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) {
  2352. var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
  2353. if (motionArgs.repeatIsExplicit) {
  2354. lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
  2355. }
  2356. return Pos(lineNum,
  2357. findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
  2358. },
  2359. textObjectManipulation: function(cm, head, motionArgs, vim) {
  2360. var mirroredPairs = {'(': ')', ')': '(',
  2361. '{': '}', '}': '{',
  2362. '[': ']', ']': '['};
  2363. var selfPaired = {'\'': true, '"': true};
  2364. var character = motionArgs.selectedCharacter;
  2365. if (character == 'b') {
  2366. character = '(';
  2367. } else if (character == 'B') {
  2368. character = '{';
  2369. }
  2370. var inclusive = !motionArgs.textObjectInner;
  2371. var tmp;
  2372. if (mirroredPairs[character]) {
  2373. tmp = selectCompanionObject(cm, head, character, inclusive);
  2374. } else if (selfPaired[character]) {
  2375. tmp = findBeginningAndEnd(cm, head, character, inclusive);
  2376. } else if (character === 'W') {
  2377. tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
  2378. true /** bigWord */);
  2379. } else if (character === 'w') {
  2380. tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
  2381. false /** bigWord */);
  2382. } else if (character === 'p') {
  2383. tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive);
  2384. motionArgs.linewise = true;
  2385. if (vim.visualMode) {
  2386. if (!vim.visualLine) { vim.visualLine = true; }
  2387. } else {
  2388. var operatorArgs = vim.inputState.operatorArgs;
  2389. if (operatorArgs) { operatorArgs.linewise = true; }
  2390. tmp.end.line--;
  2391. }
  2392. } else {
  2393. return null;
  2394. }
  2395. if (!cm.state.vim.visualMode) {
  2396. return [tmp.start, tmp.end];
  2397. } else {
  2398. return expandSelection(cm, tmp.start, tmp.end);
  2399. }
  2400. },
  2401. repeatLastCharacterSearch: function(cm, head, motionArgs) {
  2402. var lastSearch = vimGlobalState.lastChararacterSearch;
  2403. var repeat = motionArgs.repeat;
  2404. var forward = motionArgs.forward === lastSearch.forward;
  2405. var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
  2406. cm.moveH(-increment, 'char');
  2407. motionArgs.inclusive = forward ? true : false;
  2408. var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
  2409. if (!curEnd) {
  2410. cm.moveH(increment, 'char');
  2411. return head;
  2412. }
  2413. curEnd.ch += increment;
  2414. return curEnd;
  2415. }
  2416. };
  2417. function defineMotion(name, fn) {
  2418. motions[name] = fn;
  2419. }
  2420. function fillArray(val, times) {
  2421. var arr = [];
  2422. for (var i = 0; i < times; i++) {
  2423. arr.push(val);
  2424. }
  2425. return arr;
  2426. }
  2427. var operators = {
  2428. change: function(cm, args, ranges) {
  2429. var finalHead, text;
  2430. var vim = cm.state.vim;
  2431. vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock = vim.visualBlock;
  2432. if (!vim.visualMode) {
  2433. var anchor = ranges[0].anchor,
  2434. head = ranges[0].head;
  2435. text = cm.getRange(anchor, head);
  2436. var lastState = vim.lastEditInputState || {};
  2437. if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) {
  2438. var match = (/\s+$/).exec(text);
  2439. if (match && lastState.motionArgs && lastState.motionArgs.forward) {
  2440. head = offsetCursor(head, 0, - match[0].length);
  2441. text = text.slice(0, - match[0].length);
  2442. }
  2443. }
  2444. var prevLineEnd = new Pos(anchor.line - 1, Number.MAX_VALUE);
  2445. var wasLastLine = cm.firstLine() == cm.lastLine();
  2446. if (head.line > cm.lastLine() && args.linewise && !wasLastLine) {
  2447. cm.replaceRange('', prevLineEnd, head);
  2448. } else {
  2449. cm.replaceRange('', anchor, head);
  2450. }
  2451. if (args.linewise) {
  2452. if (!wasLastLine) {
  2453. cm.setCursor(prevLineEnd);
  2454. CodeMirror.commands.newlineAndIndent(cm);
  2455. }
  2456. anchor.ch = Number.MAX_VALUE;
  2457. }
  2458. finalHead = anchor;
  2459. } else {
  2460. text = cm.getSelection();
  2461. var replacement = fillArray('', ranges.length);
  2462. cm.replaceSelections(replacement);
  2463. finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
  2464. }
  2465. vimGlobalState.registerController.pushText(
  2466. args.registerName, 'change', text,
  2467. args.linewise, ranges.length > 1);
  2468. actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim);
  2469. },
  2470. 'delete': function(cm, args, ranges) {
  2471. var finalHead, text;
  2472. var vim = cm.state.vim;
  2473. if (!vim.visualBlock) {
  2474. var anchor = ranges[0].anchor,
  2475. head = ranges[0].head;
  2476. if (args.linewise &&
  2477. head.line != cm.firstLine() &&
  2478. anchor.line == cm.lastLine() &&
  2479. anchor.line == head.line - 1) {
  2480. if (anchor.line == cm.firstLine()) {
  2481. anchor.ch = 0;
  2482. } else {
  2483. anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));
  2484. }
  2485. }
  2486. text = cm.getRange(anchor, head);
  2487. cm.replaceRange('', anchor, head);
  2488. finalHead = anchor;
  2489. if (args.linewise) {
  2490. finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);
  2491. }
  2492. } else {
  2493. text = cm.getSelection();
  2494. var replacement = fillArray('', ranges.length);
  2495. cm.replaceSelections(replacement);
  2496. finalHead = ranges[0].anchor;
  2497. }
  2498. vimGlobalState.registerController.pushText(
  2499. args.registerName, 'delete', text,
  2500. args.linewise, vim.visualBlock);
  2501. return clipCursorToContent(cm, finalHead);
  2502. },
  2503. indent: function(cm, args, ranges) {
  2504. var vim = cm.state.vim;
  2505. var startLine = ranges[0].anchor.line;
  2506. var endLine = vim.visualBlock ?
  2507. ranges[ranges.length - 1].anchor.line :
  2508. ranges[0].head.line;
  2509. var repeat = (vim.visualMode) ? args.repeat : 1;
  2510. if (args.linewise) {
  2511. endLine--;
  2512. }
  2513. for (var i = startLine; i <= endLine; i++) {
  2514. for (var j = 0; j < repeat; j++) {
  2515. cm.indentLine(i, args.indentRight);
  2516. }
  2517. }
  2518. return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
  2519. },
  2520. changeCase: function(cm, args, ranges, oldAnchor, newHead) {
  2521. var selections = cm.getSelections();
  2522. var swapped = [];
  2523. var toLower = args.toLower;
  2524. for (var j = 0; j < selections.length; j++) {
  2525. var toSwap = selections[j];
  2526. var text = '';
  2527. if (toLower === true) {
  2528. text = toSwap.toLowerCase();
  2529. } else if (toLower === false) {
  2530. text = toSwap.toUpperCase();
  2531. } else {
  2532. for (var i = 0; i < toSwap.length; i++) {
  2533. var character = toSwap.charAt(i);
  2534. text += isUpperCase(character) ? character.toLowerCase() :
  2535. character.toUpperCase();
  2536. }
  2537. }
  2538. swapped.push(text);
  2539. }
  2540. cm.replaceSelections(swapped);
  2541. if (args.shouldMoveCursor){
  2542. return newHead;
  2543. } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) {
  2544. return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor);
  2545. } else if (args.linewise){
  2546. return oldAnchor;
  2547. } else {
  2548. return cursorMin(ranges[0].anchor, ranges[0].head);
  2549. }
  2550. },
  2551. yank: function(cm, args, ranges, oldAnchor) {
  2552. var vim = cm.state.vim;
  2553. var text = cm.getSelection();
  2554. var endPos = vim.visualMode
  2555. ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)
  2556. : oldAnchor;
  2557. vimGlobalState.registerController.pushText(
  2558. args.registerName, 'yank',
  2559. text, args.linewise, vim.visualBlock);
  2560. return endPos;
  2561. }
  2562. };
  2563. function defineOperator(name, fn) {
  2564. operators[name] = fn;
  2565. }
  2566. var actions = {
  2567. jumpListWalk: function(cm, actionArgs, vim) {
  2568. if (vim.visualMode) {
  2569. return;
  2570. }
  2571. var repeat = actionArgs.repeat;
  2572. var forward = actionArgs.forward;
  2573. var jumpList = vimGlobalState.jumpList;
  2574. var mark = jumpList.move(cm, forward ? repeat : -repeat);
  2575. var markPos = mark ? mark.find() : undefined;
  2576. markPos = markPos ? markPos : cm.getCursor();
  2577. cm.setCursor(markPos);
  2578. cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch
  2579. },
  2580. scroll: function(cm, actionArgs, vim) {
  2581. if (vim.visualMode) {
  2582. return;
  2583. }
  2584. var repeat = actionArgs.repeat || 1;
  2585. var lineHeight = cm.defaultTextHeight();
  2586. var top = cm.getScrollInfo().top;
  2587. var delta = lineHeight * repeat;
  2588. var newPos = actionArgs.forward ? top + delta : top - delta;
  2589. var cursor = copyCursor(cm.getCursor());
  2590. var cursorCoords = cm.charCoords(cursor, 'local');
  2591. if (actionArgs.forward) {
  2592. if (newPos > cursorCoords.top) {
  2593. cursor.line += (newPos - cursorCoords.top) / lineHeight;
  2594. cursor.line = Math.ceil(cursor.line);
  2595. cm.setCursor(cursor);
  2596. cursorCoords = cm.charCoords(cursor, 'local');
  2597. cm.scrollTo(null, cursorCoords.top);
  2598. } else {
  2599. cm.scrollTo(null, newPos);
  2600. }
  2601. } else {
  2602. var newBottom = newPos + cm.getScrollInfo().clientHeight;
  2603. if (newBottom < cursorCoords.bottom) {
  2604. cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
  2605. cursor.line = Math.floor(cursor.line);
  2606. cm.setCursor(cursor);
  2607. cursorCoords = cm.charCoords(cursor, 'local');
  2608. cm.scrollTo(
  2609. null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
  2610. } else {
  2611. cm.scrollTo(null, newPos);
  2612. }
  2613. }
  2614. },
  2615. scrollToCursor: function(cm, actionArgs) {
  2616. var lineNum = cm.getCursor().line;
  2617. var charCoords = cm.charCoords(Pos(lineNum, 0), 'local');
  2618. var height = cm.getScrollInfo().clientHeight;
  2619. var y = charCoords.top;
  2620. var lineHeight = charCoords.bottom - y;
  2621. switch (actionArgs.position) {
  2622. case 'center': y = y - (height / 2) + lineHeight;
  2623. break;
  2624. case 'bottom': y = y - height + lineHeight*1.4;
  2625. break;
  2626. case 'top': y = y + lineHeight*0.4;
  2627. break;
  2628. }
  2629. cm.scrollTo(null, y);
  2630. },
  2631. replayMacro: function(cm, actionArgs, vim) {
  2632. var registerName = actionArgs.selectedCharacter;
  2633. var repeat = actionArgs.repeat;
  2634. var macroModeState = vimGlobalState.macroModeState;
  2635. if (registerName == '@') {
  2636. registerName = macroModeState.latestRegister;
  2637. }
  2638. while(repeat--){
  2639. executeMacroRegister(cm, vim, macroModeState, registerName);
  2640. }
  2641. },
  2642. enterMacroRecordMode: function(cm, actionArgs) {
  2643. var macroModeState = vimGlobalState.macroModeState;
  2644. var registerName = actionArgs.selectedCharacter;
  2645. macroModeState.enterMacroRecordMode(cm, registerName);
  2646. },
  2647. enterInsertMode: function(cm, actionArgs, vim) {
  2648. if (cm.getOption('readOnly')) { return; }
  2649. vim.insertMode = true;
  2650. vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
  2651. var insertAt = (actionArgs) ? actionArgs.insertAt : null;
  2652. var sel = vim.sel;
  2653. var head = actionArgs.head || cm.getCursor('head');
  2654. var height = cm.listSelections().length;
  2655. if (insertAt == 'eol') {
  2656. head = Pos(head.line, lineLength(cm, head.line));
  2657. } else if (insertAt == 'charAfter') {
  2658. head = offsetCursor(head, 0, 1);
  2659. } else if (insertAt == 'firstNonBlank') {
  2660. head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head);
  2661. } else if (insertAt == 'startOfSelectedArea') {
  2662. if (!vim.visualBlock) {
  2663. if (sel.head.line < sel.anchor.line) {
  2664. head = sel.head;
  2665. } else {
  2666. head = Pos(sel.anchor.line, 0);
  2667. }
  2668. } else {
  2669. head = Pos(
  2670. Math.min(sel.head.line, sel.anchor.line),
  2671. Math.min(sel.head.ch, sel.anchor.ch));
  2672. height = Math.abs(sel.head.line - sel.anchor.line) + 1;
  2673. }
  2674. } else if (insertAt == 'endOfSelectedArea') {
  2675. if (!vim.visualBlock) {
  2676. if (sel.head.line >= sel.anchor.line) {
  2677. head = offsetCursor(sel.head, 0, 1);
  2678. } else {
  2679. head = Pos(sel.anchor.line, 0);
  2680. }
  2681. } else {
  2682. head = Pos(
  2683. Math.min(sel.head.line, sel.anchor.line),
  2684. Math.max(sel.head.ch + 1, sel.anchor.ch));
  2685. height = Math.abs(sel.head.line - sel.anchor.line) + 1;
  2686. }
  2687. } else if (insertAt == 'inplace') {
  2688. if (vim.visualMode){
  2689. return;
  2690. }
  2691. }
  2692. cm.setOption('keyMap', 'vim-insert');
  2693. cm.setOption('disableInput', false);
  2694. if (actionArgs && actionArgs.replace) {
  2695. cm.toggleOverwrite(true);
  2696. cm.setOption('keyMap', 'vim-replace');
  2697. CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
  2698. } else {
  2699. cm.setOption('keyMap', 'vim-insert');
  2700. CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
  2701. }
  2702. if (!vimGlobalState.macroModeState.isPlaying) {
  2703. cm.on('change', onChange);
  2704. CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
  2705. }
  2706. if (vim.visualMode) {
  2707. exitVisualMode(cm);
  2708. }
  2709. selectForInsert(cm, head, height);
  2710. },
  2711. toggleVisualMode: function(cm, actionArgs, vim) {
  2712. var repeat = actionArgs.repeat;
  2713. var anchor = cm.getCursor();
  2714. var head;
  2715. if (!vim.visualMode) {
  2716. vim.visualMode = true;
  2717. vim.visualLine = !!actionArgs.linewise;
  2718. vim.visualBlock = !!actionArgs.blockwise;
  2719. head = clipCursorToContent(
  2720. cm, Pos(anchor.line, anchor.ch + repeat - 1),
  2721. true /** includeLineBreak */);
  2722. vim.sel = {
  2723. anchor: anchor,
  2724. head: head
  2725. };
  2726. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
  2727. updateCmSelection(cm);
  2728. updateMark(cm, vim, '<', cursorMin(anchor, head));
  2729. updateMark(cm, vim, '>', cursorMax(anchor, head));
  2730. } else if (vim.visualLine ^ actionArgs.linewise ||
  2731. vim.visualBlock ^ actionArgs.blockwise) {
  2732. vim.visualLine = !!actionArgs.linewise;
  2733. vim.visualBlock = !!actionArgs.blockwise;
  2734. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
  2735. updateCmSelection(cm);
  2736. } else {
  2737. exitVisualMode(cm);
  2738. }
  2739. },
  2740. reselectLastSelection: function(cm, _actionArgs, vim) {
  2741. var lastSelection = vim.lastSelection;
  2742. if (vim.visualMode) {
  2743. updateLastSelection(cm, vim);
  2744. }
  2745. if (lastSelection) {
  2746. var anchor = lastSelection.anchorMark.find();
  2747. var head = lastSelection.headMark.find();
  2748. if (!anchor || !head) {
  2749. return;
  2750. }
  2751. vim.sel = {
  2752. anchor: anchor,
  2753. head: head
  2754. };
  2755. vim.visualMode = true;
  2756. vim.visualLine = lastSelection.visualLine;
  2757. vim.visualBlock = lastSelection.visualBlock;
  2758. updateCmSelection(cm);
  2759. updateMark(cm, vim, '<', cursorMin(anchor, head));
  2760. updateMark(cm, vim, '>', cursorMax(anchor, head));
  2761. CodeMirror.signal(cm, 'vim-mode-change', {
  2762. mode: 'visual',
  2763. subMode: vim.visualLine ? 'linewise' :
  2764. vim.visualBlock ? 'blockwise' : ''});
  2765. }
  2766. },
  2767. joinLines: function(cm, actionArgs, vim) {
  2768. var curStart, curEnd;
  2769. if (vim.visualMode) {
  2770. curStart = cm.getCursor('anchor');
  2771. curEnd = cm.getCursor('head');
  2772. if (cursorIsBefore(curEnd, curStart)) {
  2773. var tmp = curEnd;
  2774. curEnd = curStart;
  2775. curStart = tmp;
  2776. }
  2777. curEnd.ch = lineLength(cm, curEnd.line) - 1;
  2778. } else {
  2779. var repeat = Math.max(actionArgs.repeat, 2);
  2780. curStart = cm.getCursor();
  2781. curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1,
  2782. Infinity));
  2783. }
  2784. var finalCh = 0;
  2785. for (var i = curStart.line; i < curEnd.line; i++) {
  2786. finalCh = lineLength(cm, curStart.line);
  2787. var tmp = Pos(curStart.line + 1,
  2788. lineLength(cm, curStart.line + 1));
  2789. var text = cm.getRange(curStart, tmp);
  2790. text = text.replace(/\n\s*/g, ' ');
  2791. cm.replaceRange(text, curStart, tmp);
  2792. }
  2793. var curFinalPos = Pos(curStart.line, finalCh);
  2794. if (vim.visualMode) {
  2795. exitVisualMode(cm, false);
  2796. }
  2797. cm.setCursor(curFinalPos);
  2798. },
  2799. newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
  2800. vim.insertMode = true;
  2801. var insertAt = copyCursor(cm.getCursor());
  2802. if (insertAt.line === cm.firstLine() && !actionArgs.after) {
  2803. cm.replaceRange('\n', Pos(cm.firstLine(), 0));
  2804. cm.setCursor(cm.firstLine(), 0);
  2805. } else {
  2806. insertAt.line = (actionArgs.after) ? insertAt.line :
  2807. insertAt.line - 1;
  2808. insertAt.ch = lineLength(cm, insertAt.line);
  2809. cm.setCursor(insertAt);
  2810. var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
  2811. CodeMirror.commands.newlineAndIndent;
  2812. newlineFn(cm);
  2813. }
  2814. this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
  2815. },
  2816. paste: function(cm, actionArgs, vim) {
  2817. var cur = copyCursor(cm.getCursor());
  2818. var register = vimGlobalState.registerController.getRegister(
  2819. actionArgs.registerName);
  2820. var text = register.toString();
  2821. if (!text) {
  2822. return;
  2823. }
  2824. if (actionArgs.matchIndent) {
  2825. var tabSize = cm.getOption("tabSize");
  2826. var whitespaceLength = function(str) {
  2827. var tabs = (str.split("\t").length - 1);
  2828. var spaces = (str.split(" ").length - 1);
  2829. return tabs * tabSize + spaces * 1;
  2830. };
  2831. var currentLine = cm.getLine(cm.getCursor().line);
  2832. var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
  2833. var chompedText = text.replace(/\n$/, '');
  2834. var wasChomped = text !== chompedText;
  2835. var firstIndent = whitespaceLength(text.match(/^\s*/)[0]);
  2836. var text = chompedText.replace(/^\s*/gm, function(wspace) {
  2837. var newIndent = indent + (whitespaceLength(wspace) - firstIndent);
  2838. if (newIndent < 0) {
  2839. return "";
  2840. }
  2841. else if (cm.getOption("indentWithTabs")) {
  2842. var quotient = Math.floor(newIndent / tabSize);
  2843. return Array(quotient + 1).join('\t');
  2844. }
  2845. else {
  2846. return Array(newIndent + 1).join(' ');
  2847. }
  2848. });
  2849. text += wasChomped ? "\n" : "";
  2850. }
  2851. if (actionArgs.repeat > 1) {
  2852. var text = Array(actionArgs.repeat + 1).join(text);
  2853. }
  2854. var linewise = register.linewise;
  2855. var blockwise = register.blockwise;
  2856. if (linewise && !blockwise) {
  2857. if(vim.visualMode) {
  2858. text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n';
  2859. } else if (actionArgs.after) {
  2860. text = '\n' + text.slice(0, text.length - 1);
  2861. cur.ch = lineLength(cm, cur.line);
  2862. } else {
  2863. cur.ch = 0;
  2864. }
  2865. } else {
  2866. if (blockwise) {
  2867. text = text.split('\n');
  2868. for (var i = 0; i < text.length; i++) {
  2869. text[i] = (text[i] == '') ? ' ' : text[i];
  2870. }
  2871. }
  2872. cur.ch += actionArgs.after ? 1 : 0;
  2873. }
  2874. var curPosFinal;
  2875. var idx;
  2876. if (vim.visualMode) {
  2877. vim.lastPastedText = text;
  2878. var lastSelectionCurEnd;
  2879. var selectedArea = getSelectedAreaRange(cm, vim);
  2880. var selectionStart = selectedArea[0];
  2881. var selectionEnd = selectedArea[1];
  2882. var selectedText = cm.getSelection();
  2883. var selections = cm.listSelections();
  2884. var emptyStrings = new Array(selections.length).join('1').split('1');
  2885. if (vim.lastSelection) {
  2886. lastSelectionCurEnd = vim.lastSelection.headMark.find();
  2887. }
  2888. vimGlobalState.registerController.unnamedRegister.setText(selectedText);
  2889. if (blockwise) {
  2890. cm.replaceSelections(emptyStrings);
  2891. selectionEnd = Pos(selectionStart.line + text.length-1, selectionStart.ch);
  2892. cm.setCursor(selectionStart);
  2893. selectBlock(cm, selectionEnd);
  2894. cm.replaceSelections(text);
  2895. curPosFinal = selectionStart;
  2896. } else if (vim.visualBlock) {
  2897. cm.replaceSelections(emptyStrings);
  2898. cm.setCursor(selectionStart);
  2899. cm.replaceRange(text, selectionStart, selectionStart);
  2900. curPosFinal = selectionStart;
  2901. } else {
  2902. cm.replaceRange(text, selectionStart, selectionEnd);
  2903. curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1);
  2904. }
  2905. if(lastSelectionCurEnd) {
  2906. vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);
  2907. }
  2908. if (linewise) {
  2909. curPosFinal.ch=0;
  2910. }
  2911. } else {
  2912. if (blockwise) {
  2913. cm.setCursor(cur);
  2914. for (var i = 0; i < text.length; i++) {
  2915. var line = cur.line+i;
  2916. if (line > cm.lastLine()) {
  2917. cm.replaceRange('\n', Pos(line, 0));
  2918. }
  2919. var lastCh = lineLength(cm, line);
  2920. if (lastCh < cur.ch) {
  2921. extendLineToColumn(cm, line, cur.ch);
  2922. }
  2923. }
  2924. cm.setCursor(cur);
  2925. selectBlock(cm, Pos(cur.line + text.length-1, cur.ch));
  2926. cm.replaceSelections(text);
  2927. curPosFinal = cur;
  2928. } else {
  2929. cm.replaceRange(text, cur);
  2930. if (linewise && actionArgs.after) {
  2931. curPosFinal = Pos(
  2932. cur.line + 1,
  2933. findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)));
  2934. } else if (linewise && !actionArgs.after) {
  2935. curPosFinal = Pos(
  2936. cur.line,
  2937. findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)));
  2938. } else if (!linewise && actionArgs.after) {
  2939. idx = cm.indexFromPos(cur);
  2940. curPosFinal = cm.posFromIndex(idx + text.length - 1);
  2941. } else {
  2942. idx = cm.indexFromPos(cur);
  2943. curPosFinal = cm.posFromIndex(idx + text.length);
  2944. }
  2945. }
  2946. }
  2947. if (vim.visualMode) {
  2948. exitVisualMode(cm, false);
  2949. }
  2950. cm.setCursor(curPosFinal);
  2951. },
  2952. undo: function(cm, actionArgs) {
  2953. cm.operation(function() {
  2954. repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
  2955. cm.setCursor(cm.getCursor('anchor'));
  2956. });
  2957. },
  2958. redo: function(cm, actionArgs) {
  2959. repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
  2960. },
  2961. setRegister: function(_cm, actionArgs, vim) {
  2962. vim.inputState.registerName = actionArgs.selectedCharacter;
  2963. },
  2964. setMark: function(cm, actionArgs, vim) {
  2965. var markName = actionArgs.selectedCharacter;
  2966. updateMark(cm, vim, markName, cm.getCursor());
  2967. },
  2968. replace: function(cm, actionArgs, vim) {
  2969. var replaceWith = actionArgs.selectedCharacter;
  2970. var curStart = cm.getCursor();
  2971. var replaceTo;
  2972. var curEnd;
  2973. var selections = cm.listSelections();
  2974. if (vim.visualMode) {
  2975. curStart = cm.getCursor('start');
  2976. curEnd = cm.getCursor('end');
  2977. } else {
  2978. var line = cm.getLine(curStart.line);
  2979. replaceTo = curStart.ch + actionArgs.repeat;
  2980. if (replaceTo > line.length) {
  2981. replaceTo=line.length;
  2982. }
  2983. curEnd = Pos(curStart.line, replaceTo);
  2984. }
  2985. if (replaceWith=='\n') {
  2986. if (!vim.visualMode) cm.replaceRange('', curStart, curEnd);
  2987. (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
  2988. } else {
  2989. var replaceWithStr = cm.getRange(curStart, curEnd);
  2990. replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith);
  2991. if (vim.visualBlock) {
  2992. var spaces = new Array(cm.getOption("tabSize")+1).join(' ');
  2993. replaceWithStr = cm.getSelection();
  2994. replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n');
  2995. cm.replaceSelections(replaceWithStr);
  2996. } else {
  2997. cm.replaceRange(replaceWithStr, curStart, curEnd);
  2998. }
  2999. if (vim.visualMode) {
  3000. curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ?
  3001. selections[0].anchor : selections[0].head;
  3002. cm.setCursor(curStart);
  3003. exitVisualMode(cm, false);
  3004. } else {
  3005. cm.setCursor(offsetCursor(curEnd, 0, -1));
  3006. }
  3007. }
  3008. },
  3009. incrementNumberToken: function(cm, actionArgs) {
  3010. var cur = cm.getCursor();
  3011. var lineStr = cm.getLine(cur.line);
  3012. var re = /-?\d+/g;
  3013. var match;
  3014. var start;
  3015. var end;
  3016. var numberStr;
  3017. var token;
  3018. while ((match = re.exec(lineStr)) !== null) {
  3019. token = match[0];
  3020. start = match.index;
  3021. end = start + token.length;
  3022. if (cur.ch < end)break;
  3023. }
  3024. if (!actionArgs.backtrack && (end <= cur.ch))return;
  3025. if (token) {
  3026. var increment = actionArgs.increase ? 1 : -1;
  3027. var number = parseInt(token) + (increment * actionArgs.repeat);
  3028. var from = Pos(cur.line, start);
  3029. var to = Pos(cur.line, end);
  3030. numberStr = number.toString();
  3031. cm.replaceRange(numberStr, from, to);
  3032. } else {
  3033. return;
  3034. }
  3035. cm.setCursor(Pos(cur.line, start + numberStr.length - 1));
  3036. },
  3037. repeatLastEdit: function(cm, actionArgs, vim) {
  3038. var lastEditInputState = vim.lastEditInputState;
  3039. if (!lastEditInputState) { return; }
  3040. var repeat = actionArgs.repeat;
  3041. if (repeat && actionArgs.repeatIsExplicit) {
  3042. vim.lastEditInputState.repeatOverride = repeat;
  3043. } else {
  3044. repeat = vim.lastEditInputState.repeatOverride || repeat;
  3045. }
  3046. repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
  3047. },
  3048. exitInsertMode: exitInsertMode
  3049. };
  3050. function defineAction(name, fn) {
  3051. actions[name] = fn;
  3052. }
  3053. function clipCursorToContent(cm, cur, includeLineBreak) {
  3054. var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
  3055. var maxCh = lineLength(cm, line) - 1;
  3056. maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
  3057. var ch = Math.min(Math.max(0, cur.ch), maxCh);
  3058. return Pos(line, ch);
  3059. }
  3060. function copyArgs(args) {
  3061. var ret = {};
  3062. for (var prop in args) {
  3063. if (args.hasOwnProperty(prop)) {
  3064. ret[prop] = args[prop];
  3065. }
  3066. }
  3067. return ret;
  3068. }
  3069. function offsetCursor(cur, offsetLine, offsetCh) {
  3070. if (typeof offsetLine === 'object') {
  3071. offsetCh = offsetLine.ch;
  3072. offsetLine = offsetLine.line;
  3073. }
  3074. return Pos(cur.line + offsetLine, cur.ch + offsetCh);
  3075. }
  3076. function getOffset(anchor, head) {
  3077. return {
  3078. line: head.line - anchor.line,
  3079. ch: head.line - anchor.line
  3080. };
  3081. }
  3082. function commandMatches(keys, keyMap, context, inputState) {
  3083. var match, partial = [], full = [];
  3084. for (var i = 0; i < keyMap.length; i++) {
  3085. var command = keyMap[i];
  3086. if (context == 'insert' && command.context != 'insert' ||
  3087. command.context && command.context != context ||
  3088. inputState.operator && command.type == 'action' ||
  3089. !(match = commandMatch(keys, command.keys))) { continue; }
  3090. if (match == 'partial') { partial.push(command); }
  3091. if (match == 'full') { full.push(command); }
  3092. }
  3093. return {
  3094. partial: partial.length && partial,
  3095. full: full.length && full
  3096. };
  3097. }
  3098. function commandMatch(pressed, mapped) {
  3099. if (mapped.slice(-11) == '<character>') {
  3100. var prefixLen = mapped.length - 11;
  3101. var pressedPrefix = pressed.slice(0, prefixLen);
  3102. var mappedPrefix = mapped.slice(0, prefixLen);
  3103. return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' :
  3104. mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false;
  3105. } else {
  3106. return pressed == mapped ? 'full' :
  3107. mapped.indexOf(pressed) == 0 ? 'partial' : false;
  3108. }
  3109. }
  3110. function lastChar(keys) {
  3111. var match = /^.*(<[\w\-]+>)$/.exec(keys);
  3112. var selectedCharacter = match ? match[1] : keys.slice(-1);
  3113. if (selectedCharacter.length > 1){
  3114. switch(selectedCharacter){
  3115. case '<CR>':
  3116. selectedCharacter='\n';
  3117. break;
  3118. case '<Space>':
  3119. selectedCharacter=' ';
  3120. break;
  3121. default:
  3122. break;
  3123. }
  3124. }
  3125. return selectedCharacter;
  3126. }
  3127. function repeatFn(cm, fn, repeat) {
  3128. return function() {
  3129. for (var i = 0; i < repeat; i++) {
  3130. fn(cm);
  3131. }
  3132. };
  3133. }
  3134. function copyCursor(cur) {
  3135. return Pos(cur.line, cur.ch);
  3136. }
  3137. function cursorEqual(cur1, cur2) {
  3138. return cur1.ch == cur2.ch && cur1.line == cur2.line;
  3139. }
  3140. function cursorIsBefore(cur1, cur2) {
  3141. if (cur1.line < cur2.line) {
  3142. return true;
  3143. }
  3144. if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
  3145. return true;
  3146. }
  3147. return false;
  3148. }
  3149. function cursorMin(cur1, cur2) {
  3150. if (arguments.length > 2) {
  3151. cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));
  3152. }
  3153. return cursorIsBefore(cur1, cur2) ? cur1 : cur2;
  3154. }
  3155. function cursorMax(cur1, cur2) {
  3156. if (arguments.length > 2) {
  3157. cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));
  3158. }
  3159. return cursorIsBefore(cur1, cur2) ? cur2 : cur1;
  3160. }
  3161. function cursorIsBetween(cur1, cur2, cur3) {
  3162. var cur1before2 = cursorIsBefore(cur1, cur2);
  3163. var cur2before3 = cursorIsBefore(cur2, cur3);
  3164. return cur1before2 && cur2before3;
  3165. }
  3166. function lineLength(cm, lineNum) {
  3167. return cm.getLine(lineNum).length;
  3168. }
  3169. function trim(s) {
  3170. if (s.trim) {
  3171. return s.trim();
  3172. }
  3173. return s.replace(/^\s+|\s+$/g, '');
  3174. }
  3175. function escapeRegex(s) {
  3176. return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
  3177. }
  3178. function extendLineToColumn(cm, lineNum, column) {
  3179. var endCh = lineLength(cm, lineNum);
  3180. var spaces = new Array(column-endCh+1).join(' ');
  3181. cm.setCursor(Pos(lineNum, endCh));
  3182. cm.replaceRange(spaces, cm.getCursor());
  3183. }
  3184. function selectBlock(cm, selectionEnd) {
  3185. var selections = [], ranges = cm.listSelections();
  3186. var head = copyCursor(cm.clipPos(selectionEnd));
  3187. var isClipped = !cursorEqual(selectionEnd, head);
  3188. var curHead = cm.getCursor('head');
  3189. var primIndex = getIndex(ranges, curHead);
  3190. var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor);
  3191. var max = ranges.length - 1;
  3192. var index = max - primIndex > primIndex ? max : 0;
  3193. var base = ranges[index].anchor;
  3194. var firstLine = Math.min(base.line, head.line);
  3195. var lastLine = Math.max(base.line, head.line);
  3196. var baseCh = base.ch, headCh = head.ch;
  3197. var dir = ranges[index].head.ch - baseCh;
  3198. var newDir = headCh - baseCh;
  3199. if (dir > 0 && newDir <= 0) {
  3200. baseCh++;
  3201. if (!isClipped) { headCh--; }
  3202. } else if (dir < 0 && newDir >= 0) {
  3203. baseCh--;
  3204. if (!wasClipped) { headCh++; }
  3205. } else if (dir < 0 && newDir == -1) {
  3206. baseCh--;
  3207. headCh++;
  3208. }
  3209. for (var line = firstLine; line <= lastLine; line++) {
  3210. var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)};
  3211. selections.push(range);
  3212. }
  3213. primIndex = head.line == lastLine ? selections.length - 1 : 0;
  3214. cm.setSelections(selections);
  3215. selectionEnd.ch = headCh;
  3216. base.ch = baseCh;
  3217. return base;
  3218. }
  3219. function selectForInsert(cm, head, height) {
  3220. var sel = [];
  3221. for (var i = 0; i < height; i++) {
  3222. var lineHead = offsetCursor(head, i, 0);
  3223. sel.push({anchor: lineHead, head: lineHead});
  3224. }
  3225. cm.setSelections(sel, 0);
  3226. }
  3227. function getIndex(ranges, cursor, end) {
  3228. for (var i = 0; i < ranges.length; i++) {
  3229. var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor);
  3230. var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor);
  3231. if (atAnchor || atHead) {
  3232. return i;
  3233. }
  3234. }
  3235. return -1;
  3236. }
  3237. function getSelectedAreaRange(cm, vim) {
  3238. var lastSelection = vim.lastSelection;
  3239. var getCurrentSelectedAreaRange = function() {
  3240. var selections = cm.listSelections();
  3241. var start = selections[0];
  3242. var end = selections[selections.length-1];
  3243. var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
  3244. var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
  3245. return [selectionStart, selectionEnd];
  3246. };
  3247. var getLastSelectedAreaRange = function() {
  3248. var selectionStart = cm.getCursor();
  3249. var selectionEnd = cm.getCursor();
  3250. var block = lastSelection.visualBlock;
  3251. if (block) {
  3252. var width = block.width;
  3253. var height = block.height;
  3254. selectionEnd = Pos(selectionStart.line + height, selectionStart.ch + width);
  3255. var selections = [];
  3256. for (var i = selectionStart.line; i < selectionEnd.line; i++) {
  3257. var anchor = Pos(i, selectionStart.ch);
  3258. var head = Pos(i, selectionEnd.ch);
  3259. var range = {anchor: anchor, head: head};
  3260. selections.push(range);
  3261. }
  3262. cm.setSelections(selections);
  3263. } else {
  3264. var start = lastSelection.anchorMark.find();
  3265. var end = lastSelection.headMark.find();
  3266. var line = end.line - start.line;
  3267. var ch = end.ch - start.ch;
  3268. selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch};
  3269. if (lastSelection.visualLine) {
  3270. selectionStart = Pos(selectionStart.line, 0);
  3271. selectionEnd = Pos(selectionEnd.line, lineLength(cm, selectionEnd.line));
  3272. }
  3273. cm.setSelection(selectionStart, selectionEnd);
  3274. }
  3275. return [selectionStart, selectionEnd];
  3276. };
  3277. if (!vim.visualMode) {
  3278. return getLastSelectedAreaRange();
  3279. } else {
  3280. return getCurrentSelectedAreaRange();
  3281. }
  3282. }
  3283. function updateLastSelection(cm, vim) {
  3284. var anchor = vim.sel.anchor;
  3285. var head = vim.sel.head;
  3286. if (vim.lastPastedText) {
  3287. head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);
  3288. vim.lastPastedText = null;
  3289. }
  3290. vim.lastSelection = {'anchorMark': cm.setBookmark(anchor),
  3291. 'headMark': cm.setBookmark(head),
  3292. 'anchor': copyCursor(anchor),
  3293. 'head': copyCursor(head),
  3294. 'visualMode': vim.visualMode,
  3295. 'visualLine': vim.visualLine,
  3296. 'visualBlock': vim.visualBlock};
  3297. }
  3298. function expandSelection(cm, start, end) {
  3299. var sel = cm.state.vim.sel;
  3300. var head = sel.head;
  3301. var anchor = sel.anchor;
  3302. var tmp;
  3303. if (cursorIsBefore(end, start)) {
  3304. tmp = end;
  3305. end = start;
  3306. start = tmp;
  3307. }
  3308. if (cursorIsBefore(head, anchor)) {
  3309. head = cursorMin(start, head);
  3310. anchor = cursorMax(anchor, end);
  3311. } else {
  3312. anchor = cursorMin(start, anchor);
  3313. head = cursorMax(head, end);
  3314. head = offsetCursor(head, 0, -1);
  3315. if (head.ch == -1 && head.line != cm.firstLine()) {
  3316. head = Pos(head.line - 1, lineLength(cm, head.line - 1));
  3317. }
  3318. }
  3319. return [anchor, head];
  3320. }
  3321. function updateCmSelection(cm, sel, mode) {
  3322. var vim = cm.state.vim;
  3323. sel = sel || vim.sel;
  3324. var mode = mode ||
  3325. vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';
  3326. var cmSel = makeCmSelection(cm, sel, mode);
  3327. cm.setSelections(cmSel.ranges, cmSel.primary);
  3328. updateFakeCursor(cm);
  3329. }
  3330. function makeCmSelection(cm, sel, mode, exclusive) {
  3331. var head = copyCursor(sel.head);
  3332. var anchor = copyCursor(sel.anchor);
  3333. if (mode == 'char') {
  3334. var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
  3335. var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
  3336. head = offsetCursor(sel.head, 0, headOffset);
  3337. anchor = offsetCursor(sel.anchor, 0, anchorOffset);
  3338. return {
  3339. ranges: [{anchor: anchor, head: head}],
  3340. primary: 0
  3341. };
  3342. } else if (mode == 'line') {
  3343. if (!cursorIsBefore(sel.head, sel.anchor)) {
  3344. anchor.ch = 0;
  3345. var lastLine = cm.lastLine();
  3346. if (head.line > lastLine) {
  3347. head.line = lastLine;
  3348. }
  3349. head.ch = lineLength(cm, head.line);
  3350. } else {
  3351. head.ch = 0;
  3352. anchor.ch = lineLength(cm, anchor.line);
  3353. }
  3354. return {
  3355. ranges: [{anchor: anchor, head: head}],
  3356. primary: 0
  3357. };
  3358. } else if (mode == 'block') {
  3359. var top = Math.min(anchor.line, head.line),
  3360. left = Math.min(anchor.ch, head.ch),
  3361. bottom = Math.max(anchor.line, head.line),
  3362. right = Math.max(anchor.ch, head.ch) + 1;
  3363. var height = bottom - top + 1;
  3364. var primary = head.line == top ? 0 : height - 1;
  3365. var ranges = [];
  3366. for (var i = 0; i < height; i++) {
  3367. ranges.push({
  3368. anchor: Pos(top + i, left),
  3369. head: Pos(top + i, right)
  3370. });
  3371. }
  3372. return {
  3373. ranges: ranges,
  3374. primary: primary
  3375. };
  3376. }
  3377. }
  3378. function getHead(cm) {
  3379. var cur = cm.getCursor('head');
  3380. if (cm.getSelection().length == 1) {
  3381. cur = cursorMin(cur, cm.getCursor('anchor'));
  3382. }
  3383. return cur;
  3384. }
  3385. function exitVisualMode(cm, moveHead) {
  3386. var vim = cm.state.vim;
  3387. if (moveHead !== false) {
  3388. cm.setCursor(clipCursorToContent(cm, vim.sel.head));
  3389. }
  3390. updateLastSelection(cm, vim);
  3391. vim.visualMode = false;
  3392. vim.visualLine = false;
  3393. vim.visualBlock = false;
  3394. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  3395. if (vim.fakeCursor) {
  3396. vim.fakeCursor.clear();
  3397. }
  3398. }
  3399. function clipToLine(cm, curStart, curEnd) {
  3400. var selection = cm.getRange(curStart, curEnd);
  3401. if (/\n\s*$/.test(selection)) {
  3402. var lines = selection.split('\n');
  3403. lines.pop();
  3404. var line;
  3405. for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
  3406. curEnd.line--;
  3407. curEnd.ch = 0;
  3408. }
  3409. if (line) {
  3410. curEnd.line--;
  3411. curEnd.ch = lineLength(cm, curEnd.line);
  3412. } else {
  3413. curEnd.ch = 0;
  3414. }
  3415. }
  3416. }
  3417. function expandSelectionToLine(_cm, curStart, curEnd) {
  3418. curStart.ch = 0;
  3419. curEnd.ch = 0;
  3420. curEnd.line++;
  3421. }
  3422. function findFirstNonWhiteSpaceCharacter(text) {
  3423. if (!text) {
  3424. return 0;
  3425. }
  3426. var firstNonWS = text.search(/\S/);
  3427. return firstNonWS == -1 ? text.length : firstNonWS;
  3428. }
  3429. function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
  3430. var cur = getHead(cm);
  3431. var line = cm.getLine(cur.line);
  3432. var idx = cur.ch;
  3433. var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0];
  3434. while (!test(line.charAt(idx))) {
  3435. idx++;
  3436. if (idx >= line.length) { return null; }
  3437. }
  3438. if (bigWord) {
  3439. test = bigWordCharTest[0];
  3440. } else {
  3441. test = wordCharTest[0];
  3442. if (!test(line.charAt(idx))) {
  3443. test = wordCharTest[1];
  3444. }
  3445. }
  3446. var end = idx, start = idx;
  3447. while (test(line.charAt(end)) && end < line.length) { end++; }
  3448. while (test(line.charAt(start)) && start >= 0) { start--; }
  3449. start++;
  3450. if (inclusive) {
  3451. var wordEnd = end;
  3452. while (/\s/.test(line.charAt(end)) && end < line.length) { end++; }
  3453. if (wordEnd == end) {
  3454. var wordStart = start;
  3455. while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; }
  3456. if (!start) { start = wordStart; }
  3457. }
  3458. }
  3459. return { start: Pos(cur.line, start), end: Pos(cur.line, end) };
  3460. }
  3461. function recordJumpPosition(cm, oldCur, newCur) {
  3462. if (!cursorEqual(oldCur, newCur)) {
  3463. vimGlobalState.jumpList.add(cm, oldCur, newCur);
  3464. }
  3465. }
  3466. function recordLastCharacterSearch(increment, args) {
  3467. vimGlobalState.lastChararacterSearch.increment = increment;
  3468. vimGlobalState.lastChararacterSearch.forward = args.forward;
  3469. vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter;
  3470. }
  3471. var symbolToMode = {
  3472. '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
  3473. '[': 'section', ']': 'section',
  3474. '*': 'comment', '/': 'comment',
  3475. 'm': 'method', 'M': 'method',
  3476. '#': 'preprocess'
  3477. };
  3478. var findSymbolModes = {
  3479. bracket: {
  3480. isComplete: function(state) {
  3481. if (state.nextCh === state.symb) {
  3482. state.depth++;
  3483. if (state.depth >= 1)return true;
  3484. } else if (state.nextCh === state.reverseSymb) {
  3485. state.depth--;
  3486. }
  3487. return false;
  3488. }
  3489. },
  3490. section: {
  3491. init: function(state) {
  3492. state.curMoveThrough = true;
  3493. state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
  3494. },
  3495. isComplete: function(state) {
  3496. return state.index === 0 && state.nextCh === state.symb;
  3497. }
  3498. },
  3499. comment: {
  3500. isComplete: function(state) {
  3501. var found = state.lastCh === '*' && state.nextCh === '/';
  3502. state.lastCh = state.nextCh;
  3503. return found;
  3504. }
  3505. },
  3506. method: {
  3507. init: function(state) {
  3508. state.symb = (state.symb === 'm' ? '{' : '}');
  3509. state.reverseSymb = state.symb === '{' ? '}' : '{';
  3510. },
  3511. isComplete: function(state) {
  3512. if (state.nextCh === state.symb)return true;
  3513. return false;
  3514. }
  3515. },
  3516. preprocess: {
  3517. init: function(state) {
  3518. state.index = 0;
  3519. },
  3520. isComplete: function(state) {
  3521. if (state.nextCh === '#') {
  3522. var token = state.lineText.match(/#(\w+)/)[1];
  3523. if (token === 'endif') {
  3524. if (state.forward && state.depth === 0) {
  3525. return true;
  3526. }
  3527. state.depth++;
  3528. } else if (token === 'if') {
  3529. if (!state.forward && state.depth === 0) {
  3530. return true;
  3531. }
  3532. state.depth--;
  3533. }
  3534. if (token === 'else' && state.depth === 0)return true;
  3535. }
  3536. return false;
  3537. }
  3538. }
  3539. };
  3540. function findSymbol(cm, repeat, forward, symb) {
  3541. var cur = copyCursor(cm.getCursor());
  3542. var increment = forward ? 1 : -1;
  3543. var endLine = forward ? cm.lineCount() : -1;
  3544. var curCh = cur.ch;
  3545. var line = cur.line;
  3546. var lineText = cm.getLine(line);
  3547. var state = {
  3548. lineText: lineText,
  3549. nextCh: lineText.charAt(curCh),
  3550. lastCh: null,
  3551. index: curCh,
  3552. symb: symb,
  3553. reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
  3554. forward: forward,
  3555. depth: 0,
  3556. curMoveThrough: false
  3557. };
  3558. var mode = symbolToMode[symb];
  3559. if (!mode)return cur;
  3560. var init = findSymbolModes[mode].init;
  3561. var isComplete = findSymbolModes[mode].isComplete;
  3562. if (init) { init(state); }
  3563. while (line !== endLine && repeat) {
  3564. state.index += increment;
  3565. state.nextCh = state.lineText.charAt(state.index);
  3566. if (!state.nextCh) {
  3567. line += increment;
  3568. state.lineText = cm.getLine(line) || '';
  3569. if (increment > 0) {
  3570. state.index = 0;
  3571. } else {
  3572. var lineLen = state.lineText.length;
  3573. state.index = (lineLen > 0) ? (lineLen-1) : 0;
  3574. }
  3575. state.nextCh = state.lineText.charAt(state.index);
  3576. }
  3577. if (isComplete(state)) {
  3578. cur.line = line;
  3579. cur.ch = state.index;
  3580. repeat--;
  3581. }
  3582. }
  3583. if (state.nextCh || state.curMoveThrough) {
  3584. return Pos(line, state.index);
  3585. }
  3586. return cur;
  3587. }
  3588. function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
  3589. var lineNum = cur.line;
  3590. var pos = cur.ch;
  3591. var line = cm.getLine(lineNum);
  3592. var dir = forward ? 1 : -1;
  3593. var charTests = bigWord ? bigWordCharTest: wordCharTest;
  3594. if (emptyLineIsWord && line == '') {
  3595. lineNum += dir;
  3596. line = cm.getLine(lineNum);
  3597. if (!isLine(cm, lineNum)) {
  3598. return null;
  3599. }
  3600. pos = (forward) ? 0 : line.length;
  3601. }
  3602. while (true) {
  3603. if (emptyLineIsWord && line == '') {
  3604. return { from: 0, to: 0, line: lineNum };
  3605. }
  3606. var stop = (dir > 0) ? line.length : -1;
  3607. var wordStart = stop, wordEnd = stop;
  3608. while (pos != stop) {
  3609. var foundWord = false;
  3610. for (var i = 0; i < charTests.length && !foundWord; ++i) {
  3611. if (charTests[i](line.charAt(pos))) {
  3612. wordStart = pos;
  3613. while (pos != stop && charTests[i](line.charAt(pos))) {
  3614. pos += dir;
  3615. }
  3616. wordEnd = pos;
  3617. foundWord = wordStart != wordEnd;
  3618. if (wordStart == cur.ch && lineNum == cur.line &&
  3619. wordEnd == wordStart + dir) {
  3620. continue;
  3621. } else {
  3622. return {
  3623. from: Math.min(wordStart, wordEnd + 1),
  3624. to: Math.max(wordStart, wordEnd),
  3625. line: lineNum };
  3626. }
  3627. }
  3628. }
  3629. if (!foundWord) {
  3630. pos += dir;
  3631. }
  3632. }
  3633. lineNum += dir;
  3634. if (!isLine(cm, lineNum)) {
  3635. return null;
  3636. }
  3637. line = cm.getLine(lineNum);
  3638. pos = (dir > 0) ? 0 : line.length;
  3639. }
  3640. throw new Error('The impossible happened.');
  3641. }
  3642. function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {
  3643. var curStart = copyCursor(cur);
  3644. var words = [];
  3645. if (forward && !wordEnd || !forward && wordEnd) {
  3646. repeat++;
  3647. }
  3648. var emptyLineIsWord = !(forward && wordEnd);
  3649. for (var i = 0; i < repeat; i++) {
  3650. var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
  3651. if (!word) {
  3652. var eodCh = lineLength(cm, cm.lastLine());
  3653. words.push(forward
  3654. ? {line: cm.lastLine(), from: eodCh, to: eodCh}
  3655. : {line: 0, from: 0, to: 0});
  3656. break;
  3657. }
  3658. words.push(word);
  3659. cur = Pos(word.line, forward ? (word.to - 1) : word.from);
  3660. }
  3661. var shortCircuit = words.length != repeat;
  3662. var firstWord = words[0];
  3663. var lastWord = words.pop();
  3664. if (forward && !wordEnd) {
  3665. if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
  3666. lastWord = words.pop();
  3667. }
  3668. return Pos(lastWord.line, lastWord.from);
  3669. } else if (forward && wordEnd) {
  3670. return Pos(lastWord.line, lastWord.to - 1);
  3671. } else if (!forward && wordEnd) {
  3672. if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
  3673. lastWord = words.pop();
  3674. }
  3675. return Pos(lastWord.line, lastWord.to);
  3676. } else {
  3677. return Pos(lastWord.line, lastWord.from);
  3678. }
  3679. }
  3680. function moveToCharacter(cm, repeat, forward, character) {
  3681. var cur = cm.getCursor();
  3682. var start = cur.ch;
  3683. var idx;
  3684. for (var i = 0; i < repeat; i ++) {
  3685. var line = cm.getLine(cur.line);
  3686. idx = charIdxInLine(start, line, character, forward, true);
  3687. if (idx == -1) {
  3688. return null;
  3689. }
  3690. start = idx;
  3691. }
  3692. return Pos(cm.getCursor().line, idx);
  3693. }
  3694. function moveToColumn(cm, repeat) {
  3695. var line = cm.getCursor().line;
  3696. return clipCursorToContent(cm, Pos(line, repeat - 1));
  3697. }
  3698. function updateMark(cm, vim, markName, pos) {
  3699. if (!inArray(markName, validMarks)) {
  3700. return;
  3701. }
  3702. if (vim.marks[markName]) {
  3703. vim.marks[markName].clear();
  3704. }
  3705. vim.marks[markName] = cm.setBookmark(pos);
  3706. }
  3707. function charIdxInLine(start, line, character, forward, includeChar) {
  3708. var idx;
  3709. if (forward) {
  3710. idx = line.indexOf(character, start + 1);
  3711. if (idx != -1 && !includeChar) {
  3712. idx -= 1;
  3713. }
  3714. } else {
  3715. idx = line.lastIndexOf(character, start - 1);
  3716. if (idx != -1 && !includeChar) {
  3717. idx += 1;
  3718. }
  3719. }
  3720. return idx;
  3721. }
  3722. function findParagraph(cm, head, repeat, dir, inclusive) {
  3723. var line = head.line;
  3724. var min = cm.firstLine();
  3725. var max = cm.lastLine();
  3726. var start, end, i = line;
  3727. function isEmpty(i) { return !/\S/.test(cm.getLine(i)); } // ace_patch
  3728. function isBoundary(i, dir, any) {
  3729. if (any) { return isEmpty(i) != isEmpty(i + dir); }
  3730. return !isEmpty(i) && isEmpty(i + dir);
  3731. }
  3732. function skipFold(i) {
  3733. dir = dir > 0 ? 1 : -1;
  3734. var foldLine = cm.ace.session.getFoldLine(i);
  3735. if (foldLine) {
  3736. if (i + dir > foldLine.start.row && i + dir < foldLine.end.row)
  3737. dir = (dir > 0 ? foldLine.end.row : foldLine.start.row) - i;
  3738. }
  3739. }
  3740. if (dir) {
  3741. while (min <= i && i <= max && repeat > 0) {
  3742. skipFold(i);
  3743. if (isBoundary(i, dir)) { repeat--; }
  3744. i += dir;
  3745. }
  3746. return new Pos(i, 0);
  3747. }
  3748. var vim = cm.state.vim;
  3749. if (vim.visualLine && isBoundary(line, 1, true)) {
  3750. var anchor = vim.sel.anchor;
  3751. if (isBoundary(anchor.line, -1, true)) {
  3752. if (!inclusive || anchor.line != line) {
  3753. line += 1;
  3754. }
  3755. }
  3756. }
  3757. var startState = isEmpty(line);
  3758. for (i = line; i <= max && repeat; i++) {
  3759. if (isBoundary(i, 1, true)) {
  3760. if (!inclusive || isEmpty(i) != startState) {
  3761. repeat--;
  3762. }
  3763. }
  3764. }
  3765. end = new Pos(i, 0);
  3766. if (i > max && !startState) { startState = true; }
  3767. else { inclusive = false; }
  3768. for (i = line; i > min; i--) {
  3769. if (!inclusive || isEmpty(i) == startState || i == line) {
  3770. if (isBoundary(i, -1, true)) { break; }
  3771. }
  3772. }
  3773. start = new Pos(i, 0);
  3774. return { start: start, end: end };
  3775. }
  3776. function selectCompanionObject(cm, head, symb, inclusive) {
  3777. var cur = head, start, end;
  3778. var bracketRegexp = ({
  3779. '(': /[()]/, ')': /[()]/,
  3780. '[': /[[\]]/, ']': /[[\]]/,
  3781. '{': /[{}]/, '}': /[{}]/})[symb];
  3782. var openSym = ({
  3783. '(': '(', ')': '(',
  3784. '[': '[', ']': '[',
  3785. '{': '{', '}': '{'})[symb];
  3786. var curChar = cm.getLine(cur.line).charAt(cur.ch);
  3787. var offset = curChar === openSym ? 1 : 0;
  3788. start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, null, {'bracketRegex': bracketRegexp});
  3789. end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, null, {'bracketRegex': bracketRegexp});
  3790. if (!start || !end) {
  3791. return { start: cur, end: cur };
  3792. }
  3793. start = start.pos;
  3794. end = end.pos;
  3795. if ((start.line == end.line && start.ch > end.ch)
  3796. || (start.line > end.line)) {
  3797. var tmp = start;
  3798. start = end;
  3799. end = tmp;
  3800. }
  3801. if (inclusive) {
  3802. end.ch += 1;
  3803. } else {
  3804. start.ch += 1;
  3805. }
  3806. return { start: start, end: end };
  3807. }
  3808. function findBeginningAndEnd(cm, head, symb, inclusive) {
  3809. var cur = copyCursor(head);
  3810. var line = cm.getLine(cur.line);
  3811. var chars = line.split('');
  3812. var start, end, i, len;
  3813. var firstIndex = chars.indexOf(symb);
  3814. if (cur.ch < firstIndex) {
  3815. cur.ch = firstIndex;
  3816. }
  3817. else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
  3818. end = cur.ch; // assign end to the current cursor
  3819. --cur.ch; // make sure to look backwards
  3820. }
  3821. if (chars[cur.ch] == symb && !end) {
  3822. start = cur.ch + 1; // assign start to ahead of the cursor
  3823. } else {
  3824. for (i = cur.ch; i > -1 && !start; i--) {
  3825. if (chars[i] == symb) {
  3826. start = i + 1;
  3827. }
  3828. }
  3829. }
  3830. if (start && !end) {
  3831. for (i = start, len = chars.length; i < len && !end; i++) {
  3832. if (chars[i] == symb) {
  3833. end = i;
  3834. }
  3835. }
  3836. }
  3837. if (!start || !end) {
  3838. return { start: cur, end: cur };
  3839. }
  3840. if (inclusive) {
  3841. --start; ++end;
  3842. }
  3843. return {
  3844. start: Pos(cur.line, start),
  3845. end: Pos(cur.line, end)
  3846. };
  3847. }
  3848. defineOption('pcre', true, 'boolean');
  3849. function SearchState() {}
  3850. SearchState.prototype = {
  3851. getQuery: function() {
  3852. return vimGlobalState.query;
  3853. },
  3854. setQuery: function(query) {
  3855. vimGlobalState.query = query;
  3856. },
  3857. getOverlay: function() {
  3858. return this.searchOverlay;
  3859. },
  3860. setOverlay: function(overlay) {
  3861. this.searchOverlay = overlay;
  3862. },
  3863. isReversed: function() {
  3864. return vimGlobalState.isReversed;
  3865. },
  3866. setReversed: function(reversed) {
  3867. vimGlobalState.isReversed = reversed;
  3868. },
  3869. getScrollbarAnnotate: function() {
  3870. return this.annotate;
  3871. },
  3872. setScrollbarAnnotate: function(annotate) {
  3873. this.annotate = annotate;
  3874. }
  3875. };
  3876. function getSearchState(cm) {
  3877. var vim = cm.state.vim;
  3878. return vim.searchState_ || (vim.searchState_ = new SearchState());
  3879. }
  3880. function dialog(cm, template, shortText, onClose, options) {
  3881. if (cm.openDialog) {
  3882. cm.openDialog(template, onClose, { bottom: true, value: options.value,
  3883. onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp,
  3884. selectValueOnOpen: false});
  3885. }
  3886. else {
  3887. onClose(prompt(shortText, ''));
  3888. }
  3889. }
  3890. function splitBySlash(argString) {
  3891. var slashes = findUnescapedSlashes(argString) || [];
  3892. if (!slashes.length) return [];
  3893. var tokens = [];
  3894. if (slashes[0] !== 0) return;
  3895. for (var i = 0; i < slashes.length; i++) {
  3896. if (typeof slashes[i] == 'number')
  3897. tokens.push(argString.substring(slashes[i] + 1, slashes[i+1]));
  3898. }
  3899. return tokens;
  3900. }
  3901. function findUnescapedSlashes(str) {
  3902. var escapeNextChar = false;
  3903. var slashes = [];
  3904. for (var i = 0; i < str.length; i++) {
  3905. var c = str.charAt(i);
  3906. if (!escapeNextChar && c == '/') {
  3907. slashes.push(i);
  3908. }
  3909. escapeNextChar = !escapeNextChar && (c == '\\');
  3910. }
  3911. return slashes;
  3912. }
  3913. function translateRegex(str) {
  3914. var specials = '|(){';
  3915. var unescape = '}';
  3916. var escapeNextChar = false;
  3917. var out = [];
  3918. for (var i = -1; i < str.length; i++) {
  3919. var c = str.charAt(i) || '';
  3920. var n = str.charAt(i+1) || '';
  3921. var specialComesNext = (n && specials.indexOf(n) != -1);
  3922. if (escapeNextChar) {
  3923. if (c !== '\\' || !specialComesNext) {
  3924. out.push(c);
  3925. }
  3926. escapeNextChar = false;
  3927. } else {
  3928. if (c === '\\') {
  3929. escapeNextChar = true;
  3930. if (n && unescape.indexOf(n) != -1) {
  3931. specialComesNext = true;
  3932. }
  3933. if (!specialComesNext || n === '\\') {
  3934. out.push(c);
  3935. }
  3936. } else {
  3937. out.push(c);
  3938. if (specialComesNext && n !== '\\') {
  3939. out.push('\\');
  3940. }
  3941. }
  3942. }
  3943. }
  3944. return out.join('');
  3945. }
  3946. var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'};
  3947. function translateRegexReplace(str) {
  3948. var escapeNextChar = false;
  3949. var out = [];
  3950. for (var i = -1; i < str.length; i++) {
  3951. var c = str.charAt(i) || '';
  3952. var n = str.charAt(i+1) || '';
  3953. if (charUnescapes[c + n]) {
  3954. out.push(charUnescapes[c+n]);
  3955. i++;
  3956. } else if (escapeNextChar) {
  3957. out.push(c);
  3958. escapeNextChar = false;
  3959. } else {
  3960. if (c === '\\') {
  3961. escapeNextChar = true;
  3962. if ((isNumber(n) || n === '$')) {
  3963. out.push('$');
  3964. } else if (n !== '/' && n !== '\\') {
  3965. out.push('\\');
  3966. }
  3967. } else {
  3968. if (c === '$') {
  3969. out.push('$');
  3970. }
  3971. out.push(c);
  3972. if (n === '/') {
  3973. out.push('\\');
  3974. }
  3975. }
  3976. }
  3977. }
  3978. return out.join('');
  3979. }
  3980. var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t'};
  3981. function unescapeRegexReplace(str) {
  3982. var stream = new CodeMirror.StringStream(str);
  3983. var output = [];
  3984. while (!stream.eol()) {
  3985. while (stream.peek() && stream.peek() != '\\') {
  3986. output.push(stream.next());
  3987. }
  3988. var matched = false;
  3989. for (var matcher in unescapes) {
  3990. if (stream.match(matcher, true)) {
  3991. matched = true;
  3992. output.push(unescapes[matcher]);
  3993. break;
  3994. }
  3995. }
  3996. if (!matched) {
  3997. output.push(stream.next());
  3998. }
  3999. }
  4000. return output.join('');
  4001. }
  4002. function parseQuery(query, ignoreCase, smartCase) {
  4003. var lastSearchRegister = vimGlobalState.registerController.getRegister('/');
  4004. lastSearchRegister.setText(query);
  4005. if (query instanceof RegExp) { return query; }
  4006. var slashes = findUnescapedSlashes(query);
  4007. var regexPart;
  4008. var forceIgnoreCase;
  4009. if (!slashes.length) {
  4010. regexPart = query;
  4011. } else {
  4012. regexPart = query.substring(0, slashes[0]);
  4013. var flagsPart = query.substring(slashes[0]);
  4014. forceIgnoreCase = (flagsPart.indexOf('i') != -1);
  4015. }
  4016. if (!regexPart) {
  4017. return null;
  4018. }
  4019. if (!getOption('pcre')) {
  4020. regexPart = translateRegex(regexPart);
  4021. }
  4022. if (smartCase) {
  4023. ignoreCase = (/^[^A-Z]*$/).test(regexPart);
  4024. }
  4025. var regexp = new RegExp(regexPart,
  4026. (ignoreCase || forceIgnoreCase) ? 'i' : undefined);
  4027. return regexp;
  4028. }
  4029. function showConfirm(cm, text) {
  4030. if (cm.openNotification) {
  4031. cm.openNotification('<span style="color: red">' + text + '</span>',
  4032. {bottom: true, duration: 5000});
  4033. } else {
  4034. alert(text);
  4035. }
  4036. }
  4037. function makePrompt(prefix, desc) {
  4038. var raw = '';
  4039. if (prefix) {
  4040. raw += '<span style="font-family: monospace">' + prefix + '</span>';
  4041. }
  4042. raw += '<input type="text"/> ' +
  4043. '<span style="color: #888">';
  4044. if (desc) {
  4045. raw += '<span style="color: #888">';
  4046. raw += desc;
  4047. raw += '</span>';
  4048. }
  4049. return raw;
  4050. }
  4051. var searchPromptDesc = '(Javascript regexp)';
  4052. function showPrompt(cm, options) {
  4053. var shortText = (options.prefix || '') + ' ' + (options.desc || '');
  4054. var prompt = makePrompt(options.prefix, options.desc);
  4055. dialog(cm, prompt, shortText, options.onClose, options);
  4056. }
  4057. function regexEqual(r1, r2) {
  4058. if (r1 instanceof RegExp && r2 instanceof RegExp) {
  4059. var props = ['global', 'multiline', 'ignoreCase', 'source'];
  4060. for (var i = 0; i < props.length; i++) {
  4061. var prop = props[i];
  4062. if (r1[prop] !== r2[prop]) {
  4063. return false;
  4064. }
  4065. }
  4066. return true;
  4067. }
  4068. return false;
  4069. }
  4070. function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
  4071. if (!rawQuery) {
  4072. return;
  4073. }
  4074. var state = getSearchState(cm);
  4075. var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
  4076. if (!query) {
  4077. return;
  4078. }
  4079. highlightSearchMatches(cm, query);
  4080. if (regexEqual(query, state.getQuery())) {
  4081. return query;
  4082. }
  4083. state.setQuery(query);
  4084. return query;
  4085. }
  4086. function searchOverlay(query) {
  4087. if (query.source.charAt(0) == '^') {
  4088. var matchSol = true;
  4089. }
  4090. return {
  4091. token: function(stream) {
  4092. if (matchSol && !stream.sol()) {
  4093. stream.skipToEnd();
  4094. return;
  4095. }
  4096. var match = stream.match(query, false);
  4097. if (match) {
  4098. if (match[0].length == 0) {
  4099. stream.next();
  4100. return 'searching';
  4101. }
  4102. if (!stream.sol()) {
  4103. stream.backUp(1);
  4104. if (!query.exec(stream.next() + match[0])) {
  4105. stream.next();
  4106. return null;
  4107. }
  4108. }
  4109. stream.match(query);
  4110. return 'searching';
  4111. }
  4112. while (!stream.eol()) {
  4113. stream.next();
  4114. if (stream.match(query, false)) break;
  4115. }
  4116. },
  4117. query: query
  4118. };
  4119. }
  4120. function highlightSearchMatches(cm, query) {
  4121. var searchState = getSearchState(cm);
  4122. var overlay = searchState.getOverlay();
  4123. if (!overlay || query != overlay.query) {
  4124. if (overlay) {
  4125. cm.removeOverlay(overlay);
  4126. }
  4127. overlay = searchOverlay(query);
  4128. cm.addOverlay(overlay);
  4129. if (cm.showMatchesOnScrollbar) {
  4130. if (searchState.getScrollbarAnnotate()) {
  4131. searchState.getScrollbarAnnotate().clear();
  4132. }
  4133. searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query));
  4134. }
  4135. searchState.setOverlay(overlay);
  4136. }
  4137. }
  4138. function findNext(cm, prev, query, repeat) {
  4139. if (repeat === undefined) { repeat = 1; }
  4140. return cm.operation(function() {
  4141. var pos = cm.getCursor();
  4142. var cursor = cm.getSearchCursor(query, pos);
  4143. for (var i = 0; i < repeat; i++) {
  4144. var found = cursor.find(prev);
  4145. if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
  4146. if (!found) {
  4147. cursor = cm.getSearchCursor(query,
  4148. (prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) );
  4149. if (!cursor.find(prev)) {
  4150. return;
  4151. }
  4152. }
  4153. }
  4154. return cursor.from();
  4155. });
  4156. }
  4157. function clearSearchHighlight(cm) {
  4158. var state = getSearchState(cm);
  4159. cm.removeOverlay(getSearchState(cm).getOverlay());
  4160. state.setOverlay(null);
  4161. if (state.getScrollbarAnnotate()) {
  4162. state.getScrollbarAnnotate().clear();
  4163. state.setScrollbarAnnotate(null);
  4164. }
  4165. }
  4166. function isInRange(pos, start, end) {
  4167. if (typeof pos != 'number') {
  4168. pos = pos.line;
  4169. }
  4170. if (start instanceof Array) {
  4171. return inArray(pos, start);
  4172. } else {
  4173. if (end) {
  4174. return (pos >= start && pos <= end);
  4175. } else {
  4176. return pos == start;
  4177. }
  4178. }
  4179. }
  4180. function getUserVisibleLines(cm) {
  4181. var renderer = cm.ace.renderer;
  4182. return {
  4183. top: renderer.getFirstFullyVisibleRow(),
  4184. bottom: renderer.getLastFullyVisibleRow()
  4185. }
  4186. }
  4187. var ExCommandDispatcher = function() {
  4188. this.buildCommandMap_();
  4189. };
  4190. ExCommandDispatcher.prototype = {
  4191. processCommand: function(cm, input, opt_params) {
  4192. var that = this;
  4193. cm.operation(function () {
  4194. cm.curOp.isVimOp = true;
  4195. that._processCommand(cm, input, opt_params);
  4196. });
  4197. },
  4198. _processCommand: function(cm, input, opt_params) {
  4199. var vim = cm.state.vim;
  4200. var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');
  4201. var previousCommand = commandHistoryRegister.toString();
  4202. if (vim.visualMode) {
  4203. exitVisualMode(cm);
  4204. }
  4205. var inputStream = new CodeMirror.StringStream(input);
  4206. commandHistoryRegister.setText(input);
  4207. var params = opt_params || {};
  4208. params.input = input;
  4209. try {
  4210. this.parseInput_(cm, inputStream, params);
  4211. } catch(e) {
  4212. showConfirm(cm, e);
  4213. throw e;
  4214. }
  4215. var command;
  4216. var commandName;
  4217. if (!params.commandName) {
  4218. if (params.line !== undefined) {
  4219. commandName = 'move';
  4220. }
  4221. } else {
  4222. command = this.matchCommand_(params.commandName);
  4223. if (command) {
  4224. commandName = command.name;
  4225. if (command.excludeFromCommandHistory) {
  4226. commandHistoryRegister.setText(previousCommand);
  4227. }
  4228. this.parseCommandArgs_(inputStream, params, command);
  4229. if (command.type == 'exToKey') {
  4230. for (var i = 0; i < command.toKeys.length; i++) {
  4231. CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping');
  4232. }
  4233. return;
  4234. } else if (command.type == 'exToEx') {
  4235. this.processCommand(cm, command.toInput);
  4236. return;
  4237. }
  4238. }
  4239. }
  4240. if (!commandName) {
  4241. showConfirm(cm, 'Not an editor command ":' + input + '"');
  4242. return;
  4243. }
  4244. try {
  4245. exCommands[commandName](cm, params);
  4246. if ((!command || !command.possiblyAsync) && params.callback) {
  4247. params.callback();
  4248. }
  4249. } catch(e) {
  4250. showConfirm(cm, e);
  4251. throw e;
  4252. }
  4253. },
  4254. parseInput_: function(cm, inputStream, result) {
  4255. inputStream.eatWhile(':');
  4256. if (inputStream.eat('%')) {
  4257. result.line = cm.firstLine();
  4258. result.lineEnd = cm.lastLine();
  4259. } else {
  4260. result.line = this.parseLineSpec_(cm, inputStream);
  4261. if (result.line !== undefined && inputStream.eat(',')) {
  4262. result.lineEnd = this.parseLineSpec_(cm, inputStream);
  4263. }
  4264. }
  4265. var commandMatch = inputStream.match(/^(\w+)/);
  4266. if (commandMatch) {
  4267. result.commandName = commandMatch[1];
  4268. } else {
  4269. result.commandName = inputStream.match(/.*/)[0];
  4270. }
  4271. return result;
  4272. },
  4273. parseLineSpec_: function(cm, inputStream) {
  4274. var numberMatch = inputStream.match(/^(\d+)/);
  4275. if (numberMatch) {
  4276. return parseInt(numberMatch[1], 10) - 1;
  4277. }
  4278. switch (inputStream.next()) {
  4279. case '.':
  4280. return cm.getCursor().line;
  4281. case '$':
  4282. return cm.lastLine();
  4283. case '\'':
  4284. var mark = cm.state.vim.marks[inputStream.next()];
  4285. if (mark && mark.find()) {
  4286. return mark.find().line;
  4287. }
  4288. throw new Error('Mark not set');
  4289. default:
  4290. inputStream.backUp(1);
  4291. return undefined;
  4292. }
  4293. },
  4294. parseCommandArgs_: function(inputStream, params, command) {
  4295. if (inputStream.eol()) {
  4296. return;
  4297. }
  4298. params.argString = inputStream.match(/.*/)[0];
  4299. var delim = command.argDelimiter || /\s+/;
  4300. var args = trim(params.argString).split(delim);
  4301. if (args.length && args[0]) {
  4302. params.args = args;
  4303. }
  4304. },
  4305. matchCommand_: function(commandName) {
  4306. for (var i = commandName.length; i > 0; i--) {
  4307. var prefix = commandName.substring(0, i);
  4308. if (this.commandMap_[prefix]) {
  4309. var command = this.commandMap_[prefix];
  4310. if (command.name.indexOf(commandName) === 0) {
  4311. return command;
  4312. }
  4313. }
  4314. }
  4315. return null;
  4316. },
  4317. buildCommandMap_: function() {
  4318. this.commandMap_ = {};
  4319. for (var i = 0; i < defaultExCommandMap.length; i++) {
  4320. var command = defaultExCommandMap[i];
  4321. var key = command.shortName || command.name;
  4322. this.commandMap_[key] = command;
  4323. }
  4324. },
  4325. map: function(lhs, rhs, ctx) {
  4326. if (lhs != ':' && lhs.charAt(0) == ':') {
  4327. if (ctx) { throw Error('Mode not supported for ex mappings'); }
  4328. var commandName = lhs.substring(1);
  4329. if (rhs != ':' && rhs.charAt(0) == ':') {
  4330. this.commandMap_[commandName] = {
  4331. name: commandName,
  4332. type: 'exToEx',
  4333. toInput: rhs.substring(1),
  4334. user: true
  4335. };
  4336. } else {
  4337. this.commandMap_[commandName] = {
  4338. name: commandName,
  4339. type: 'exToKey',
  4340. toKeys: rhs,
  4341. user: true
  4342. };
  4343. }
  4344. } else {
  4345. if (rhs != ':' && rhs.charAt(0) == ':') {
  4346. var mapping = {
  4347. keys: lhs,
  4348. type: 'keyToEx',
  4349. exArgs: { input: rhs.substring(1) },
  4350. user: true};
  4351. if (ctx) { mapping.context = ctx; }
  4352. defaultKeymap.unshift(mapping);
  4353. } else {
  4354. var mapping = {
  4355. keys: lhs,
  4356. type: 'keyToKey',
  4357. toKeys: rhs,
  4358. user: true
  4359. };
  4360. if (ctx) { mapping.context = ctx; }
  4361. defaultKeymap.unshift(mapping);
  4362. }
  4363. }
  4364. },
  4365. unmap: function(lhs, ctx) {
  4366. if (lhs != ':' && lhs.charAt(0) == ':') {
  4367. if (ctx) { throw Error('Mode not supported for ex mappings'); }
  4368. var commandName = lhs.substring(1);
  4369. if (this.commandMap_[commandName] && this.commandMap_[commandName].user) {
  4370. delete this.commandMap_[commandName];
  4371. return;
  4372. }
  4373. } else {
  4374. var keys = lhs;
  4375. for (var i = 0; i < defaultKeymap.length; i++) {
  4376. if (keys == defaultKeymap[i].keys
  4377. && defaultKeymap[i].context === ctx
  4378. && defaultKeymap[i].user) {
  4379. defaultKeymap.splice(i, 1);
  4380. return;
  4381. }
  4382. }
  4383. }
  4384. }
  4385. };
  4386. var exCommands = {
  4387. colorscheme: function(cm, params) {
  4388. if (!params.args || params.args.length < 1) {
  4389. showConfirm(cm, cm.getOption('theme'));
  4390. return;
  4391. }
  4392. cm.setOption('theme', params.args[0]);
  4393. },
  4394. map: function(cm, params, ctx) {
  4395. var mapArgs = params.args;
  4396. if (!mapArgs || mapArgs.length < 2) {
  4397. if (cm) {
  4398. showConfirm(cm, 'Invalid mapping: ' + params.input);
  4399. }
  4400. return;
  4401. }
  4402. exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
  4403. },
  4404. imap: function(cm, params) { this.map(cm, params, 'insert'); },
  4405. nmap: function(cm, params) { this.map(cm, params, 'normal'); },
  4406. vmap: function(cm, params) { this.map(cm, params, 'visual'); },
  4407. unmap: function(cm, params, ctx) {
  4408. var mapArgs = params.args;
  4409. if (!mapArgs || mapArgs.length < 1) {
  4410. if (cm) {
  4411. showConfirm(cm, 'No such mapping: ' + params.input);
  4412. }
  4413. return;
  4414. }
  4415. exCommandDispatcher.unmap(mapArgs[0], ctx);
  4416. },
  4417. move: function(cm, params) {
  4418. commandDispatcher.processCommand(cm, cm.state.vim, {
  4419. type: 'motion',
  4420. motion: 'moveToLineOrEdgeOfDocument',
  4421. motionArgs: { forward: false, explicitRepeat: true,
  4422. linewise: true },
  4423. repeatOverride: params.line+1});
  4424. },
  4425. set: function(cm, params) {
  4426. var setArgs = params.args;
  4427. var setCfg = params.setCfg || {};
  4428. if (!setArgs || setArgs.length < 1) {
  4429. if (cm) {
  4430. showConfirm(cm, 'Invalid mapping: ' + params.input);
  4431. }
  4432. return;
  4433. }
  4434. var expr = setArgs[0].split('=');
  4435. var optionName = expr[0];
  4436. var value = expr[1];
  4437. var forceGet = false;
  4438. if (optionName.charAt(optionName.length - 1) == '?') {
  4439. if (value) { throw Error('Trailing characters: ' + params.argString); }
  4440. optionName = optionName.substring(0, optionName.length - 1);
  4441. forceGet = true;
  4442. }
  4443. if (value === undefined && optionName.substring(0, 2) == 'no') {
  4444. optionName = optionName.substring(2);
  4445. value = false;
  4446. }
  4447. var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';
  4448. if (optionIsBoolean && value == undefined) {
  4449. value = true;
  4450. }
  4451. if (!optionIsBoolean && value === undefined || forceGet) {
  4452. var oldValue = getOption(optionName, cm, setCfg);
  4453. if (oldValue === true || oldValue === false) {
  4454. showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName);
  4455. } else {
  4456. showConfirm(cm, ' ' + optionName + '=' + oldValue);
  4457. }
  4458. } else {
  4459. setOption(optionName, value, cm, setCfg);
  4460. }
  4461. },
  4462. setlocal: function (cm, params) {
  4463. params.setCfg = {scope: 'local'};
  4464. this.set(cm, params);
  4465. },
  4466. setglobal: function (cm, params) {
  4467. params.setCfg = {scope: 'global'};
  4468. this.set(cm, params);
  4469. },
  4470. registers: function(cm, params) {
  4471. var regArgs = params.args;
  4472. var registers = vimGlobalState.registerController.registers;
  4473. var regInfo = '----------Registers----------<br><br>';
  4474. if (!regArgs) {
  4475. for (var registerName in registers) {
  4476. var text = registers[registerName].toString();
  4477. if (text.length) {
  4478. regInfo += '"' + registerName + ' ' + text + '<br>';
  4479. }
  4480. }
  4481. } else {
  4482. var registerName;
  4483. regArgs = regArgs.join('');
  4484. for (var i = 0; i < regArgs.length; i++) {
  4485. registerName = regArgs.charAt(i);
  4486. if (!vimGlobalState.registerController.isValidRegister(registerName)) {
  4487. continue;
  4488. }
  4489. var register = registers[registerName] || new Register();
  4490. regInfo += '"' + registerName + ' ' + register.toString() + '<br>';
  4491. }
  4492. }
  4493. showConfirm(cm, regInfo);
  4494. },
  4495. sort: function(cm, params) {
  4496. var reverse, ignoreCase, unique, number;
  4497. function parseArgs() {
  4498. if (params.argString) {
  4499. var args = new CodeMirror.StringStream(params.argString);
  4500. if (args.eat('!')) { reverse = true; }
  4501. if (args.eol()) { return; }
  4502. if (!args.eatSpace()) { return 'Invalid arguments'; }
  4503. var opts = args.match(/[a-z]+/);
  4504. if (opts) {
  4505. opts = opts[0];
  4506. ignoreCase = opts.indexOf('i') != -1;
  4507. unique = opts.indexOf('u') != -1;
  4508. var decimal = opts.indexOf('d') != -1 && 1;
  4509. var hex = opts.indexOf('x') != -1 && 1;
  4510. var octal = opts.indexOf('o') != -1 && 1;
  4511. if (decimal + hex + octal > 1) { return 'Invalid arguments'; }
  4512. number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
  4513. }
  4514. if (args.match(/\/.*\//)) { return 'patterns not supported'; }
  4515. }
  4516. }
  4517. var err = parseArgs();
  4518. if (err) {
  4519. showConfirm(cm, err + ': ' + params.argString);
  4520. return;
  4521. }
  4522. var lineStart = params.line || cm.firstLine();
  4523. var lineEnd = params.lineEnd || params.line || cm.lastLine();
  4524. if (lineStart == lineEnd) { return; }
  4525. var curStart = Pos(lineStart, 0);
  4526. var curEnd = Pos(lineEnd, lineLength(cm, lineEnd));
  4527. var text = cm.getRange(curStart, curEnd).split('\n');
  4528. var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ :
  4529. (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
  4530. (number == 'octal') ? /([0-7]+)/ : null;
  4531. var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
  4532. var numPart = [], textPart = [];
  4533. if (number) {
  4534. for (var i = 0; i < text.length; i++) {
  4535. if (numberRegex.exec(text[i])) {
  4536. numPart.push(text[i]);
  4537. } else {
  4538. textPart.push(text[i]);
  4539. }
  4540. }
  4541. } else {
  4542. textPart = text;
  4543. }
  4544. function compareFn(a, b) {
  4545. if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
  4546. if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
  4547. var anum = number && numberRegex.exec(a);
  4548. var bnum = number && numberRegex.exec(b);
  4549. if (!anum) { return a < b ? -1 : 1; }
  4550. anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
  4551. bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
  4552. return anum - bnum;
  4553. }
  4554. numPart.sort(compareFn);
  4555. textPart.sort(compareFn);
  4556. text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
  4557. if (unique) { // Remove duplicate lines
  4558. var textOld = text;
  4559. var lastLine;
  4560. text = [];
  4561. for (var i = 0; i < textOld.length; i++) {
  4562. if (textOld[i] != lastLine) {
  4563. text.push(textOld[i]);
  4564. }
  4565. lastLine = textOld[i];
  4566. }
  4567. }
  4568. cm.replaceRange(text.join('\n'), curStart, curEnd);
  4569. },
  4570. global: function(cm, params) {
  4571. var argString = params.argString;
  4572. if (!argString) {
  4573. showConfirm(cm, 'Regular Expression missing from global');
  4574. return;
  4575. }
  4576. var lineStart = (params.line !== undefined) ? params.line : cm.firstLine();
  4577. var lineEnd = params.lineEnd || params.line || cm.lastLine();
  4578. var tokens = splitBySlash(argString);
  4579. var regexPart = argString, cmd;
  4580. if (tokens.length) {
  4581. regexPart = tokens[0];
  4582. cmd = tokens.slice(1, tokens.length).join('/');
  4583. }
  4584. if (regexPart) {
  4585. try {
  4586. updateSearchQuery(cm, regexPart, true /** ignoreCase */,
  4587. true /** smartCase */);
  4588. } catch (e) {
  4589. showConfirm(cm, 'Invalid regex: ' + regexPart);
  4590. return;
  4591. }
  4592. }
  4593. var query = getSearchState(cm).getQuery();
  4594. var matchedLines = [], content = '';
  4595. for (var i = lineStart; i <= lineEnd; i++) {
  4596. var matched = query.test(cm.getLine(i));
  4597. if (matched) {
  4598. matchedLines.push(i+1);
  4599. content+= cm.getLine(i) + '<br>';
  4600. }
  4601. }
  4602. if (!cmd) {
  4603. showConfirm(cm, content);
  4604. return;
  4605. }
  4606. var index = 0;
  4607. var nextCommand = function() {
  4608. if (index < matchedLines.length) {
  4609. var command = matchedLines[index] + cmd;
  4610. exCommandDispatcher.processCommand(cm, command, {
  4611. callback: nextCommand
  4612. });
  4613. }
  4614. index++;
  4615. };
  4616. nextCommand();
  4617. },
  4618. substitute: function(cm, params) {
  4619. if (!cm.getSearchCursor) {
  4620. throw new Error('Search feature not available. Requires searchcursor.js or ' +
  4621. 'any other getSearchCursor implementation.');
  4622. }
  4623. var argString = params.argString;
  4624. var tokens = argString ? splitBySlash(argString) : [];
  4625. var regexPart, replacePart = '', trailing, flagsPart, count;
  4626. var confirm = false; // Whether to confirm each replace.
  4627. var global = false; // True to replace all instances on a line, false to replace only 1.
  4628. if (tokens.length) {
  4629. regexPart = tokens[0];
  4630. replacePart = tokens[1];
  4631. if (replacePart !== undefined) {
  4632. if (getOption('pcre')) {
  4633. replacePart = unescapeRegexReplace(replacePart);
  4634. } else {
  4635. replacePart = translateRegexReplace(replacePart);
  4636. }
  4637. vimGlobalState.lastSubstituteReplacePart = replacePart;
  4638. }
  4639. trailing = tokens[2] ? tokens[2].split(' ') : [];
  4640. } else {
  4641. if (argString && argString.length) {
  4642. showConfirm(cm, 'Substitutions should be of the form ' +
  4643. ':s/pattern/replace/');
  4644. return;
  4645. }
  4646. }
  4647. if (trailing) {
  4648. flagsPart = trailing[0];
  4649. count = parseInt(trailing[1]);
  4650. if (flagsPart) {
  4651. if (flagsPart.indexOf('c') != -1) {
  4652. confirm = true;
  4653. flagsPart.replace('c', '');
  4654. }
  4655. if (flagsPart.indexOf('g') != -1) {
  4656. global = true;
  4657. flagsPart.replace('g', '');
  4658. }
  4659. regexPart = regexPart + '/' + flagsPart;
  4660. }
  4661. }
  4662. if (regexPart) {
  4663. try {
  4664. updateSearchQuery(cm, regexPart, true /** ignoreCase */,
  4665. true /** smartCase */);
  4666. } catch (e) {
  4667. showConfirm(cm, 'Invalid regex: ' + regexPart);
  4668. return;
  4669. }
  4670. }
  4671. replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart;
  4672. if (replacePart === undefined) {
  4673. showConfirm(cm, 'No previous substitute regular expression');
  4674. return;
  4675. }
  4676. var state = getSearchState(cm);
  4677. var query = state.getQuery();
  4678. var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
  4679. var lineEnd = params.lineEnd || lineStart;
  4680. if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) {
  4681. lineEnd = Infinity;
  4682. }
  4683. if (count) {
  4684. lineStart = lineEnd;
  4685. lineEnd = lineStart + count - 1;
  4686. }
  4687. var startPos = clipCursorToContent(cm, Pos(lineStart, 0));
  4688. var cursor = cm.getSearchCursor(query, startPos);
  4689. doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback);
  4690. },
  4691. redo: CodeMirror.commands.redo,
  4692. undo: CodeMirror.commands.undo,
  4693. write: function(cm) {
  4694. if (CodeMirror.commands.save) {
  4695. CodeMirror.commands.save(cm);
  4696. } else {
  4697. cm.save();
  4698. }
  4699. },
  4700. nohlsearch: function(cm) {
  4701. clearSearchHighlight(cm);
  4702. },
  4703. delmarks: function(cm, params) {
  4704. if (!params.argString || !trim(params.argString)) {
  4705. showConfirm(cm, 'Argument acequired');
  4706. return;
  4707. }
  4708. var state = cm.state.vim;
  4709. var stream = new CodeMirror.StringStream(trim(params.argString));
  4710. while (!stream.eol()) {
  4711. stream.eatSpace();
  4712. var count = stream.pos;
  4713. if (!stream.match(/[a-zA-Z]/, false)) {
  4714. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  4715. return;
  4716. }
  4717. var sym = stream.next();
  4718. if (stream.match('-', true)) {
  4719. if (!stream.match(/[a-zA-Z]/, false)) {
  4720. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  4721. return;
  4722. }
  4723. var startMark = sym;
  4724. var finishMark = stream.next();
  4725. if (isLowerCase(startMark) && isLowerCase(finishMark) ||
  4726. isUpperCase(startMark) && isUpperCase(finishMark)) {
  4727. var start = startMark.charCodeAt(0);
  4728. var finish = finishMark.charCodeAt(0);
  4729. if (start >= finish) {
  4730. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  4731. return;
  4732. }
  4733. for (var j = 0; j <= finish - start; j++) {
  4734. var mark = String.fromCharCode(start + j);
  4735. delete state.marks[mark];
  4736. }
  4737. } else {
  4738. showConfirm(cm, 'Invalid argument: ' + startMark + '-');
  4739. return;
  4740. }
  4741. } else {
  4742. delete state.marks[sym];
  4743. }
  4744. }
  4745. }
  4746. };
  4747. var exCommandDispatcher = new ExCommandDispatcher();
  4748. function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query,
  4749. replaceWith, callback) {
  4750. cm.state.vim.exMode = true;
  4751. var done = false;
  4752. var lastPos = searchCursor.from();
  4753. function replaceAll() {
  4754. cm.operation(function() {
  4755. while (!done) {
  4756. replace();
  4757. next();
  4758. }
  4759. stop();
  4760. });
  4761. }
  4762. function replace() {
  4763. var text = cm.getRange(searchCursor.from(), searchCursor.to());
  4764. var newText = text.replace(query, replaceWith);
  4765. searchCursor.replace(newText);
  4766. }
  4767. function next() {
  4768. while(searchCursor.findNext() &&
  4769. isInRange(searchCursor.from(), lineStart, lineEnd)) {
  4770. if (!global && lastPos && searchCursor.from().line == lastPos.line) {
  4771. continue;
  4772. }
  4773. cm.scrollIntoView(searchCursor.from(), 30);
  4774. cm.setSelection(searchCursor.from(), searchCursor.to());
  4775. lastPos = searchCursor.from();
  4776. done = false;
  4777. return;
  4778. }
  4779. done = true;
  4780. }
  4781. function stop(close) {
  4782. if (close) { close(); }
  4783. cm.focus();
  4784. if (lastPos) {
  4785. cm.setCursor(lastPos);
  4786. var vim = cm.state.vim;
  4787. vim.exMode = false;
  4788. vim.lastHPos = vim.lastHSPos = lastPos.ch;
  4789. }
  4790. if (callback) { callback(); }
  4791. }
  4792. function onPromptKeyDown(e, _value, close) {
  4793. CodeMirror.e_stop(e);
  4794. var keyName = CodeMirror.keyName(e);
  4795. switch (keyName) {
  4796. case 'Y':
  4797. replace(); next(); break;
  4798. case 'N':
  4799. next(); break;
  4800. case 'A':
  4801. var savedCallback = callback;
  4802. callback = undefined;
  4803. cm.operation(replaceAll);
  4804. callback = savedCallback;
  4805. break;
  4806. case 'L':
  4807. replace();
  4808. case 'Q':
  4809. case 'Esc':
  4810. case 'Ctrl-C':
  4811. case 'Ctrl-[':
  4812. stop(close);
  4813. break;
  4814. }
  4815. if (done) { stop(close); }
  4816. return true;
  4817. }
  4818. next();
  4819. if (done) {
  4820. showConfirm(cm, 'No matches for ' + query.source);
  4821. return;
  4822. }
  4823. if (!confirm) {
  4824. replaceAll();
  4825. if (callback) { callback(); }
  4826. return;
  4827. }
  4828. showPrompt(cm, {
  4829. prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',
  4830. onKeyDown: onPromptKeyDown
  4831. });
  4832. }
  4833. CodeMirror.keyMap.vim = {
  4834. attach: attachVimMap,
  4835. detach: detachVimMap,
  4836. call: cmKey
  4837. };
  4838. function exitInsertMode(cm) {
  4839. var vim = cm.state.vim;
  4840. var macroModeState = vimGlobalState.macroModeState;
  4841. var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.');
  4842. var isPlaying = macroModeState.isPlaying;
  4843. var lastChange = macroModeState.lastInsertModeChanges;
  4844. var text = [];
  4845. if (!isPlaying) {
  4846. var selLength = lastChange.inVisualBlock ? vim.lastSelection.visualBlock.height : 1;
  4847. var changes = lastChange.changes;
  4848. var text = [];
  4849. var i = 0;
  4850. while (i < changes.length) {
  4851. text.push(changes[i]);
  4852. if (changes[i] instanceof InsertModeKey) {
  4853. i++;
  4854. } else {
  4855. i+= selLength;
  4856. }
  4857. }
  4858. lastChange.changes = text;
  4859. cm.off('change', onChange);
  4860. CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
  4861. }
  4862. if (!isPlaying && vim.insertModeRepeat > 1) {
  4863. repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
  4864. true /** repeatForInsert */);
  4865. vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
  4866. }
  4867. delete vim.insertModeRepeat;
  4868. vim.insertMode = false;
  4869. cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1);
  4870. cm.setOption('keyMap', 'vim');
  4871. cm.setOption('disableInput', true);
  4872. lastChange.overwrite = cm.state.overwrite;
  4873. cm.toggleOverwrite(false); // exit replace mode if we were in it.
  4874. insertModeChangeRegister.setText(lastChange.changes.join(''));
  4875. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  4876. if (macroModeState.isRecording) {
  4877. logInsertModeChange(macroModeState);
  4878. }
  4879. }
  4880. function _mapCommand(command) {
  4881. defaultKeymap.unshift(command);
  4882. }
  4883. function mapCommand(keys, type, name, args, extra) {
  4884. var command = {keys: keys, type: type};
  4885. command[type] = name;
  4886. command[type + "Args"] = args;
  4887. for (var key in extra)
  4888. command[key] = extra[key];
  4889. _mapCommand(command);
  4890. }
  4891. defineOption('insertModeEscKeysTimeout', 200, 'number');
  4892. CodeMirror.keyMap['vim-insert'] = {
  4893. 'Ctrl-N': 'autocomplete',
  4894. 'Ctrl-P': 'autocomplete',
  4895. 'Enter': function(cm) {
  4896. var fn = CodeMirror.commands.newlineAndIndentContinueComment ||
  4897. CodeMirror.commands.newlineAndIndent;
  4898. fn(cm);
  4899. },
  4900. fallthrough: ['default'],
  4901. attach: attachVimMap,
  4902. detach: detachVimMap,
  4903. call: cmKey
  4904. };
  4905. CodeMirror.keyMap['vim-replace'] = {
  4906. 'Backspace': 'goCharLeft',
  4907. fallthrough: ['vim-insert'],
  4908. attach: attachVimMap,
  4909. detach: detachVimMap,
  4910. call: cmKey
  4911. };
  4912. function executeMacroRegister(cm, vim, macroModeState, registerName) {
  4913. var register = vimGlobalState.registerController.getRegister(registerName);
  4914. if (registerName == ':') {
  4915. if (register.keyBuffer[0]) {
  4916. exCommandDispatcher.processCommand(cm, register.keyBuffer[0]);
  4917. }
  4918. macroModeState.isPlaying = false;
  4919. return;
  4920. }
  4921. var keyBuffer = register.keyBuffer;
  4922. var imc = 0;
  4923. macroModeState.isPlaying = true;
  4924. macroModeState.replaySearchQueries = register.searchQueries.slice(0);
  4925. for (var i = 0; i < keyBuffer.length; i++) {
  4926. var text = keyBuffer[i];
  4927. var match, key;
  4928. while (text) {
  4929. match = (/<\w+-.+?>|<\w+>|./).exec(text);
  4930. key = match[0];
  4931. text = text.substring(match.index + key.length);
  4932. CodeMirror.Vim.handleKey(cm, key, 'macro');
  4933. if (vim.insertMode) {
  4934. var changes = register.insertModeChanges[imc++].changes;
  4935. vimGlobalState.macroModeState.lastInsertModeChanges.changes =
  4936. changes;
  4937. repeatInsertModeChanges(cm, changes, 1);
  4938. exitInsertMode(cm);
  4939. }
  4940. }
  4941. }
  4942. macroModeState.isPlaying = false;
  4943. }
  4944. function logKey(macroModeState, key) {
  4945. if (macroModeState.isPlaying) { return; }
  4946. var registerName = macroModeState.latestRegister;
  4947. var register = vimGlobalState.registerController.getRegister(registerName);
  4948. if (register) {
  4949. register.pushText(key);
  4950. }
  4951. }
  4952. function logInsertModeChange(macroModeState) {
  4953. if (macroModeState.isPlaying) { return; }
  4954. var registerName = macroModeState.latestRegister;
  4955. var register = vimGlobalState.registerController.getRegister(registerName);
  4956. if (register && register.pushInsertModeChanges) {
  4957. register.pushInsertModeChanges(macroModeState.lastInsertModeChanges);
  4958. }
  4959. }
  4960. function logSearchQuery(macroModeState, query) {
  4961. if (macroModeState.isPlaying) { return; }
  4962. var registerName = macroModeState.latestRegister;
  4963. var register = vimGlobalState.registerController.getRegister(registerName);
  4964. if (register && register.pushSearchQuery) {
  4965. register.pushSearchQuery(query);
  4966. }
  4967. }
  4968. function onChange(_cm, changeObj) {
  4969. var macroModeState = vimGlobalState.macroModeState;
  4970. var lastChange = macroModeState.lastInsertModeChanges;
  4971. if (!macroModeState.isPlaying) {
  4972. while(changeObj) {
  4973. lastChange.expectCursorActivityForChange = true;
  4974. if (changeObj.origin == '+input' || changeObj.origin == 'paste'
  4975. || changeObj.origin === undefined /* only in testing */) {
  4976. var text = changeObj.text.join('\n');
  4977. if (lastChange.maybeReset) {
  4978. lastChange.changes = [];
  4979. lastChange.maybeReset = false;
  4980. }
  4981. lastChange.changes.push(text);
  4982. }
  4983. changeObj = changeObj.next;
  4984. }
  4985. }
  4986. }
  4987. function onCursorActivity(cm) {
  4988. var vim = cm.state.vim;
  4989. if (vim.insertMode) {
  4990. var macroModeState = vimGlobalState.macroModeState;
  4991. if (macroModeState.isPlaying) { return; }
  4992. var lastChange = macroModeState.lastInsertModeChanges;
  4993. if (lastChange.expectCursorActivityForChange) {
  4994. lastChange.expectCursorActivityForChange = false;
  4995. } else {
  4996. lastChange.maybeReset = true;
  4997. }
  4998. } else if (!cm.curOp.isVimOp) {
  4999. handleExternalSelection(cm, vim);
  5000. }
  5001. if (vim.visualMode) {
  5002. updateFakeCursor(cm);
  5003. }
  5004. }
  5005. function updateFakeCursor(cm) {
  5006. var vim = cm.state.vim;
  5007. var from = clipCursorToContent(cm, copyCursor(vim.sel.head));
  5008. var to = offsetCursor(from, 0, 1);
  5009. if (vim.fakeCursor) {
  5010. vim.fakeCursor.clear();
  5011. }
  5012. vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'});
  5013. }
  5014. function handleExternalSelection(cm, vim) {
  5015. var anchor = cm.getCursor('anchor');
  5016. var head = cm.getCursor('head');
  5017. if (vim.visualMode && !cm.somethingSelected()) {
  5018. exitVisualMode(cm, false);
  5019. } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) {
  5020. vim.visualMode = true;
  5021. vim.visualLine = false;
  5022. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
  5023. }
  5024. if (vim.visualMode) {
  5025. var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
  5026. var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
  5027. head = offsetCursor(head, 0, headOffset);
  5028. anchor = offsetCursor(anchor, 0, anchorOffset);
  5029. vim.sel = {
  5030. anchor: anchor,
  5031. head: head
  5032. };
  5033. updateMark(cm, vim, '<', cursorMin(head, anchor));
  5034. updateMark(cm, vim, '>', cursorMax(head, anchor));
  5035. } else if (!vim.insertMode) {
  5036. vim.lastHPos = cm.getCursor().ch;
  5037. }
  5038. }
  5039. function InsertModeKey(keyName) {
  5040. this.keyName = keyName;
  5041. }
  5042. function onKeyEventTargetKeyDown(e) {
  5043. var macroModeState = vimGlobalState.macroModeState;
  5044. var lastChange = macroModeState.lastInsertModeChanges;
  5045. var keyName = CodeMirror.keyName(e);
  5046. if (!keyName) { return; }
  5047. function onKeyFound() {
  5048. if (lastChange.maybeReset) {
  5049. lastChange.changes = [];
  5050. lastChange.maybeReset = false;
  5051. }
  5052. lastChange.changes.push(new InsertModeKey(keyName));
  5053. return true;
  5054. }
  5055. if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
  5056. CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound);
  5057. }
  5058. }
  5059. function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
  5060. var macroModeState = vimGlobalState.macroModeState;
  5061. macroModeState.isPlaying = true;
  5062. var isAction = !!vim.lastEditActionCommand;
  5063. var cachedInputState = vim.inputState;
  5064. function repeatCommand() {
  5065. if (isAction) {
  5066. commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
  5067. } else {
  5068. commandDispatcher.evalInput(cm, vim);
  5069. }
  5070. }
  5071. function repeatInsert(repeat) {
  5072. if (macroModeState.lastInsertModeChanges.changes.length > 0) {
  5073. repeat = !vim.lastEditActionCommand ? 1 : repeat;
  5074. var changeObject = macroModeState.lastInsertModeChanges;
  5075. repeatInsertModeChanges(cm, changeObject.changes, repeat, changeObject.overwrite);
  5076. }
  5077. }
  5078. vim.inputState = vim.lastEditInputState;
  5079. if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
  5080. for (var i = 0; i < repeat; i++) {
  5081. repeatCommand();
  5082. repeatInsert(1);
  5083. }
  5084. } else {
  5085. if (!repeatForInsert) {
  5086. repeatCommand();
  5087. }
  5088. repeatInsert(repeat);
  5089. }
  5090. vim.inputState = cachedInputState;
  5091. if (vim.insertMode && !repeatForInsert) {
  5092. exitInsertMode(cm);
  5093. }
  5094. macroModeState.isPlaying = false;
  5095. }
  5096. function repeatInsertModeChanges(cm, changes, repeat, overwrite) {
  5097. function keyHandler(binding) {
  5098. if (typeof binding == 'string') {
  5099. CodeMirror.commands[binding](cm);
  5100. } else {
  5101. binding(cm);
  5102. }
  5103. return true;
  5104. }
  5105. var head = cm.getCursor('head');
  5106. var inVisualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock;
  5107. if (inVisualBlock) {
  5108. var vim = cm.state.vim;
  5109. var lastSel = vim.lastSelection;
  5110. var offset = getOffset(lastSel.anchor, lastSel.head);
  5111. selectForInsert(cm, head, offset.line + 1);
  5112. repeat = cm.listSelections().length;
  5113. cm.setCursor(head);
  5114. }
  5115. for (var i = 0; i < repeat; i++) {
  5116. if (inVisualBlock) {
  5117. cm.setCursor(offsetCursor(head, i, 0));
  5118. }
  5119. for (var j = 0; j < changes.length; j++) {
  5120. var change = changes[j];
  5121. if (change instanceof InsertModeKey) {
  5122. CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler);
  5123. } else {
  5124. var cur = cm.getCursor();
  5125. var end = cur;
  5126. if (overwrite && !/\n/.test(change)) {
  5127. end = offsetCursor(cur, 0, change.length);
  5128. }
  5129. cm.replaceRange(change, cur, end);
  5130. }
  5131. }
  5132. }
  5133. if (inVisualBlock) {
  5134. cm.setCursor(offsetCursor(head, 0, 1));
  5135. }
  5136. }
  5137. resetVimGlobalState();
  5138. CodeMirror.Vim = Vim();
  5139. Vim = CodeMirror.Vim;
  5140. var specialKey = {'return':'CR',backspace:'BS','delete':'Del',esc:'Esc',
  5141. left:'Left',right:'Right',up:'Up',down:'Down',space: 'Space',
  5142. home:'Home',end:'End',pageup:'PageUp',pagedown:'PageDown', enter: 'CR'
  5143. };
  5144. function lookupKey(hashId, key, e) {
  5145. if (key.length > 1 && key[0] == "n") {
  5146. key = key.replace("numpad", "");
  5147. }
  5148. key = specialKey[key] || key;
  5149. var name = '';
  5150. if (e.ctrlKey) { name += 'C-'; }
  5151. if (e.altKey) { name += 'A-'; }
  5152. if (e.shiftKey) { name += 'S-'; }
  5153. name += key;
  5154. if (name.length > 1) { name = '<' + name + '>'; }
  5155. return name;
  5156. }
  5157. var handleKey = Vim.handleKey.bind(Vim);
  5158. Vim.handleKey = function(cm, key, origin) {
  5159. return cm.operation(function() {
  5160. return handleKey(cm, key, origin);
  5161. }, true);
  5162. }
  5163. function cloneVimState(state) {
  5164. var n = new state.constructor();
  5165. Object.keys(state).forEach(function(key) {
  5166. var o = state[key];
  5167. if (Array.isArray(o))
  5168. o = o.slice();
  5169. else if (o && typeof o == "object" && o.constructor != Object)
  5170. o = cloneVimState(o);
  5171. n[key] = o;
  5172. });
  5173. if (state.sel) {
  5174. n.sel = {
  5175. head: state.sel.head && copyCursor(state.sel.head),
  5176. anchor: state.sel.anchor && copyCursor(state.sel.anchor)
  5177. };
  5178. }
  5179. return n;
  5180. }
  5181. function multiSelectHandleKey(cm, key, origin) {
  5182. var isHandled = false;
  5183. var vim = Vim.maybeInitVimState_(cm);
  5184. var visualBlock = vim.visualBlock || vim.wasInVisualBlock;
  5185. if (vim.wasInVisualBlock && !cm.ace.inMultiSelectMode) {
  5186. vim.wasInVisualBlock = false;
  5187. } else if (cm.ace.inMultiSelectMode && vim.visualBlock) {
  5188. vim.wasInVisualBlock = true;
  5189. }
  5190. if (key == '<Esc>' && !vim.insertMode && !vim.visualMode && cm.ace.inMultiSelectMode) {
  5191. cm.ace.exitMultiSelectMode();
  5192. } else if (visualBlock || !cm.ace.inMultiSelectMode || cm.ace.inVirtualSelectionMode) {
  5193. isHandled = Vim.handleKey(cm, key, origin);
  5194. } else {
  5195. var old = cloneVimState(vim);
  5196. cm.operation(function() {
  5197. cm.ace.forEachSelection(function() {
  5198. var sel = cm.ace.selection;
  5199. cm.state.vim.lastHPos = sel.$desiredColumn == null ? sel.lead.column : sel.$desiredColumn;
  5200. var head = cm.getCursor("head");
  5201. var anchor = cm.getCursor("anchor");
  5202. var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
  5203. var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
  5204. head = offsetCursor(head, 0, headOffset);
  5205. anchor = offsetCursor(anchor, 0, anchorOffset);
  5206. cm.state.vim.sel.head = head;
  5207. cm.state.vim.sel.anchor = anchor;
  5208. isHandled = handleKey(cm, key, origin);
  5209. sel.$desiredColumn = cm.state.vim.lastHPos == -1 ? null : cm.state.vim.lastHPos;
  5210. if (cm.virtualSelectionMode()) {
  5211. cm.state.vim = cloneVimState(old);
  5212. }
  5213. });
  5214. if (cm.curOp.cursorActivity && !isHandled)
  5215. cm.curOp.cursorActivity = false;
  5216. }, true);
  5217. }
  5218. return isHandled;
  5219. }
  5220. exports.CodeMirror = CodeMirror;
  5221. var getVim = Vim.maybeInitVimState_;
  5222. exports.handler = {
  5223. $id: "ace/keyboard/vim",
  5224. drawCursor: function(style, pixelPos, config, sel, session) {
  5225. var vim = this.state.vim || {};
  5226. var w = config.characterWidth;
  5227. var h = config.lineHeight;
  5228. var top = pixelPos.top;
  5229. var left = pixelPos.left;
  5230. if (!vim.insertMode) {
  5231. var isbackwards = !sel.cursor
  5232. ? session.selection.isBackwards() || session.selection.isEmpty()
  5233. : Range.comparePoints(sel.cursor, sel.start) <= 0;
  5234. if (!isbackwards && left > w)
  5235. left -= w;
  5236. }
  5237. if (!vim.insertMode && vim.status) {
  5238. h = h / 2;
  5239. top += h;
  5240. }
  5241. style.left = left + "px";
  5242. style.top = top + "px";
  5243. style.width = w + "px";
  5244. style.height = h + "px";
  5245. },
  5246. handleKeyboard: function(data, hashId, key, keyCode, e) {
  5247. var editor = data.editor;
  5248. var cm = editor.state.cm;
  5249. var vim = getVim(cm);
  5250. if (keyCode == -1) return;
  5251. if (key == "c" && hashId == 1) { // key == "ctrl-c"
  5252. if (!useragent.isMac && editor.getCopyText()) {
  5253. editor.once("copy", function() {
  5254. editor.selection.clearSelection();
  5255. });
  5256. return {command: "null", passEvent: true};
  5257. }
  5258. } else if (!vim.insertMode) {
  5259. if (useragent.isMac && this.handleMacRepeat(data, hashId, key)) {
  5260. hashId = -1;
  5261. key = data.inputChar;
  5262. }
  5263. }
  5264. if (hashId == -1 || hashId & 1 || hashId === 0 && key.length > 1) {
  5265. var insertMode = vim.insertMode;
  5266. var name = lookupKey(hashId, key, e || {});
  5267. if (vim.status == null)
  5268. vim.status = "";
  5269. var isHandled = multiSelectHandleKey(cm, name, 'user');
  5270. vim = getVim(cm); // may be changed by multiSelectHandleKey
  5271. if (isHandled && vim.status != null)
  5272. vim.status += name;
  5273. else if (vim.status == null)
  5274. vim.status = "";
  5275. cm._signal("changeStatus");
  5276. if (!isHandled && (hashId != -1 || insertMode))
  5277. return;
  5278. return {command: "null", passEvent: !isHandled};
  5279. }
  5280. },
  5281. attach: function(editor) {
  5282. if (!editor.state) editor.state = {};
  5283. var cm = new CodeMirror(editor);
  5284. editor.state.cm = cm;
  5285. editor.$vimModeHandler = this;
  5286. CodeMirror.keyMap.vim.attach(cm);
  5287. getVim(cm).status = null;
  5288. cm.on('vim-command-done', function() {
  5289. if (cm.virtualSelectionMode()) return;
  5290. getVim(cm).status = null;
  5291. cm.ace._signal("changeStatus");
  5292. cm.ace.session.markUndoGroup();
  5293. });
  5294. cm.on("changeStatus", function() {
  5295. cm.ace.renderer.updateCursor();
  5296. cm.ace._signal("changeStatus");
  5297. });
  5298. cm.on("vim-mode-change", function() {
  5299. if (cm.virtualSelectionMode()) return;
  5300. cm.ace.renderer.setStyle("normal-mode", !getVim(cm).insertMode);
  5301. cm._signal("changeStatus");
  5302. });
  5303. cm.ace.renderer.setStyle("normal-mode", !getVim(cm).insertMode);
  5304. editor.renderer.$cursorLayer.drawCursor = this.drawCursor.bind(cm);
  5305. this.updateMacCompositionHandlers(editor, true);
  5306. },
  5307. detach: function(editor) {
  5308. var cm = editor.state.cm;
  5309. CodeMirror.keyMap.vim.detach(cm);
  5310. cm.destroy();
  5311. editor.state.cm = null;
  5312. editor.$vimModeHandler = null;
  5313. editor.renderer.$cursorLayer.drawCursor = null;
  5314. editor.renderer.setStyle("normal-mode", false);
  5315. this.updateMacCompositionHandlers(editor, false);
  5316. },
  5317. getStatusText: function(editor) {
  5318. var cm = editor.state.cm;
  5319. var vim = getVim(cm);
  5320. if (vim.insertMode)
  5321. return "INSERT";
  5322. var status = "";
  5323. if (vim.visualMode) {
  5324. status += "VISUAL";
  5325. if (vim.visualLine)
  5326. status += " LINE";
  5327. if (vim.visualBlock)
  5328. status += " BLOCK";
  5329. }
  5330. if (vim.status)
  5331. status += (status ? " " : "") + vim.status;
  5332. return status;
  5333. },
  5334. handleMacRepeat: function(data, hashId, key) {
  5335. if (hashId == -1) {
  5336. data.inputChar = key;
  5337. data.lastEvent = "input";
  5338. } else if (data.inputChar && data.$lastHash == hashId && data.$lastKey == key) {
  5339. if (data.lastEvent == "input") {
  5340. data.lastEvent = "input1";
  5341. } else if (data.lastEvent == "input1") {
  5342. return true;
  5343. }
  5344. } else {
  5345. data.$lastHash = hashId;
  5346. data.$lastKey = key;
  5347. data.lastEvent = "keypress";
  5348. }
  5349. },
  5350. updateMacCompositionHandlers: function(editor, enable) {
  5351. var onCompositionUpdateOverride = function(text) {
  5352. var cm = editor.state.cm;
  5353. var vim = getVim(cm);
  5354. if (!vim.insertMode) {
  5355. var el = this.textInput.getElement();
  5356. el.blur();
  5357. el.focus();
  5358. el.value = text;
  5359. } else {
  5360. this.onCompositionUpdateOrig(text);
  5361. }
  5362. };
  5363. var onCompositionStartOverride = function(text) {
  5364. var cm = editor.state.cm;
  5365. var vim = getVim(cm);
  5366. if (!vim.insertMode) {
  5367. this.onCompositionStartOrig(text);
  5368. }
  5369. };
  5370. if (enable) {
  5371. if (!editor.onCompositionUpdateOrig) {
  5372. editor.onCompositionUpdateOrig = editor.onCompositionUpdate;
  5373. editor.onCompositionUpdate = onCompositionUpdateOverride;
  5374. editor.onCompositionStartOrig = editor.onCompositionStart;
  5375. editor.onCompositionStart = onCompositionStartOverride;
  5376. }
  5377. } else {
  5378. if (editor.onCompositionUpdateOrig) {
  5379. editor.onCompositionUpdate = editor.onCompositionUpdateOrig;
  5380. editor.onCompositionUpdateOrig = null;
  5381. editor.onCompositionStart = editor.onCompositionStartOrig;
  5382. editor.onCompositionStartOrig = null;
  5383. }
  5384. }
  5385. }
  5386. };
  5387. var renderVirtualNumbers = {
  5388. getText: function(session, row) {
  5389. return (Math.abs(session.selection.lead.row - row) || (row + 1 + (row < 9? "\xb7" : "" ))) + "";
  5390. },
  5391. getWidth: function(session, lastLineNumber, config) {
  5392. return session.getLength().toString().length * config.characterWidth;
  5393. },
  5394. update: function(e, editor) {
  5395. editor.renderer.$loop.schedule(editor.renderer.CHANGE_GUTTER);
  5396. },
  5397. attach: function(editor) {
  5398. editor.renderer.$gutterLayer.$renderer = this;
  5399. editor.on("changeSelection", this.update);
  5400. },
  5401. detach: function(editor) {
  5402. editor.renderer.$gutterLayer.$renderer = null;
  5403. editor.off("changeSelection", this.update);
  5404. }
  5405. };
  5406. Vim.defineOption({
  5407. name: "wrap",
  5408. set: function(value, cm) {
  5409. if (cm) {cm.ace.setOption("wrap", value)}
  5410. },
  5411. type: "boolean"
  5412. }, false);
  5413. Vim.defineEx('write', 'w', function() {
  5414. console.log(':write is not implemented')
  5415. });
  5416. defaultKeymap.push(
  5417. { keys: 'zc', type: 'action', action: 'fold', actionArgs: { open: false } },
  5418. { keys: 'zC', type: 'action', action: 'fold', actionArgs: { open: false, all: true } },
  5419. { keys: 'zo', type: 'action', action: 'fold', actionArgs: { open: true } },
  5420. { keys: 'zO', type: 'action', action: 'fold', actionArgs: { open: true, all: true } },
  5421. { keys: 'za', type: 'action', action: 'fold', actionArgs: { toggle: true } },
  5422. { keys: 'zA', type: 'action', action: 'fold', actionArgs: { toggle: true, all: true } },
  5423. { keys: 'zf', type: 'action', action: 'fold', actionArgs: { open: true, all: true } },
  5424. { keys: 'zd', type: 'action', action: 'fold', actionArgs: { open: true, all: true } },
  5425. { keys: '<C-A-k>', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAbove" } },
  5426. { keys: '<C-A-j>', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelow" } },
  5427. { keys: '<C-A-S-k>', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAboveSkipCurrent" } },
  5428. { keys: '<C-A-S-j>', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelowSkipCurrent" } },
  5429. { keys: '<C-A-h>', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreBefore" } },
  5430. { keys: '<C-A-l>', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreAfter" } },
  5431. { keys: '<C-A-S-h>', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextBefore" } },
  5432. { keys: '<C-A-S-l>', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextAfter" } }
  5433. );
  5434. actions.aceCommand = function(cm, actionArgs, vim) {
  5435. cm.vimCmd = actionArgs;
  5436. if (cm.ace.inVirtualSelectionMode)
  5437. cm.ace.on("beforeEndOperation", delayedExecAceCommand);
  5438. else
  5439. delayedExecAceCommand(null, cm.ace);
  5440. };
  5441. function delayedExecAceCommand(op, ace) {
  5442. ace.off("beforeEndOperation", delayedExecAceCommand);
  5443. var cmd = ace.state.cm.vimCmd;
  5444. if (cmd) {
  5445. ace.execCommand(cmd.exec ? cmd : cmd.name, cmd.args);
  5446. }
  5447. ace.curOp = ace.prevOp;
  5448. }
  5449. actions.fold = function(cm, actionArgs, vim) {
  5450. cm.ace.execCommand(['toggleFoldWidget', 'toggleFoldWidget', 'foldOther', 'unfoldall'
  5451. ][(actionArgs.all ? 2 : 0) + (actionArgs.open ? 1 : 0)]);
  5452. };
  5453. exports.handler.defaultKeymap = defaultKeymap;
  5454. exports.handler.actions = actions;
  5455. exports.Vim = Vim;
  5456. Vim.map("Y", "yy", "normal");
  5457. });