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>
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) Events.KILL,
127 this.addMode("MENU", {
128 description: "Active when a menu or other pop-up is open",
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);
141 this.addMode("LINE", {
142 extended: true, hidden: true
145 this.push(this.NORMAL, 0, {
146 enter: function (stack, prev) {
147 if (prefs.get("accessibility.browsewithcaret"))
148 prefs.set("accessibility.browsewithcaret", false);
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();
167 cleanup: function cleanup() {
172 "io.source": function ioSource(context, file, modTime) {
173 cache.flushEntry("modes.dtd", modTime);
177 _getModeMessage: function _getModeMessage() {
178 // when recording a macro
181 macromode = "recording " + this.recording + " ";
182 else if (this.replaying)
183 macromode = "replaying";
185 if (!options.get("showmode").getKey(this.main.allBases, false))
188 let modeName = this._modeMap[this._main].display();
193 macromode = " " + macromode;
194 return "-- " + modeName + " --" + macromode;
199 __iterator__: function __iterator__() array.iterValues(this.all),
201 get all() this._modes.slice(),
203 get mainModes() (mode for ([k, mode] in Iterator(modes._modeMap)) if (!mode.extended && mode.name == k)),
205 get mainMode() this._modeMap[this._main],
207 get passThrough() !!(this.main & (this.PASS_THROUGH|this.QUOTE)) ^ (this.getStack(1).main === this.PASS_THROUGH),
209 get topOfStack() this._modeStack[this._modeStack.length - 1],
211 addMode: function addMode(name, options, params) {
212 let mode = Modes.Mode(name, options, params);
216 this.modeChars[mode.char] = (this.modeChars[mode.char] || []).concat(mode);
217 this._modeMap[name] = mode;
218 this._modeMap[mode] = mode;
220 this._modes.push(mode);
222 this._mainModes.push(mode);
224 dactyl.triggerObserver("modes.add", mode);
227 removeMode: function removeMode(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];
236 this._mainModes = this._mainModes.filter(function (m) m != mode);
239 dumpStack: function dumpStack() {
240 util.dump("Mode stack:");
241 for (let [i, mode] in array.iterItems(this._modeStack))
242 util.dump(" " + i + ": " + mode);
245 getMode: function getMode(name) this._modeMap[name],
247 getStack: function getStack(idx) this._modeStack[this._modeStack.length - idx - 1] || this._modeStack[0],
249 get stack() this._modeStack.slice(),
251 getCharModes: function getCharModes(chr) (this.modeChars[chr] || []).slice(),
253 have: function have(mode) this._modeStack.some(function (m) isinstance(m.main, mode)),
255 matchModes: function matchModes(obj)
256 this._modes.filter(function (mode) Object.keys(obj)
257 .every(function (k) obj[k] == (mode[k] || false))),
259 // show the current mode string in the command line
260 show: function show() {
264 let msg = this._getModeMessage();
266 if (msg || loaded.commandline)
267 commandline.widgets.mode = msg || null;
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));
276 else if (this.stack.some(function (m) m.main == mode)) {
283 delay: function delay(callback, self) { this.delayed.push([callback, self]); },
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 };
294 set: function set(mainMode, extendedMode, params, stack) {
295 var delayed, oldExtended, oldMain, prev, push;
298 dactyl.reportError(Error(_("mode.recursiveSet")), true);
302 params = params || this.getMode(mainMode || this.main).params;
304 if (!stack && mainMode != null && this._modeStack.length > 1)
307 this.withSavedValues(["inSet"], function set() {
310 oldMain = this._main, oldExtended = this._extended;
312 if (extendedMode != null)
313 this._extended = extendedMode;
314 if (mainMode != null) {
315 this._main = mainMode;
317 this._extended = this.NONE;
320 if (stack && stack.pop && stack.pop.params.leave)
321 dactyl.trapErrors("leave", stack.pop.params,
322 stack, this.topOfStack);
324 push = mainMode != null && !(stack && stack.pop) &&
325 Modes.StackElement(this._main, this._extended, params, {});
327 if (push && this.topOfStack) {
328 if (this.topOfStack.params.leave)
329 dactyl.trapErrors("leave", this.topOfStack.params,
330 { push: push }, push);
332 for (let [id, { obj, prop, test }] in Iterator(this.boundProperties)) {
334 delete this.boundProperties[id];
336 this.topOfStack.saved[id] = { obj: obj.get(), prop: prop, value: obj.get()[prop], test: test };
340 delayed = this.delayed;
343 prev = stack && stack.pop || this.topOfStack;
345 this._modeStack.push(push);
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 });
355 if (this.topOfStack.params.enter && prev)
356 dactyl.trapErrors("enter", this.topOfStack.params,
357 push ? { push: push } : stack || {},
360 delayed.forEach(function ([fn, self]) dactyl.trapErrors(fn, self));
362 dactyl.triggerObserver("modes.change", [oldMain, oldExtended], [this._main, this._extended], stack);
366 onCaretChange: function onPrefChange(value) {
367 if (!value && modes.main == modes.CARET)
369 if (value && modes.main == modes.NORMAL)
370 modes.push(modes.CARET);
373 push: function push(mainMode, extendedMode, params) {
374 if (this.main == this.IGNORE)
377 this.set(mainMode, extendedMode, params, { push: this.topOfStack });
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));
391 replace: function replace(mode, oldMode, args) {
392 while (oldMode && this._modeStack.length > 1 && this.main != oldMode)
395 if (this._modeStack.length > 1)
396 this.set(mode, null, null,
397 update({ push: this.topOfStack, pop: this._modeStack.pop() },
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)
409 get recording() this._recording,
410 set recording(value) { this._recording = value; this.show(); },
412 get replaying() this._replaying,
413 set replaying(value) { this._replaying = value; this.show(); },
415 get main() this._main,
416 set main(value) { this.set(value); },
418 get extended() this._extended,
419 set extended(value) { this.set(null, value); }
421 Mode: Class("Mode", {
422 init: function init(name, options, params) {
424 util.assert(options.bases.every(function (m) m instanceof this, this.constructor),
425 _("mode.invalidBases"), false);
428 id: 1 << Modes.Mode._id++,
435 description: Messages.Localized(""),
437 displayName: Class.Memoize(function () this.name.split("_").map(util.capitalize).join(" ")),
439 isinstance: function isinstance(obj)
440 this.allBases.indexOf(obj) >= 0 || callable(obj) && this instanceof obj,
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)) {
447 queue.push.apply(queue, mode.bases);
452 get bases() this.input ? [modes.INPUT] : [modes.MAIN],
454 get count() !this.insert,
456 _display: Class.Memoize(function _display() this.name.replace("_", " ", "g")),
458 display: function display() this._display,
464 input: Class.Memoize(function input() this.insert || this.bases.length && this.bases.some(function (b) b.input)),
466 insert: Class.Memoize(function insert() this.bases.length && this.bases.some(function (b) b.insert)),
468 ownsFocus: Class.Memoize(function ownsFocus() this.bases.length && this.bases.some(function (b) b.ownsFocus)),
470 passEvent: function passEvent(event) this.input && event.charCode && !(event.ctrlKey || event.altKey || event.metaKey),
472 passUnknown: Class.Memoize(function () options.get("passunknown").getKey(this.name)),
476 get toStringParams() [this.name],
478 valueOf: function valueOf() this.id
482 StackElement: (function () {
483 const StackElement = Struct("main", "extended", "params", "saved");
484 StackElement.className = "Modes.StackElement";
485 StackElement.defaultValue("params", function () this.main.params);
487 update(StackElement.prototype, {
488 get toStringParams() !loaded.modes ? this.main.name : [
490 <>({ modes.all.filter(function (m) this.extended & m, this).map(function (m) m.name).join("|") })</>
496 boundProperty: function BoundProperty(desc) {
497 let id = this.cacheId++;
501 return Class.Property(update({
504 init: function bound_init(prop) update(this, {
505 get: function bound_get() {
507 var val = desc.get.call(this, value);
508 return val === undefined ? value : val;
510 set: function bound_set(val) {
511 modes.save(id, this, prop, desc.test);
513 value = desc.set.call(this, val);
514 value = !desc.set || value === undefined ? val : value;
520 cache: function initCache() {
521 function makeTree() {
522 let list = modes.all.filter(function (m) m.name !== m.description);
526 for (let mode in values(list))
527 tree[mode.name] = {};
529 for (let mode in values(list))
530 for (let base in values(mode.bases))
531 tree[base.name][mode.name] = tree[mode.name];
533 let roots = iter([m.name, tree[m.name]] for (m in values(list)) if (!m.bases.length)).toObject();
535 default xml namespace = NS;
537 XML.ignoreWhitespace = XML.prettyPrinting = false;
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}{
555 cache.register("modes.dtd", function ()
556 util.makeDTD(iter({ "modes.tree": makeTree() },
559 mappings: function initMappings() {
560 mappings.add([modes.BASE, modes.NORMAL],
562 "Return to Normal mode",
563 function () { modes.reset(); });
565 mappings.add([modes.INPUT, modes.COMMAND, modes.OPERATOR, modes.PASS_THROUGH, modes.QUOTE],
567 "Return to the previous mode",
568 function () { modes.pop(null, { fromEscape: true }); });
570 mappings.add([modes.AUTOCOMPLETE, modes.MENU], ["<C-c>"],
571 "Leave Autocomplete or Menu mode",
572 function () { modes.pop(); });
574 mappings.add([modes.MENU], ["<Esc>"],
575 "Close the current popup",
577 if (events.popups.active.length)
578 return Events.PASS_THROUGH;
582 mappings.add([modes.MENU], ["<C-[>"],
583 "Close the current popup",
584 function () { events.feedkeys("<Esc>"); });
586 options: function initOptions() {
588 completer: function completer(context, extra) {
589 if (extra.value && context.filter[0] == "!")
591 return completer.superapply(this, arguments);
594 getKey: function getKey(val, default_) {
596 return (array.nth(this.value, function (v) val.some(function (m) m.name === v.mode), 0)
597 || { result: default_ }).result;
599 return Set.has(this.valueMap, val) ? this.valueMap[val] : default_;
602 setter: function (vals) {
603 modes.all.forEach(function (m) { delete m.passUnknown });
605 vals = vals.map(function (v) update(new String(v.toLowerCase()), {
606 mode: v.replace(/^!/, "").toUpperCase(),
610 this.valueMap = values(vals).map(function (v) [v.mode, v.result]).toObject();
614 validator: function validator(vals) vals.map(function (v) v.replace(/^!/, "")).every(Set.has(this.values)),
616 get values() array.toObject([[m.name.toLowerCase(), m.description] for (m in values(modes._modes)) if (!m.hidden)])
619 options.add(["passunknown", "pu"],
620 "Pass through unknown keys in these modes",
621 "stringlist", "!text_edit,!visual,base",
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",
629 prefs: function initPrefs() {
630 prefs.watch("accessibility.browsewithcaret",
631 function () { modes.onCaretChange.apply(modes, arguments) });
635 // vim: set fdm=marker sw=4 ts=4 et: