summaryrefslogtreecommitdiff
path: root/common/content/editor.js
blob: 539fd0955b2822c6f3f413fc5fbb78dda78f2c1a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
// Copyright (c) 2008-2014 Kris Maglione <maglione.k at Gmail>
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.
"use strict";

/** @scope modules */

// command names taken from:
// http://developer.mozilla.org/en/docs/Editor_Embedding_Guide

/** @instance editor */
var Editor = Module("editor", XPCOM(Ci.nsIEditActionListener, ModuleBase), {
    init: function init(elem) {
        if (elem)
            this.element = elem;
        else
            this.__defineGetter__("element", () => {
                let elem = dactyl.focusedElement;
                if (elem)
                    return elem.inputField || elem;

                let win = document.commandDispatcher.focusedWindow;
                return DOM(win).isEditable && win || null;
            });
    },

    get registers() {
        return storage.newMap("registers",
                              { privateData: true, store: true });
    },
    get registerRing() {
        return storage.newArray("register-ring",
                                { privateData: true, store: true });
    },

    skipSave: false,

    // Fixme: Move off this object.
    currentRegister: null,

    /**
     * Temporarily set the default register for the span of the next
     * mapping.
     */
    pushRegister: function pushRegister(arg) {
        let restore = this.currentRegister;
        this.currentRegister = arg;
        mappings.afterCommands(2, function () {
            this.currentRegister = restore;
        }, this);
    },

    defaultRegister: "*+",

    selectionRegisters: {
        "*": "selection",
        "+": "global"
    },

    /**
     * Get the value of the register *name*.
     *
     * @param {string|number} name The name of the register to get.
     * @returns {string|null}
     * @see #setRegister
     */
    getRegister: function getRegister(name) {
        if (name == null)
            name = editor.currentRegister || editor.defaultRegister;

        name = String(name)[0];
        if (name == '"')
            name = 0;
        if (name == "_")
            var res = null;
        else if (hasOwnProperty(this.selectionRegisters, name))
            res = { text: dactyl.clipboardRead(this.selectionRegisters[name]) || "" };
        else if (!/^[0-9]$/.test(name))
            res = this.registers.get(name);
        else
            res = this.registerRing.get(name);

        return res != null ? res.text : res;
    },

    /**
     * Sets the value of register *name* to value. The following
     * registers have special semantics:
     *
     *   *   - Tied to the PRIMARY selection value on X11 systems.
     *   +   - Tied to the primary global clipboard.
     *   _   - The null register. Never has any value.
     *   "   - Equivalent to 0.
     *   0-9 - These act as a kill ring. Setting any of them pushes the
     *         values of higher numbered registers up one slot.
     *
     * @param {string|number} name The name of the register to set.
     * @param {string|Range|Selection|Node} value The value to save to
     *      the register.
     */
    setRegister: function setRegister(name, value, verbose) {
        if (name == null)
            name = editor.currentRegister || editor.defaultRegister;

        if (isinstance(value, [Ci.nsIDOMRange, Ci.nsIDOMNode, Ci.nsISelection]))
            value = DOM.stringify(value);
        value = { text: value, isLine: modes.extended & modes.LINE, timestamp: Date.now() * 1000 };

        for (let n of String(name)) {
            if (n == '"')
                n = 0;
            if (n == "_")
                ;
            else if (hasOwnProperty(this.selectionRegisters, n))
                dactyl.clipboardWrite(value.text, verbose, this.selectionRegisters[n]);
            else if (!/^[0-9]$/.test(n))
                this.registers.set(n, value);
            else {
                this.registerRing.insert(value, n);
                this.registerRing.truncate(10);
            }
        }
    },

    get isCaret() { return modes.getStack(1).main == modes.CARET; },
    get isTextEdit() { return modes.getStack(1).main == modes.TEXT_EDIT; },

    get editor() { return DOM(this.element).editor; },

    getController: function getController(cmd) {
        let controllers = this.element && this.element.controllers;
        dactyl.assert(controllers);

        return controllers.getControllerForCommand(cmd || "cmd_beginLine");
    },

    get selection() { return this.editor && this.editor.selection || null; },
    get selectionController() {
        return this.editor && this.editor.selectionController || null;
    },

    deselect: function () {
        if (this.selection && this.selection.focusNode)
            this.selection.collapse(this.selection.focusNode,
                                    this.selection.focusOffset);
    },

    get selectedRange() {
        if (!this.selection)
            return null;

        if (!this.selection.rangeCount) {
            let range = RangeFind.nodeContents(this.editor.rootElement.ownerDocument);
            range.collapse(true);
            this.selectedRange = range;
        }
        return this.selection.getRangeAt(0);
    },
    set selectedRange(range) {
        this.selection.removeAllRanges();
        if (range != null)
            this.selection.addRange(range);
    },

    get selectedText() { return String(this.selection); },

    get preserveSelection() {
        return this.editor && !this.editor.shouldTxnSetSelection;
    },
    set preserveSelection(val) {
        if (this.editor)
            this.editor.setShouldTxnSetSelection(!val);
    },

    copy: function copy(range, name) {
        range = range || this.selection;

        if (!range.collapsed)
            this.setRegister(name, range);
    },

    cut: function cut(range, name, noStrip) {
        if (range)
            this.selectedRange = range;

        if (!this.selection.isCollapsed)
            this.setRegister(name, this.selection);

        this.editor.deleteSelection(0, this.editor[noStrip ? "eNoStrip" : "eStrip"]);
    },

    paste: function paste(name) {
        let text = this.getRegister(name);
        dactyl.assert(text && this.editor instanceof Ci.nsIPlaintextEditor);

        this.editor.insertText(text);
    },

    // count is optional, defaults to 1
    executeCommand: function executeCommand(cmd, count) {
        if (!callable(cmd)) {
            var controller = this.getController(cmd);
            util.assert(controller &&
                        controller.supportsCommand(cmd) &&
                        controller.isCommandEnabled(cmd));
            cmd = bind("doCommand", controller, cmd);
        }

        // XXX: better as a precondition
        if (count == null)
            count = 1;

        let didCommand = false;
        while (count--) {
            // some commands need this try/catch workaround, because a cmd_charPrevious triggered
            // at the beginning of the textarea, would hang the doCommand()
            // good thing is, we need this code anyway for proper beeping

            // What huh? --Kris
            try {
                cmd(this.editor, controller);
                didCommand = true;
            }
            catch (e) {
                util.reportError(e);
                dactyl.assert(didCommand);
                break;
            }
        }
    },

    moveToPosition: function (pos, select) {
        if (isObject(pos))
            var { startContainer, startOffset } = pos;
        else
            [startOffset, startOffset] = [this.selection.focusNode, pos];
        this.selection[select ? "extend" : "collapse"](startContainer, startOffset);
    },

    mungeRange: function mungeRange(range, munger, selectEnd) {
        let { editor } = this;
        editor.beginPlaceHolderTransaction(null);

        let [container, offset] = ["startContainer", "startOffset"];
        if (selectEnd)
            [container, offset] = ["endContainer", "endOffset"];

        try {
            // :(
            let idx = range[offset];
            let parent = range[container].parentNode;
            let parentIdx = Array.indexOf(parent.childNodes,
                                          range[container]);

            let delta = 0;
            for (let node of Editor.TextsIterator(range)) {
                let text = node.textContent;
                let start = 0, end = text.length;
                if (node == range.startContainer)
                    start = range.startOffset;
                if (node == range.endContainer)
                    end = range.endOffset;

                if (start == 0 && end == text.length)
                    text = munger(text);
                else
                    text = text.slice(0, start)
                         + munger(text.slice(start, end))
                         + text.slice(end);

                if (text == node.textContent)
                    continue;

                if (selectEnd)
                    delta = text.length - node.textContent.length;

                if (editor instanceof Ci.nsIPlaintextEditor) {
                    this.selectedRange = RangeFind.nodeContents(node);
                    editor.insertText(text);
                }
                else
                    node.textContent = text;
            }
            let node = parent.childNodes[parentIdx];
            if (node instanceof Text)
                idx = Math.constrain(idx + delta, 0, node.textContent.length);
            this.selection.collapse(node, idx);
        }
        finally {
            editor.endPlaceHolderTransaction();
        }
    },

    findChar: function findChar(key, count, backward, offset) {
        count  = count || 1; // XXX ?
        offset = (offset || 0) - !!backward;

        // Grab the charcode of the key spec. Using the key name
        // directly will break keys like <
        let code = DOM.Event.parse(key)[0].charCode;
        let char = String.fromCharCode(code);
        util.assert(code);

        let range = this.selectedRange.cloneRange();
        let collapse = DOM(this.element).whiteSpace == "normal";

        // Find the *count*th occurance of *char* before a non-collapsed
        // \n, ignoring the character at the caret.
        let i = 0;
        function test(c) {
            return (collapse || c != "\n") && !!(!i++ || c != char || --count);
        }

        Editor.extendRange(range, !backward, { test: test }, true);
        dactyl.assert(count == 0);
        range.collapse(backward);

        // Skip to any requested offset.
        count = Math.abs(offset);
        Editor.extendRange(range, offset > 0,
                           { test: c => !!count-- },
                           true);
        range.collapse(offset < 0);

        return range;
    },

    findNumber: function findNumber(range) {
        if (!range)
            range = this.selectedRange.cloneRange();

        // Find digit (or \n).
        Editor.extendRange(range, true, /[^\n\d]/, true);
        range.collapse(false);
        // Select entire number.
        Editor.extendRange(range, true, /\d/, true);
        Editor.extendRange(range, false, /\d/, true);

        // Sanity check.
        dactyl.assert(/^\d+$/.test(range));

        if (false) // Skip for now.
        if (range.startContainer instanceof Text && range.startOffset > 2) {
            if (range.startContainer.textContent.substr(range.startOffset - 2, 2) == "0x")
                range.setStart(range.startContainer, range.startOffset - 2);
        }

        // Grab the sign, if it's there.
        Editor.extendRange(range, false, /[+-]/, true);

        return range;
    },

    modifyNumber: function modifyNumber(delta, range) {
        range = this.findNumber(range);
        let number = parseInt(range) + delta;
        if (/^[+-]?0x/.test(range))
            number = number.toString(16).replace(/^[+-]?/, "$&0x");
        else if (/^[+-]?0\d/.test(range))
            number = number.toString(8).replace(/^[+-]?/, "$&0");

        this.selectedRange = range;
        this.editor.insertText(String(number));
        this.selection.modify("move", "backward", "character");
    },

    /**
     * Edits the given file in the external editor as specified by the
     * 'editor' option.
     *
     * @param {object|File|string} args An object specifying the file, line,
     *     and column to edit. If a non-object is specified, it is treated as
     *     the file parameter of the object.
     * @param {boolean} blocking If true, this function does not return
     *     until the editor exits.
     */
    editFileExternally: function (args, blocking) {
        if (!isObject(args) || args instanceof File)
            args = { file: args };
        args.file = args.file.path || args.file;

        args = options.get("editor").format(args);

        dactyl.assert(args.length >= 1, _("option.notSet", "editor"));

        return io.run(args.shift(), args, blocking);
    },

    // TODO: clean up with 2 functions for textboxes and currentEditor?
    editFieldExternally: function editFieldExternally(forceEditing) {
        if (!options["editor"])
            return;

        let textBox = config.isComposeWindow ? null : dactyl.focusedElement;
        if (!DOM(textBox).isInput)
            textBox = null;

        let line, column;
        let keepFocus = modes.stack.some(m => isinstance(m.main, modes.COMMAND_LINE));

        if (!forceEditing && textBox && textBox.type == "password") {
            commandline.input(_("editor.prompt.editPassword") + " ")
                .then(function (resp) {
                    if (resp && resp.match(/^y(es)?$/i))
                        editor.editFieldExternally(true);
                });
                return;
        }

        if (textBox) {
            var text = textBox.value;
            var pre = text.substr(0, textBox.selectionStart);
        }
        else {
            var editor_ = window.GetCurrentEditor ? GetCurrentEditor()
                                                  : Editor.getEditor(document.commandDispatcher.focusedWindow);
            dactyl.assert(editor_);
            text = Array.map(editor_.rootElement.childNodes,
                             e => DOM.stringify(e, true))
                        .join("");

            if (!editor_.selection.rangeCount)
                var sel = "";
            else {
                let range = RangeFind.nodeContents(editor_.rootElement);
                let end = editor_.selection.getRangeAt(0);
                range.setEnd(end.startContainer, end.startOffset);
                pre = DOM.stringify(range, true);
                if (range.startContainer instanceof Text)
                    pre = pre.replace(/^(?:<[^>"]+>)+/, "");
                if (range.endContainer instanceof Text)
                    pre = pre.replace(/(?:<\/[^>"]+>)+$/, "");
            }
        }

        line = 1 + pre.replace(/[^\n]/g, "").length;
        column = 1 + pre.replace(/[^]*\n/, "").length;

        let origGroup = DOM(textBox).highlight.toString();
        let cleanup = promises.task(function* cleanup(error) {
            if (timer)
                timer.cancel();

            let blink = ["EditorBlink1", "EditorBlink2"];
            if (error) {
                dactyl.reportError(error, true);
                blink[1] = "EditorError";
            }
            else
                dactyl.trapErrors(update, null, true);

            if (tmpfile && tmpfile.exists())
                tmpfile.remove(false);

            if (textBox) {
                DOM(textBox).highlight.remove("EditorEditing");
                if (!keepFocus)
                    dactyl.focus(textBox);

                for (let group of blink.concat(blink, "")) {
                    highlight.highlightNode(textBox, origGroup + " " + group);

                    yield promises.sleep(100);
                }
            }
        });

        function update(force) {
            if (force !== true && tmpfile.lastModifiedTime <= lastUpdate)
                return;
            lastUpdate = Date.now();

            let val = tmpfile.read();
            if (textBox) {
                textBox.value = val;

                if (true) {
                    let elem = DOM(textBox);
                    elem.attrNS(NS, "modifiable", true)
                        .style.MozUserInput;
                    elem.input().attrNS(NS, "modifiable", null);
                }
            }
            else {
                while (editor_.rootElement.firstChild)
                    editor_.rootElement.removeChild(editor_.rootElement.firstChild);
                editor_.rootElement.innerHTML = val;
            }
        }

        try {
            var tmpfile = io.createTempFile("txt", "." + buffer.uri.host);
            if (!tmpfile)
                throw Error(_("io.cantCreateTempFile"));

            if (textBox) {
                if (!keepFocus)
                    textBox.blur();
                DOM(textBox).highlight.add("EditorEditing");
            }

            if (!tmpfile.write(text))
                throw Error(_("io.cantEncode"));

            var lastUpdate = Date.now();

            var timer = services.Timer(update, 100, services.Timer.TYPE_REPEATING_SLACK);
            this.editFileExternally({ file: tmpfile.path, line: line, column: column }, cleanup);
        }
        catch (e) {
            cleanup(e);
        }
    },

    /**
     * Expands an abbreviation in the currently active textbox.
     *
     * @param {string} mode The mode filter.
     * @see Abbreviation#expand
     */
    expandAbbreviation: function (mode) {
        if (!this.selection)
            return;

        let range = this.selectedRange.cloneRange();
        if (!range.collapsed)
            return;

        Editor.extendRange(range, false, /\S/, true);
        let abbrev = abbreviations.match(mode, String(range));
        if (abbrev) {
            range.setStart(range.startContainer, range.endOffset - abbrev.lhs.length);
            this.selectedRange = range;
            this.editor.insertText(abbrev.expand(this.element));
        }
    },

    // nsIEditActionListener:
    WillDeleteNode: util.wrapCallback(function WillDeleteNode(node) {
        if (!editor.skipSave && node.textContent)
            this.setRegister(0, node);
    }),
    WillDeleteSelection: util.wrapCallback(function WillDeleteSelection(selection) {
        if (!editor.skipSave && !selection.isCollapsed)
            this.setRegister(0, selection);
    }),
    WillDeleteText: util.wrapCallback(function WillDeleteText(node, start, length) {
        if (!editor.skipSave && length)
            this.setRegister(0, node.textContent.substr(start, length));
    })
}, {
    TextsIterator: Class("TextsIterator", {
        init: function init(range, context, after) {
            this.after = after;
            this.start = context || range[after ? "endContainer" : "startContainer"];
            if (after)
                this.context = this.start;
            this.range = range;
        },

        "@@iterator": function* __iterator__() {
            while (this.nextNode())
                yield this.context;
        },

        prevNode: function prevNode() {
            if (!this.context)
                return this.context = this.start;

            var node = this.context;
            if (!this.after)
                node = node.previousSibling;

            if (!node)
                node = this.context.parentNode;
            else
                while (node.lastChild)
                    node = node.lastChild;

            if (!node || !RangeFind.containsNode(this.range, node, true))
                return null;
            this.after = false;
            return this.context = node;
        },

        nextNode: function nextNode() {
            if (!this.context)
                return this.context = this.start;

            if (!this.after)
                var node = this.context.firstChild;

            if (!node) {
                node = this.context;
                while (node.parentNode && node != this.range.endContainer
                        && !node.nextSibling)
                    node = node.parentNode;

                node = node.nextSibling;
            }

            if (!node || !RangeFind.containsNode(this.range, node, true))
                return null;
            this.after = false;
            return this.context = node;
        },

        getPrev: function getPrev() {
            return this.filter("prevNode");
        },

        getNext: function getNext() {
            return this.filter("nextNode");
        },

        filter: function filter(meth) {
            let node;
            while (node = this[meth]())
                if (node instanceof Ci.nsIDOMText &&
                        DOM(node).isVisible &&
                        DOM(node).style.MozUserSelect != "none")
                    return node;
        }
    }),

    extendRange: function extendRange(range, forward, re, sameWord, root, end) {
        function advance(positive) {
            while (true) {
                while (idx == text.length && (node = iterator.getNext())) {
                    if (node == iterator.start)
                        idx = range[offset];

                    start = text.length;
                    text += node.textContent;
                    range[set](node, idx - start);
                }

                if (idx >= text.length || re.test(text[idx]) != positive)
                    break;
                range[set](range[container], ++idx - start);
            }
        }
        function retreat(positive) {
            while (true) {
                while (idx == 0 && (node = iterator.getPrev())) {
                    let str = node.textContent;
                    if (node == iterator.start)
                        idx = range[offset];
                    else
                        idx = str.length;

                    text = str + text;
                    range[set](node, idx);
                }
                if (idx == 0 || re.test(text[idx - 1]) != positive)
                    break;
                range[set](range[container], --idx);
            }
        }

        if (end == null)
            end = forward ? "end" : "start";
        let [container, offset, set] = [end + "Container", end + "Offset",
                                        "set" + util.capitalize(end)];

        if (!root)
            for (root = range[container];
                 root.parentNode instanceof Element && !DOM(root).isEditable;
                 root = root.parentNode)
                ;
        if (root instanceof Ci.nsIDOMNSEditableElement)
            root = root.editor;
        if (root instanceof Ci.nsIEditor)
            root = root.rootElement;

        let node = range[container];
        let iterator = Editor.TextsIterator(RangeFind.nodeContents(root),
                                            node, !forward);

        let text = "";
        let idx  = 0;
        let start = 0;

        if (forward) {
            advance(true);
            if (!sameWord)
                advance(false);
        }
        else {
            if (!sameWord)
                retreat(false);
            retreat(true);
        }
        return range;
    },

    getEditor: function (elem) {
        if (arguments.length === 0) {
            dactyl.assert(dactyl.focusedElement);
            return dactyl.focusedElement;
        }

        if (!elem)
            elem = dactyl.focusedElement || document.commandDispatcher.focusedWindow;
        dactyl.assert(elem);

        return DOM(elem).editor;
    }
}, {
    modes: function initModes() {
        modes.addMode("OPERATOR", {
            char: "o",
            description: "Mappings which move the cursor",
            bases: []
        });
        modes.addMode("VISUAL", {
            char: "v",
            description: "Active when text is selected",
            display: function () "VISUAL" + (this._extended & modes.LINE ? " LINE" : ""),
            bases: [modes.COMMAND],
            ownsFocus: true
        }, {
            enter: function (stack) {
                if (editor.selectionController)
                    editor.selectionController.setCaretVisibilityDuringSelection(true);
            },
            leave: function (stack, newMode) {
                if (newMode.main == modes.CARET) {
                    let selection = content.getSelection();
                    if (selection && !selection.isCollapsed)
                        selection.collapseToStart();
                }
                else if (stack.pop)
                    editor.deselect();
            }
        });
        modes.addMode("TEXT_EDIT", {
            char: "t",
            description: "Vim-like editing of input elements",
            bases: [modes.COMMAND],
            ownsFocus: true
        }, {
            onKeyPress: function (eventList) {
                const KILL = false, PASS = true;

                // Hack, really.
                if (eventList[0].charCode || /^<(?:.-)*(?:BS|Del|C-h|C-w|C-u|C-k)>$/.test(DOM.Event.stringify(eventList[0]))) {
                    dactyl.beep();
                    return KILL;
                }
                return PASS;
            }
        });

        modes.addMode("INSERT", {
            char: "i",
            description: "Active when an input element is focused",
            insert: true,
            ownsFocus: true
        });
        modes.addMode("AUTOCOMPLETE", {
            description: "Active when an input autocomplete pop-up is active",
            display: function () "AUTOCOMPLETE (insert)",
            bases: [modes.INSERT]
        });
    },
    commands: function initCommands() {
        commands.add(["reg[isters]"],
            "List the contents of known registers",
            function (args) {
                completion.listCompleter("register", args[0]);
            },
            { argCount: "*" });
    },
    completion: function initCompletion() {
        completion.register = function complete_register(context) {
            context = context.fork("registers");
            context.keys = { text: util.identity, description: editor.bound.getRegister };

            context.match = function (r) !this.filter || this.filter.contains(r);

            context.fork("clipboard", 0, this, ctxt => {
                ctxt.match = context.match;
                ctxt.title = ["Clipboard Registers"];
                ctxt.completions = Object.keys(editor.selectionRegisters);
            });
            context.fork("kill-ring", 0, this, ctxt => {
                ctxt.match = context.match;
                ctxt.title = ["Kill Ring Registers"];
                ctxt.completions = Array.slice("0123456789");
            });
            context.fork("user", 0, this, ctxt => {
                ctxt.match = context.match;
                ctxt.title = ["User Defined Registers"];
                ctxt.completions = editor.registers.keys();
            });
        };
    },
    mappings: function initMappings() {

        Map.types["editor"] = {
            preExecute: function preExecute(args) {
                if (editor.editor && !this.editor) {
                    this.editor = editor.editor;
                    if (!this.noTransaction)
                        this.editor.beginTransaction();
                }
                editor.inEditMap = true;
            },
            postExecute: function preExecute(args) {
                editor.inEditMap = false;
                if (this.editor) {
                    if (!this.noTransaction)
                        this.editor.endTransaction();
                    this.editor = null;
                }
            }
        };
        Map.types["operator"] = {
            preExecute: function preExecute(args) {
                editor.inEditMap = true;
            },
            postExecute: function preExecute(args) {
                editor.inEditMap = true;
                if (modes.main == modes.OPERATOR)
                    modes.pop();
            }
        };

        // add mappings for commands like h,j,k,l,etc. in CARET, VISUAL and TEXT_EDIT mode
        function addMovementMap(keys, description, hasCount, caretModeMethod, caretModeArg, textEditCommand, visualTextEditCommand) {
            let extraInfo = {
                count: !!hasCount,
                type: "operator"
            };

            function caretExecute(arg) {
                let win = document.commandDispatcher.focusedWindow;
                let controller = util.selectionController(win);
                let sel = controller.getSelection(controller.SELECTION_NORMAL);

                let buffer = Buffer(win);
                if (!sel.rangeCount) // Hack.
                    buffer.resetCaret();

                if (caretModeMethod == "pageMove") { // Grr.
                    buffer.scrollVertical("pages", caretModeArg ? 1 : -1);
                    buffer.resetCaret();
                }
                else
                    controller[caretModeMethod](caretModeArg, arg);
            }

            mappings.add([modes.VISUAL], keys, description,
                function ({ count }) {
                    count = count || 1;

                    let caret = !dactyl.focusedElement;

                    while (count-- && modes.main == modes.VISUAL) {
                        if (caret)
                            caretExecute(true, true);
                        else {
                            if (callable(visualTextEditCommand))
                                visualTextEditCommand(editor.editor);
                            else
                                editor.executeCommand(visualTextEditCommand);
                        }
                    }
                },
                extraInfo);

            mappings.add([modes.CARET, modes.TEXT_EDIT, modes.OPERATOR], keys, description,
                function ({ count }) {
                    count = count || 1;

                    if (editor.editor)
                        editor.executeCommand(textEditCommand, count);
                    else {
                        while (count--)
                            caretExecute(false);
                    }
                },
                extraInfo);
        }

        // add mappings for commands like i,a,s,c,etc. in TEXT_EDIT mode
        function addBeginInsertModeMap(keys, commands, description) {
            mappings.add([modes.TEXT_EDIT], keys, description || "",
                function () {
                    commands.forEach(function (cmd) { editor.executeCommand(cmd, 1); });
                    modes.push(modes.INSERT);
                },
                { type: "editor" });
        }

        function selectPreviousLine() {
            editor.executeCommand("cmd_selectLinePrevious");
            if ((modes.extended & modes.LINE) && !editor.selectedText)
                editor.executeCommand("cmd_selectLinePrevious");
        }

        function selectNextLine() {
            editor.executeCommand("cmd_selectLineNext");
            if ((modes.extended & modes.LINE) && !editor.selectedText)
                editor.executeCommand("cmd_selectLineNext");
        }

        function updateRange(editor, forward, re, modify, sameWord) {
            let sel   = editor.selection;
            let range = sel.getRangeAt(0);

            let end = range.endContainer == sel.focusNode && range.endOffset == sel.focusOffset;
            if (range.collapsed)
                end = forward;

            Editor.extendRange(range, forward, re, sameWord,
                               editor.rootElement, end ? "end" : "start");
            modify(range);
            editor.selectionController.repaintSelection(editor.selectionController.SELECTION_NORMAL);
        }

        function clear(forward, re)
            function _clear(editor) {
                updateRange(editor, forward, re, range => {});
                dactyl.assert(!editor.selection.isCollapsed);
                editor.selection.deleteFromDocument();
                let parent = DOM(editor.rootElement.parentNode);
                if (parent.isInput)
                    parent.input();
            }

        function move(forward, re, sameWord)
            function _move(editor) {
                updateRange(editor, forward, re,
                            range => { range.collapse(!forward); },
                            sameWord);
            }
        function select(forward, re)
            function _select(editor) {
                updateRange(editor, forward, re, range => {});
            }
        function beginLine(editor_) {
            editor.executeCommand("cmd_beginLine");
            move(true, /\s/, true)(editor_);
        }

        //             COUNT  CARET                   TEXT_EDIT            VISUAL_TEXT_EDIT
        addMovementMap(["k", "<Up>"],                 "Move up one line",
                       true,  "lineMove", false,      "cmd_linePrevious", selectPreviousLine);
        addMovementMap(["j", "<Down>", "<Return>"],   "Move down one line",
                       true,  "lineMove", true,       "cmd_lineNext",     selectNextLine);
        addMovementMap(["h", "<Left>", "<BS>"],       "Move left one character",
                       true,  "characterMove", false, "cmd_charPrevious", "cmd_selectCharPrevious");
        addMovementMap(["l", "<Right>", "<Space>"],   "Move right one character",
                       true,  "characterMove", true,  "cmd_charNext",     "cmd_selectCharNext");
        addMovementMap(["b", "<C-Left>"],             "Move left one word",
                       true,  "wordMove", false,      move(false,  /\w/), select(false, /\w/));
        addMovementMap(["w", "<C-Right>"],            "Move right one word",
                       true,  "wordMove", true,       move(true,  /\w/),  select(true, /\w/));
        addMovementMap(["B"],                         "Move left to the previous white space",
                       true,  "wordMove", false,      move(false, /\S/),  select(false, /\S/));
        addMovementMap(["W"],                         "Move right to just beyond the next white space",
                       true,  "wordMove", true,       move(true,  /\S/),  select(true,  /\S/));
        addMovementMap(["e"],                         "Move to the end of the current word",
                       true,  "wordMove", true,       move(true,  /\W/),  select(true,  /\W/));
        addMovementMap(["E"],                         "Move right to the next white space",
                       true,  "wordMove", true,       move(true,  /\s/),  select(true,  /\s/));
        addMovementMap(["<C-f>", "<PageDown>"],       "Move down one page",
                       true,  "pageMove", true,       "cmd_movePageDown", "cmd_selectNextPage");
        addMovementMap(["<C-b>", "<PageUp>"],         "Move up one page",
                       true,  "pageMove", false,      "cmd_movePageUp",   "cmd_selectPreviousPage");
        addMovementMap(["gg", "<C-Home>"],            "Move to the start of text",
                       false, "completeMove", false,  "cmd_moveTop",      "cmd_selectTop");
        addMovementMap(["G", "<C-End>"],              "Move to the end of text",
                       false, "completeMove", true,   "cmd_moveBottom",   "cmd_selectBottom");
        addMovementMap(["0", "<Home>"],               "Move to the beginning of the line",
                       false, "intraLineMove", false, "cmd_beginLine",    "cmd_selectBeginLine");
        addMovementMap(["^"],                         "Move to the first non-whitespace character of the line",
                       false, "intraLineMove", false, beginLine,          "cmd_selectBeginLine");
        addMovementMap(["$", "<End>"],                "Move to the end of the current line",
                       false, "intraLineMove", true,  "cmd_endLine" ,     "cmd_selectEndLine");

        addBeginInsertModeMap(["i", "<Insert>"], [], "Insert text before the cursor");
        addBeginInsertModeMap(["a"],             ["cmd_charNext"], "Append text after the cursor");
        addBeginInsertModeMap(["I"],             ["cmd_beginLine"], "Insert text at the beginning of the line");
        addBeginInsertModeMap(["A"],             ["cmd_endLine"], "Append text at the end of the line");
        addBeginInsertModeMap(["s"],             ["cmd_deleteCharForward"], "Delete the character in front of the cursor and start insert");
        addBeginInsertModeMap(["S"],             ["cmd_deleteToEndOfLine", "cmd_deleteToBeginningOfLine"], "Delete the current line and start insert");
        addBeginInsertModeMap(["C"],             ["cmd_deleteToEndOfLine"], "Delete from the cursor to the end of the line and start insert");

        function addMotionMap(key, desc, select, cmd, mode, caretOk) {
            function doTxn(range, editor) {
                try {
                    editor.editor.beginTransaction();
                    cmd(editor, range, editor.editor);
                }
                finally {
                    editor.editor.endTransaction();
                }
            }

            mappings.add([modes.TEXT_EDIT], key,
                desc,
                function ({ command, count, motion }) {
                    let start = editor.selectedRange.cloneRange();

                    mappings.pushCommand();
                    modes.push(modes.OPERATOR, null, {
                        forCommand: command,

                        count: count,

                        leave: function leave(stack) {
                            try {
                                if (stack.push || stack.fromEscape)
                                    return;

                                editor.withSavedValues(["inEditMap"], function () {
                                    this.inEditMap = true;

                                    let range = RangeFind.union(start, editor.selectedRange);
                                    editor.selectedRange = select ? range : start;
                                    doTxn(range, editor);
                                });

                                editor.currentRegister = null;
                                modes.delay(function () {
                                    if (mode)
                                        modes.push(mode);
                                });
                            }
                            finally {
                                if (!stack.push)
                                    mappings.popCommand();
                            }
                        }
                    });
                },
                { count: true, type: "motion" });

            mappings.add([modes.VISUAL], key,
                desc,
                function ({ count,  motion }) {
                    dactyl.assert(caretOk || editor.isTextEdit);
                    if (editor.isTextEdit)
                        doTxn(editor.selectedRange, editor);
                    else
                        cmd(editor, buffer.selection.getRangeAt(0));
                },
                { count: true, type: "motion" });
        }

        addMotionMap(["d", "x"], "Delete text", true,  function (editor) { editor.cut(); });
        addMotionMap(["c"],      "Change text", true,  function (editor) { editor.cut(null, null, true); }, modes.INSERT);
        addMotionMap(["y"],      "Yank text",   false, function (editor, range) { editor.copy(range); }, null, true);

        addMotionMap(["gu"], "Lowercase text", false,
             function (editor, range) {
                 editor.mungeRange(range, String.toLocaleLowerCase);
             });

        addMotionMap(["gU"], "Uppercase text", false,
            function (editor, range) {
                editor.mungeRange(range, String.toLocaleUpperCase);
            });

        mappings.add([modes.OPERATOR],
            ["c", "d", "y"], "Select the entire line",
            function ({ command, count }) {
                dactyl.assert(command == modes.getStack(0).params.forCommand);

                let sel = editor.selection;
                sel.modify("move", "backward", "lineboundary");
                sel.modify("extend", "forward", "lineboundary");

                if (command != "c")
                    sel.modify("extend", "forward", "character");
            },
            { count: true, type: "operator" });

        let bind = function bind(names, description, action, params)
            mappings.add([modes.INPUT], names, description,
                         action, update({ type: "editor" }, params));

        bind(["<C-w>"], "Delete previous word",
             function () {
                 if (editor.editor)
                     clear(false, /\w/)(editor.editor);
                 else
                     editor.executeCommand("cmd_deleteWordBackward", 1);
             });

        bind(["<C-u>"], "Delete until beginning of current line",
             function () {
                 // Deletes the whole line. What the hell.
                 // editor.executeCommand("cmd_deleteToBeginningOfLine", 1);

                 editor.executeCommand("cmd_selectBeginLine", 1);
                 if (editor.selection && editor.selection.isCollapsed) {
                     editor.executeCommand("cmd_deleteCharBackward", 1);
                     editor.executeCommand("cmd_selectBeginLine", 1);
                 }

                 if (editor.getController("cmd_delete").isCommandEnabled("cmd_delete"))
                     editor.executeCommand("cmd_delete", 1);
             });

        bind(["<C-k>"], "Delete until end of current line",
             function () { editor.executeCommand("cmd_deleteToEndOfLine", 1); });

        bind(["<C-a>"], "Move cursor to beginning of current line",
             function () { editor.executeCommand("cmd_beginLine", 1); });

        bind(["<C-e>"], "Move cursor to end of current line",
             function () { editor.executeCommand("cmd_endLine", 1); });

        bind(["<C-h>"], "Delete character to the left",
             function () { events.feedkeys("<BS>", true); });

        bind(["<C-d>"], "Delete character to the right",
             function () { editor.executeCommand("cmd_deleteCharForward", 1); });

        bind(["<S-Insert>"], "Insert clipboard/selection",
             function () { editor.paste(); });

        bind(["<C-i>"], "Edit text field with an external editor",
             function () { editor.editFieldExternally(); });

        bind(["<C-t>"], "Edit text field in Text Edit mode",
             function () {
                 dactyl.assert(!editor.isTextEdit && editor.editor);
                 if (!dactyl.focusedElement) {
                     // Sites like Google like to use a
                     // hidden, editable window for keyboard
                     // focus and use their own WYSIWYG editor
                     // implementations for the visible area,
                     // which we can't handle.
                     let f = document.commandDispatcher.focusedWindow.frameElement;
                     dactyl.assert(f && Hints.isVisible(f, true));
                 }

                 modes.push(modes.TEXT_EDIT);
             });

        // Ugh.
        mappings.add([modes.INPUT, modes.CARET],
            ["<*-CR>", "<*-BS>", "<*-Del>", "<*-Left>", "<*-Right>", "<*-Up>", "<*-Down>",
             "<*-Home>", "<*-End>", "<*-PageUp>", "<*-PageDown>",
             "<M-c>", "<M-v>", "<*-Tab>"],
            "Handled by " + config.host,
            () => Events.PASS_THROUGH);

        mappings.add([modes.INSERT],
            ["<Space>", "<Return>"], "Expand Insert mode abbreviation",
            function () {
                editor.expandAbbreviation(modes.INSERT);
                return Events.PASS_THROUGH;
            });

        mappings.add([modes.INSERT],
            ["<C-]>", "<C-5>"], "Expand Insert mode abbreviation",
            function () { editor.expandAbbreviation(modes.INSERT); });

        bind = function bind(names, description, action, params)
            mappings.add([modes.TEXT_EDIT], names, description,
                         action, update({ type: "editor" }, params));

        bind(["<C-a>"], "Increment the next number",
             function ({ count }) { editor.modifyNumber(count || 1); },
             { count: true });

        bind(["<C-x>"], "Decrement the next number",
             function ({ count }) { editor.modifyNumber(-(count || 1)); },
             { count: true });

        // text edit mode
        bind(["u"], "Undo changes",
             function ({ count }) {
                 editor.editor.undo(Math.max(count, 1));
                 editor.deselect();
             },
             { count: true, noTransaction: true });

        bind(["<C-r>"], "Redo undone changes",
             function ({ count }) {
                 editor.editor.redo(Math.max(count, 1));
                 editor.deselect();
             },
             { count: true, noTransaction: true });

        bind(["D"], "Delete characters from the cursor to the end of the line",
             function () { editor.executeCommand("cmd_deleteToEndOfLine"); });

        bind(["o"], "Open line below current",
             function () {
                 editor.executeCommand("cmd_endLine", 1);
                 modes.push(modes.INSERT);
                 events.feedkeys("<Return>");
             });

        bind(["O"], "Open line above current",
             function () {
                 editor.executeCommand("cmd_beginLine", 1);
                 modes.push(modes.INSERT);
                 events.feedkeys("<Return>");
                 editor.executeCommand("cmd_linePrevious", 1);
             });

        bind(["X"], "Delete character to the left",
             function (args) { editor.executeCommand("cmd_deleteCharBackward", Math.max(args.count, 1)); },
            { count: true });

        bind(["x"], "Delete character to the right",
             function (args) { editor.executeCommand("cmd_deleteCharForward", Math.max(args.count, 1)); },
            { count: true });

        // visual mode
        mappings.add([modes.CARET, modes.TEXT_EDIT],
            ["v"], "Start Visual mode",
            function () { modes.push(modes.VISUAL); });

        mappings.add([modes.VISUAL],
            ["v", "V"], "End Visual mode",
            function () { modes.pop(); });

        bind(["V"], "Start Visual Line mode",
             function () {
                 modes.push(modes.VISUAL, modes.LINE);
                 editor.executeCommand("cmd_beginLine", 1);
                 editor.executeCommand("cmd_selectLineNext", 1);
             });

        mappings.add([modes.VISUAL],
            ["s"], "Change selected text",
            function () {
                dactyl.assert(editor.isTextEdit);
                editor.executeCommand("cmd_cut");
                modes.push(modes.INSERT);
            });

        mappings.add([modes.VISUAL],
            ["o"], "Move cursor to the other end of the selection",
            function () {
                if (editor.isTextEdit)
                    var selection = editor.selection;
                else
                    selection = buffer.focusedFrame.getSelection();

                util.assert(selection.focusNode);
                let { focusOffset, anchorOffset, focusNode, anchorNode } = selection;
                selection.collapse(focusNode, focusOffset);
                selection.extend(anchorNode, anchorOffset);
            });

        bind(["p"], "Paste clipboard contents",
             function ({ count }) {
                dactyl.assert(!editor.isCaret);
                editor.executeCommand(modules.bind("paste", editor, null),
                                      count || 1);
            },
            { count: true });

        mappings.add([modes.COMMAND],
            ['"'], "Bind a register to the next command",
            function ({ arg }) {
                editor.pushRegister(arg);
            },
            { arg: true });

        mappings.add([modes.INPUT],
            ["<C-'>", '<C-">'], "Bind a register to the next command",
            function ({ arg }) {
                editor.pushRegister(arg);
            },
            { arg: true });

        bind = function bind(names, description, action, params)
            mappings.add([modes.TEXT_EDIT, modes.OPERATOR, modes.VISUAL],
                         names, description,
                         action, update({ type: "editor" }, params));

        // finding characters
        function offset(backward, before, pos) {
            if (!backward && modes.main != modes.TEXT_EDIT)
                return before ? 0 : 1;
            if (before)
                return backward ? +1 : -1;
            return 0;
        }

        bind(["f"], "Find a character on the current line, forwards",
             function ({ arg, count }) {
                 editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), false,
                                                       offset(false, false)),
                                       modes.main == modes.VISUAL);
             },
             { arg: true, count: true, type: "operator" });

        bind(["F"], "Find a character on the current line, backwards",
             function ({ arg, count }) {
                 editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), true,
                                                       offset(true, false)),
                                       modes.main == modes.VISUAL);
             },
             { arg: true, count: true, type: "operator" });

        bind(["t"], "Find a character on the current line, forwards, and move to the character before it",
             function ({ arg, count }) {
                 editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), false,
                                                       offset(false, true)),
                                       modes.main == modes.VISUAL);
             },
             { arg: true, count: true, type: "operator" });

        bind(["T"], "Find a character on the current line, backwards, and move to the character after it",
             function ({ arg, count }) {
                 editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), true,
                                                       offset(true, true)),
                                       modes.main == modes.VISUAL);
             },
             { arg: true, count: true, type: "operator" });

        // text edit and visual mode
        mappings.add([modes.TEXT_EDIT, modes.VISUAL],
            ["~"], "Switch case of the character under the cursor and move the cursor to the right",
            function ({ count }) {
                function munger(range)
                    String(range).replace(/./g, c => {
                        let lc = c.toLocaleLowerCase();
                        return c == lc ? c.toLocaleUpperCase() : lc;
                    });

                var range = editor.selectedRange;
                if (range.collapsed) {
                    count = count || 1;
                    Editor.extendRange(range, true, { test: c => !!count-- }, true);
                }
                editor.mungeRange(range, munger, count != null);

                modes.pop(modes.TEXT_EDIT);
            },
            { count: true });

        bind = function bind(...args) apply(mappings, "add", [[modes.AUTOCOMPLETE]].concat(args));

        bind(["<Esc>"], "Return to Insert mode",
             () => Events.PASS_THROUGH);

        bind(["<C-[>"], "Return to Insert mode",
             function () { events.feedkeys("<Esc>", { skipmap: true }); });

        bind(["<Up>"], "Select the previous autocomplete result",
             () => Events.PASS_THROUGH);

        bind(["<C-p>"], "Select the previous autocomplete result",
             function () { events.feedkeys("<Up>", { skipmap: true }); });

        bind(["<Down>"], "Select the next autocomplete result",
             () => Events.PASS_THROUGH);

        bind(["<C-n>"], "Select the next autocomplete result",
             function () { events.feedkeys("<Down>", { skipmap: true }); });
    },
    options: function initOptions() {
        options.add(["editor"],
            "The external text editor",
            "string", 'gvim -f +<line> +"sil! call cursor(0, <column>)" <file>', {
                format: function (obj, value) {
                    let args = commands.parseArgs(value || this.value,
                                                  { argCount: "*", allowUnknownOptions: true })
                                       .map(util.compileMacro)
                                       .filter(fmt => fmt.valid(obj))
                                       .map(fmt => fmt(obj));

                    if (obj["file"] && !this.has("file"))
                        args.push(obj["file"]);
                    return args;
                },
                has: function (key) util.compileMacro(this.value).seen.has(key),
                validator: function (value) {
                    this.format({}, value);
                    let allowed = new RealSet(["column", "file", "line"]);
                    return [k for (k of util.compileMacro(value).seen)]
                                .every(k => allowed.has(k));
                }
            });

        options.add(["insertmode", "im"],
            "Enter Insert mode rather than Text Edit mode when focusing text areas",
            "boolean", true);

        options.add(["spelllang", "spl"],
            "The language used by the spell checker",
            "string", config.locale,
            {
                initValue: function () {},
                getter: function getter() {
                    try {
                        return services.spell.dictionary || "";
                    }
                    catch (e) {
                        return "";
                    }
                },
                setter: function setter(val) { services.spell.dictionary = val; },
                completer: function completer(context) {
                    let res = {};
                    services.spell.getDictionaryList(res, {});
                    context.completions = res.value;
                    context.keys = { text: util.identity, description: util.identity };
                }
            });
    },
    sanitizer: function initSanitizer() {
        sanitizer.addItem("registers", {
            description: "Register values",
            persistent: true,
            action: function (timespan, host) {
                if (!host) {
                    for (let [k, v] of editor.registers)
                        if (timespan.contains(v.timestamp))
                            editor.registers.remove(k);
                    editor.registerRing.truncate(0);
                }
            }
        });
    }
});

// vim: set fdm=marker sw=4 sts=4 ts=8 et: