emacs.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. /* ***** BEGIN LICENSE BLOCK *****
  2. * Distributed under the BSD license:
  3. *
  4. * Copyright (c) 2010, Ajax.org B.V.
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * * Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * * Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * * Neither the name of Ajax.org B.V. nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * ***** END LICENSE BLOCK ***** */
  30. define(function(require, exports, module) {
  31. "use strict";
  32. var dom = require("../lib/dom");
  33. require("../incremental_search");
  34. var iSearchCommandModule = require("../commands/incremental_search_commands");
  35. var screenToTextBlockCoordinates = function(x, y) {
  36. var canvasPos = this.scroller.getBoundingClientRect();
  37. var col = Math.floor(
  38. (x + this.scrollLeft - canvasPos.left - this.$padding) / this.characterWidth
  39. );
  40. var row = Math.floor(
  41. (y + this.scrollTop - canvasPos.top) / this.lineHeight
  42. );
  43. return this.session.screenToDocumentPosition(row, col);
  44. };
  45. var HashHandler = require("./hash_handler").HashHandler;
  46. exports.handler = new HashHandler();
  47. exports.handler.isEmacs = true;
  48. exports.handler.$id = "ace/keyboard/emacs";
  49. var initialized = false;
  50. var $formerLongWords;
  51. var $formerLineStart;
  52. exports.handler.attach = function(editor) {
  53. if (!initialized) {
  54. initialized = true;
  55. dom.importCssString('\
  56. .emacs-mode .ace_cursor{\
  57. border: 1px rgba(50,250,50,0.8) solid!important;\
  58. -moz-box-sizing: border-box!important;\
  59. -webkit-box-sizing: border-box!important;\
  60. box-sizing: border-box!important;\
  61. background-color: rgba(0,250,0,0.9);\
  62. opacity: 0.5;\
  63. }\
  64. .emacs-mode .ace_hidden-cursors .ace_cursor{\
  65. opacity: 1;\
  66. background-color: transparent;\
  67. }\
  68. .emacs-mode .ace_overwrite-cursors .ace_cursor {\
  69. opacity: 1;\
  70. background-color: transparent;\
  71. border-width: 0 0 2px 2px !important;\
  72. }\
  73. .emacs-mode .ace_text-layer {\
  74. z-index: 4\
  75. }\
  76. .emacs-mode .ace_cursor-layer {\
  77. z-index: 2\
  78. }', 'emacsMode'
  79. );
  80. }
  81. // in emacs, gotowordleft/right should not count a space as a word..
  82. $formerLongWords = editor.session.$selectLongWords;
  83. editor.session.$selectLongWords = true;
  84. // CTRL-A should go to actual beginning of line
  85. $formerLineStart = editor.session.$useEmacsStyleLineStart;
  86. editor.session.$useEmacsStyleLineStart = true;
  87. editor.session.$emacsMark = null; // the active mark
  88. editor.session.$emacsMarkRing = editor.session.$emacsMarkRing || [];
  89. editor.emacsMark = function() {
  90. return this.session.$emacsMark;
  91. };
  92. editor.setEmacsMark = function(p) {
  93. // to deactivate pass in a falsy value
  94. this.session.$emacsMark = p;
  95. };
  96. editor.pushEmacsMark = function(p, activate) {
  97. var prevMark = this.session.$emacsMark;
  98. if (prevMark)
  99. this.session.$emacsMarkRing.push(prevMark);
  100. if (!p || activate) this.setEmacsMark(p);
  101. else this.session.$emacsMarkRing.push(p);
  102. };
  103. editor.popEmacsMark = function() {
  104. var mark = this.emacsMark();
  105. if (mark) { this.setEmacsMark(null); return mark; }
  106. return this.session.$emacsMarkRing.pop();
  107. };
  108. editor.getLastEmacsMark = function(p) {
  109. return this.session.$emacsMark || this.session.$emacsMarkRing.slice(-1)[0];
  110. };
  111. editor.emacsMarkForSelection = function(replacement) {
  112. // find the mark in $emacsMarkRing corresponding to the current
  113. // selection
  114. var sel = this.selection,
  115. multiRangeLength = this.multiSelect ?
  116. this.multiSelect.getAllRanges().length : 1,
  117. selIndex = sel.index || 0,
  118. markRing = this.session.$emacsMarkRing,
  119. markIndex = markRing.length - (multiRangeLength - selIndex),
  120. lastMark = markRing[markIndex] || sel.anchor;
  121. if (replacement) {
  122. markRing.splice(markIndex, 1,
  123. "row" in replacement && "column" in replacement ?
  124. replacement : undefined);
  125. }
  126. return lastMark;
  127. }
  128. editor.on("click", $resetMarkMode);
  129. editor.on("changeSession", $kbSessionChange);
  130. editor.renderer.screenToTextCoordinates = screenToTextBlockCoordinates;
  131. editor.setStyle("emacs-mode");
  132. editor.commands.addCommands(commands);
  133. exports.handler.platform = editor.commands.platform;
  134. editor.$emacsModeHandler = this;
  135. editor.addEventListener('copy', this.onCopy);
  136. editor.addEventListener('paste', this.onPaste);
  137. };
  138. exports.handler.detach = function(editor) {
  139. delete editor.renderer.screenToTextCoordinates;
  140. editor.session.$selectLongWords = $formerLongWords;
  141. editor.session.$useEmacsStyleLineStart = $formerLineStart;
  142. editor.removeEventListener("click", $resetMarkMode);
  143. editor.removeEventListener("changeSession", $kbSessionChange);
  144. editor.unsetStyle("emacs-mode");
  145. editor.commands.removeCommands(commands);
  146. editor.removeEventListener('copy', this.onCopy);
  147. editor.removeEventListener('paste', this.onPaste);
  148. editor.$emacsModeHandler = null;
  149. };
  150. var $kbSessionChange = function(e) {
  151. if (e.oldSession) {
  152. e.oldSession.$selectLongWords = $formerLongWords;
  153. e.oldSession.$useEmacsStyleLineStart = $formerLineStart;
  154. }
  155. $formerLongWords = e.session.$selectLongWords;
  156. e.session.$selectLongWords = true;
  157. $formerLineStart = e.session.$useEmacsStyleLineStart;
  158. e.session.$useEmacsStyleLineStart = true;
  159. if (!e.session.hasOwnProperty('$emacsMark'))
  160. e.session.$emacsMark = null;
  161. if (!e.session.hasOwnProperty('$emacsMarkRing'))
  162. e.session.$emacsMarkRing = [];
  163. };
  164. var $resetMarkMode = function(e) {
  165. e.editor.session.$emacsMark = null;
  166. };
  167. var keys = require("../lib/keys").KEY_MODS;
  168. var eMods = {C: "ctrl", S: "shift", M: "alt", CMD: "command"};
  169. var combinations = ["C-S-M-CMD",
  170. "S-M-CMD", "C-M-CMD", "C-S-CMD", "C-S-M",
  171. "M-CMD", "S-CMD", "S-M", "C-CMD", "C-M", "C-S",
  172. "CMD", "M", "S", "C"];
  173. combinations.forEach(function(c) {
  174. var hashId = 0;
  175. c.split("-").forEach(function(c) {
  176. hashId = hashId | keys[eMods[c]];
  177. });
  178. eMods[hashId] = c.toLowerCase() + "-";
  179. });
  180. exports.handler.onCopy = function(e, editor) {
  181. if (editor.$handlesEmacsOnCopy) return;
  182. editor.$handlesEmacsOnCopy = true;
  183. exports.handler.commands.killRingSave.exec(editor);
  184. editor.$handlesEmacsOnCopy = false;
  185. };
  186. exports.handler.onPaste = function(e, editor) {
  187. editor.pushEmacsMark(editor.getCursorPosition());
  188. };
  189. exports.handler.bindKey = function(key, command) {
  190. if (typeof key == "object")
  191. key = key[this.platform];
  192. if (!key)
  193. return;
  194. var ckb = this.commandKeyBinding;
  195. key.split("|").forEach(function(keyPart) {
  196. keyPart = keyPart.toLowerCase();
  197. ckb[keyPart] = command;
  198. // register all partial key combos as null commands
  199. // to be able to activate key combos with arbitrary length
  200. // Example: if keyPart is "C-c C-l t" then "C-c C-l t" will
  201. // get command assigned and "C-c" and "C-c C-l" will get
  202. // a null command assigned in this.commandKeyBinding. For
  203. // the lookup logic see handleKeyboard()
  204. var keyParts = keyPart.split(" ").slice(0,-1);
  205. keyParts.reduce(function(keyMapKeys, keyPart, i) {
  206. var prefix = keyMapKeys[i-1] ? keyMapKeys[i-1] + ' ' : '';
  207. return keyMapKeys.concat([prefix + keyPart]);
  208. }, []).forEach(function(keyPart) {
  209. if (!ckb[keyPart]) ckb[keyPart] = "null";
  210. });
  211. }, this);
  212. };
  213. exports.handler.getStatusText = function(editor, data) {
  214. var str = "";
  215. if (data.count)
  216. str += data.count;
  217. if (data.keyChain)
  218. str += " " + data.keyChain
  219. return str;
  220. };
  221. exports.handler.handleKeyboard = function(data, hashId, key, keyCode) {
  222. // if keyCode == -1 a non-printable key was pressed, such as just
  223. // control. Handling those is currently not supported in this handler
  224. if (keyCode === -1) return undefined;
  225. var editor = data.editor;
  226. editor._signal("changeStatus");
  227. // insertstring data.count times
  228. if (hashId == -1) {
  229. editor.pushEmacsMark();
  230. if (data.count) {
  231. var str = new Array(data.count + 1).join(key);
  232. data.count = null;
  233. return {command: "insertstring", args: str};
  234. }
  235. }
  236. var modifier = eMods[hashId];
  237. // CTRL + number / universalArgument for setting data.count
  238. if (modifier == "c-" || data.count) {
  239. var count = parseInt(key[key.length - 1]);
  240. if (typeof count === 'number' && !isNaN(count)) {
  241. data.count = Math.max(data.count, 0) || 0;
  242. data.count = 10 * data.count + count;
  243. return {command: "null"};
  244. }
  245. }
  246. // this.commandKeyBinding maps key specs like "c-p" (for CTRL + P) to
  247. // command objects, for lookup key needs to include the modifier
  248. if (modifier) key = modifier + key;
  249. // Key combos like CTRL+X H build up the data.keyChain
  250. if (data.keyChain) key = data.keyChain += " " + key;
  251. // Key combo prefixes get stored as "null" (String!) in this
  252. // this.commandKeyBinding. When encountered no command is invoked but we
  253. // buld up data.keyChain
  254. var command = this.commandKeyBinding[key];
  255. data.keyChain = command == "null" ? key : "";
  256. // there really is no command
  257. if (!command) return undefined;
  258. // we pass b/c of key combo or universalArgument
  259. if (command === "null") return {command: "null"};
  260. if (command === "universalArgument") {
  261. // if no number pressed emacs repeats action 4 times.
  262. // minus sign is needed to allow next keypress to replace it
  263. data.count = -4;
  264. return {command: "null"};
  265. }
  266. // lookup command
  267. // TODO extract special handling of markmode
  268. // TODO special case command.command is really unnecessary, remove
  269. var args;
  270. if (typeof command !== "string") {
  271. args = command.args;
  272. if (command.command) command = command.command;
  273. if (command === "goorselect") {
  274. command = editor.emacsMark() ? args[1] : args[0];
  275. args = null;
  276. }
  277. }
  278. if (typeof command === "string") {
  279. if (command === "insertstring" ||
  280. command === "splitline" ||
  281. command === "togglecomment") {
  282. editor.pushEmacsMark();
  283. }
  284. command = this.commands[command] || editor.commands.commands[command];
  285. if (!command) return undefined;
  286. }
  287. if (!command.readOnly && !command.isYank)
  288. data.lastCommand = null;
  289. if (!command.readOnly && editor.emacsMark())
  290. editor.setEmacsMark(null)
  291. if (data.count) {
  292. var count = data.count;
  293. data.count = 0;
  294. if (!command || !command.handlesCount) {
  295. return {
  296. args: args,
  297. command: {
  298. exec: function(editor, args) {
  299. for (var i = 0; i < count; i++)
  300. command.exec(editor, args);
  301. },
  302. multiSelectAction: command.multiSelectAction
  303. }
  304. };
  305. } else {
  306. if (!args) args = {};
  307. if (typeof args === 'object') args.count = count;
  308. }
  309. }
  310. return {command: command, args: args};
  311. };
  312. exports.emacsKeys = {
  313. // movement
  314. "Up|C-p" : {command: "goorselect", args: ["golineup","selectup"]},
  315. "Down|C-n" : {command: "goorselect", args: ["golinedown","selectdown"]},
  316. "Left|C-b" : {command: "goorselect", args: ["gotoleft","selectleft"]},
  317. "Right|C-f" : {command: "goorselect", args: ["gotoright","selectright"]},
  318. "C-Left|M-b" : {command: "goorselect", args: ["gotowordleft","selectwordleft"]},
  319. "C-Right|M-f" : {command: "goorselect", args: ["gotowordright","selectwordright"]},
  320. "Home|C-a" : {command: "goorselect", args: ["gotolinestart","selecttolinestart"]},
  321. "End|C-e" : {command: "goorselect", args: ["gotolineend","selecttolineend"]},
  322. "C-Home|S-M-,": {command: "goorselect", args: ["gotostart","selecttostart"]},
  323. "C-End|S-M-." : {command: "goorselect", args: ["gotoend","selecttoend"]},
  324. // selection
  325. "S-Up|S-C-p" : "selectup",
  326. "S-Down|S-C-n" : "selectdown",
  327. "S-Left|S-C-b" : "selectleft",
  328. "S-Right|S-C-f" : "selectright",
  329. "S-C-Left|S-M-b" : "selectwordleft",
  330. "S-C-Right|S-M-f" : "selectwordright",
  331. "S-Home|S-C-a" : "selecttolinestart",
  332. "S-End|S-C-e" : "selecttolineend",
  333. "S-C-Home" : "selecttostart",
  334. "S-C-End" : "selecttoend",
  335. "C-l" : "recenterTopBottom",
  336. "M-s" : "centerselection",
  337. "M-g": "gotoline",
  338. "C-x C-p": "selectall",
  339. // todo fix these
  340. "C-Down": {command: "goorselect", args: ["gotopagedown","selectpagedown"]},
  341. "C-Up": {command: "goorselect", args: ["gotopageup","selectpageup"]},
  342. "PageDown|C-v": {command: "goorselect", args: ["gotopagedown","selectpagedown"]},
  343. "PageUp|M-v": {command: "goorselect", args: ["gotopageup","selectpageup"]},
  344. "S-C-Down": "selectpagedown",
  345. "S-C-Up": "selectpageup",
  346. "C-s": "iSearch",
  347. "C-r": "iSearchBackwards",
  348. "M-C-s": "findnext",
  349. "M-C-r": "findprevious",
  350. "S-M-5": "replace",
  351. // basic editing
  352. "Backspace": "backspace",
  353. "Delete|C-d": "del",
  354. "Return|C-m": {command: "insertstring", args: "\n"}, // "newline"
  355. "C-o": "splitline",
  356. "M-d|C-Delete": {command: "killWord", args: "right"},
  357. "C-Backspace|M-Backspace|M-Delete": {command: "killWord", args: "left"},
  358. "C-k": "killLine",
  359. "C-y|S-Delete": "yank",
  360. "M-y": "yankRotate",
  361. "C-g": "keyboardQuit",
  362. "C-w|C-S-W": "killRegion",
  363. "M-w": "killRingSave",
  364. "C-Space": "setMark",
  365. "C-x C-x": "exchangePointAndMark",
  366. "C-t": "transposeletters",
  367. "M-u": "touppercase", // Doesn't work
  368. "M-l": "tolowercase",
  369. "M-/": "autocomplete", // Doesn't work
  370. "C-u": "universalArgument",
  371. "M-;": "togglecomment",
  372. "C-/|C-x u|S-C--|C-z": "undo",
  373. "S-C-/|S-C-x u|C--|S-C-z": "redo", // infinite undo?
  374. // vertical editing
  375. "C-x r": "selectRectangularRegion",
  376. "M-x": {command: "focusCommandLine", args: "M-x "}
  377. // todo
  378. // "C-x C-t" "M-t" "M-c" "F11" "C-M- "M-q"
  379. };
  380. exports.handler.bindKeys(exports.emacsKeys);
  381. exports.handler.addCommands({
  382. recenterTopBottom: function(editor) {
  383. var renderer = editor.renderer;
  384. var pos = renderer.$cursorLayer.getPixelPosition();
  385. var h = renderer.$size.scrollerHeight - renderer.lineHeight;
  386. var scrollTop = renderer.scrollTop;
  387. if (Math.abs(pos.top - scrollTop) < 2) {
  388. scrollTop = pos.top - h;
  389. } else if (Math.abs(pos.top - scrollTop - h * 0.5) < 2) {
  390. scrollTop = pos.top;
  391. } else {
  392. scrollTop = pos.top - h * 0.5;
  393. }
  394. editor.session.setScrollTop(scrollTop);
  395. },
  396. selectRectangularRegion: function(editor) {
  397. editor.multiSelect.toggleBlockSelection();
  398. },
  399. setMark: {
  400. exec: function(editor, args) {
  401. // Sets mark-mode and clears current selection.
  402. // When mark is set, keyboard cursor movement commands become
  403. // selection modification commands. That is,
  404. // "goto" commands become "select" commands.
  405. // Any insertion or mouse click resets mark-mode.
  406. // setMark twice in a row at the same place resets markmode.
  407. // in multi select mode, ea selection is handled individually
  408. if (args && args.count) {
  409. if (editor.inMultiSelectMode) editor.forEachSelection(moveToMark);
  410. else moveToMark();
  411. moveToMark();
  412. return;
  413. }
  414. var mark = editor.emacsMark(),
  415. ranges = editor.selection.getAllRanges(),
  416. rangePositions = ranges.map(function(r) { return {row: r.start.row, column: r.start.column}; }),
  417. transientMarkModeActive = true,
  418. hasNoSelection = ranges.every(function(range) { return range.isEmpty(); });
  419. // if transientMarkModeActive then mark behavior is a little
  420. // different. Deactivate the mark when setMark is run with active
  421. // mark
  422. if (transientMarkModeActive && (mark || !hasNoSelection)) {
  423. if (editor.inMultiSelectMode) editor.forEachSelection({exec: editor.clearSelection.bind(editor)});
  424. else editor.clearSelection();
  425. if (mark) editor.pushEmacsMark(null);
  426. return;
  427. }
  428. if (!mark) {
  429. rangePositions.forEach(function(pos) { editor.pushEmacsMark(pos); });
  430. editor.setEmacsMark(rangePositions[rangePositions.length-1]);
  431. return;
  432. }
  433. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  434. function moveToMark() {
  435. var mark = editor.popEmacsMark();
  436. mark && editor.moveCursorToPosition(mark);
  437. }
  438. },
  439. readOnly: true,
  440. handlesCount: true
  441. },
  442. exchangePointAndMark: {
  443. exec: function exchangePointAndMark$exec(editor, args) {
  444. var sel = editor.selection;
  445. if (!args.count && !sel.isEmpty()) { // just invert selection
  446. sel.setSelectionRange(sel.getRange(), !sel.isBackwards());
  447. return;
  448. }
  449. if (args.count) { // replace mark and point
  450. var pos = {row: sel.lead.row, column: sel.lead.column};
  451. sel.clearSelection();
  452. sel.moveCursorToPosition(editor.emacsMarkForSelection(pos));
  453. } else { // create selection to last mark
  454. sel.selectToPosition(editor.emacsMarkForSelection());
  455. }
  456. },
  457. readOnly: true,
  458. handlesCount: true,
  459. multiSelectAction: "forEach"
  460. },
  461. killWord: {
  462. exec: function(editor, dir) {
  463. editor.clearSelection();
  464. if (dir == "left")
  465. editor.selection.selectWordLeft();
  466. else
  467. editor.selection.selectWordRight();
  468. var range = editor.getSelectionRange();
  469. var text = editor.session.getTextRange(range);
  470. exports.killRing.add(text);
  471. editor.session.remove(range);
  472. editor.clearSelection();
  473. },
  474. multiSelectAction: "forEach"
  475. },
  476. killLine: function(editor) {
  477. editor.pushEmacsMark(null);
  478. // don't delete the selection if it's before the cursor
  479. editor.clearSelection();
  480. var range = editor.getSelectionRange();
  481. var line = editor.session.getLine(range.start.row);
  482. range.end.column = line.length;
  483. line = line.substr(range.start.column)
  484. var foldLine = editor.session.getFoldLine(range.start.row);
  485. if (foldLine && range.end.row != foldLine.end.row) {
  486. range.end.row = foldLine.end.row;
  487. line = "x";
  488. }
  489. // remove EOL if only whitespace remains after the cursor
  490. if (/^\s*$/.test(line)) {
  491. range.end.row++;
  492. line = editor.session.getLine(range.end.row);
  493. range.end.column = /^\s*$/.test(line) ? line.length : 0;
  494. }
  495. var text = editor.session.getTextRange(range);
  496. if (editor.prevOp.command == this)
  497. exports.killRing.append(text);
  498. else
  499. exports.killRing.add(text);
  500. editor.session.remove(range);
  501. editor.clearSelection();
  502. },
  503. yank: function(editor) {
  504. editor.onPaste(exports.killRing.get() || '');
  505. editor.keyBinding.$data.lastCommand = "yank";
  506. },
  507. yankRotate: function(editor) {
  508. if (editor.keyBinding.$data.lastCommand != "yank")
  509. return;
  510. editor.undo();
  511. editor.session.$emacsMarkRing.pop(); // also undo recording mark
  512. editor.onPaste(exports.killRing.rotate());
  513. editor.keyBinding.$data.lastCommand = "yank";
  514. },
  515. killRegion: {
  516. exec: function(editor) {
  517. exports.killRing.add(editor.getCopyText());
  518. editor.commands.byName.cut.exec(editor);
  519. },
  520. readOnly: true,
  521. multiSelectAction: "forEach"
  522. },
  523. killRingSave: {
  524. exec: function(editor) {
  525. // copy text and deselect. will save marks for starts of the
  526. // selection(s)
  527. editor.$handlesEmacsOnCopy = true;
  528. var marks = editor.session.$emacsMarkRing.slice(),
  529. deselectedMarks = [];
  530. exports.killRing.add(editor.getCopyText());
  531. setTimeout(function() {
  532. function deselect() {
  533. var sel = editor.selection, range = sel.getRange(),
  534. pos = sel.isBackwards() ? range.end : range.start;
  535. deselectedMarks.push({row: pos.row, column: pos.column});
  536. sel.clearSelection();
  537. }
  538. editor.$handlesEmacsOnCopy = false;
  539. if (editor.inMultiSelectMode) editor.forEachSelection({exec: deselect});
  540. else deselect();
  541. editor.session.$emacsMarkRing = marks.concat(deselectedMarks.reverse());
  542. }, 0);
  543. },
  544. readOnly: true
  545. },
  546. keyboardQuit: function(editor) {
  547. editor.selection.clearSelection();
  548. editor.setEmacsMark(null);
  549. editor.keyBinding.$data.count = null;
  550. },
  551. focusCommandLine: function(editor, arg) {
  552. if (editor.showCommandLine)
  553. editor.showCommandLine(arg);
  554. }
  555. });
  556. exports.handler.addCommands(iSearchCommandModule.iSearchStartCommands);
  557. var commands = exports.handler.commands;
  558. commands.yank.isYank = true;
  559. commands.yankRotate.isYank = true;
  560. exports.killRing = {
  561. $data: [],
  562. add: function(str) {
  563. str && this.$data.push(str);
  564. if (this.$data.length > 30)
  565. this.$data.shift();
  566. },
  567. append: function(str) {
  568. var idx = this.$data.length - 1;
  569. var text = this.$data[idx] || "";
  570. if (str) text += str;
  571. if (text) this.$data[idx] = text;
  572. },
  573. get: function(n) {
  574. n = n || 1;
  575. return this.$data.slice(this.$data.length-n, this.$data.length).reverse().join('\n');
  576. },
  577. pop: function() {
  578. if (this.$data.length > 1)
  579. this.$data.pop();
  580. return this.get();
  581. },
  582. rotate: function() {
  583. this.$data.unshift(this.$data.pop());
  584. return this.get();
  585. }
  586. };
  587. });