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-2013 Kris Maglione <maglione.k@gmail.com>
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
11 var Modes = Module("modes", {
12 init: function init() {
14 this._main = 1; // NORMAL
15 this._extended = 0; // NONE
17 this._lastShown = null;
19 this._passNextKey = false;
20 this._passAllKeys = false;
21 this._recording = false;
22 this._replaying = false; // playing a macro
24 this._modeStack = update([], {
27 throw Error("Trying to pop last element in mode stack");
28 return pop.superapply(this, arguments);
36 this.boundProperties = {};
38 this.addMode("BASE", {
40 description: "The base mode for all other modes",
44 this.addMode("MAIN", {
46 description: "The base mode for most other modes",
50 this.addMode("COMMAND", {
52 description: "The base mode for most modes which accept commands rather than input"
55 this.addMode("NORMAL", {
57 description: "Active when nothing is focused",
60 this.addMode("CARET", {
62 description: "Active when the caret is visible in the web content",
66 get pref() prefs.get("accessibility.browsewithcaret"),
67 set pref(val) prefs.set("accessibility.browsewithcaret", val),
69 enter: function (stack) {
70 if (stack.pop && !this.pref)
72 else if (!stack.pop && !this.pref)
78 leave: function (stack) {
79 if (!stack.push && this.pref)
84 this.addMode("INPUT", {
86 description: "The base mode for input modes, including Insert and Command Line",
91 this.addMode("EMBED", {
92 description: "Active when an <embed> or <object> element is focused",
99 this.addMode("PASS_THROUGH", {
100 description: "All keys but <C-v> are ignored by " + config.appName,
106 this.addMode("QUOTE", {
107 description: "The next key sequence is ignored by " + config.appName + ", unless in Pass Through mode",
112 (modes.getStack(1).main == modes.PASS_THROUGH
113 ? (modes.getStack(2).main.display() || modes.getStack(2).main.name)
114 : "PASS THROUGH") + " (next)"
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(); }
121 this.addMode("IGNORE", { hidden: true }, {
122 onKeyPress: function (events_) {
123 if (events.isCancelKey(DOM.Event.stringify(events_[0])))
131 this.addMode("MENU", {
132 description: "Active when a menu or other pop-up is open",
137 leave: function leave(stack) {
138 util.timeout(function () {
139 if (stack.pop && !modes.main.input && Events.isInputElement(dactyl.focusedElement))
140 modes.push(modes.INSERT);
145 this.addMode("LINE", {
146 extended: true, hidden: true
149 this.push(this.NORMAL, 0, {
150 enter: function (stack, prev) {
151 if (prefs.get("accessibility.browsewithcaret"))
152 prefs.set("accessibility.browsewithcaret", false);
154 statusline.updateStatus();
155 if (!stack.fromFocus && prev.main.ownsFocus)
156 dactyl.focusContent(true);
157 if (prev.main == modes.NORMAL) {
158 dactyl.focusContent(true);
159 for (let frame in values(buffer.allFrames())) {
160 // clear any selection made
161 let selection = frame.getSelection();
162 if (selection && !selection.isCollapsed)
163 selection.collapseToStart();
171 cleanup: function cleanup() {
176 "io.source": function ioSource(context, file, modTime) {
177 cache.flushEntry("modes.dtd", modTime);
181 _getModeMessage: function _getModeMessage() {
182 // when recording a macro
185 macromode = "recording " + this.recording + " ";
186 else if (this.replaying)
187 macromode = "replaying";
189 if (!options.get("showmode").getKey(this.main.allBases, false))
192 let modeName = this._modeMap[this._main].display();
197 macromode = " " + macromode;
198 return "-- " + modeName + " --" + macromode;
203 __iterator__: function __iterator__() array.iterValues(this.all),
205 get all() this._modes.slice(),
207 get mainModes() (mode for ([k, mode] in Iterator(modes._modeMap)) if (!mode.extended && mode.name == k)),
209 get mainMode() this._modeMap[this._main],
211 get passThrough() !!(this.main & (this.PASS_THROUGH|this.QUOTE)) ^ (this.getStack(1).main === this.PASS_THROUGH),
213 get topOfStack() this._modeStack[this._modeStack.length - 1],
215 addMode: function addMode(name, options, params) {
216 let mode = Modes.Mode(name, options, params);
220 this.modeChars[mode.char] = (this.modeChars[mode.char] || []).concat(mode);
221 this._modeMap[name] = mode;
222 this._modeMap[mode] = mode;
224 this._modes.push(mode);
226 this._mainModes.push(mode);
228 dactyl.triggerObserver("modes.add", mode);
231 removeMode: function removeMode(mode) {
233 if (this[mode.name] == mode)
234 delete this[mode.name];
235 if (this._modeMap[mode.name] == mode)
236 delete this._modeMap[mode.name];
237 if (this._modeMap[mode.mode] == mode)
238 delete this._modeMap[mode.mode];
240 this._mainModes = this._mainModes.filter(m => m != mode);
243 dumpStack: function dumpStack() {
244 util.dump("Mode stack:");
245 for (let [i, mode] in array.iterItems(this._modeStack))
246 util.dump(" " + i + ": " + mode);
249 getMode: function getMode(name) this._modeMap[name],
251 getStack: function getStack(idx) this._modeStack[this._modeStack.length - idx - 1] || this._modeStack[0],
253 get stack() this._modeStack.slice(),
255 getCharModes: function getCharModes(chr) (this.modeChars[chr] || []).slice(),
257 have: function have(mode) this._modeStack.some(m => isinstance(m.main, mode)),
259 matchModes: function matchModes(obj)
260 this._modes.filter(mode => Object.keys(obj)
261 .every(k => obj[k] == (mode[k] || false))),
263 // show the current mode string in the command line
264 show: function show() {
268 let msg = this._getModeMessage();
270 if (msg || loaded.commandline)
271 commandline.widgets.mode = msg || null;
274 remove: function remove(mode, covert) {
275 if (covert && this.topOfStack.main != mode) {
276 util.assert(mode != this.NORMAL);
277 for (let m; m = array.nth(this.modeStack, m => m.main == mode, 0);)
278 this._modeStack.splice(this._modeStack.indexOf(m));
280 else if (this.stack.some(m => m.main == mode)) {
287 delay: function delay(callback, self) { this.delayed.push([callback, self]); },
289 save: function save(id, obj, prop, test) {
290 if (!(id in this.boundProperties))
291 for (let elem in array.iterValues(this._modeStack))
292 elem.saved[id] = { obj: obj, prop: prop, value: obj[prop], test: test };
293 this.boundProperties[id] = { obj: util.weakReference(obj), prop: prop, test: test };
298 set: function set(mainMode, extendedMode, params, stack) {
299 var delayed, oldExtended, oldMain, prev, push;
302 dactyl.reportError(Error(_("mode.recursiveSet")), true);
306 params = params || Object.create(this.getMode(mainMode || this.main).params);
308 if (!stack && mainMode != null && this._modeStack.length > 1)
311 this.withSavedValues(["inSet"], function set() {
314 oldMain = this._main, oldExtended = this._extended;
316 if (extendedMode != null)
317 this._extended = extendedMode;
318 if (mainMode != null) {
319 this._main = mainMode;
321 this._extended = this.NONE;
324 if (stack && stack.pop && stack.pop.params.leave)
325 dactyl.trapErrors("leave", stack.pop.params,
326 stack, this.topOfStack);
328 push = mainMode != null && !(stack && stack.pop) &&
329 Modes.StackElement(this._main, this._extended, params, {});
331 if (push && this.topOfStack) {
332 if (this.topOfStack.params.leave)
333 dactyl.trapErrors("leave", this.topOfStack.params,
334 { push: push }, push);
336 for (let [id, { obj, prop, test }] in Iterator(this.boundProperties)) {
338 delete this.boundProperties[id];
340 this.topOfStack.saved[id] = { obj: obj.get(), prop: prop, value: obj.get()[prop], test: test };
344 delayed = this.delayed;
347 prev = stack && stack.pop || this.topOfStack;
349 this._modeStack.push(push);
352 if (stack && stack.pop)
353 for (let { obj, prop, value, test } in values(this.topOfStack.saved))
354 if (!test || !test(stack, prev))
355 dactyl.trapErrors(function () { obj[prop] = value });
359 if (this.topOfStack.params.enter && prev)
360 dactyl.trapErrors("enter", this.topOfStack.params,
361 push ? { push: push } : stack || {},
364 delayed.forEach(([fn, self]) => {
365 dactyl.trapErrors(fn, self);
368 dactyl.triggerObserver("modes.change", [oldMain, oldExtended], [this._main, this._extended], stack);
372 onCaretChange: function onPrefChange(value) {
373 if (!value && modes.main == modes.CARET)
375 if (value && modes.main == modes.NORMAL)
376 modes.push(modes.CARET);
379 push: function push(mainMode, extendedMode, params) {
380 if (this.main == this.IGNORE)
383 this.set(mainMode, extendedMode, params, { push: this.topOfStack });
386 pop: function pop(mode, args) {
387 while (this._modeStack.length > 1 && this.main != mode) {
388 let a = this._modeStack.pop();
389 this.set(this.topOfStack.main, this.topOfStack.extended, this.topOfStack.params,
390 update({ pop: a }, args));
397 replace: function replace(mode, oldMode, args) {
398 while (oldMode && this._modeStack.length > 1 && this.main != oldMode)
401 if (this._modeStack.length > 1)
402 this.set(mode, null, null,
403 update({ push: this.topOfStack, pop: this._modeStack.pop() },
408 reset: function reset() {
409 if (this._modeStack.length == 1 && this.topOfStack.params.enter)
410 this.topOfStack.params.enter({}, this.topOfStack);
411 while (this._modeStack.length > 1)
415 get recording() this._recording,
416 set recording(value) { this._recording = value; this.show(); },
418 get replaying() this._replaying,
419 set replaying(value) { this._replaying = value; this.show(); },
421 get main() this._main,
422 set main(value) { this.set(value); },
424 get extended() this._extended,
425 set extended(value) { this.set(null, value); }
427 Mode: Class("Mode", {
428 init: function init(name, options, params) {
430 util.assert(options.bases.every(m => m instanceof this.constructor),
431 _("mode.invalidBases"), false);
434 id: 1 << Modes.Mode._id++,
441 description: Messages.Localized(""),
443 displayName: Class.Memoize(function () this.name.split("_").map(util.capitalize).join(" ")),
445 isinstance: function isinstance(obj)
446 this.allBases.indexOf(obj) >= 0 || callable(obj) && this instanceof obj,
448 allBases: Class.Memoize(function () {
449 let seen = {}, res = [], queue = [this].concat(this.bases);
450 for (let mode in array.iterValues(queue))
451 if (!Set.add(seen, mode)) {
453 queue.push.apply(queue, mode.bases);
458 get bases() this.input ? [modes.INPUT] : [modes.MAIN],
460 get count() !this.insert,
462 _display: Class.Memoize(function _display() this.name.replace("_", " ", "g")),
464 display: function display() this._display,
470 input: Class.Memoize(function input() this.insert || this.bases.length && this.bases.some(b => b.input)),
472 insert: Class.Memoize(function insert() this.bases.length && this.bases.some(b => b.insert)),
474 ownsFocus: Class.Memoize(function ownsFocus() this.bases.length && this.bases.some(b => b.ownsFocus)),
476 passEvent: function passEvent(event) this.input && event.charCode && !(event.ctrlKey || event.altKey || event.metaKey),
478 passUnknown: Class.Memoize(function () options.get("passunknown").getKey(this.name)),
482 get toStringParams() [this.name],
484 valueOf: function valueOf() this.id
488 StackElement: (function () {
489 const StackElement = Struct("main", "extended", "params", "saved");
490 StackElement.className = "Modes.StackElement";
491 StackElement.defaultValue("params", function () this.main.params);
493 update(StackElement.prototype, {
494 get toStringParams() !loaded.modes ? this.main.name : [
496 ["(", modes.all.filter(m => this.extended & m)
505 boundProperty: function BoundProperty(desc = {}) {
506 let id = this.cacheId++;
509 return Class.Property(update({
512 init: function bound_init(prop) update(this, {
513 get: function bound_get() {
515 var val = desc.get.call(this, value);
516 return val === undefined ? value : val;
518 set: function bound_set(val) {
519 modes.save(id, this, prop, desc.test);
521 value = desc.set.call(this, val);
522 value = !desc.set || value === undefined ? val : value;
528 cache: function initCache() {
529 function makeTree() {
530 let list = modes.all.filter(m => m.name !== m.description);
534 for (let mode in values(list))
535 tree[mode.name] = {};
537 for (let mode in values(list))
538 for (let base in values(mode.bases))
539 tree[base.name][mode.name] = tree[mode.name];
541 let roots = iter([m.name, tree[m.name]]
542 for (m in values(list))
543 if (!m.bases.length)).toObject();
546 let res = ["ul", { "dactyl:highlight": "Dense" }];
547 Object.keys(obj).sort().forEach(function (name) {
548 let mode = modes.getMode(name);
550 ["em", {}, mode.displayName],
551 ": ", mode.description,
563 cache.register("modes.dtd", () =>
564 util.makeDTD(iter({ "modes.tree": makeTree() },
567 mappings: function initMappings() {
568 mappings.add([modes.BASE, modes.NORMAL],
570 "Return to Normal mode",
571 function () { modes.reset(); });
573 mappings.add([modes.INPUT, modes.COMMAND, modes.OPERATOR, modes.PASS_THROUGH, modes.QUOTE],
575 "Return to the previous mode",
576 function () { modes.pop(null, { fromEscape: true }); });
578 mappings.add([modes.AUTOCOMPLETE, modes.MENU], ["<C-c>"],
579 "Leave Autocomplete or Menu mode",
580 function () { modes.pop(); });
582 mappings.add([modes.MENU], ["<Esc>"],
583 "Close the current popup",
585 if (events.popups.active.length)
586 return Events.PASS_THROUGH;
590 mappings.add([modes.MENU], ["<C-[>"],
591 "Close the current popup",
592 function () { events.feedkeys("<Esc>"); });
594 options: function initOptions() {
596 completer: function completer(context, extra) {
597 if (extra.value && context.filter[0] == "!")
599 return completer.superapply(this, arguments);
602 getKey: function getKey(val, default_) {
604 return (array.nth(this.value, v => val.some(m => m.name === v.mode), 0)
605 || { result: default_ }).result;
607 return Set.has(this.valueMap, val) ? this.valueMap[val] : default_;
610 setter: function (vals) {
611 modes.all.forEach(function (m) { delete m.passUnknown; });
613 vals = vals.map(v => update(new String(v.toLowerCase()),
615 mode: v.replace(/^!/, "").toUpperCase(),
619 this.valueMap = values(vals).map(v => [v.mode, v.result])
624 validator: function validator(vals) vals.map(v => v.replace(/^!/, ""))
625 .every(Set.has(this.values)),
627 get values() array.toObject([[m.name.toLowerCase(), m.description] for (m in values(modes._modes)) if (!m.hidden)])
630 options.add(["passunknown", "pu"],
631 "Pass through unknown keys in these modes",
632 "stringlist", "!text_edit,!visual,base",
635 options.add(["showmode", "smd"],
636 "Show the current mode in the command line when it matches this expression",
637 "stringlist", "caret,output_multiline,!normal,base,operator",
640 prefs: function initPrefs() {
641 prefs.watch("accessibility.browsewithcaret",
642 function () { modes.onCaretChange.apply(modes, arguments); });
646 // vim: set fdm=marker sw=4 sts=4 ts=8 et: