1 // Copyright (c) 2008-2011 Kris Maglione <maglione.k at Gmail>
2 // Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
4 // This work is licensed for reuse under an MIT license. Details are
5 // given in the LICENSE.txt file included with this file.
10 // command names taken from:
11 // http://developer.mozilla.org/en/docs/Editor_Embedding_Guide
13 /** @instance editor */
14 var Editor = Module("editor", XPCOM(Ci.nsIEditActionListener, ModuleBase), {
15 init: function init(elem) {
19 this.__defineGetter__("element", function () {
20 let elem = dactyl.focusedElement;
22 return elem.inputField || elem;
24 let win = document.commandDispatcher.focusedWindow;
25 return DOM(win).isEditable && win || null;
29 get registers() storage.newMap("registers", { privateData: true, store: true }),
30 get registerRing() storage.newArray("register-ring", { privateData: true, store: true }),
34 // Fixme: Move off this object.
35 currentRegister: null,
38 * Temporarily set the default register for the span of the next
41 pushRegister: function pushRegister(arg) {
42 let restore = this.currentRegister;
43 this.currentRegister = arg;
44 mappings.afterCommands(2, function () {
45 this.currentRegister = restore;
57 * Get the value of the register *name*.
59 * @param {string|number} name The name of the register to get.
60 * @returns {string|null}
63 getRegister: function getRegister(name) {
65 name = editor.currentRegister || editor.defaultRegister;
71 else if (Set.has(this.selectionRegisters, name))
72 res = { text: dactyl.clipboardRead(this.selectionRegisters[name]) || "" };
73 else if (!/^[0-9]$/.test(name))
74 res = this.registers.get(name);
76 res = this.registerRing.get(name);
78 return res != null ? res.text : res;
82 * Sets the value of register *name* to value. The following
83 * registers have special semantics:
85 * * - Tied to the PRIMARY selection value on X11 systems.
86 * + - Tied to the primary global clipboard.
87 * _ - The null register. Never has any value.
88 * " - Equivalent to 0.
89 * 0-9 - These act as a kill ring. Setting any of them pushes the
90 * values of higher numbered registers up one slot.
92 * @param {string|number} name The name of the register to set.
93 * @param {string|Range|Selection|Node} value The value to save to
96 setRegister: function setRegister(name, value, verbose) {
98 name = editor.currentRegister || editor.defaultRegister;
100 if (isinstance(value, [Ci.nsIDOMRange, Ci.nsIDOMNode, Ci.nsISelection]))
101 value = DOM.stringify(value);
102 value = { text: value, isLine: modes.extended & modes.LINE, timestamp: Date.now() * 1000 };
108 else if (Set.has(this.selectionRegisters, name))
109 dactyl.clipboardWrite(value.text, verbose, this.selectionRegisters[name]);
110 else if (!/^[0-9]$/.test(name))
111 this.registers.set(name, value);
113 this.registerRing.insert(value, name);
114 this.registerRing.truncate(10);
118 get isCaret() modes.getStack(1).main == modes.CARET,
119 get isTextEdit() modes.getStack(1).main == modes.TEXT_EDIT,
121 get editor() DOM(this.element).editor,
123 getController: function getController(cmd) {
124 let controllers = this.element && this.element.controllers;
125 dactyl.assert(controllers);
127 return controllers.getControllerForCommand(cmd || "cmd_beginLine");
130 get selection() this.editor && this.editor.selection || null,
131 get selectionController() this.editor && this.editor.selectionController || null,
133 deselect: function () {
134 if (this.selection && this.selection.focusNode)
135 this.selection.collapse(this.selection.focusNode,
136 this.selection.focusOffset);
139 get selectedRange() {
143 if (!this.selection.rangeCount) {
144 let range = RangeFind.nodeContents(this.editor.rootElement.ownerDocument);
145 range.collapse(true);
146 this.selectedRange = range;
148 return this.selection.getRangeAt(0);
150 set selectedRange(range) {
151 this.selection.removeAllRanges();
153 this.selection.addRange(range);
156 get selectedText() String(this.selection),
158 get preserveSelection() this.editor && !this.editor.shouldTxnSetSelection,
159 set preserveSelection(val) {
161 this.editor.setShouldTxnSetSelection(!val);
164 copy: function copy(range, name) {
165 range = range || this.selection;
167 if (!range.collapsed)
168 this.setRegister(name, range);
171 cut: function cut(range, name) {
173 this.selectedRange = range;
175 if (!this.selection.isCollapsed)
176 this.setRegister(name, this.selection);
178 this.editor.deleteSelection(0);
181 paste: function paste(name) {
182 let text = this.getRegister(name);
183 dactyl.assert(text && this.editor instanceof Ci.nsIPlaintextEditor);
185 this.editor.insertText(text);
188 // count is optional, defaults to 1
189 executeCommand: function executeCommand(cmd, count) {
190 if (!callable(cmd)) {
191 var controller = this.getController(cmd);
192 util.assert(controller &&
193 controller.supportsCommand(cmd) &&
194 controller.isCommandEnabled(cmd));
195 cmd = bind("doCommand", controller, cmd);
198 // XXX: better as a precondition
202 let didCommand = false;
204 // some commands need this try/catch workaround, because a cmd_charPrevious triggered
205 // at the beginning of the textarea, would hang the doCommand()
206 // good thing is, we need this code anyway for proper beeping
210 cmd(this.editor, controller);
215 dactyl.assert(didCommand);
221 moveToPosition: function (pos, select) {
223 var { startContainer, startOffset } = pos;
225 [startOffset, startOffset] = [this.selection.focusNode, pos];
226 this.selection[select ? "extend" : "collapse"](startContainer, startOffset);
229 mungeRange: function mungeRange(range, munger, selectEnd) {
230 let { editor } = this;
231 editor.beginPlaceHolderTransaction(null);
233 let [container, offset] = ["startContainer", "startOffset"];
235 [container, offset] = ["endContainer", "endOffset"];
239 let idx = range[offset];
240 let parent = range[container].parentNode;
241 let parentIdx = Array.indexOf(parent.childNodes,
245 for (let node in Editor.TextsIterator(range)) {
246 let text = node.textContent;
247 let start = 0, end = text.length;
248 if (node == range.startContainer)
249 start = range.startOffset;
250 if (node == range.endContainer)
251 end = range.endOffset;
253 if (start == 0 && end == text.length)
256 text = text.slice(0, start)
257 + munger(text.slice(start, end))
260 if (text == node.textContent)
264 delta = text.length - node.textContent.length;
266 if (editor instanceof Ci.nsIPlaintextEditor) {
267 this.selectedRange = RangeFind.nodeContents(node);
268 editor.insertText(text);
271 node.textContent = text;
273 let node = parent.childNodes[parentIdx];
274 if (node instanceof Text)
275 idx = Math.constrain(idx + delta, 0, node.textContent.length);
276 this.selection.collapse(node, idx);
279 editor.endPlaceHolderTransaction();
283 findChar: function findChar(key, count, backward, offset) {
284 count = count || 1; // XXX ?
285 offset = (offset || 0) - !!backward;
287 // Grab the charcode of the key spec. Using the key name
288 // directly will break keys like <
289 let code = DOM.Event.parse(key)[0].charCode;
290 let char = String.fromCharCode(code);
293 let range = this.selectedRange.cloneRange();
294 let collapse = DOM(this.element).whiteSpace == "normal";
296 // Find the *count*th occurance of *char* before a non-collapsed
297 // \n, ignoring the character at the caret.
299 function test(c) (collapse || c != "\n") && !!(!i++ || c != char || --count)
301 Editor.extendRange(range, !backward, { test: test }, true);
302 dactyl.assert(count == 0);
303 range.collapse(backward);
305 // Skip to any requested offset.
306 count = Math.abs(offset);
307 Editor.extendRange(range, offset > 0, { test: function (c) !!count-- }, true);
308 range.collapse(offset < 0);
313 findNumber: function findNumber(range) {
315 range = this.selectedRange.cloneRange();
317 // Find digit (or \n).
318 Editor.extendRange(range, true, /[^\n\d]/, true);
319 range.collapse(false);
320 // Select entire number.
321 Editor.extendRange(range, true, /\d/, true);
322 Editor.extendRange(range, false, /\d/, true);
325 dactyl.assert(/^\d+$/.test(range));
327 if (false) // Skip for now.
328 if (range.startContainer instanceof Text && range.startOffset > 2) {
329 if (range.startContainer.textContent.substr(range.startOffset - 2, 2) == "0x")
330 range.setStart(range.startContainer, range.startOffset - 2);
333 // Grab the sign, if it's there.
334 Editor.extendRange(range, false, /[+-]/, true);
339 modifyNumber: function modifyNumber(delta, range) {
340 range = this.findNumber(range);
341 let number = parseInt(range) + delta;
342 if (/^[+-]?0x/.test(range))
343 number = number.toString(16).replace(/^[+-]?/, "$&0x");
344 else if (/^[+-]?0\d/.test(range))
345 number = number.toString(8).replace(/^[+-]?/, "$&0");
347 this.selectedRange = range;
348 this.editor.insertText(String(number));
349 this.selection.modify("move", "backward", "character");
353 * Edits the given file in the external editor as specified by the
356 * @param {object|File|string} args An object specifying the file, line,
357 * and column to edit. If a non-object is specified, it is treated as
358 * the file parameter of the object.
359 * @param {boolean} blocking If true, this function does not return
360 * until the editor exits.
362 editFileExternally: function (args, blocking) {
363 if (!isObject(args) || args instanceof File)
364 args = { file: args };
365 args.file = args.file.path || args.file;
367 let args = options.get("editor").format(args);
369 dactyl.assert(args.length >= 1, _("option.notSet", "editor"));
371 io.run(args.shift(), args, blocking);
374 // TODO: clean up with 2 functions for textboxes and currentEditor?
375 editFieldExternally: function editFieldExternally(forceEditing) {
376 if (!options["editor"])
379 let textBox = config.isComposeWindow ? null : dactyl.focusedElement;
380 if (!DOM(textBox).isInput)
384 let keepFocus = modes.stack.some(function (m) isinstance(m.main, modes.COMMAND_LINE));
386 if (!forceEditing && textBox && textBox.type == "password") {
387 commandline.input(_("editor.prompt.editPassword") + " ",
389 if (resp && resp.match(/^y(es)?$/i))
390 editor.editFieldExternally(true);
396 var text = textBox.value;
397 var pre = text.substr(0, textBox.selectionStart);
400 var editor_ = window.GetCurrentEditor ? GetCurrentEditor()
401 : Editor.getEditor(document.commandDispatcher.focusedWindow);
402 dactyl.assert(editor_);
403 text = Array.map(editor_.rootElement.childNodes, function (e) DOM.stringify(e, true)).join("");
405 if (!editor_.selection.rangeCount)
408 let range = RangeFind.nodeContents(editor_.rootElement);
409 let end = editor_.selection.getRangeAt(0);
410 range.setEnd(end.startContainer, end.startOffset);
411 pre = DOM.stringify(range, true);
412 if (range.startContainer instanceof Text)
413 pre = pre.replace(/^(?:<[^>"]+>)+/, "");
414 if (range.endContainer instanceof Text)
415 pre = pre.replace(/(?:<\/[^>"]+>)+$/, "");
419 line = 1 + pre.replace(/[^\n]/g, "").length;
420 column = 1 + pre.replace(/[^]*\n/, "").length;
422 let origGroup = DOM(textBox).highlight.toString();
423 let cleanup = util.yieldable(function cleanup(error) {
427 let blink = ["EditorBlink1", "EditorBlink2"];
429 dactyl.reportError(error, true);
430 blink[1] = "EditorError";
433 dactyl.trapErrors(update, null, true);
435 if (tmpfile && tmpfile.exists())
436 tmpfile.remove(false);
439 DOM(textBox).highlight.remove("EditorEditing");
441 dactyl.focus(textBox);
442 for (let group in values(blink.concat(blink, ""))) {
443 highlight.highlightNode(textBox, origGroup + " " + group);
449 function update(force) {
450 if (force !== true && tmpfile.lastModifiedTime <= lastUpdate)
452 lastUpdate = Date.now();
454 let val = tmpfile.read();
459 let elem = DOM(textBox);
460 elem.attrNS(NS, "modifiable", true)
462 elem.input().attrNS(NS, "modifiable", null);
466 while (editor_.rootElement.firstChild)
467 editor_.rootElement.removeChild(editor_.rootElement.firstChild);
468 editor_.rootElement.innerHTML = val;
473 var tmpfile = io.createTempFile();
475 throw Error(_("io.cantCreateTempFile"));
480 DOM(textBox).highlight.add("EditorEditing");
483 if (!tmpfile.write(text))
484 throw Error(_("io.cantEncode"));
486 var lastUpdate = Date.now();
488 var timer = services.Timer(update, 100, services.Timer.TYPE_REPEATING_SLACK);
489 this.editFileExternally({ file: tmpfile.path, line: line, column: column }, cleanup);
497 * Expands an abbreviation in the currently active textbox.
499 * @param {string} mode The mode filter.
500 * @see Abbreviation#expand
502 expandAbbreviation: function (mode) {
506 let range = this.selectedRange.cloneRange();
507 if (!range.collapsed)
510 Editor.extendRange(range, false, /\S/, true);
511 let abbrev = abbreviations.match(mode, String(range));
513 range.setStart(range.startContainer, range.endOffset - abbrev.lhs.length);
514 this.selectedRange = range;
515 this.editor.insertText(abbrev.expand(this.element));
519 // nsIEditActionListener:
520 WillDeleteNode: util.wrapCallback(function WillDeleteNode(node) {
521 if (!editor.skipSave && node.textContent)
522 this.setRegister(0, node);
524 WillDeleteSelection: util.wrapCallback(function WillDeleteSelection(selection) {
525 if (!editor.skipSave && !selection.isCollapsed)
526 this.setRegister(0, selection);
528 WillDeleteText: util.wrapCallback(function WillDeleteText(node, start, length) {
529 if (!editor.skipSave && length)
530 this.setRegister(0, node.textContent.substr(start, length));
533 TextsIterator: Class("TextsIterator", {
534 init: function init(range, context, after) {
536 this.start = context || range[after ? "endContainer" : "startContainer"];
538 this.context = this.start;
542 __iterator__: function __iterator__() {
543 while (this.nextNode())
547 prevNode: function prevNode() {
549 return this.context = this.start;
551 var node = this.context;
553 node = node.previousSibling;
556 node = this.context.parentNode;
558 while (node.lastChild)
559 node = node.lastChild;
561 if (!node || !RangeFind.containsNode(this.range, node, true))
564 return this.context = node;
567 nextNode: function nextNode() {
569 return this.context = this.start;
572 var node = this.context.firstChild;
576 while (node.parentNode && node != this.range.endContainer
577 && !node.nextSibling)
578 node = node.parentNode;
580 node = node.nextSibling;
583 if (!node || !RangeFind.containsNode(this.range, node, true))
586 return this.context = node;
589 getPrev: function getPrev() {
590 return this.filter("prevNode");
593 getNext: function getNext() {
594 return this.filter("nextNode");
597 filter: function filter(meth) {
599 while (node = this[meth]())
600 if (node instanceof Ci.nsIDOMText &&
601 DOM(node).isVisible &&
602 DOM(node).style.MozUserSelect != "none")
607 extendRange: function extendRange(range, forward, re, sameWord, root, end) {
608 function advance(positive) {
610 while (idx == text.length && (node = iterator.getNext())) {
611 if (node == iterator.start)
615 text += node.textContent;
616 range[set](node, idx - start);
619 if (idx >= text.length || re.test(text[idx]) != positive)
621 range[set](range[container], ++idx - start);
624 function retreat(positive) {
626 while (idx == 0 && (node = iterator.getPrev())) {
627 let str = node.textContent;
628 if (node == iterator.start)
634 range[set](node, idx);
636 if (idx == 0 || re.test(text[idx - 1]) != positive)
638 range[set](range[container], --idx);
643 end = forward ? "end" : "start";
644 let [container, offset, set] = [end + "Container", end + "Offset",
645 "set" + util.capitalize(end)];
648 for (root = range[container];
649 root.parentNode instanceof Element && !DOM(root).isEditable;
650 root = root.parentNode)
652 if (root instanceof Ci.nsIDOMNSEditableElement)
654 if (root instanceof Ci.nsIEditor)
655 root = root.rootElement;
657 let node = range[container];
658 let iterator = Editor.TextsIterator(RangeFind.nodeContents(root),
678 getEditor: function (elem) {
679 if (arguments.length === 0) {
680 dactyl.assert(dactyl.focusedElement);
681 return dactyl.focusedElement;
685 elem = dactyl.focusedElement || document.commandDispatcher.focusedWindow;
688 return DOM(elem).editor;
691 modes: function init_modes() {
692 modes.addMode("OPERATOR", {
694 description: "Mappings which move the cursor",
697 modes.addMode("VISUAL", {
699 description: "Active when text is selected",
700 display: function () "VISUAL" + (this._extended & modes.LINE ? " LINE" : ""),
701 bases: [modes.COMMAND],
704 enter: function (stack) {
705 if (editor.selectionController)
706 editor.selectionController.setCaretVisibilityDuringSelection(true);
708 leave: function (stack, newMode) {
709 if (newMode.main == modes.CARET) {
710 let selection = content.getSelection();
711 if (selection && !selection.isCollapsed)
712 selection.collapseToStart();
718 modes.addMode("TEXT_EDIT", {
720 description: "Vim-like editing of input elements",
721 bases: [modes.COMMAND],
724 onKeyPress: function (eventList) {
725 const KILL = false, PASS = true;
728 if (eventList[0].charCode || /^<(?:.-)*(?:BS|Del|C-h|C-w|C-u|C-k)>$/.test(DOM.Event.stringify(eventList[0]))) {
736 modes.addMode("INSERT", {
738 description: "Active when an input element is focused",
742 modes.addMode("AUTOCOMPLETE", {
743 description: "Active when an input autocomplete pop-up is active",
744 display: function () "AUTOCOMPLETE (insert)",
745 bases: [modes.INSERT]
748 commands: function init_commands() {
749 commands.add(["reg[isters]"],
750 "List the contents of known registers",
752 completion.listCompleter("register", args[0]);
756 completion: function init_completion() {
757 completion.register = function complete_register(context) {
758 context = context.fork("registers");
759 context.keys = { text: util.identity, description: editor.closure.getRegister };
761 context.match = function (r) !this.filter || ~this.filter.indexOf(r);
763 context.fork("clipboard", 0, this, function (ctxt) {
764 ctxt.match = context.match;
765 ctxt.title = ["Clipboard Registers"];
766 ctxt.completions = Object.keys(editor.selectionRegisters);
768 context.fork("kill-ring", 0, this, function (ctxt) {
769 ctxt.match = context.match;
770 ctxt.title = ["Kill Ring Registers"];
771 ctxt.completions = Array.slice("0123456789");
773 context.fork("user", 0, this, function (ctxt) {
774 ctxt.match = context.match;
775 ctxt.title = ["User Defined Registers"];
776 ctxt.completions = editor.registers.keys();
780 mappings: function init_mappings() {
782 Map.types["editor"] = {
783 preExecute: function preExecute(args) {
784 if (editor.editor && !this.editor) {
785 this.editor = editor.editor;
786 if (!this.noTransaction)
787 this.editor.beginTransaction();
789 editor.inEditMap = true;
791 postExecute: function preExecute(args) {
792 editor.inEditMap = false;
794 if (!this.noTransaction)
795 this.editor.endTransaction();
800 Map.types["operator"] = {
801 preExecute: function preExecute(args) {
802 editor.inEditMap = true;
804 postExecute: function preExecute(args) {
805 editor.inEditMap = true;
806 if (modes.main == modes.OPERATOR)
811 // add mappings for commands like h,j,k,l,etc. in CARET, VISUAL and TEXT_EDIT mode
812 function addMovementMap(keys, description, hasCount, caretModeMethod, caretModeArg, textEditCommand, visualTextEditCommand) {
818 function caretExecute(arg) {
819 let win = document.commandDispatcher.focusedWindow;
820 let controller = util.selectionController(win);
821 let sel = controller.getSelection(controller.SELECTION_NORMAL);
823 let buffer = Buffer(win);
824 if (!sel.rangeCount) // Hack.
827 if (caretModeMethod == "pageMove") { // Grr.
828 buffer.scrollVertical("pages", caretModeArg ? 1 : -1);
832 controller[caretModeMethod](caretModeArg, arg);
835 mappings.add([modes.VISUAL], keys, description,
836 function ({ count }) {
839 let caret = !dactyl.focusedElement;
840 let controller = buffer.selectionController;
842 while (count-- && modes.main == modes.VISUAL) {
844 caretExecute(true, true);
846 if (callable(visualTextEditCommand))
847 visualTextEditCommand(editor.editor);
849 editor.executeCommand(visualTextEditCommand);
855 mappings.add([modes.CARET, modes.TEXT_EDIT, modes.OPERATOR], keys, description,
856 function ({ count }) {
860 editor.executeCommand(textEditCommand, count);
869 // add mappings for commands like i,a,s,c,etc. in TEXT_EDIT mode
870 function addBeginInsertModeMap(keys, commands, description) {
871 mappings.add([modes.TEXT_EDIT], keys, description || "",
873 commands.forEach(function (cmd) { editor.executeCommand(cmd, 1) });
874 modes.push(modes.INSERT);
879 function selectPreviousLine() {
880 editor.executeCommand("cmd_selectLinePrevious");
881 if ((modes.extended & modes.LINE) && !editor.selectedText)
882 editor.executeCommand("cmd_selectLinePrevious");
885 function selectNextLine() {
886 editor.executeCommand("cmd_selectLineNext");
887 if ((modes.extended & modes.LINE) && !editor.selectedText)
888 editor.executeCommand("cmd_selectLineNext");
891 function updateRange(editor, forward, re, modify, sameWord) {
892 let sel = editor.selection;
893 let range = sel.getRangeAt(0);
895 let end = range.endContainer == sel.focusNode && range.endOffset == sel.focusOffset;
899 Editor.extendRange(range, forward, re, sameWord,
900 editor.rootElement, end ? "end" : "start");
902 editor.selectionController.repaintSelection(editor.selectionController.SELECTION_NORMAL);
905 function clear(forward, re)
906 function _clear(editor) {
907 updateRange(editor, forward, re, function (range) {});
908 dactyl.assert(!editor.selection.isCollapsed);
909 editor.selection.deleteFromDocument();
910 let parent = DOM(editor.rootElement.parentNode);
915 function move(forward, re, sameWord)
916 function _move(editor) {
917 updateRange(editor, forward, re,
918 function (range) { range.collapse(!forward); },
921 function select(forward, re)
922 function _select(editor) {
923 updateRange(editor, forward, re,
924 function (range) {});
926 function beginLine(editor_) {
927 editor.executeCommand("cmd_beginLine");
928 move(true, /\s/, true)(editor_);
931 // COUNT CARET TEXT_EDIT VISUAL_TEXT_EDIT
932 addMovementMap(["k", "<Up>"], "Move up one line",
933 true, "lineMove", false, "cmd_linePrevious", selectPreviousLine);
934 addMovementMap(["j", "<Down>", "<Return>"], "Move down one line",
935 true, "lineMove", true, "cmd_lineNext", selectNextLine);
936 addMovementMap(["h", "<Left>", "<BS>"], "Move left one character",
937 true, "characterMove", false, "cmd_charPrevious", "cmd_selectCharPrevious");
938 addMovementMap(["l", "<Right>", "<Space>"], "Move right one character",
939 true, "characterMove", true, "cmd_charNext", "cmd_selectCharNext");
940 addMovementMap(["b", "<C-Left>"], "Move left one word",
941 true, "wordMove", false, move(false, /\w/), select(false, /\w/));
942 addMovementMap(["w", "<C-Right>"], "Move right one word",
943 true, "wordMove", true, move(true, /\w/), select(true, /\w/));
944 addMovementMap(["B"], "Move left to the previous white space",
945 true, "wordMove", false, move(false, /\S/), select(false, /\S/));
946 addMovementMap(["W"], "Move right to just beyond the next white space",
947 true, "wordMove", true, move(true, /\S/), select(true, /\S/));
948 addMovementMap(["e"], "Move to the end of the current word",
949 true, "wordMove", true, move(true, /\W/), select(true, /\W/));
950 addMovementMap(["E"], "Move right to the next white space",
951 true, "wordMove", true, move(true, /\s/), select(true, /\s/));
952 addMovementMap(["<C-f>", "<PageDown>"], "Move down one page",
953 true, "pageMove", true, "cmd_movePageDown", "cmd_selectNextPage");
954 addMovementMap(["<C-b>", "<PageUp>"], "Move up one page",
955 true, "pageMove", false, "cmd_movePageUp", "cmd_selectPreviousPage");
956 addMovementMap(["gg", "<C-Home>"], "Move to the start of text",
957 false, "completeMove", false, "cmd_moveTop", "cmd_selectTop");
958 addMovementMap(["G", "<C-End>"], "Move to the end of text",
959 false, "completeMove", true, "cmd_moveBottom", "cmd_selectBottom");
960 addMovementMap(["0", "<Home>"], "Move to the beginning of the line",
961 false, "intraLineMove", false, "cmd_beginLine", "cmd_selectBeginLine");
962 addMovementMap(["^"], "Move to the first non-whitespace character of the line",
963 false, "intraLineMove", false, beginLine, "cmd_selectBeginLine");
964 addMovementMap(["$", "<End>"], "Move to the end of the current line",
965 false, "intraLineMove", true, "cmd_endLine" , "cmd_selectEndLine");
967 addBeginInsertModeMap(["i", "<Insert>"], [], "Insert text before the cursor");
968 addBeginInsertModeMap(["a"], ["cmd_charNext"], "Append text after the cursor");
969 addBeginInsertModeMap(["I"], ["cmd_beginLine"], "Insert text at the beginning of the line");
970 addBeginInsertModeMap(["A"], ["cmd_endLine"], "Append text at the end of the line");
971 addBeginInsertModeMap(["s"], ["cmd_deleteCharForward"], "Delete the character in front of the cursor and start insert");
972 addBeginInsertModeMap(["S"], ["cmd_deleteToEndOfLine", "cmd_deleteToBeginningOfLine"], "Delete the current line and start insert");
973 addBeginInsertModeMap(["C"], ["cmd_deleteToEndOfLine"], "Delete from the cursor to the end of the line and start insert");
975 function addMotionMap(key, desc, select, cmd, mode, caretOk) {
976 function doTxn(range, editor) {
978 editor.editor.beginTransaction();
979 cmd(editor, range, editor.editor);
982 editor.editor.endTransaction();
986 mappings.add([modes.TEXT_EDIT], key,
988 function ({ command, count, motion }) {
989 let start = editor.selectedRange.cloneRange();
991 mappings.pushCommand();
992 modes.push(modes.OPERATOR, null, {
997 leave: function leave(stack) {
999 if (stack.push || stack.fromEscape)
1002 editor.withSavedValues(["inEditMap"], function () {
1003 this.inEditMap = true;
1005 let range = RangeFind.union(start, editor.selectedRange);
1006 editor.selectedRange = select ? range : start;
1007 doTxn(range, editor);
1010 editor.currentRegister = null;
1011 modes.delay(function () {
1018 mappings.popCommand();
1023 { count: true, type: "motion" });
1025 mappings.add([modes.VISUAL], key,
1027 function ({ count, motion }) {
1028 dactyl.assert(caretOk || editor.isTextEdit);
1029 if (editor.isTextEdit)
1030 doTxn(editor.selectedRange, editor);
1032 cmd(editor, buffer.selection.getRangeAt(0));
1034 { count: true, type: "motion" });
1037 addMotionMap(["d", "x"], "Delete text", true, function (editor) { editor.cut(); });
1038 addMotionMap(["c"], "Change text", true, function (editor) { editor.cut(); }, modes.INSERT);
1039 addMotionMap(["y"], "Yank text", false, function (editor, range) { editor.copy(range); }, null, true);
1041 addMotionMap(["gu"], "Lowercase text", false,
1042 function (editor, range) {
1043 editor.mungeRange(range, String.toLocaleLowerCase);
1046 addMotionMap(["gU"], "Uppercase text", false,
1047 function (editor, range) {
1048 editor.mungeRange(range, String.toLocaleUpperCase);
1051 mappings.add([modes.OPERATOR],
1052 ["c", "d", "y"], "Select the entire line",
1053 function ({ command, count }) {
1054 dactyl.assert(command == modes.getStack(0).params.forCommand);
1056 let sel = editor.selection;
1057 sel.modify("move", "backward", "lineboundary");
1058 sel.modify("extend", "forward", "lineboundary");
1061 sel.modify("extend", "forward", "character");
1063 { count: true, type: "operator" });
1065 let bind = function bind(names, description, action, params)
1066 mappings.add([modes.INPUT], names, description,
1067 action, update({ type: "editor" }, params));
1069 bind(["<C-w>"], "Delete previous word",
1072 clear(false, /\w/)(editor.editor);
1074 editor.executeCommand("cmd_deleteWordBackward", 1);
1077 bind(["<C-u>"], "Delete until beginning of current line",
1079 // Deletes the whole line. What the hell.
1080 // editor.executeCommand("cmd_deleteToBeginningOfLine", 1);
1082 editor.executeCommand("cmd_selectBeginLine", 1);
1083 if (editor.selection && editor.selection.isCollapsed) {
1084 editor.executeCommand("cmd_deleteCharBackward", 1);
1085 editor.executeCommand("cmd_selectBeginLine", 1);
1088 if (editor.getController("cmd_delete").isCommandEnabled("cmd_delete"))
1089 editor.executeCommand("cmd_delete", 1);
1092 bind(["<C-k>"], "Delete until end of current line",
1093 function () { editor.executeCommand("cmd_deleteToEndOfLine", 1); });
1095 bind(["<C-a>"], "Move cursor to beginning of current line",
1096 function () { editor.executeCommand("cmd_beginLine", 1); });
1098 bind(["<C-e>"], "Move cursor to end of current line",
1099 function () { editor.executeCommand("cmd_endLine", 1); });
1101 bind(["<C-h>"], "Delete character to the left",
1102 function () { events.feedkeys("<BS>", true); });
1104 bind(["<C-d>"], "Delete character to the right",
1105 function () { editor.executeCommand("cmd_deleteCharForward", 1); });
1107 bind(["<S-Insert>"], "Insert clipboard/selection",
1108 function () { editor.paste(); });
1110 bind(["<C-i>"], "Edit text field with an external editor",
1111 function () { editor.editFieldExternally(); });
1113 bind(["<C-t>"], "Edit text field in Text Edit mode",
1115 dactyl.assert(!editor.isTextEdit && editor.editor);
1116 dactyl.assert(dactyl.focusedElement ||
1117 // Sites like Google like to use a
1118 // hidden, editable window for keyboard
1119 // focus and use their own WYSIWYG editor
1120 // implementations for the visible area,
1121 // which we can't handle.
1122 let (f = document.commandDispatcher.focusedWindow.frameElement)
1123 f && Hints.isVisible(f, true));
1125 modes.push(modes.TEXT_EDIT);
1129 mappings.add([modes.INPUT, modes.CARET],
1130 ["<*-CR>", "<*-BS>", "<*-Del>", "<*-Left>", "<*-Right>", "<*-Up>", "<*-Down>",
1131 "<*-Home>", "<*-End>", "<*-PageUp>", "<*-PageDown>",
1132 "<M-c>", "<M-v>", "<*-Tab>"],
1133 "Handled by " + config.host,
1134 function () Events.PASS_THROUGH);
1136 mappings.add([modes.INSERT],
1137 ["<Space>", "<Return>"], "Expand Insert mode abbreviation",
1139 editor.expandAbbreviation(modes.INSERT);
1140 return Events.PASS_THROUGH;
1143 mappings.add([modes.INSERT],
1144 ["<C-]>", "<C-5>"], "Expand Insert mode abbreviation",
1145 function () { editor.expandAbbreviation(modes.INSERT); });
1147 let bind = function bind(names, description, action, params)
1148 mappings.add([modes.TEXT_EDIT], names, description,
1149 action, update({ type: "editor" }, params));
1152 bind(["<C-a>"], "Increment the next number",
1153 function ({ count }) { editor.modifyNumber(count || 1) },
1156 bind(["<C-x>"], "Decrement the next number",
1157 function ({ count }) { editor.modifyNumber(-(count || 1)) },
1161 bind(["u"], "Undo changes",
1163 editor.editor.undo(Math.max(args.count, 1));
1166 { count: true, noTransaction: true });
1168 bind(["<C-r>"], "Redo undone changes",
1170 editor.editor.redo(Math.max(args.count, 1));
1173 { count: true, noTransaction: true });
1175 bind(["D"], "Delete characters from the cursor to the end of the line",
1176 function () { editor.executeCommand("cmd_deleteToEndOfLine"); });
1178 bind(["o"], "Open line below current",
1180 editor.executeCommand("cmd_endLine", 1);
1181 modes.push(modes.INSERT);
1182 events.feedkeys("<Return>");
1185 bind(["O"], "Open line above current",
1187 editor.executeCommand("cmd_beginLine", 1);
1188 modes.push(modes.INSERT);
1189 events.feedkeys("<Return>");
1190 editor.executeCommand("cmd_linePrevious", 1);
1193 bind(["X"], "Delete character to the left",
1194 function (args) { editor.executeCommand("cmd_deleteCharBackward", Math.max(args.count, 1)); },
1197 bind(["x"], "Delete character to the right",
1198 function (args) { editor.executeCommand("cmd_deleteCharForward", Math.max(args.count, 1)); },
1202 mappings.add([modes.CARET, modes.TEXT_EDIT],
1203 ["v"], "Start Visual mode",
1204 function () { modes.push(modes.VISUAL); });
1206 mappings.add([modes.VISUAL],
1207 ["v", "V"], "End Visual mode",
1208 function () { modes.pop(); });
1210 bind(["V"], "Start Visual Line mode",
1212 modes.push(modes.VISUAL, modes.LINE);
1213 editor.executeCommand("cmd_beginLine", 1);
1214 editor.executeCommand("cmd_selectLineNext", 1);
1217 mappings.add([modes.VISUAL],
1218 ["s"], "Change selected text",
1220 dactyl.assert(editor.isTextEdit);
1221 editor.executeCommand("cmd_cut");
1222 modes.push(modes.INSERT);
1225 mappings.add([modes.VISUAL],
1226 ["o"], "Move cursor to the other end of the selection",
1228 if (editor.isTextEdit)
1229 var selection = editor.selection;
1231 selection = buffer.focusedFrame.getSelection();
1233 util.assert(selection.focusNode);
1234 let { focusOffset, anchorOffset, focusNode, anchorNode } = selection;
1235 selection.collapse(focusNode, focusOffset);
1236 selection.extend(anchorNode, anchorOffset);
1239 bind(["p"], "Paste clipboard contents",
1240 function ({ count }) {
1241 dactyl.assert(!editor.isCaret);
1242 editor.executeCommand(modules.bind("paste", editor, null),
1247 mappings.add([modes.COMMAND],
1248 ['"'], "Bind a register to the next command",
1249 function ({ arg }) {
1250 editor.pushRegister(arg);
1254 mappings.add([modes.INPUT],
1255 ["<C-'>", '<C-">'], "Bind a register to the next command",
1256 function ({ arg }) {
1257 editor.pushRegister(arg);
1261 let bind = function bind(names, description, action, params)
1262 mappings.add([modes.TEXT_EDIT, modes.OPERATOR, modes.VISUAL],
1264 action, update({ type: "editor" }, params));
1266 // finding characters
1267 function offset(backward, before, pos) {
1268 if (!backward && modes.main != modes.TEXT_EDIT)
1269 return before ? 0 : 1;
1271 return backward ? +1 : -1;
1275 bind(["f"], "Find a character on the current line, forwards",
1276 function ({ arg, count }) {
1277 editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), false,
1278 offset(false, false)),
1279 modes.main == modes.VISUAL);
1281 { arg: true, count: true, type: "operator" });
1283 bind(["F"], "Find a character on the current line, backwards",
1284 function ({ arg, count }) {
1285 editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), true,
1286 offset(true, false)),
1287 modes.main == modes.VISUAL);
1289 { arg: true, count: true, type: "operator" });
1291 bind(["t"], "Find a character on the current line, forwards, and move to the character before it",
1292 function ({ arg, count }) {
1293 editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), false,
1294 offset(false, true)),
1295 modes.main == modes.VISUAL);
1297 { arg: true, count: true, type: "operator" });
1299 bind(["T"], "Find a character on the current line, backwards, and move to the character after it",
1300 function ({ arg, count }) {
1301 editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), true,
1302 offset(true, true)),
1303 modes.main == modes.VISUAL);
1305 { arg: true, count: true, type: "operator" });
1307 // text edit and visual mode
1308 mappings.add([modes.TEXT_EDIT, modes.VISUAL],
1309 ["~"], "Switch case of the character under the cursor and move the cursor to the right",
1310 function ({ count }) {
1311 function munger(range)
1312 String(range).replace(/./g, function (c) {
1313 let lc = c.toLocaleLowerCase();
1314 return c == lc ? c.toLocaleUpperCase() : lc;
1317 var range = editor.selectedRange;
1318 if (range.collapsed) {
1320 Editor.extendRange(range, true, { test: function (c) !!count-- }, true);
1322 editor.mungeRange(range, munger, count != null);
1324 modes.pop(modes.TEXT_EDIT);
1328 let bind = function bind() mappings.add.apply(mappings,
1329 [[modes.AUTOCOMPLETE]].concat(Array.slice(arguments)))
1331 bind(["<Esc>"], "Return to Insert mode",
1332 function () Events.PASS_THROUGH);
1334 bind(["<C-[>"], "Return to Insert mode",
1335 function () { events.feedkeys("<Esc>", { skipmap: true }); });
1337 bind(["<Up>"], "Select the previous autocomplete result",
1338 function () Events.PASS_THROUGH);
1340 bind(["<C-p>"], "Select the previous autocomplete result",
1341 function () { events.feedkeys("<Up>", { skipmap: true }); });
1343 bind(["<Down>"], "Select the next autocomplete result",
1344 function () Events.PASS_THROUGH);
1346 bind(["<C-n>"], "Select the next autocomplete result",
1347 function () { events.feedkeys("<Down>", { skipmap: true }); });
1349 options: function init_options() {
1350 options.add(["editor"],
1351 "The external text editor",
1352 "string", 'gvim -f +<line> +"sil! call cursor(0, <column>)" <file>', {
1353 format: function (obj, value) {
1354 let args = commands.parseArgs(value || this.value, { argCount: "*", allowUnknownOptions: true })
1355 .map(util.compileMacro).filter(function (fmt) fmt.valid(obj))
1356 .map(function (fmt) fmt(obj));
1357 if (obj["file"] && !this.has("file"))
1358 args.push(obj["file"]);
1361 has: function (key) Set.has(util.compileMacro(this.value).seen, key),
1362 validator: function (value) {
1363 this.format({}, value);
1364 return Object.keys(util.compileMacro(value).seen).every(function (k) ["column", "file", "line"].indexOf(k) >= 0);
1368 options.add(["insertmode", "im"],
1369 "Enter Insert mode rather than Text Edit mode when focusing text areas",
1372 options.add(["spelllang", "spl"],
1373 "The language used by the spell checker",
1374 "string", config.locale,
1376 initValue: function () {},
1377 getter: function getter() {
1379 return services.spell.dictionary || "";
1385 setter: function setter(val) { services.spell.dictionary = val; },
1386 completer: function completer(context) {
1388 services.spell.getDictionaryList(res, {});
1389 context.completions = res.value;
1390 context.keys = { text: util.identity, description: util.identity };
1394 sanitizer: function () {
1395 sanitizer.addItem("registers", {
1396 description: "Register values",
1398 action: function (timespan, host) {
1400 for (let [k, v] in editor.registers)
1401 if (timespan.contains(v.timestamp))
1402 editor.registers.remove(k);
1403 editor.registerRing.truncate(0);
1410 // vim: set fdm=marker sw=4 ts=4 et: