]> git.donarmstrong.com Git - dactyl.git/blob - common/content/modes.js
Import 1.0 supporting Firefox up to 14.*
[dactyl.git] / common / content / modes.js
1 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
3 // Copyright (c) 2008-2011 by Kris Maglione <maglione.k@gmail.com>
4 //
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
7 /* use strict */
8
9 /** @scope modules */
10
11 var Modes = Module("modes", {
12     init: function init() {
13         this.modeChars = {};
14         this._main = 1;     // NORMAL
15         this._extended = 0; // NONE
16
17         this._lastShown = null;
18
19         this._passNextKey = false;
20         this._passAllKeys = false;
21         this._recording = false;
22         this._replaying = false; // playing a macro
23
24         this._modeStack = update([], {
25             pop: function pop() {
26                 if (this.length <= 1)
27                     throw Error("Trying to pop last element in mode stack");
28                 return pop.superapply(this, arguments);
29             }
30         });
31
32         this._modes = [];
33         this._mainModes = [];
34         this._modeMap = {};
35
36         this.boundProperties = {};
37
38         this.addMode("BASE", {
39             char: "b",
40             description: "The base mode for all other modes",
41             bases: [],
42             count: false
43         });
44         this.addMode("MAIN", {
45             char: "m",
46             description: "The base mode for most other modes",
47             bases: [this.BASE],
48             count: false
49         });
50         this.addMode("COMMAND", {
51             char: "C",
52             description: "The base mode for most modes which accept commands rather than input"
53         });
54
55         this.addMode("NORMAL", {
56             char: "n",
57             description: "Active when nothing is focused",
58             bases: [this.COMMAND]
59         });
60         this.addMode("CARET", {
61             char: "caret",
62             description: "Active when the caret is visible in the web content",
63             bases: [this.NORMAL]
64         }, {
65
66             get pref()    prefs.get("accessibility.browsewithcaret"),
67             set pref(val) prefs.set("accessibility.browsewithcaret", val),
68
69             enter: function (stack) {
70                 if (stack.pop && !this.pref)
71                     modes.pop();
72                 else if (!stack.pop && !this.pref)
73                     this.pref = true;
74                 if (!stack.pop)
75                     buffer.resetCaret();
76             },
77
78             leave: function (stack) {
79                 if (!stack.push && this.pref)
80                     this.pref = false;
81             }
82         });
83
84         this.addMode("INPUT", {
85             char: "I",
86             description: "The base mode for input modes, including Insert and Command Line",
87             bases: [this.MAIN],
88             insert: true
89         });
90
91         this.addMode("EMBED", {
92             description: "Active when an <embed> or <object> element is focused",
93             bases: [modes.MAIN],
94             insert: true,
95             ownsFocus: true,
96             passthrough: true
97         });
98
99         this.addMode("PASS_THROUGH", {
100             description: "All keys but <C-v> are ignored by " + config.appName,
101             bases: [this.BASE],
102             hidden: true,
103             insert: true,
104             passthrough: true
105         });
106         this.addMode("QUOTE", {
107             description: "The next key sequence is ignored by " + config.appName + ", unless in Pass Through mode",
108             bases: [this.BASE],
109             hidden: true,
110             passthrough: true,
111             display: function ()
112                 (modes.getStack(1).main == modes.PASS_THROUGH
113                     ? (modes.getStack(2).main.display() || modes.getStack(2).main.name)
114                     : "PASS THROUGH") + " (next)"
115         }, {
116             // Fix me.
117             preExecute: function (map) { if (modes.main == modes.QUOTE && map.name !== "<C-v>") modes.pop(); },
118             postExecute: function (map) { if (modes.main == modes.QUOTE && map.name === "<C-v>") modes.pop(); },
119             onKeyPress: function (events) { if (modes.main == modes.QUOTE) modes.pop(); }
120         });
121         this.addMode("IGNORE", { hidden: true }, {
122             onKeyPress: function (events) false,
123             bases: [],
124             passthrough: true
125         });
126
127         this.addMode("MENU", {
128             description: "Active when a menu or other pop-up is open",
129             input: true,
130             passthrough: true,
131             ownsInput: false
132         }, {
133             leave: function leave(stack) {
134                 util.timeout(function () {
135                     if (stack.pop && !modes.main.input && Events.isInputElement(dactyl.focusedElement))
136                         modes.push(modes.INSERT);
137                 });
138             }
139         });
140
141         this.addMode("LINE", {
142             extended: true, hidden: true
143         });
144
145         this.push(this.NORMAL, 0, {
146             enter: function (stack, prev) {
147                 if (prefs.get("accessibility.browsewithcaret"))
148                     prefs.set("accessibility.browsewithcaret", false);
149
150                 statusline.updateStatus();
151                 if (!stack.fromFocus && prev.main.ownsFocus)
152                     dactyl.focusContent(true);
153                 if (prev.main == modes.NORMAL) {
154                     dactyl.focusContent(true);
155                     for (let frame in values(buffer.allFrames())) {
156                         // clear any selection made
157                         let selection = frame.getSelection();
158                         if (selection && !selection.isCollapsed)
159                             selection.collapseToStart();
160                     }
161                 }
162
163             }
164         });
165     },
166
167     cleanup: function cleanup() {
168         modes.reset();
169     },
170
171     signals: {
172         "io.source": function ioSource(context, file, modTime) {
173             cache.flushEntry("modes.dtd", modTime);
174         }
175     },
176
177     _getModeMessage: function _getModeMessage() {
178         // when recording a macro
179         let macromode = "";
180         if (this.recording)
181             macromode = "recording " + this.recording + " ";
182         else if (this.replaying)
183             macromode = "replaying";
184
185         if (!options.get("showmode").getKey(this.main.allBases, false))
186             return macromode;
187
188         let modeName = this._modeMap[this._main].display();
189         if (!modeName)
190             return macromode;
191
192         if (macromode)
193             macromode = " " + macromode;
194         return "-- " + modeName + " --" + macromode;
195     },
196
197     NONE: 0,
198
199     __iterator__: function __iterator__() array.iterValues(this.all),
200
201     get all() this._modes.slice(),
202
203     get mainModes() (mode for ([k, mode] in Iterator(modes._modeMap)) if (!mode.extended && mode.name == k)),
204
205     get mainMode() this._modeMap[this._main],
206
207     get passThrough() !!(this.main & (this.PASS_THROUGH|this.QUOTE)) ^ (this.getStack(1).main === this.PASS_THROUGH),
208
209     get topOfStack() this._modeStack[this._modeStack.length - 1],
210
211     addMode: function addMode(name, options, params) {
212         let mode = Modes.Mode(name, options, params);
213
214         this[name] = mode;
215         if (mode.char)
216             this.modeChars[mode.char] = (this.modeChars[mode.char] || []).concat(mode);
217         this._modeMap[name] = mode;
218         this._modeMap[mode] = mode;
219
220         this._modes.push(mode);
221         if (!mode.extended)
222             this._mainModes.push(mode);
223
224         dactyl.triggerObserver("modes.add", mode);
225     },
226
227     removeMode: function removeMode(mode) {
228         this.remove(mode);
229         if (this[mode.name] == mode)
230             delete this[mode.name];
231         if (this._modeMap[mode.name] == mode)
232             delete this._modeMap[mode.name];
233         if (this._modeMap[mode.mode] == mode)
234             delete this._modeMap[mode.mode];
235
236         this._mainModes = this._mainModes.filter(function (m) m != mode);
237     },
238
239     dumpStack: function dumpStack() {
240         util.dump("Mode stack:");
241         for (let [i, mode] in array.iterItems(this._modeStack))
242             util.dump("    " + i + ": " + mode);
243     },
244
245     getMode: function getMode(name) this._modeMap[name],
246
247     getStack: function getStack(idx) this._modeStack[this._modeStack.length - idx - 1] || this._modeStack[0],
248
249     get stack() this._modeStack.slice(),
250
251     getCharModes: function getCharModes(chr) (this.modeChars[chr] || []).slice(),
252
253     have: function have(mode) this._modeStack.some(function (m) isinstance(m.main, mode)),
254
255     matchModes: function matchModes(obj)
256         this._modes.filter(function (mode) Object.keys(obj)
257                                                  .every(function (k) obj[k] == (mode[k] || false))),
258
259     // show the current mode string in the command line
260     show: function show() {
261         if (!loaded.modes)
262             return;
263
264         let msg = this._getModeMessage();
265
266         if (msg || loaded.commandline)
267             commandline.widgets.mode = msg || null;
268     },
269
270     remove: function remove(mode, covert) {
271         if (covert && this.topOfStack.main != mode) {
272             util.assert(mode != this.NORMAL);
273             for (let m; m = array.nth(this.modeStack, function (m) m.main == mode, 0);)
274                 this._modeStack.splice(this._modeStack.indexOf(m));
275         }
276         else if (this.stack.some(function (m) m.main == mode)) {
277             this.pop(mode);
278             this.pop();
279         }
280     },
281
282     delayed: [],
283     delay: function delay(callback, self) { this.delayed.push([callback, self]); },
284
285     save: function save(id, obj, prop, test) {
286         if (!(id in this.boundProperties))
287             for (let elem in array.iterValues(this._modeStack))
288                 elem.saved[id] = { obj: obj, prop: prop, value: obj[prop], test: test };
289         this.boundProperties[id] = { obj: util.weakReference(obj), prop: prop, test: test };
290     },
291
292     inSet: false,
293
294     set: function set(mainMode, extendedMode, params, stack) {
295         var delayed, oldExtended, oldMain, prev, push;
296
297         if (this.inSet) {
298             dactyl.reportError(Error(_("mode.recursiveSet")), true);
299             return;
300         }
301
302         params = params || Object.create(this.getMode(mainMode || this.main).params);
303
304         if (!stack && mainMode != null && this._modeStack.length > 1)
305             this.reset();
306
307         this.withSavedValues(["inSet"], function set() {
308             this.inSet = true;
309
310             oldMain = this._main, oldExtended = this._extended;
311
312             if (extendedMode != null)
313                 this._extended = extendedMode;
314             if (mainMode != null) {
315                 this._main = mainMode;
316                 if (!extendedMode)
317                     this._extended = this.NONE;
318             }
319
320             if (stack && stack.pop && stack.pop.params.leave)
321                 dactyl.trapErrors("leave", stack.pop.params,
322                                   stack, this.topOfStack);
323
324             push = mainMode != null && !(stack && stack.pop) &&
325                 Modes.StackElement(this._main, this._extended, params, {});
326
327             if (push && this.topOfStack) {
328                 if (this.topOfStack.params.leave)
329                     dactyl.trapErrors("leave", this.topOfStack.params,
330                                       { push: push }, push);
331
332                 for (let [id, { obj, prop, test }] in Iterator(this.boundProperties)) {
333                     if (!obj.get())
334                         delete this.boundProperties[id];
335                     else
336                         this.topOfStack.saved[id] = { obj: obj.get(), prop: prop, value: obj.get()[prop], test: test };
337                 }
338             }
339
340             delayed = this.delayed;
341             this.delayed = [];
342
343             prev = stack && stack.pop || this.topOfStack;
344             if (push)
345                 this._modeStack.push(push);
346         });
347
348         if (stack && stack.pop)
349             for (let { obj, prop, value, test } in values(this.topOfStack.saved))
350                 if (!test || !test(stack, prev))
351                     dactyl.trapErrors(function () { obj[prop] = value });
352
353         this.show();
354
355         if (this.topOfStack.params.enter && prev)
356             dactyl.trapErrors("enter", this.topOfStack.params,
357                               push ? { push: push } : stack || {},
358                               prev);
359
360         delayed.forEach(function ([fn, self]) dactyl.trapErrors(fn, self));
361
362         dactyl.triggerObserver("modes.change", [oldMain, oldExtended], [this._main, this._extended], stack);
363         this.show();
364     },
365
366     onCaretChange: function onPrefChange(value) {
367         if (!value && modes.main == modes.CARET)
368             modes.pop();
369         if (value && modes.main == modes.NORMAL)
370             modes.push(modes.CARET);
371     },
372
373     push: function push(mainMode, extendedMode, params) {
374         if (this.main == this.IGNORE)
375             this.pop();
376
377         this.set(mainMode, extendedMode, params, { push: this.topOfStack });
378     },
379
380     pop: function pop(mode, args) {
381         while (this._modeStack.length > 1 && this.main != mode) {
382             let a = this._modeStack.pop();
383             this.set(this.topOfStack.main, this.topOfStack.extended, this.topOfStack.params,
384                      update({ pop: a }, args));
385
386             if (mode == null)
387                 return;
388         }
389     },
390
391     replace: function replace(mode, oldMode, args) {
392         while (oldMode && this._modeStack.length > 1 && this.main != oldMode)
393             this.pop();
394
395         if (this._modeStack.length > 1)
396             this.set(mode, null, null,
397                      update({ push: this.topOfStack, pop: this._modeStack.pop() },
398                             args || {}));
399         this.push(mode);
400     },
401
402     reset: function reset() {
403         if (this._modeStack.length == 1 && this.topOfStack.params.enter)
404             this.topOfStack.params.enter({}, this.topOfStack);
405         while (this._modeStack.length > 1)
406             this.pop();
407     },
408
409     get recording() this._recording,
410     set recording(value) { this._recording = value; this.show(); },
411
412     get replaying() this._replaying,
413     set replaying(value) { this._replaying = value; this.show(); },
414
415     get main() this._main,
416     set main(value) { this.set(value); },
417
418     get extended() this._extended,
419     set extended(value) { this.set(null, value); }
420 }, {
421     Mode: Class("Mode", {
422         init: function init(name, options, params) {
423             if (options.bases)
424                 util.assert(options.bases.every(function (m) m instanceof this, this.constructor),
425                            _("mode.invalidBases"), false);
426
427             this.update({
428                 id: 1 << Modes.Mode._id++,
429                 description: name,
430                 name: name,
431                 params: params || {}
432             }, options);
433         },
434
435         description: Messages.Localized(""),
436
437         displayName: Class.Memoize(function () this.name.split("_").map(util.capitalize).join(" ")),
438
439         isinstance: function isinstance(obj)
440             this.allBases.indexOf(obj) >= 0 || callable(obj) && this instanceof obj,
441
442         allBases: Class.Memoize(function () {
443             let seen = {}, res = [], queue = [this].concat(this.bases);
444             for (let mode in array.iterValues(queue))
445                 if (!Set.add(seen, mode)) {
446                     res.push(mode);
447                     queue.push.apply(queue, mode.bases);
448                 }
449             return res;
450         }),
451
452         get bases() this.input ? [modes.INPUT] : [modes.MAIN],
453
454         get count() !this.insert,
455
456         _display: Class.Memoize(function _display() this.name.replace("_", " ", "g")),
457
458         display: function display() this._display,
459
460         extended: false,
461
462         hidden: false,
463
464         input: Class.Memoize(function input() this.insert || this.bases.length && this.bases.some(function (b) b.input)),
465
466         insert: Class.Memoize(function insert() this.bases.length && this.bases.some(function (b) b.insert)),
467
468         ownsFocus: Class.Memoize(function ownsFocus() this.bases.length && this.bases.some(function (b) b.ownsFocus)),
469
470         passEvent: function passEvent(event) this.input && event.charCode && !(event.ctrlKey || event.altKey || event.metaKey),
471
472         passUnknown: Class.Memoize(function () options.get("passunknown").getKey(this.name)),
473
474         get mask() this,
475
476         get toStringParams() [this.name],
477
478         valueOf: function valueOf() this.id
479     }, {
480         _id: 0
481     }),
482     StackElement: (function () {
483         const StackElement = Struct("main", "extended", "params", "saved");
484         StackElement.className = "Modes.StackElement";
485         StackElement.defaultValue("params", function () this.main.params);
486
487         update(StackElement.prototype, {
488             get toStringParams() !loaded.modes ? this.main.name : [
489                 this.main.name,
490                 <>({ modes.all.filter(function (m) this.extended & m, this).map(function (m) m.name).join("|") })</>
491             ]
492         });
493         return StackElement;
494     })(),
495     cacheId: 0,
496     boundProperty: function BoundProperty(desc) {
497         let id = this.cacheId++;
498         let value;
499
500         desc = desc || {};
501         return Class.Property(update({
502             configurable: true,
503             enumerable: true,
504             init: function bound_init(prop) update(this, {
505                 get: function bound_get() {
506                     if (desc.get)
507                         var val = desc.get.call(this, value);
508                     return val === undefined ? value : val;
509                 },
510                 set: function bound_set(val) {
511                     modes.save(id, this, prop, desc.test);
512                     if (desc.set)
513                         value = desc.set.call(this, val);
514                     value = !desc.set || value === undefined ? val : value;
515                 }
516             })
517         }, desc));
518     }
519 }, {
520     cache: function initCache() {
521         function makeTree() {
522             let list = modes.all.filter(function (m) m.name !== m.description);
523
524             let tree = {};
525
526             for (let mode in values(list))
527                 tree[mode.name] = {};
528
529             for (let mode in values(list))
530                 for (let base in values(mode.bases))
531                     tree[base.name][mode.name] = tree[mode.name];
532
533             let roots = iter([m.name, tree[m.name]] for (m in values(list)) if (!m.bases.length)).toObject();
534
535             default xml namespace = NS;
536             function rec(obj) {
537                 XML.ignoreWhitespace = XML.prettyPrinting = false;
538
539                 let res = <ul dactyl:highlight="Dense" xmlns:dactyl={NS}/>;
540                 Object.keys(obj).sort().forEach(function (name) {
541                     let mode = modes.getMode(name);
542                     res.* += <li><em>{mode.displayName}</em>: {mode.description}{
543                         rec(obj[name])
544                     }</li>;
545                 });
546
547                 if (res.*.length())
548                     return res;
549                 return <></>;
550             }
551
552             return rec(roots);
553         }
554
555         cache.register("modes.dtd", function ()
556             util.makeDTD(iter({ "modes.tree": makeTree() },
557                               config.dtd)));
558     },
559     mappings: function initMappings() {
560         mappings.add([modes.BASE, modes.NORMAL],
561             ["<Esc>", "<C-[>"],
562             "Return to Normal mode",
563             function () { modes.reset(); });
564
565         mappings.add([modes.INPUT, modes.COMMAND, modes.OPERATOR, modes.PASS_THROUGH, modes.QUOTE],
566             ["<Esc>", "<C-[>"],
567             "Return to the previous mode",
568             function () { modes.pop(null, { fromEscape: true }); });
569
570         mappings.add([modes.AUTOCOMPLETE, modes.MENU], ["<C-c>"],
571             "Leave Autocomplete or Menu mode",
572             function () { modes.pop(); });
573
574         mappings.add([modes.MENU], ["<Esc>"],
575             "Close the current popup",
576             function () {
577                 if (events.popups.active.length)
578                     return Events.PASS_THROUGH;
579                 modes.pop();
580             });
581
582         mappings.add([modes.MENU], ["<C-[>"],
583             "Close the current popup",
584             function () { events.feedkeys("<Esc>"); });
585     },
586     options: function initOptions() {
587         let opts = {
588             completer: function completer(context, extra) {
589                 if (extra.value && context.filter[0] == "!")
590                     context.advance(1);
591                 return completer.superapply(this, arguments);
592             },
593
594             getKey: function getKey(val, default_) {
595                 if (isArray(val))
596                     return (array.nth(this.value, function (v) val.some(function (m) m.name === v.mode), 0)
597                                 || { result: default_ }).result;
598
599                 return Set.has(this.valueMap, val) ? this.valueMap[val] : default_;
600             },
601
602             setter: function (vals) {
603                 modes.all.forEach(function (m) { delete m.passUnknown });
604
605                 vals = vals.map(function (v) update(new String(v.toLowerCase()), {
606                     mode: v.replace(/^!/, "").toUpperCase(),
607                     result: v[0] !== "!"
608                 }));
609
610                 this.valueMap = values(vals).map(function (v) [v.mode, v.result]).toObject();
611                 return vals;
612             },
613
614             validator: function validator(vals) vals.map(function (v) v.replace(/^!/, "")).every(Set.has(this.values)),
615
616             get values() array.toObject([[m.name.toLowerCase(), m.description] for (m in values(modes._modes)) if (!m.hidden)])
617         };
618
619         options.add(["passunknown", "pu"],
620             "Pass through unknown keys in these modes",
621             "stringlist", "!text_edit,!visual,base",
622             opts);
623
624         options.add(["showmode", "smd"],
625             "Show the current mode in the command line when it matches this expression",
626             "stringlist", "caret,output_multiline,!normal,base,operator",
627             opts);
628     },
629     prefs: function initPrefs() {
630         prefs.watch("accessibility.browsewithcaret",
631                     function () { modes.onCaretChange.apply(modes, arguments) });
632     }
633 });
634
635 // vim: set fdm=marker sw=4 ts=4 et: