emacs.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3. (function(mod) {
  4. if (typeof exports == "object" && typeof module == "object") // CommonJS
  5. mod(require("../lib/codemirror"));
  6. else if (typeof define == "function" && define.amd) // AMD
  7. define(["../lib/codemirror"], mod);
  8. else // Plain browser env
  9. mod(CodeMirror);
  10. })(function(CodeMirror) {
  11. "use strict";
  12. var cmds = CodeMirror.commands;
  13. var Pos = CodeMirror.Pos;
  14. function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
  15. // Kill 'ring'
  16. var killRing = [];
  17. function addToRing(str) {
  18. killRing.push(str);
  19. if (killRing.length > 50) killRing.shift();
  20. }
  21. function growRingTop(str) {
  22. if (!killRing.length) return addToRing(str);
  23. killRing[killRing.length - 1] += str;
  24. }
  25. function getFromRing(n) { return killRing[killRing.length - (n ? Math.min(n, 1) : 1)] || ""; }
  26. function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); }
  27. var lastKill = null;
  28. // Internal generic kill function, used by several mapped kill "family" functions.
  29. function _kill(cm, from, to, ring, text) {
  30. if (text == null) text = cm.getRange(from, to);
  31. if (ring == "grow" && lastKill && lastKill.cm == cm && posEq(from, lastKill.pos) && cm.isClean(lastKill.gen))
  32. growRingTop(text);
  33. else if (ring !== false)
  34. addToRing(text);
  35. cm.replaceRange("", from, to, "+delete");
  36. if (ring == "grow") lastKill = {cm: cm, pos: from, gen: cm.changeGeneration()};
  37. else lastKill = null;
  38. }
  39. // Boundaries of various units
  40. function byChar(cm, pos, dir) {
  41. return cm.findPosH(pos, dir, "char", true);
  42. }
  43. function byWord(cm, pos, dir) {
  44. return cm.findPosH(pos, dir, "word", true);
  45. }
  46. function byLine(cm, pos, dir) {
  47. return cm.findPosV(pos, dir, "line", cm.doc.sel.goalColumn);
  48. }
  49. function byPage(cm, pos, dir) {
  50. return cm.findPosV(pos, dir, "page", cm.doc.sel.goalColumn);
  51. }
  52. function byParagraph(cm, pos, dir) {
  53. var no = pos.line, line = cm.getLine(no);
  54. var sawText = /\S/.test(dir < 0 ? line.slice(0, pos.ch) : line.slice(pos.ch));
  55. var fst = cm.firstLine(), lst = cm.lastLine();
  56. for (;;) {
  57. no += dir;
  58. if (no < fst || no > lst)
  59. return cm.clipPos(Pos(no - dir, dir < 0 ? 0 : null));
  60. line = cm.getLine(no);
  61. var hasText = /\S/.test(line);
  62. if (hasText) sawText = true;
  63. else if (sawText) return Pos(no, 0);
  64. }
  65. }
  66. function bySentence(cm, pos, dir) {
  67. var line = pos.line, ch = pos.ch;
  68. var text = cm.getLine(pos.line), sawWord = false;
  69. for (;;) {
  70. var next = text.charAt(ch + (dir < 0 ? -1 : 0));
  71. if (!next) { // End/beginning of line reached
  72. if (line == (dir < 0 ? cm.firstLine() : cm.lastLine())) return Pos(line, ch);
  73. text = cm.getLine(line + dir);
  74. if (!/\S/.test(text)) return Pos(line, ch);
  75. line += dir;
  76. ch = dir < 0 ? text.length : 0;
  77. continue;
  78. }
  79. if (sawWord && /[!?.]/.test(next)) return Pos(line, ch + (dir > 0 ? 1 : 0));
  80. if (!sawWord) sawWord = /\w/.test(next);
  81. ch += dir;
  82. }
  83. }
  84. function byExpr(cm, pos, dir) {
  85. var wrap;
  86. if (cm.findMatchingBracket && (wrap = cm.findMatchingBracket(pos, {strict: true}))
  87. && wrap.match && (wrap.forward ? 1 : -1) == dir)
  88. return dir > 0 ? Pos(wrap.to.line, wrap.to.ch + 1) : wrap.to;
  89. for (var first = true;; first = false) {
  90. var token = cm.getTokenAt(pos);
  91. var after = Pos(pos.line, dir < 0 ? token.start : token.end);
  92. if (first && dir > 0 && token.end == pos.ch || !/\w/.test(token.string)) {
  93. var newPos = cm.findPosH(after, dir, "char");
  94. if (posEq(after, newPos)) return pos;
  95. else pos = newPos;
  96. } else {
  97. return after;
  98. }
  99. }
  100. }
  101. // Prefixes (only crudely supported)
  102. function getPrefix(cm, precise) {
  103. var digits = cm.state.emacsPrefix;
  104. if (!digits) return precise ? null : 1;
  105. clearPrefix(cm);
  106. return digits == "-" ? -1 : Number(digits);
  107. }
  108. function repeated(cmd) {
  109. var f = typeof cmd == "string" ? function(cm) { cm.execCommand(cmd); } : cmd;
  110. return function(cm) {
  111. var prefix = getPrefix(cm);
  112. f(cm);
  113. for (var i = 1; i < prefix; ++i) f(cm);
  114. };
  115. }
  116. function findEnd(cm, pos, by, dir) {
  117. var prefix = getPrefix(cm);
  118. if (prefix < 0) { dir = -dir; prefix = -prefix; }
  119. for (var i = 0; i < prefix; ++i) {
  120. var newPos = by(cm, pos, dir);
  121. if (posEq(newPos, pos)) break;
  122. pos = newPos;
  123. }
  124. return pos;
  125. }
  126. function move(by, dir) {
  127. var f = function(cm) {
  128. cm.extendSelection(findEnd(cm, cm.getCursor(), by, dir));
  129. };
  130. f.motion = true;
  131. return f;
  132. }
  133. function killTo(cm, by, dir, ring) {
  134. var selections = cm.listSelections(), cursor;
  135. var i = selections.length;
  136. while (i--) {
  137. cursor = selections[i].head;
  138. _kill(cm, cursor, findEnd(cm, cursor, by, dir), ring);
  139. }
  140. }
  141. function _killRegion(cm, ring) {
  142. if (cm.somethingSelected()) {
  143. var selections = cm.listSelections(), selection;
  144. var i = selections.length;
  145. while (i--) {
  146. selection = selections[i];
  147. _kill(cm, selection.anchor, selection.head, ring);
  148. }
  149. return true;
  150. }
  151. }
  152. function addPrefix(cm, digit) {
  153. if (cm.state.emacsPrefix) {
  154. if (digit != "-") cm.state.emacsPrefix += digit;
  155. return;
  156. }
  157. // Not active yet
  158. cm.state.emacsPrefix = digit;
  159. cm.on("keyHandled", maybeClearPrefix);
  160. cm.on("inputRead", maybeDuplicateInput);
  161. }
  162. var prefixPreservingKeys = {"Alt-G": true, "Ctrl-X": true, "Ctrl-Q": true, "Ctrl-U": true};
  163. function maybeClearPrefix(cm, arg) {
  164. if (!cm.state.emacsPrefixMap && !prefixPreservingKeys.hasOwnProperty(arg))
  165. clearPrefix(cm);
  166. }
  167. function clearPrefix(cm) {
  168. cm.state.emacsPrefix = null;
  169. cm.off("keyHandled", maybeClearPrefix);
  170. cm.off("inputRead", maybeDuplicateInput);
  171. }
  172. function maybeDuplicateInput(cm, event) {
  173. var dup = getPrefix(cm);
  174. if (dup > 1 && event.origin == "+input") {
  175. var one = event.text.join("\n"), txt = "";
  176. for (var i = 1; i < dup; ++i) txt += one;
  177. cm.replaceSelection(txt);
  178. }
  179. }
  180. function maybeRemovePrefixMap(cm, arg) {
  181. if (typeof arg == "string" && (/^\d$/.test(arg) || arg == "Ctrl-U")) return;
  182. cm.removeKeyMap(prefixMap);
  183. cm.state.emacsPrefixMap = false;
  184. cm.off("keyHandled", maybeRemovePrefixMap);
  185. cm.off("inputRead", maybeRemovePrefixMap);
  186. }
  187. // Utilities
  188. cmds.setMark = function (cm) {
  189. cm.setCursor(cm.getCursor());
  190. cm.setExtending(!cm.getExtending());
  191. cm.on("change", function() { cm.setExtending(false); });
  192. }
  193. function clearMark(cm) {
  194. cm.setExtending(false);
  195. cm.setCursor(cm.getCursor());
  196. }
  197. function makePrompt(msg) {
  198. var fragment = document.createDocumentFragment();
  199. var input = document.createElement("input");
  200. input.setAttribute("type", "text");
  201. input.style.width = "10em";
  202. fragment.appendChild(document.createTextNode(msg + ": "));
  203. fragment.appendChild(input);
  204. return fragment;
  205. }
  206. function getInput(cm, msg, f) {
  207. if (cm.openDialog)
  208. cm.openDialog(makePrompt(msg), f, {bottom: true});
  209. else
  210. f(prompt(msg, ""));
  211. }
  212. function operateOnWord(cm, op) {
  213. var start = cm.getCursor(), end = cm.findPosH(start, 1, "word");
  214. cm.replaceRange(op(cm.getRange(start, end)), start, end);
  215. cm.setCursor(end);
  216. }
  217. function toEnclosingExpr(cm) {
  218. var pos = cm.getCursor(), line = pos.line, ch = pos.ch;
  219. var stack = [];
  220. while (line >= cm.firstLine()) {
  221. var text = cm.getLine(line);
  222. for (var i = ch == null ? text.length : ch; i > 0;) {
  223. var ch = text.charAt(--i);
  224. if (ch == ")")
  225. stack.push("(");
  226. else if (ch == "]")
  227. stack.push("[");
  228. else if (ch == "}")
  229. stack.push("{");
  230. else if (/[\(\{\[]/.test(ch) && (!stack.length || stack.pop() != ch))
  231. return cm.extendSelection(Pos(line, i));
  232. }
  233. --line; ch = null;
  234. }
  235. }
  236. // Commands. Names should match emacs function names (albeit in camelCase)
  237. // except where emacs function names collide with code mirror core commands.
  238. cmds.killRegion = function(cm) {
  239. _kill(cm, cm.getCursor("start"), cm.getCursor("end"), true);
  240. };
  241. // Maps to emacs kill-line
  242. cmds.killLineEmacs = repeated(function(cm) {
  243. var start = cm.getCursor(), end = cm.clipPos(Pos(start.line));
  244. var text = cm.getRange(start, end);
  245. if (!/\S/.test(text)) {
  246. text += "\n";
  247. end = Pos(start.line + 1, 0);
  248. }
  249. _kill(cm, start, end, "grow", text);
  250. });
  251. cmds.killRingSave = function(cm) {
  252. addToRing(cm.getSelection());
  253. clearMark(cm);
  254. };
  255. cmds.yank = function(cm) {
  256. var start = cm.getCursor();
  257. cm.replaceRange(getFromRing(getPrefix(cm)), start, start, "paste");
  258. cm.setSelection(start, cm.getCursor());
  259. };
  260. cmds.yankPop = function(cm) {
  261. cm.replaceSelection(popFromRing(), "around", "paste");
  262. };
  263. cmds.forwardChar = move(byChar, 1);
  264. cmds.backwardChar = move(byChar, -1)
  265. cmds.deleteChar = function(cm) { killTo(cm, byChar, 1, false); };
  266. cmds.deleteForwardChar = function(cm) {
  267. _killRegion(cm, false) || killTo(cm, byChar, 1, false);
  268. };
  269. cmds.deleteBackwardChar = function(cm) {
  270. _killRegion(cm, false) || killTo(cm, byChar, -1, false);
  271. };
  272. cmds.forwardWord = move(byWord, 1);
  273. cmds.backwardWord = move(byWord, -1);
  274. cmds.killWord = function(cm) { killTo(cm, byWord, 1, "grow"); };
  275. cmds.backwardKillWord = function(cm) { killTo(cm, byWord, -1, "grow"); };
  276. cmds.nextLine = move(byLine, 1);
  277. cmds.previousLine = move(byLine, -1);
  278. cmds.scrollDownCommand = move(byPage, -1);
  279. cmds.scrollUpCommand = move(byPage, 1);
  280. cmds.backwardParagraph = move(byParagraph, -1);
  281. cmds.forwardParagraph = move(byParagraph, 1);
  282. cmds.backwardSentence = move(bySentence, -1);
  283. cmds.forwardSentence = move(bySentence, 1);
  284. cmds.killSentence = function(cm) { killTo(cm, bySentence, 1, "grow"); };
  285. cmds.backwardKillSentence = function(cm) {
  286. _kill(cm, cm.getCursor(), bySentence(cm, cm.getCursor(), 1), "grow");
  287. };
  288. cmds.killSexp = function(cm) { killTo(cm, byExpr, 1, "grow"); };
  289. cmds.backwardKillSexp = function(cm) { killTo(cm, byExpr, -1, "grow"); };
  290. cmds.forwardSexp = move(byExpr, 1);
  291. cmds.backwardSexp = move(byExpr, -1);
  292. cmds.markSexp = function(cm) {
  293. var cursor = cm.getCursor();
  294. cm.setSelection(findEnd(cm, cursor, byExpr, 1), cursor);
  295. };
  296. cmds.transposeSexps = function(cm) {
  297. var leftStart = byExpr(cm, cm.getCursor(), -1);
  298. var leftEnd = byExpr(cm, leftStart, 1);
  299. var rightEnd = byExpr(cm, leftEnd, 1);
  300. var rightStart = byExpr(cm, rightEnd, -1);
  301. cm.replaceRange(cm.getRange(rightStart, rightEnd) +
  302. cm.getRange(leftEnd, rightStart) +
  303. cm.getRange(leftStart, leftEnd), leftStart, rightEnd);
  304. };
  305. cmds.backwardUpList = repeated(toEnclosingExpr);
  306. cmds.justOneSpace = function(cm) {
  307. var pos = cm.getCursor(), from = pos.ch;
  308. var to = pos.ch, text = cm.getLine(pos.line);
  309. while (from && /\s/.test(text.charAt(from - 1))) --from;
  310. while (to < text.length && /\s/.test(text.charAt(to))) ++to;
  311. cm.replaceRange(" ", Pos(pos.line, from), Pos(pos.line, to));
  312. };
  313. cmds.openLine = repeated(function(cm) {
  314. cm.replaceSelection("\n", "start");
  315. });
  316. // maps to emacs 'transpose-chars'
  317. cmds.transposeCharsRepeatable = repeated(function(cm) {
  318. cm.execCommand("transposeChars");
  319. });
  320. cmds.capitalizeWord = repeated(function(cm) {
  321. operateOnWord(cm, function(w) {
  322. var letter = w.search(/\w/);
  323. if (letter == -1) return w;
  324. return w.slice(0, letter) + w.charAt(letter).toUpperCase() +
  325. w.slice(letter + 1).toLowerCase();
  326. });
  327. });
  328. cmds.upcaseWord = repeated(function(cm) {
  329. operateOnWord(cm, function(w) { return w.toUpperCase(); });
  330. });
  331. cmds.downcaseWord = repeated(function(cm) {
  332. operateOnWord(cm, function(w) { return w.toLowerCase(); });
  333. });
  334. // maps to emacs 'undo'
  335. cmds.undoRepeatable = repeated("undo");
  336. cmds.keyboardQuit = function(cm) {
  337. cm.execCommand("clearSearch");
  338. clearMark(cm);
  339. }
  340. cmds.newline = repeated(function(cm) { cm.replaceSelection("\n", "end"); });
  341. cmds.gotoLine = function(cm) {
  342. var prefix = getPrefix(cm, true);
  343. if (prefix != null && prefix > 0) return cm.setCursor(prefix - 1);
  344. getInput(cm, "Goto line", function(str) {
  345. var num;
  346. if (str && !isNaN(num = Number(str)) && num == (num|0) && num > 0)
  347. cm.setCursor(num - 1);
  348. });
  349. };
  350. cmds.indentRigidly = function(cm) {
  351. cm.indentSelection(getPrefix(cm, true) || cm.getOption("indentUnit"));
  352. };
  353. cmds.exchangePointAndMark = function(cm) {
  354. cm.setSelection(cm.getCursor("head"), cm.getCursor("anchor"));
  355. };
  356. cmds.quotedInsertTab = repeated("insertTab");
  357. cmds.universalArgument = function addPrefixMap(cm) {
  358. cm.state.emacsPrefixMap = true;
  359. cm.addKeyMap(prefixMap);
  360. cm.on("keyHandled", maybeRemovePrefixMap);
  361. cm.on("inputRead", maybeRemovePrefixMap);
  362. };
  363. CodeMirror.emacs = {kill: _kill, killRegion: _killRegion, repeated: repeated};
  364. // Actual keymap
  365. var keyMap = CodeMirror.keyMap.emacs = CodeMirror.normalizeKeyMap({
  366. "Ctrl-W": "killRegion",
  367. "Ctrl-K": "killLineEmacs",
  368. "Alt-W": "killRingSave",
  369. "Ctrl-Y": "yank",
  370. "Alt-Y": "yankPop",
  371. "Ctrl-Space": "setMark",
  372. "Ctrl-Shift-2": "setMark",
  373. "Ctrl-F": "forwardChar",
  374. "Ctrl-B": "backwardChar",
  375. "Right": "forwardChar",
  376. "Left": "backwardChar",
  377. "Ctrl-D": "deleteChar",
  378. "Delete": "deleteForwardChar",
  379. "Ctrl-H": "deleteBackwardChar",
  380. "Backspace": "deleteBackwardChar",
  381. "Alt-F": "forwardWord",
  382. "Alt-B": "backwardWord",
  383. "Alt-Right": "forwardWord",
  384. "Alt-Left": "backwardWord",
  385. "Alt-D": "killWord",
  386. "Alt-Backspace": "backwardKillWord",
  387. "Ctrl-N": "nextLine",
  388. "Ctrl-P": "previousLine",
  389. "Down": "nextLine",
  390. "Up": "previousLine",
  391. "Ctrl-A": "goLineStart",
  392. "Ctrl-E": "goLineEnd",
  393. "End": "goLineEnd",
  394. "Home": "goLineStart",
  395. "Alt-V": "scrollDownCommand",
  396. "Ctrl-V": "scrollUpCommand",
  397. "PageUp": "scrollDownCommand",
  398. "PageDown": "scrollUpCommand",
  399. "Ctrl-Up": "backwardParagraph",
  400. "Ctrl-Down": "forwardParagraph",
  401. "Alt-{": "backwardParagraph",
  402. "Alt-}": "forwardParagraph",
  403. "Alt-A": "backwardSentence",
  404. "Alt-E": "forwardSentence",
  405. "Alt-K": "killSentence",
  406. "Ctrl-X Delete": "backwardKillSentence",
  407. "Ctrl-Alt-K": "killSexp",
  408. "Ctrl-Alt-Backspace": "backwardKillSexp",
  409. "Ctrl-Alt-F": "forwardSexp",
  410. "Ctrl-Alt-B": "backwardSexp",
  411. "Shift-Ctrl-Alt-2": "markSexp",
  412. "Ctrl-Alt-T": "transposeSexps",
  413. "Ctrl-Alt-U": "backwardUpList",
  414. "Alt-Space": "justOneSpace",
  415. "Ctrl-O": "openLine",
  416. "Ctrl-T": "transposeCharsRepeatable",
  417. "Alt-C": "capitalizeWord",
  418. "Alt-U": "upcaseWord",
  419. "Alt-L": "downcaseWord",
  420. "Alt-;": "toggleComment",
  421. "Ctrl-/": "undoRepeatable",
  422. "Shift-Ctrl--": "undoRepeatable",
  423. "Ctrl-Z": "undoRepeatable",
  424. "Cmd-Z": "undoRepeatable",
  425. "Ctrl-X U": "undoRepeatable",
  426. "Shift-Ctrl-Z": "redo",
  427. "Shift-Alt-,": "goDocStart",
  428. "Shift-Alt-.": "goDocEnd",
  429. "Ctrl-S": "findPersistentNext",
  430. "Ctrl-R": "findPersistentPrev",
  431. "Ctrl-G": "keyboardQuit",
  432. "Shift-Alt-5": "replace",
  433. "Alt-/": "autocomplete",
  434. "Enter": "newlineAndIndent",
  435. "Ctrl-J": "newline",
  436. "Tab": "indentAuto",
  437. "Alt-G G": "gotoLine",
  438. "Ctrl-X Tab": "indentRigidly",
  439. "Ctrl-X Ctrl-X": "exchangePointAndMark",
  440. "Ctrl-X Ctrl-S": "save",
  441. "Ctrl-X Ctrl-W": "save",
  442. "Ctrl-X S": "saveAll",
  443. "Ctrl-X F": "open",
  444. "Ctrl-X K": "close",
  445. "Ctrl-X H": "selectAll",
  446. "Ctrl-Q Tab": "quotedInsertTab",
  447. "Ctrl-U": "universalArgument",
  448. "fallthrough": "default"
  449. });
  450. var prefixMap = {"Ctrl-G": clearPrefix};
  451. function regPrefix(d) {
  452. prefixMap[d] = function(cm) { addPrefix(cm, d); };
  453. keyMap["Ctrl-" + d] = function(cm) { addPrefix(cm, d); };
  454. prefixPreservingKeys["Ctrl-" + d] = true;
  455. }
  456. for (var i = 0; i < 10; ++i) regPrefix(String(i));
  457. regPrefix("-");
  458. });