]> git.donarmstrong.com Git - dactyl.git/blob - common/content/editor.js
01a25ebddb60346e5412d735ae2422b5716a99e1
[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, noStrip) {
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, this.editor[noStrip ? "eNoStrip" : "eStrip"]);
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 findChar(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 (true) {
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("txt", "." + buffer.uri.host);
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 initModes() {
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 initCommands() {
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 initCompletion() {
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 initMappings() {
781
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();
788                 }
789                 editor.inEditMap = true;
790             },
791             postExecute: function preExecute(args) {
792                 editor.inEditMap = false;
793                 if (this.editor) {
794                     if (!this.noTransaction)
795                         this.editor.endTransaction();
796                     this.editor = null;
797                 }
798             },
799         };
800         Map.types["operator"] = {
801             preExecute: function preExecute(args) {
802                 editor.inEditMap = true;
803             },
804             postExecute: function preExecute(args) {
805                 editor.inEditMap = true;
806                 if (modes.main == modes.OPERATOR)
807                     modes.pop();
808             }
809         };
810
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) {
813             let extraInfo = {
814                 count: !!hasCount,
815                 type: "operator"
816             };
817
818             function caretExecute(arg) {
819                 let win = document.commandDispatcher.focusedWindow;
820                 let controller = util.selectionController(win);
821                 let sel = controller.getSelection(controller.SELECTION_NORMAL);
822
823                 let buffer = Buffer(win);
824                 if (!sel.rangeCount) // Hack.
825                     buffer.resetCaret();
826
827                 if (caretModeMethod == "pageMove") { // Grr.
828                     buffer.scrollVertical("pages", caretModeArg ? 1 : -1);
829                     buffer.resetCaret();
830                 }
831                 else
832                     controller[caretModeMethod](caretModeArg, arg);
833             }
834
835             mappings.add([modes.VISUAL], keys, description,
836                 function ({ count }) {
837                     count = count || 1;
838
839                     let caret = !dactyl.focusedElement;
840                     let controller = buffer.selectionController;
841
842                     while (count-- && modes.main == modes.VISUAL) {
843                         if (caret)
844                             caretExecute(true, true);
845                         else {
846                             if (callable(visualTextEditCommand))
847                                 visualTextEditCommand(editor.editor);
848                             else
849                                 editor.executeCommand(visualTextEditCommand);
850                         }
851                     }
852                 },
853                 extraInfo);
854
855             mappings.add([modes.CARET, modes.TEXT_EDIT, modes.OPERATOR], keys, description,
856                 function ({ count }) {
857                     count = count || 1;
858
859                     if (editor.editor)
860                         editor.executeCommand(textEditCommand, count);
861                     else {
862                         while (count--)
863                             caretExecute(false);
864                     }
865                 },
866                 extraInfo);
867         }
868
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 || "",
872                 function () {
873                     commands.forEach(function (cmd) { editor.executeCommand(cmd, 1); });
874                     modes.push(modes.INSERT);
875                 },
876                 { type: "editor" });
877         }
878
879         function selectPreviousLine() {
880             editor.executeCommand("cmd_selectLinePrevious");
881             if ((modes.extended & modes.LINE) && !editor.selectedText)
882                 editor.executeCommand("cmd_selectLinePrevious");
883         }
884
885         function selectNextLine() {
886             editor.executeCommand("cmd_selectLineNext");
887             if ((modes.extended & modes.LINE) && !editor.selectedText)
888                 editor.executeCommand("cmd_selectLineNext");
889         }
890
891         function updateRange(editor, forward, re, modify, sameWord) {
892             let sel   = editor.selection;
893             let range = sel.getRangeAt(0);
894
895             let end = range.endContainer == sel.focusNode && range.endOffset == sel.focusOffset;
896             if (range.collapsed)
897                 end = forward;
898
899             Editor.extendRange(range, forward, re, sameWord,
900                                editor.rootElement, end ? "end" : "start");
901             modify(range);
902             editor.selectionController.repaintSelection(editor.selectionController.SELECTION_NORMAL);
903         }
904
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);
911                 if (parent.isInput)
912                     parent.input();
913             }
914
915         function move(forward, re, sameWord)
916             function _move(editor) {
917                 updateRange(editor, forward, re,
918                             function (range) { range.collapse(!forward); },
919                             sameWord);
920             }
921         function select(forward, re)
922             function _select(editor) {
923                 updateRange(editor, forward, re,
924                             function (range) {});
925             }
926         function beginLine(editor_) {
927             editor.executeCommand("cmd_beginLine");
928             move(true, /\s/, true)(editor_);
929         }
930
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");
966
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");
974
975         function addMotionMap(key, desc, select, cmd, mode, caretOk) {
976             function doTxn(range, editor) {
977                 try {
978                     editor.editor.beginTransaction();
979                     cmd(editor, range, editor.editor);
980                 }
981                 finally {
982                     editor.editor.endTransaction();
983                 }
984             }
985
986             mappings.add([modes.TEXT_EDIT], key,
987                 desc,
988                 function ({ command, count, motion }) {
989                     let start = editor.selectedRange.cloneRange();
990
991                     mappings.pushCommand();
992                     modes.push(modes.OPERATOR, null, {
993                         forCommand: command,
994
995                         count: count,
996
997                         leave: function leave(stack) {
998                             try {
999                                 if (stack.push || stack.fromEscape)
1000                                     return;
1001
1002                                 editor.withSavedValues(["inEditMap"], function () {
1003                                     this.inEditMap = true;
1004
1005                                     let range = RangeFind.union(start, editor.selectedRange);
1006                                     editor.selectedRange = select ? range : start;
1007                                     doTxn(range, editor);
1008                                 });
1009
1010                                 editor.currentRegister = null;
1011                                 modes.delay(function () {
1012                                     if (mode)
1013                                         modes.push(mode);
1014                                 });
1015                             }
1016                             finally {
1017                                 if (!stack.push)
1018                                     mappings.popCommand();
1019                             }
1020                         }
1021                     });
1022                 },
1023                 { count: true, type: "motion" });
1024
1025             mappings.add([modes.VISUAL], key,
1026                 desc,
1027                 function ({ count,  motion }) {
1028                     dactyl.assert(caretOk || editor.isTextEdit);
1029                     if (editor.isTextEdit)
1030                         doTxn(editor.selectedRange, editor);
1031                     else
1032                         cmd(editor, buffer.selection.getRangeAt(0));
1033                 },
1034                 { count: true, type: "motion" });
1035         }
1036
1037         addMotionMap(["d", "x"], "Delete text", true,  function (editor) { editor.cut(); });
1038         addMotionMap(["c"],      "Change text", true,  function (editor) { editor.cut(null, null, true); }, modes.INSERT);
1039         addMotionMap(["y"],      "Yank text",   false, function (editor, range) { editor.copy(range); }, null, true);
1040
1041         addMotionMap(["gu"], "Lowercase text", false,
1042              function (editor, range) {
1043                  editor.mungeRange(range, String.toLocaleLowerCase);
1044              });
1045
1046         addMotionMap(["gU"], "Uppercase text", false,
1047             function (editor, range) {
1048                 editor.mungeRange(range, String.toLocaleUpperCase);
1049             });
1050
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);
1055
1056                 let sel = editor.selection;
1057                 sel.modify("move", "backward", "lineboundary");
1058                 sel.modify("extend", "forward", "lineboundary");
1059
1060                 if (command != "c")
1061                     sel.modify("extend", "forward", "character");
1062             },
1063             { count: true, type: "operator" });
1064
1065         let bind = function bind(names, description, action, params)
1066             mappings.add([modes.INPUT], names, description,
1067                          action, update({ type: "editor" }, params));
1068
1069         bind(["<C-w>"], "Delete previous word",
1070              function () {
1071                  if (editor.editor)
1072                      clear(false, /\w/)(editor.editor);
1073                  else
1074                      editor.executeCommand("cmd_deleteWordBackward", 1);
1075              });
1076
1077         bind(["<C-u>"], "Delete until beginning of current line",
1078              function () {
1079                  // Deletes the whole line. What the hell.
1080                  // editor.executeCommand("cmd_deleteToBeginningOfLine", 1);
1081
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);
1086                  }
1087
1088                  if (editor.getController("cmd_delete").isCommandEnabled("cmd_delete"))
1089                      editor.executeCommand("cmd_delete", 1);
1090              });
1091
1092         bind(["<C-k>"], "Delete until end of current line",
1093              function () { editor.executeCommand("cmd_deleteToEndOfLine", 1); });
1094
1095         bind(["<C-a>"], "Move cursor to beginning of current line",
1096              function () { editor.executeCommand("cmd_beginLine", 1); });
1097
1098         bind(["<C-e>"], "Move cursor to end of current line",
1099              function () { editor.executeCommand("cmd_endLine", 1); });
1100
1101         bind(["<C-h>"], "Delete character to the left",
1102              function () { events.feedkeys("<BS>", true); });
1103
1104         bind(["<C-d>"], "Delete character to the right",
1105              function () { editor.executeCommand("cmd_deleteCharForward", 1); });
1106
1107         bind(["<S-Insert>"], "Insert clipboard/selection",
1108              function () { editor.paste(); });
1109
1110         bind(["<C-i>"], "Edit text field with an external editor",
1111              function () { editor.editFieldExternally(); });
1112
1113         bind(["<C-t>"], "Edit text field in Text Edit mode",
1114              function () {
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));
1124
1125                  modes.push(modes.TEXT_EDIT);
1126              });
1127
1128         // Ugh.
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);
1135
1136         mappings.add([modes.INSERT],
1137             ["<Space>", "<Return>"], "Expand Insert mode abbreviation",
1138             function () {
1139                 editor.expandAbbreviation(modes.INSERT);
1140                 return Events.PASS_THROUGH;
1141             });
1142
1143         mappings.add([modes.INSERT],
1144             ["<C-]>", "<C-5>"], "Expand Insert mode abbreviation",
1145             function () { editor.expandAbbreviation(modes.INSERT); });
1146
1147         let bind = function bind(names, description, action, params)
1148             mappings.add([modes.TEXT_EDIT], names, description,
1149                          action, update({ type: "editor" }, params));
1150
1151         bind(["<C-a>"], "Increment the next number",
1152              function ({ count }) { editor.modifyNumber(count || 1); },
1153              { count: true });
1154
1155         bind(["<C-x>"], "Decrement the next number",
1156              function ({ count }) { editor.modifyNumber(-(count || 1)); },
1157              { count: true });
1158
1159         // text edit mode
1160         bind(["u"], "Undo changes",
1161              function ({ count }) {
1162                  editor.editor.undo(Math.max(count, 1));
1163                  editor.deselect();
1164              },
1165              { count: true, noTransaction: true });
1166
1167         bind(["<C-r>"], "Redo undone changes",
1168              function ({ count }) {
1169                  editor.editor.redo(Math.max(count, 1));
1170                  editor.deselect();
1171              },
1172              { count: true, noTransaction: true });
1173
1174         bind(["D"], "Delete characters from the cursor to the end of the line",
1175              function () { editor.executeCommand("cmd_deleteToEndOfLine"); });
1176
1177         bind(["o"], "Open line below current",
1178              function () {
1179                  editor.executeCommand("cmd_endLine", 1);
1180                  modes.push(modes.INSERT);
1181                  events.feedkeys("<Return>");
1182              });
1183
1184         bind(["O"], "Open line above current",
1185              function () {
1186                  editor.executeCommand("cmd_beginLine", 1);
1187                  modes.push(modes.INSERT);
1188                  events.feedkeys("<Return>");
1189                  editor.executeCommand("cmd_linePrevious", 1);
1190              });
1191
1192         bind(["X"], "Delete character to the left",
1193              function (args) { editor.executeCommand("cmd_deleteCharBackward", Math.max(args.count, 1)); },
1194             { count: true });
1195
1196         bind(["x"], "Delete character to the right",
1197              function (args) { editor.executeCommand("cmd_deleteCharForward", Math.max(args.count, 1)); },
1198             { count: true });
1199
1200         // visual mode
1201         mappings.add([modes.CARET, modes.TEXT_EDIT],
1202             ["v"], "Start Visual mode",
1203             function () { modes.push(modes.VISUAL); });
1204
1205         mappings.add([modes.VISUAL],
1206             ["v", "V"], "End Visual mode",
1207             function () { modes.pop(); });
1208
1209         bind(["V"], "Start Visual Line mode",
1210              function () {
1211                  modes.push(modes.VISUAL, modes.LINE);
1212                  editor.executeCommand("cmd_beginLine", 1);
1213                  editor.executeCommand("cmd_selectLineNext", 1);
1214              });
1215
1216         mappings.add([modes.VISUAL],
1217             ["s"], "Change selected text",
1218             function () {
1219                 dactyl.assert(editor.isTextEdit);
1220                 editor.executeCommand("cmd_cut");
1221                 modes.push(modes.INSERT);
1222             });
1223
1224         mappings.add([modes.VISUAL],
1225             ["o"], "Move cursor to the other end of the selection",
1226             function () {
1227                 if (editor.isTextEdit)
1228                     var selection = editor.selection;
1229                 else
1230                     selection = buffer.focusedFrame.getSelection();
1231
1232                 util.assert(selection.focusNode);
1233                 let { focusOffset, anchorOffset, focusNode, anchorNode } = selection;
1234                 selection.collapse(focusNode, focusOffset);
1235                 selection.extend(anchorNode, anchorOffset);
1236             });
1237
1238         bind(["p"], "Paste clipboard contents",
1239              function ({ count }) {
1240                 dactyl.assert(!editor.isCaret);
1241                 editor.executeCommand(modules.bind("paste", editor, null),
1242                                       count || 1);
1243             },
1244             { count: true });
1245
1246         mappings.add([modes.COMMAND],
1247             ['"'], "Bind a register to the next command",
1248             function ({ arg }) {
1249                 editor.pushRegister(arg);
1250             },
1251             { arg: true });
1252
1253         mappings.add([modes.INPUT],
1254             ["<C-'>", '<C-">'], "Bind a register to the next command",
1255             function ({ arg }) {
1256                 editor.pushRegister(arg);
1257             },
1258             { arg: true });
1259
1260         let bind = function bind(names, description, action, params)
1261             mappings.add([modes.TEXT_EDIT, modes.OPERATOR, modes.VISUAL],
1262                          names, description,
1263                          action, update({ type: "editor" }, params));
1264
1265         // finding characters
1266         function offset(backward, before, pos) {
1267             if (!backward && modes.main != modes.TEXT_EDIT)
1268                 return before ? 0 : 1;
1269             if (before)
1270                 return backward ? +1 : -1;
1271             return 0;
1272         }
1273
1274         bind(["f"], "Find a character on the current line, forwards",
1275              function ({ arg, count }) {
1276                  editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), false,
1277                                                        offset(false, false)),
1278                                        modes.main == modes.VISUAL);
1279              },
1280              { arg: true, count: true, type: "operator" });
1281
1282         bind(["F"], "Find a character on the current line, backwards",
1283              function ({ arg, count }) {
1284                  editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), true,
1285                                                        offset(true, false)),
1286                                        modes.main == modes.VISUAL);
1287              },
1288              { arg: true, count: true, type: "operator" });
1289
1290         bind(["t"], "Find a character on the current line, forwards, and move to the character before it",
1291              function ({ arg, count }) {
1292                  editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), false,
1293                                                        offset(false, true)),
1294                                        modes.main == modes.VISUAL);
1295              },
1296              { arg: true, count: true, type: "operator" });
1297
1298         bind(["T"], "Find a character on the current line, backwards, and move to the character after it",
1299              function ({ arg, count }) {
1300                  editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), true,
1301                                                        offset(true, true)),
1302                                        modes.main == modes.VISUAL);
1303              },
1304              { arg: true, count: true, type: "operator" });
1305
1306         // text edit and visual mode
1307         mappings.add([modes.TEXT_EDIT, modes.VISUAL],
1308             ["~"], "Switch case of the character under the cursor and move the cursor to the right",
1309             function ({ count }) {
1310                 function munger(range)
1311                     String(range).replace(/./g, function (c) {
1312                         let lc = c.toLocaleLowerCase();
1313                         return c == lc ? c.toLocaleUpperCase() : lc;
1314                     });
1315
1316                 var range = editor.selectedRange;
1317                 if (range.collapsed) {
1318                     count = count || 1;
1319                     Editor.extendRange(range, true, { test: function (c) !!count-- }, true);
1320                 }
1321                 editor.mungeRange(range, munger, count != null);
1322
1323                 modes.pop(modes.TEXT_EDIT);
1324             },
1325             { count: true });
1326
1327         let bind = function bind(...args) mappings.add.apply(mappings, [[modes.AUTOCOMPLETE]].concat(args));
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 initOptions() {
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 initSanitizer() {
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 sts=4 ts=8 et: