]> git.donarmstrong.com Git - dactyl.git/blob - common/content/editor.js
Import 1.0rc1 supporting Firefox up to 11.*
[dactyl.git] / common / content / editor.js
1 // Copyright (c) 2008-2011 Kris Maglione <maglione.k at Gmail>
2 // Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
3 //
4 // This work is licensed for reuse under an MIT license. Details are
5 // given in the LICENSE.txt file included with this file.
6 /* use strict */
7
8 /** @scope modules */
9
10 // command names taken from:
11 // http://developer.mozilla.org/en/docs/Editor_Embedding_Guide
12
13 /** @instance editor */
14 var Editor = Module("editor", XPCOM(Ci.nsIEditActionListener, ModuleBase), {
15     init: function init(elem) {
16         if (elem)
17             this.element = elem;
18         else
19             this.__defineGetter__("element", function () {
20                 let elem = dactyl.focusedElement;
21                 if (elem)
22                     return elem.inputField || elem;
23
24                 let win = document.commandDispatcher.focusedWindow;
25                 return DOM(win).isEditable && win || null;
26             });
27     },
28
29     get registers() storage.newMap("registers", { privateData: true, store: true }),
30     get registerRing() storage.newArray("register-ring", { privateData: true, store: true }),
31
32     skipSave: false,
33
34     // Fixme: Move off this object.
35     currentRegister: null,
36
37     /**
38      * Temporarily set the default register for the span of the next
39      * mapping.
40      */
41     pushRegister: function pushRegister(arg) {
42         let restore = this.currentRegister;
43         this.currentRegister = arg;
44         mappings.afterCommands(2, function () {
45             this.currentRegister = restore;
46         }, this);
47     },
48
49     defaultRegister: "*",
50
51     selectionRegisters: {
52         "*": "selection",
53         "+": "global"
54     },
55
56     /**
57      * Get the value of the register *name*.
58      *
59      * @param {string|number} name The name of the register to get.
60      * @returns {string|null}
61      * @see #setRegister
62      */
63     getRegister: function getRegister(name) {
64         if (name == null)
65             name = editor.currentRegister || editor.defaultRegister;
66
67         if (name == '"')
68             name = 0;
69         if (name == "_")
70             var res = null;
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);
75         else
76             res = this.registerRing.get(name);
77
78         return res != null ? res.text : res;
79     },
80
81     /**
82      * Sets the value of register *name* to value. The following
83      * registers have special semantics:
84      *
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.
91      *
92      * @param {string|number} name The name of the register to set.
93      * @param {string|Range|Selection|Node} value The value to save to
94      *      the register.
95      */
96     setRegister: function setRegister(name, value, verbose) {
97         if (name == null)
98             name = editor.currentRegister || editor.defaultRegister;
99
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 };
103
104         if (name == '"')
105             name = 0;
106         if (name == "_")
107             ;
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);
112         else {
113             this.registerRing.insert(value, name);
114             this.registerRing.truncate(10);
115         }
116     },
117
118     get isCaret() modes.getStack(1).main == modes.CARET,
119     get isTextEdit() modes.getStack(1).main == modes.TEXT_EDIT,
120
121     get editor() DOM(this.element).editor,
122
123     getController: function getController(cmd) {
124         let controllers = this.element && this.element.controllers;
125         dactyl.assert(controllers);
126
127         return controllers.getControllerForCommand(cmd || "cmd_beginLine");
128     },
129
130     get selection() this.editor && this.editor.selection || null,
131     get selectionController() this.editor && this.editor.selectionController || null,
132
133     deselect: function () {
134         if (this.selection && this.selection.focusNode)
135             this.selection.collapse(this.selection.focusNode,
136                                     this.selection.focusOffset);
137     },
138
139     get selectedRange() {
140         if (!this.selection)
141             return null;
142
143         if (!this.selection.rangeCount) {
144             let range = RangeFind.nodeContents(this.editor.rootElement.ownerDocument);
145             range.collapse(true);
146             this.selectedRange = range;
147         }
148         return this.selection.getRangeAt(0);
149     },
150     set selectedRange(range) {
151         this.selection.removeAllRanges();
152         if (range != null)
153             this.selection.addRange(range);
154     },
155
156     get selectedText() String(this.selection),
157
158     get preserveSelection() this.editor && !this.editor.shouldTxnSetSelection,
159     set preserveSelection(val) {
160         if (this.editor)
161             this.editor.setShouldTxnSetSelection(!val);
162     },
163
164     copy: function copy(range, name) {
165         range = range || this.selection;
166
167         if (!range.collapsed)
168             this.setRegister(name, range);
169     },
170
171     cut: function cut(range, name) {
172         if (range)
173             this.selectedRange = range;
174
175         if (!this.selection.isCollapsed)
176             this.setRegister(name, this.selection);
177
178         this.editor.deleteSelection(0);
179     },
180
181     paste: function paste(name) {
182         let text = this.getRegister(name);
183         dactyl.assert(text && this.editor instanceof Ci.nsIPlaintextEditor);
184
185         this.editor.insertText(text);
186     },
187
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);
196         }
197
198         // XXX: better as a precondition
199         if (count == null)
200             count = 1;
201
202         let didCommand = false;
203         while (count--) {
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
207
208             // What huh? --Kris
209             try {
210                 cmd(this.editor, controller);
211                 didCommand = true;
212             }
213             catch (e) {
214                 util.reportError(e);
215                 dactyl.assert(didCommand);
216                 break;
217             }
218         }
219     },
220
221     moveToPosition: function (pos, select) {
222         if (isObject(pos))
223             var { startContainer, startOffset } = pos;
224         else
225             [startOffset, startOffset] = [this.selection.focusNode, pos];
226         this.selection[select ? "extend" : "collapse"](startContainer, startOffset);
227     },
228
229     mungeRange: function mungeRange(range, munger, selectEnd) {
230         let { editor } = this;
231         editor.beginPlaceHolderTransaction(null);
232
233         let [container, offset] = ["startContainer", "startOffset"];
234         if (selectEnd)
235             [container, offset] = ["endContainer", "endOffset"];
236
237         try {
238             // :(
239             let idx = range[offset];
240             let parent = range[container].parentNode;
241             let parentIdx = Array.indexOf(parent.childNodes,
242                                           range[container]);
243
244             let delta = 0;
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;
252
253                 if (start == 0 && end == text.length)
254                     text = munger(text);
255                 else
256                     text = text.slice(0, start)
257                          + munger(text.slice(start, end))
258                          + text.slice(end);
259
260                 if (text == node.textContent)
261                     continue;
262
263                 if (selectEnd)
264                     delta = text.length - node.textContent.length;
265
266                 if (editor instanceof Ci.nsIPlaintextEditor) {
267                     this.selectedRange = RangeFind.nodeContents(node);
268                     editor.insertText(text);
269                 }
270                 else
271                     node.textContent = text;
272             }
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);
277         }
278         finally {
279             editor.endPlaceHolderTransaction();
280         }
281     },
282
283     findChar: function findNumber(key, count, backward, offset) {
284         count  = count || 1; // XXX ?
285         offset = (offset || 0) - !!backward;
286
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);
291         util.assert(code);
292
293         let range = this.selectedRange.cloneRange();
294         let collapse = DOM(this.element).whiteSpace == "normal";
295
296         // Find the *count*th occurance of *char* before a non-collapsed
297         // \n, ignoring the character at the caret.
298         let i = 0;
299         function test(c) (collapse || c != "\n") && !!(!i++ || c != char || --count)
300
301         Editor.extendRange(range, !backward, { test: test }, true);
302         dactyl.assert(count == 0);
303         range.collapse(backward);
304
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);
309
310         return range;
311     },
312
313     findNumber: function findNumber(range) {
314         if (!range)
315             range = this.selectedRange.cloneRange();
316
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);
323
324         // Sanity check.
325         dactyl.assert(/^\d+$/.test(range));
326
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);
331         }
332
333         // Grab the sign, if it's there.
334         Editor.extendRange(range, false, /[+-]/, true);
335
336         return range;
337     },
338
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");
346
347         this.selectedRange = range;
348         this.editor.insertText(String(number));
349         this.selection.modify("move", "backward", "character");
350     },
351
352     /**
353      * Edits the given file in the external editor as specified by the
354      * 'editor' option.
355      *
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.
361      */
362     editFileExternally: function (args, blocking) {
363         if (!isObject(args) || args instanceof File)
364             args = { file: args };
365         args.file = args.file.path || args.file;
366
367         let args = options.get("editor").format(args);
368
369         dactyl.assert(args.length >= 1, _("option.notSet", "editor"));
370
371         io.run(args.shift(), args, blocking);
372     },
373
374     // TODO: clean up with 2 functions for textboxes and currentEditor?
375     editFieldExternally: function editFieldExternally(forceEditing) {
376         if (!options["editor"])
377             return;
378
379         let textBox = config.isComposeWindow ? null : dactyl.focusedElement;
380         if (!DOM(textBox).isInput)
381             textBox = null;
382
383         let line, column;
384         let keepFocus = modes.stack.some(function (m) isinstance(m.main, modes.COMMAND_LINE));
385
386         if (!forceEditing && textBox && textBox.type == "password") {
387             commandline.input(_("editor.prompt.editPassword") + " ",
388                 function (resp) {
389                     if (resp && resp.match(/^y(es)?$/i))
390                         editor.editFieldExternally(true);
391                 });
392                 return;
393         }
394
395         if (textBox) {
396             var text = textBox.value;
397             var pre = text.substr(0, textBox.selectionStart);
398         }
399         else {
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("");
404
405             if (!editor_.selection.rangeCount)
406                 var sel = "";
407             else {
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(/(?:<\/[^>"]+>)+$/, "");
416             }
417         }
418
419         line = 1 + pre.replace(/[^\n]/g, "").length;
420         column = 1 + pre.replace(/[^]*\n/, "").length;
421
422         let origGroup = DOM(textBox).highlight.toString();
423         let cleanup = util.yieldable(function cleanup(error) {
424             if (timer)
425                 timer.cancel();
426
427             let blink = ["EditorBlink1", "EditorBlink2"];
428             if (error) {
429                 dactyl.reportError(error, true);
430                 blink[1] = "EditorError";
431             }
432             else
433                 dactyl.trapErrors(update, null, true);
434
435             if (tmpfile && tmpfile.exists())
436                 tmpfile.remove(false);
437
438             if (textBox) {
439                 DOM(textBox).highlight.remove("EditorEditing");
440                 if (!keepFocus)
441                     dactyl.focus(textBox);
442                 for (let group in values(blink.concat(blink, ""))) {
443                     highlight.highlightNode(textBox, origGroup + " " + group);
444                     yield 100;
445                 }
446             }
447         });
448
449         function update(force) {
450             if (force !== true && tmpfile.lastModifiedTime <= lastUpdate)
451                 return;
452             lastUpdate = Date.now();
453
454             let val = tmpfile.read();
455             if (textBox) {
456                 textBox.value = val;
457
458                 if (false) {
459                     let elem = DOM(textBox);
460                     elem.attrNS(NS, "modifiable", true)
461                         .style.MozUserInput;
462                     elem.input().attrNS(NS, "modifiable", null);
463                 }
464             }
465             else {
466                 while (editor_.rootElement.firstChild)
467                     editor_.rootElement.removeChild(editor_.rootElement.firstChild);
468                 editor_.rootElement.innerHTML = val;
469             }
470         }
471
472         try {
473             var tmpfile = io.createTempFile();
474             if (!tmpfile)
475                 throw Error(_("io.cantCreateTempFile"));
476
477             if (textBox) {
478                 if (!keepFocus)
479                     textBox.blur();
480                 DOM(textBox).highlight.add("EditorEditing");
481             }
482
483             if (!tmpfile.write(text))
484                 throw Error(_("io.cantEncode"));
485
486             var lastUpdate = Date.now();
487
488             var timer = services.Timer(update, 100, services.Timer.TYPE_REPEATING_SLACK);
489             this.editFileExternally({ file: tmpfile.path, line: line, column: column }, cleanup);
490         }
491         catch (e) {
492             cleanup(e);
493         }
494     },
495
496     /**
497      * Expands an abbreviation in the currently active textbox.
498      *
499      * @param {string} mode The mode filter.
500      * @see Abbreviation#expand
501      */
502     expandAbbreviation: function (mode) {
503         if (!this.selection)
504             return;
505
506         let range = this.selectedRange.cloneRange();
507         if (!range.collapsed)
508             return;
509
510         Editor.extendRange(range, false, /\S/, true);
511         let abbrev = abbreviations.match(mode, String(range));
512         if (abbrev) {
513             range.setStart(range.startContainer, range.endOffset - abbrev.lhs.length);
514             this.selectedRange = range;
515             this.editor.insertText(abbrev.expand(this.element));
516         }
517     },
518
519     // nsIEditActionListener:
520     WillDeleteNode: util.wrapCallback(function WillDeleteNode(node) {
521         if (!editor.skipSave && node.textContent)
522             this.setRegister(0, node);
523     }),
524     WillDeleteSelection: util.wrapCallback(function WillDeleteSelection(selection) {
525         if (!editor.skipSave && !selection.isCollapsed)
526             this.setRegister(0, selection);
527     }),
528     WillDeleteText: util.wrapCallback(function WillDeleteText(node, start, length) {
529         if (!editor.skipSave && length)
530             this.setRegister(0, node.textContent.substr(start, length));
531     })
532 }, {
533     TextsIterator: Class("TextsIterator", {
534         init: function init(range, context, after) {
535             this.after = after;
536             this.start = context || range[after ? "endContainer" : "startContainer"];
537             if (after)
538                 this.context = this.start;
539             this.range = range;
540         },
541
542         __iterator__: function __iterator__() {
543             while (this.nextNode())
544                 yield this.context;
545         },
546
547         prevNode: function prevNode() {
548             if (!this.context)
549                 return this.context = this.start;
550
551             var node = this.context;
552             if (!this.after)
553                 node = node.previousSibling;
554
555             if (!node)
556                 node = this.context.parentNode;
557             else
558                 while (node.lastChild)
559                     node = node.lastChild;
560
561             if (!node || !RangeFind.containsNode(this.range, node, true))
562                 return null;
563             this.after = false;
564             return this.context = node;
565         },
566
567         nextNode: function nextNode() {
568             if (!this.context)
569                 return this.context = this.start;
570
571             if (!this.after)
572                 var node = this.context.firstChild;
573
574             if (!node) {
575                 node = this.context;
576                 while (node.parentNode && node != this.range.endContainer
577                         && !node.nextSibling)
578                     node = node.parentNode;
579
580                 node = node.nextSibling;
581             }
582
583             if (!node || !RangeFind.containsNode(this.range, node, true))
584                 return null;
585             this.after = false;
586             return this.context = node;
587         },
588
589         getPrev: function getPrev() {
590             return this.filter("prevNode");
591         },
592
593         getNext: function getNext() {
594             return this.filter("nextNode");
595         },
596
597         filter: function filter(meth) {
598             let node;
599             while (node = this[meth]())
600                 if (node instanceof Ci.nsIDOMText &&
601                         DOM(node).isVisible &&
602                         DOM(node).style.MozUserSelect != "none")
603                     return node;
604         }
605     }),
606
607     extendRange: function extendRange(range, forward, re, sameWord, root, end) {
608         function advance(positive) {
609             while (true) {
610                 while (idx == text.length && (node = iterator.getNext())) {
611                     if (node == iterator.start)
612                         idx = range[offset];
613
614                     start = text.length;
615                     text += node.textContent;
616                     range[set](node, idx - start);
617                 }
618
619                 if (idx >= text.length || re.test(text[idx]) != positive)
620                     break;
621                 range[set](range[container], ++idx - start);
622             }
623         }
624         function retreat(positive) {
625             while (true) {
626                 while (idx == 0 && (node = iterator.getPrev())) {
627                     let str = node.textContent;
628                     if (node == iterator.start)
629                         idx = range[offset];
630                     else
631                         idx = str.length;
632
633                     text = str + text;
634                     range[set](node, idx);
635                 }
636                 if (idx == 0 || re.test(text[idx - 1]) != positive)
637                     break;
638                 range[set](range[container], --idx);
639             }
640         }
641
642         if (end == null)
643             end = forward ? "end" : "start";
644         let [container, offset, set] = [end + "Container", end + "Offset",
645                                         "set" + util.capitalize(end)];
646
647         if (!root)
648             for (root = range[container];
649                  root.parentNode instanceof Element && !DOM(root).isEditable;
650                  root = root.parentNode)
651                 ;
652         if (root instanceof Ci.nsIDOMNSEditableElement)
653             root = root.editor;
654         if (root instanceof Ci.nsIEditor)
655             root = root.rootElement;
656
657         let node = range[container];
658         let iterator = Editor.TextsIterator(RangeFind.nodeContents(root),
659                                             node, !forward);
660
661         let text = "";
662         let idx  = 0;
663         let start = 0;
664
665         if (forward) {
666             advance(true);
667             if (!sameWord)
668                 advance(false);
669         }
670         else {
671             if (!sameWord)
672                 retreat(false);
673             retreat(true);
674         }
675         return range;
676     },
677
678     getEditor: function (elem) {
679         if (arguments.length === 0) {
680             dactyl.assert(dactyl.focusedElement);
681             return dactyl.focusedElement;
682         }
683
684         if (!elem)
685             elem = dactyl.focusedElement || document.commandDispatcher.focusedWindow;
686         dactyl.assert(elem);
687
688         return DOM(elem).editor;
689     }
690 }, {
691     modes: function init_modes() {
692         modes.addMode("OPERATOR", {
693             char: "o",
694             description: "Mappings which move the cursor",
695             bases: []
696         });
697         modes.addMode("VISUAL", {
698             char: "v",
699             description: "Active when text is selected",
700             display: function () "VISUAL" + (this._extended & modes.LINE ? " LINE" : ""),
701             bases: [modes.COMMAND],
702             ownsFocus: true
703         }, {
704             enter: function (stack) {
705                 if (editor.selectionController)
706                     editor.selectionController.setCaretVisibilityDuringSelection(true);
707             },
708             leave: function (stack, newMode) {
709                 if (newMode.main == modes.CARET) {
710                     let selection = content.getSelection();
711                     if (selection && !selection.isCollapsed)
712                         selection.collapseToStart();
713                 }
714                 else if (stack.pop)
715                     editor.deselect();
716             }
717         });
718         modes.addMode("TEXT_EDIT", {
719             char: "t",
720             description: "Vim-like editing of input elements",
721             bases: [modes.COMMAND],
722             ownsFocus: true
723         }, {
724             onKeyPress: function (eventList) {
725                 const KILL = false, PASS = true;
726
727                 // Hack, really.
728                 if (eventList[0].charCode || /^<(?:.-)*(?:BS|Del|C-h|C-w|C-u|C-k)>$/.test(DOM.Event.stringify(eventList[0]))) {
729                     dactyl.beep();
730                     return KILL;
731                 }
732                 return PASS;
733             }
734         });
735
736         modes.addMode("INSERT", {
737             char: "i",
738             description: "Active when an input element is focused",
739             insert: true,
740             ownsFocus: true
741         });
742         modes.addMode("AUTOCOMPLETE", {
743             description: "Active when an input autocomplete pop-up is active",
744             display: function () "AUTOCOMPLETE (insert)",
745             bases: [modes.INSERT]
746         });
747     },
748     commands: function init_commands() {
749         commands.add(["reg[isters]"],
750             "List the contents of known registers",
751             function (args) {
752                 completion.listCompleter("register", args[0]);
753             },
754             { argCount: "*" });
755     },
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 };
760
761             context.match = function (r) !this.filter || ~this.filter.indexOf(r);
762
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);
767             });
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");
772             });
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();
777             });
778         };
779     },
780     mappings: function init_mappings() {
781
782         Map.types["editor"] = {
783             preExecute: function preExecute(args) {
784                 if (editor.editor && !this.editor) {
785                     this.editor = editor.editor;
786                     this.editor.beginTransaction();
787                 }
788                 editor.inEditMap = true;
789             },
790             postExecute: function preExecute(args) {
791                 editor.inEditMap = false;
792                 if (this.editor) {
793                     this.editor.endTransaction();
794                     this.editor = null;
795                 }
796             },
797         };
798         Map.types["operator"] = {
799             preExecute: function preExecute(args) {
800                 editor.inEditMap = true;
801             },
802             postExecute: function preExecute(args) {
803                 editor.inEditMap = true;
804                 if (modes.main == modes.OPERATOR)
805                     modes.pop();
806             }
807         };
808
809         // add mappings for commands like h,j,k,l,etc. in CARET, VISUAL and TEXT_EDIT mode
810         function addMovementMap(keys, description, hasCount, caretModeMethod, caretModeArg, textEditCommand, visualTextEditCommand) {
811             let extraInfo = {
812                 count: !!hasCount,
813                 type: "operator"
814             };
815
816             function caretExecute(arg) {
817                 let win = document.commandDispatcher.focusedWindow;
818                 let controller = util.selectionController(win);
819                 let sel = controller.getSelection(controller.SELECTION_NORMAL);
820
821                 let buffer = Buffer(win);
822                 if (!sel.rangeCount) // Hack.
823                     buffer.resetCaret();
824
825                 if (caretModeMethod == "pageMove") { // Grr.
826                     buffer.scrollVertical("pages", caretModeArg ? 1 : -1);
827                     buffer.resetCaret();
828                 }
829                 else
830                     controller[caretModeMethod](caretModeArg, arg);
831             }
832
833             mappings.add([modes.VISUAL], keys, description,
834                 function ({ count }) {
835                     count = count || 1;
836
837                     let caret = !dactyl.focusedElement;
838                     let controller = buffer.selectionController;
839
840                     while (count-- && modes.main == modes.VISUAL) {
841                         if (caret)
842                             caretExecute(true, true);
843                         else {
844                             if (callable(visualTextEditCommand))
845                                 visualTextEditCommand(editor.editor);
846                             else
847                                 editor.executeCommand(visualTextEditCommand);
848                         }
849                     }
850                 },
851                 extraInfo);
852
853             mappings.add([modes.CARET, modes.TEXT_EDIT, modes.OPERATOR], keys, description,
854                 function ({ count }) {
855                     count = count || 1;
856
857                     if (editor.editor)
858                         editor.executeCommand(textEditCommand, count);
859                     else {
860                         while (count--)
861                             caretExecute(false);
862                     }
863                 },
864                 extraInfo);
865         }
866
867         // add mappings for commands like i,a,s,c,etc. in TEXT_EDIT mode
868         function addBeginInsertModeMap(keys, commands, description) {
869             mappings.add([modes.TEXT_EDIT], keys, description || "",
870                 function () {
871                     commands.forEach(function (cmd) { editor.executeCommand(cmd, 1) });
872                     modes.push(modes.INSERT);
873                 },
874                 { type: "editor" });
875         }
876
877         function selectPreviousLine() {
878             editor.executeCommand("cmd_selectLinePrevious");
879             if ((modes.extended & modes.LINE) && !editor.selectedText)
880                 editor.executeCommand("cmd_selectLinePrevious");
881         }
882
883         function selectNextLine() {
884             editor.executeCommand("cmd_selectLineNext");
885             if ((modes.extended & modes.LINE) && !editor.selectedText)
886                 editor.executeCommand("cmd_selectLineNext");
887         }
888
889         function updateRange(editor, forward, re, modify, sameWord) {
890             let sel   = editor.selection;
891             let range = sel.getRangeAt(0);
892
893             let end = range.endContainer == sel.focusNode && range.endOffset == sel.focusOffset;
894             if (range.collapsed)
895                 end = forward;
896
897             Editor.extendRange(range, forward, re, sameWord,
898                                editor.rootElement, end ? "end" : "start");
899             modify(range);
900             editor.selectionController.repaintSelection(editor.selectionController.SELECTION_NORMAL);
901         }
902
903         function clear(forward, re)
904             function _clear(editor) {
905                 updateRange(editor, forward, re, function (range) {});
906                 dactyl.assert(!editor.selection.isCollapsed);
907                 editor.selection.deleteFromDocument();
908                 let parent = DOM(editor.rootElement.parentNode);
909                 if (parent.isInput)
910                     parent.input();
911             }
912
913         function move(forward, re, sameWord)
914             function _move(editor) {
915                 updateRange(editor, forward, re,
916                             function (range) { range.collapse(!forward); },
917                             sameWord);
918             }
919         function select(forward, re)
920             function _select(editor) {
921                 updateRange(editor, forward, re,
922                             function (range) {});
923             }
924         function beginLine(editor_) {
925             editor.executeCommand("cmd_beginLine");
926             move(true, /\s/, true)(editor_);
927         }
928
929         //             COUNT  CARET                   TEXT_EDIT            VISUAL_TEXT_EDIT
930         addMovementMap(["k", "<Up>"],                 "Move up one line",
931                        true,  "lineMove", false,      "cmd_linePrevious", selectPreviousLine);
932         addMovementMap(["j", "<Down>", "<Return>"],   "Move down one line",
933                        true,  "lineMove", true,       "cmd_lineNext",     selectNextLine);
934         addMovementMap(["h", "<Left>", "<BS>"],       "Move left one character",
935                        true,  "characterMove", false, "cmd_charPrevious", "cmd_selectCharPrevious");
936         addMovementMap(["l", "<Right>", "<Space>"],   "Move right one character",
937                        true,  "characterMove", true,  "cmd_charNext",     "cmd_selectCharNext");
938         addMovementMap(["b", "<C-Left>"],             "Move left one word",
939                        true,  "wordMove", false,      move(false,  /\w/), select(false, /\w/));
940         addMovementMap(["w", "<C-Right>"],            "Move right one word",
941                        true,  "wordMove", true,       move(true,  /\w/),  select(true, /\w/));
942         addMovementMap(["B"],                         "Move left to the previous white space",
943                        true,  "wordMove", false,      move(false, /\S/),  select(false, /\S/));
944         addMovementMap(["W"],                         "Move right to just beyond the next white space",
945                        true,  "wordMove", true,       move(true,  /\S/),  select(true,  /\S/));
946         addMovementMap(["e"],                         "Move to the end of the current word",
947                        true,  "wordMove", true,       move(true,  /\W/),  select(true,  /\W/));
948         addMovementMap(["E"],                         "Move right to the next white space",
949                        true,  "wordMove", true,       move(true,  /\s/),  select(true,  /\s/));
950         addMovementMap(["<C-f>", "<PageDown>"],       "Move down one page",
951                        true,  "pageMove", true,       "cmd_movePageDown", "cmd_selectNextPage");
952         addMovementMap(["<C-b>", "<PageUp>"],         "Move up one page",
953                        true,  "pageMove", false,      "cmd_movePageUp",   "cmd_selectPreviousPage");
954         addMovementMap(["gg", "<C-Home>"],            "Move to the start of text",
955                        false, "completeMove", false,  "cmd_moveTop",      "cmd_selectTop");
956         addMovementMap(["G", "<C-End>"],              "Move to the end of text",
957                        false, "completeMove", true,   "cmd_moveBottom",   "cmd_selectBottom");
958         addMovementMap(["0", "<Home>"],               "Move to the beginning of the line",
959                        false, "intraLineMove", false, "cmd_beginLine",    "cmd_selectBeginLine");
960         addMovementMap(["^"],                         "Move to the first non-whitespace character of the line",
961                        false, "intraLineMove", false, beginLine,          "cmd_selectBeginLine");
962         addMovementMap(["$", "<End>"],                "Move to the end of the current line",
963                        false, "intraLineMove", true,  "cmd_endLine" ,     "cmd_selectEndLine");
964
965         addBeginInsertModeMap(["i", "<Insert>"], [], "Insert text before the cursor");
966         addBeginInsertModeMap(["a"],             ["cmd_charNext"], "Append text after the cursor");
967         addBeginInsertModeMap(["I"],             ["cmd_beginLine"], "Insert text at the beginning of the line");
968         addBeginInsertModeMap(["A"],             ["cmd_endLine"], "Append text at the end of the line");
969         addBeginInsertModeMap(["s"],             ["cmd_deleteCharForward"], "Delete the character in front of the cursor and start insert");
970         addBeginInsertModeMap(["S"],             ["cmd_deleteToEndOfLine", "cmd_deleteToBeginningOfLine"], "Delete the current line and start insert");
971         addBeginInsertModeMap(["C"],             ["cmd_deleteToEndOfLine"], "Delete from the cursor to the end of the line and start insert");
972
973         function addMotionMap(key, desc, select, cmd, mode, caretOk) {
974             function doTxn(range, editor) {
975                 try {
976                     editor.editor.beginTransaction();
977                     cmd(editor, range, editor.editor);
978                 }
979                 finally {
980                     editor.editor.endTransaction();
981                 }
982             }
983
984             mappings.add([modes.TEXT_EDIT], key,
985                 desc,
986                 function ({ command, count, motion }) {
987                     let start = editor.selectedRange.cloneRange();
988
989                     mappings.pushCommand();
990                     modes.push(modes.OPERATOR, null, {
991                         forCommand: command,
992
993                         count: count,
994
995                         leave: function leave(stack) {
996                             try {
997                                 if (stack.push || stack.fromEscape)
998                                     return;
999
1000                                 editor.withSavedValues(["inEditMap"], function () {
1001                                     this.inEditMap = true;
1002
1003                                     let range = RangeFind.union(start, editor.selectedRange);
1004                                     editor.selectedRange = select ? range : start;
1005                                     doTxn(range, editor);
1006                                 });
1007
1008                                 editor.currentRegister = null;
1009                                 modes.delay(function () {
1010                                     if (mode)
1011                                         modes.push(mode);
1012                                 });
1013                             }
1014                             finally {
1015                                 if (!stack.push)
1016                                     mappings.popCommand();
1017                             }
1018                         }
1019                     });
1020                 },
1021                 { count: true, type: "motion" });
1022
1023             mappings.add([modes.VISUAL], key,
1024                 desc,
1025                 function ({ count,  motion }) {
1026                     dactyl.assert(caretOk || editor.isTextEdit);
1027                     if (editor.isTextEdit)
1028                         doTxn(editor.selectedRange, editor);
1029                     else
1030                         cmd(editor, buffer.selection.getRangeAt(0));
1031                 },
1032                 { count: true, type: "motion" });
1033         }
1034
1035         addMotionMap(["d", "x"], "Delete text", true,  function (editor) { editor.cut(); });
1036         addMotionMap(["c"],      "Change text", true,  function (editor) { editor.cut(); }, modes.INSERT);
1037         addMotionMap(["y"],      "Yank text",   false, function (editor, range) { editor.copy(range); }, null, true);
1038
1039         addMotionMap(["gu"], "Lowercase text", false,
1040              function (editor, range) {
1041                  editor.mungeRange(range, String.toLocaleLowerCase);
1042              });
1043
1044         addMotionMap(["gU"], "Uppercase text", false,
1045             function (editor, range) {
1046                 editor.mungeRange(range, String.toLocaleUpperCase);
1047             });
1048
1049         mappings.add([modes.OPERATOR],
1050             ["c", "d", "y"], "Select the entire line",
1051             function ({ command, count }) {
1052                 dactyl.assert(command == modes.getStack(0).params.forCommand);
1053
1054                 let sel = editor.selection;
1055                 sel.modify("move", "backward", "lineboundary");
1056                 sel.modify("extend", "forward", "lineboundary");
1057
1058                 if (command != "c")
1059                     sel.modify("extend", "forward", "character");
1060             },
1061             { count: true, type: "operator" });
1062
1063         let bind = function bind(names, description, action, params)
1064             mappings.add([modes.INPUT], names, description,
1065                          action, update({ type: "editor" }, params));
1066
1067         bind(["<C-w>"], "Delete previous word",
1068              function () {
1069                  if (editor.editor)
1070                      clear(false, /\w/)(editor.editor);
1071                  else
1072                      editor.executeCommand("cmd_deleteWordBackward", 1);
1073              });
1074
1075         bind(["<C-u>"], "Delete until beginning of current line",
1076              function () {
1077                  // Deletes the whole line. What the hell.
1078                  // editor.executeCommand("cmd_deleteToBeginningOfLine", 1);
1079
1080                  editor.executeCommand("cmd_selectBeginLine", 1);
1081                  if (editor.selection && editor.selection.isCollapsed) {
1082                      editor.executeCommand("cmd_deleteCharBackward", 1);
1083                      editor.executeCommand("cmd_selectBeginLine", 1);
1084                  }
1085
1086                  if (editor.getController("cmd_delete").isCommandEnabled("cmd_delete"))
1087                      editor.executeCommand("cmd_delete", 1);
1088              });
1089
1090         bind(["<C-k>"], "Delete until end of current line",
1091              function () { editor.executeCommand("cmd_deleteToEndOfLine", 1); });
1092
1093         bind(["<C-a>"], "Move cursor to beginning of current line",
1094              function () { editor.executeCommand("cmd_beginLine", 1); });
1095
1096         bind(["<C-e>"], "Move cursor to end of current line",
1097              function () { editor.executeCommand("cmd_endLine", 1); });
1098
1099         bind(["<C-h>"], "Delete character to the left",
1100              function () { events.feedkeys("<BS>", true); });
1101
1102         bind(["<C-d>"], "Delete character to the right",
1103              function () { editor.executeCommand("cmd_deleteCharForward", 1); });
1104
1105         bind(["<S-Insert>"], "Insert clipboard/selection",
1106              function () { editor.paste(); });
1107
1108         bind(["<C-i>"], "Edit text field with an external editor",
1109              function () { editor.editFieldExternally(); });
1110
1111         bind(["<C-t>"], "Edit text field in Text Edit mode",
1112              function () {
1113                  dactyl.assert(!editor.isTextEdit && editor.editor);
1114                  dactyl.assert(dactyl.focusedElement ||
1115                                // Sites like Google like to use a
1116                                // hidden, editable window for keyboard
1117                                // focus and use their own WYSIWYG editor
1118                                // implementations for the visible area,
1119                                // which we can't handle.
1120                                let (f = document.commandDispatcher.focusedWindow.frameElement)
1121                                     f && Hints.isVisible(f, true));
1122
1123                  modes.push(modes.TEXT_EDIT);
1124              });
1125
1126         // Ugh.
1127         mappings.add([modes.INPUT, modes.CARET],
1128             ["<*-CR>", "<*-BS>", "<*-Del>", "<*-Left>", "<*-Right>", "<*-Up>", "<*-Down>",
1129              "<*-Home>", "<*-End>", "<*-PageUp>", "<*-PageDown>",
1130              "<M-c>", "<M-v>", "<*-Tab>"],
1131             "Handled by " + config.host,
1132             function () Events.PASS_THROUGH);
1133
1134         mappings.add([modes.INSERT],
1135             ["<Space>", "<Return>"], "Expand Insert mode abbreviation",
1136             function () {
1137                 editor.expandAbbreviation(modes.INSERT);
1138                 return Events.PASS_THROUGH;
1139             });
1140
1141         mappings.add([modes.INSERT],
1142             ["<C-]>", "<C-5>"], "Expand Insert mode abbreviation",
1143             function () { editor.expandAbbreviation(modes.INSERT); });
1144
1145         let bind = function bind(names, description, action, params)
1146             mappings.add([modes.TEXT_EDIT], names, description,
1147                          action, update({ type: "editor" }, params));
1148
1149
1150         bind(["<C-a>"], "Increment the next number",
1151              function ({ count }) { editor.modifyNumber(count || 1) },
1152              { count: true });
1153
1154         bind(["<C-x>"], "Decrement the next number",
1155              function ({ count }) { editor.modifyNumber(-(count || 1)) },
1156              { count: true });
1157
1158         // text edit mode
1159         bind(["u"], "Undo changes",
1160              function (args) {
1161                  editor.executeCommand("cmd_undo", Math.max(args.count, 1));
1162                  editor.deselect();
1163              },
1164              { count: true });
1165
1166         bind(["<C-r>"], "Redo undone changes",
1167              function (args) {
1168                  editor.executeCommand("cmd_redo", Math.max(args.count, 1));
1169                  editor.deselect();
1170              },
1171              { count: true });
1172
1173         bind(["D"], "Delete characters from the cursor to the end of the line",
1174              function () { editor.executeCommand("cmd_deleteToEndOfLine"); });
1175
1176         bind(["o"], "Open line below current",
1177              function () {
1178                  editor.executeCommand("cmd_endLine", 1);
1179                  modes.push(modes.INSERT);
1180                  events.feedkeys("<Return>");
1181              });
1182
1183         bind(["O"], "Open line above current",
1184              function () {
1185                  editor.executeCommand("cmd_beginLine", 1);
1186                  modes.push(modes.INSERT);
1187                  events.feedkeys("<Return>");
1188                  editor.executeCommand("cmd_linePrevious", 1);
1189              });
1190
1191         bind(["X"], "Delete character to the left",
1192              function (args) { editor.executeCommand("cmd_deleteCharBackward", Math.max(args.count, 1)); },
1193             { count: true });
1194
1195         bind(["x"], "Delete character to the right",
1196              function (args) { editor.executeCommand("cmd_deleteCharForward", Math.max(args.count, 1)); },
1197             { count: true });
1198
1199         // visual mode
1200         mappings.add([modes.CARET, modes.TEXT_EDIT],
1201             ["v"], "Start Visual mode",
1202             function () { modes.push(modes.VISUAL); });
1203
1204         mappings.add([modes.VISUAL],
1205             ["v", "V"], "End Visual mode",
1206             function () { modes.pop(); });
1207
1208         bind(["V"], "Start Visual Line mode",
1209              function () {
1210                  modes.push(modes.VISUAL, modes.LINE);
1211                  editor.executeCommand("cmd_beginLine", 1);
1212                  editor.executeCommand("cmd_selectLineNext", 1);
1213              });
1214
1215         mappings.add([modes.VISUAL],
1216             ["s"], "Change selected text",
1217             function () {
1218                 dactyl.assert(editor.isTextEdit);
1219                 editor.executeCommand("cmd_cut");
1220                 modes.push(modes.INSERT);
1221             });
1222
1223         mappings.add([modes.VISUAL],
1224             ["o"], "Move cursor to the other end of the selection",
1225             function () {
1226                 if (editor.isTextEdit)
1227                     var selection = editor.selection;
1228                 else
1229                     selection = buffer.focusedFrame.getSelection();
1230
1231                 util.assert(selection.focusNode);
1232                 let { focusOffset, anchorOffset, focusNode, anchorNode } = selection;
1233                 selection.collapse(focusNode, focusOffset);
1234                 selection.extend(anchorNode, anchorOffset);
1235             });
1236
1237         bind(["p"], "Paste clipboard contents",
1238              function ({ count }) {
1239                 dactyl.assert(!editor.isCaret);
1240                 editor.executeCommand(modules.bind("paste", editor, null),
1241                                       count || 1);
1242             },
1243             { count: true });
1244
1245         mappings.add([modes.COMMAND],
1246             ['"'], "Bind a register to the next command",
1247             function ({ arg }) {
1248                 editor.pushRegister(arg);
1249             },
1250             { arg: true });
1251
1252         mappings.add([modes.INPUT],
1253             ["<C-'>", '<C-">'], "Bind a register to the next command",
1254             function ({ arg }) {
1255                 editor.pushRegister(arg);
1256             },
1257             { arg: true });
1258
1259         let bind = function bind(names, description, action, params)
1260             mappings.add([modes.TEXT_EDIT, modes.OPERATOR, modes.VISUAL],
1261                          names, description,
1262                          action, update({ type: "editor" }, params));
1263
1264         // finding characters
1265         function offset(backward, before, pos) {
1266             if (!backward && modes.main != modes.TEXT_EDIT)
1267                 return before ? 0 : 1;
1268             if (before)
1269                 return backward ? +1 : -1;
1270             return 0;
1271         }
1272
1273         bind(["f"], "Find a character on the current line, forwards",
1274              function ({ arg, count }) {
1275                  editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), false,
1276                                                        offset(false, false)),
1277                                        modes.main == modes.VISUAL);
1278              },
1279              { arg: true, count: true, type: "operator" });
1280
1281         bind(["F"], "Find a character on the current line, backwards",
1282              function ({ arg, count }) {
1283                  editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), true,
1284                                                        offset(true, false)),
1285                                        modes.main == modes.VISUAL);
1286              },
1287              { arg: true, count: true, type: "operator" });
1288
1289         bind(["t"], "Find a character on the current line, forwards, and move to the character before it",
1290              function ({ arg, count }) {
1291                  editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), false,
1292                                                        offset(false, true)),
1293                                        modes.main == modes.VISUAL);
1294              },
1295              { arg: true, count: true, type: "operator" });
1296
1297         bind(["T"], "Find a character on the current line, backwards, and move to the character after it",
1298              function ({ arg, count }) {
1299                  editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), true,
1300                                                        offset(true, true)),
1301                                        modes.main == modes.VISUAL);
1302              },
1303              { arg: true, count: true, type: "operator" });
1304
1305         // text edit and visual mode
1306         mappings.add([modes.TEXT_EDIT, modes.VISUAL],
1307             ["~"], "Switch case of the character under the cursor and move the cursor to the right",
1308             function ({ count }) {
1309                 function munger(range)
1310                     String(range).replace(/./g, function (c) {
1311                         let lc = c.toLocaleLowerCase();
1312                         return c == lc ? c.toLocaleUpperCase() : lc;
1313                     });
1314
1315                 var range = editor.selectedRange;
1316                 if (range.collapsed) {
1317                     count = count || 1;
1318                     Editor.extendRange(range, true, { test: function (c) !!count-- }, true);
1319                 }
1320                 editor.mungeRange(range, munger, count != null);
1321
1322                 modes.pop(modes.TEXT_EDIT);
1323             },
1324             { count: true });
1325
1326         let bind = function bind() mappings.add.apply(mappings,
1327                                                       [[modes.AUTOCOMPLETE]].concat(Array.slice(arguments)))
1328
1329         bind(["<Esc>"], "Return to Insert mode",
1330              function () Events.PASS_THROUGH);
1331
1332         bind(["<C-[>"], "Return to Insert mode",
1333              function () { events.feedkeys("<Esc>", { skipmap: true }); });
1334
1335         bind(["<Up>"], "Select the previous autocomplete result",
1336              function () Events.PASS_THROUGH);
1337
1338         bind(["<C-p>"], "Select the previous autocomplete result",
1339              function () { events.feedkeys("<Up>", { skipmap: true }); });
1340
1341         bind(["<Down>"], "Select the next autocomplete result",
1342              function () Events.PASS_THROUGH);
1343
1344         bind(["<C-n>"], "Select the next autocomplete result",
1345              function () { events.feedkeys("<Down>", { skipmap: true }); });
1346     },
1347     options: function init_options() {
1348         options.add(["editor"],
1349             "The external text editor",
1350             "string", 'gvim -f +<line> +"sil! call cursor(0, <column>)" <file>', {
1351                 format: function (obj, value) {
1352                     let args = commands.parseArgs(value || this.value, { argCount: "*", allowUnknownOptions: true })
1353                                        .map(util.compileMacro).filter(function (fmt) fmt.valid(obj))
1354                                        .map(function (fmt) fmt(obj));
1355                     if (obj["file"] && !this.has("file"))
1356                         args.push(obj["file"]);
1357                     return args;
1358                 },
1359                 has: function (key) Set.has(util.compileMacro(this.value).seen, key),
1360                 validator: function (value) {
1361                     this.format({}, value);
1362                     return Object.keys(util.compileMacro(value).seen).every(function (k) ["column", "file", "line"].indexOf(k) >= 0);
1363                 }
1364             });
1365
1366         options.add(["insertmode", "im"],
1367             "Enter Insert mode rather than Text Edit mode when focusing text areas",
1368             "boolean", true);
1369
1370         options.add(["spelllang", "spl"],
1371             "The language used by the spell checker",
1372             "string", config.locale,
1373             {
1374                 initValue: function () {},
1375                 getter: function getter() {
1376                     try {
1377                         return services.spell.dictionary || "";
1378                     }
1379                     catch (e) {
1380                         return "";
1381                     }
1382                 },
1383                 setter: function setter(val) { services.spell.dictionary = val; },
1384                 completer: function completer(context) {
1385                     let res = {};
1386                     services.spell.getDictionaryList(res, {});
1387                     context.completions = res.value;
1388                     context.keys = { text: util.identity, description: util.identity };
1389                 }
1390             });
1391     },
1392     sanitizer: function () {
1393         sanitizer.addItem("registers", {
1394             description: "Register values",
1395             persistent: true,
1396             action: function (timespan, host) {
1397                 if (!host) {
1398                     for (let [k, v] in editor.registers)
1399                         if (timespan.contains(v.timestamp))
1400                             editor.registers.remove(k);
1401                     editor.registerRing.truncate(0);
1402                 }
1403             }
1404         });
1405     }
1406 });
1407
1408 // vim: set fdm=marker sw=4 ts=4 et: