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 at Gmail>
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
12 * A class representing key mappings. Instances are created by the
13 * {@link Mappings} class.
15 * @param {[Modes.Mode]} modes The modes in which this mapping is active.
16 * @param {[string]} keys The key sequences which are bound to
18 * @param {string} description A short one line description of the key mapping.
19 * @param {function} action The action invoked by each key sequence.
20 * @param {Object} info An optional extra configuration hash. The
21 * following properties are supported.
22 * arg - see {@link Map#arg}
23 * count - see {@link Map#count}
24 * motion - see {@link Map#motion}
25 * noremap - see {@link Map#noremap}
26 * rhs - see {@link Map#rhs}
27 * silent - see {@link Map#silent}
31 var Map = Class("Map", {
32 init: function (modes, keys, description, action, info) {
37 this.description = description;
39 Object.freeze(this.modes);
42 if (Set.has(Map.types, info.type))
43 this.update(Map.types[info.type]);
48 name: Class.Memoize(function () this.names[0]),
50 /** @property {[string]} All of this mapping's names (key sequences). */
51 names: Class.Memoize(function () this._keys.map(function (k) DOM.Event.canonicalKeys(k))),
53 get toStringParams() [this.modes.map(function (m) m.name), this.names.map(String.quote)],
55 get identifier() [this.modes[0].name, this.hive.prefix + this.names[0]].join("."),
57 /** @property {number} A unique ID for this mapping. */
59 /** @property {[Modes.Mode]} All of the modes for which this mapping applies. */
61 /** @property {function (number)} The function called to execute this mapping. */
63 /** @property {string} This mapping's description, as shown in :listkeys. */
64 description: Messages.Localized(""),
66 /** @property {boolean} Whether this mapping accepts an argument. */
68 /** @property {boolean} Whether this mapping accepts a count. */
71 * @property {boolean} Whether the mapping accepts a motion mapping
76 /** @property {boolean} Whether the RHS of the mapping should expand mappings recursively. */
79 /** @property {function(object)} A function to be executed before this mapping. */
80 preExecute: function preExecute(args) {},
81 /** @property {function(object)} A function to be executed after this mapping. */
82 postExecute: function postExecute(args) {},
84 /** @property {boolean} Whether any output from the mapping should be echoed on the command line. */
87 /** @property {string} The literal RHS expansion of this mapping. */
90 /** @property {string} The type of this mapping. */
94 * @property {boolean} Specifies whether this is a user mapping. User
95 * mappings may be created by plugins, or directly by users. Users and
96 * plugin authors should create only user mappings.
101 * Returns whether this mapping can be invoked by a key sequence matching
104 * @param {string} name The name to query.
107 hasName: function (name) this.keys.indexOf(name) >= 0,
109 get keys() array.flatten(this.names.map(mappings.closure.expand)),
112 * Execute the action for this mapping.
114 * @param {object} args The arguments object for the given mapping.
116 execute: function (args) {
117 if (!isObject(args)) // Backwards compatibility :(
118 args = iter(["motion", "count", "arg", "command"])
119 .map(function ([i, prop]) [prop, this[i]], arguments)
122 args = this.hive.makeArgs(this.hive.group.lastDocument,
127 function repeat() self.action(args)
128 if (this.names[0] != ".") // FIXME: Kludge.
129 mappings.repeat = repeat;
132 util.assert(!args.keypressEvents[0].isMacro,
133 _("map.recursive", args.command),
137 dactyl.triggerObserver("mappings.willExecute", this, args);
138 mappings.pushCommand();
139 this.preExecute(args);
140 this.executing = true;
144 events.feedingKeys = false;
145 dactyl.reportError(e, true);
148 this.executing = false;
149 mappings.popCommand();
150 this.postExecute(args);
151 dactyl.triggerObserver("mappings.executed", this, args);
162 var MapHive = Class("MapHive", Contexts.Hive, {
163 init: function init(group) {
164 init.supercall(this, group);
169 * Iterates over all mappings present in all of the given *modes*.
171 * @param {[Modes.Mode]} modes The modes for which to return mappings.
173 iterate: function (modes) {
174 let stacks = Array.concat(modes).map(this.closure.getStack);
175 return values(stacks.shift().sort(function (m1, m2) String.localeCompare(m1.name, m2.name))
176 .filter(function (map) map.rhs &&
177 stacks.every(function (stack) stack.some(function (m) m.rhs && m.rhs === map.rhs && m.name === map.name))));
181 * Adds a new key mapping.
183 * @param {[Modes.Mode]} modes The modes that this mapping applies to.
184 * @param {[string]} keys The key sequences which are bound to *action*.
185 * @param {string} description A description of the key mapping.
186 * @param {function} action The action invoked by each key sequence.
187 * @param {Object} extra An optional extra configuration hash.
190 add: function (modes, keys, description, action, extra) {
193 modes = Array.concat(modes);
194 if (!modes.every(util.identity))
195 throw TypeError(/*L*/"Invalid modes: " + modes);
197 let map = Map(modes, keys, description, action, extra);
198 map.definedAt = contexts.getCaller(Components.stack.caller);
201 if (this.name !== "builtin")
202 for (let [, name] in Iterator(map.names))
203 for (let [, mode] in Iterator(map.modes))
204 this.remove(mode, name);
206 for (let mode in values(map.modes))
207 this.getStack(mode).add(map);
212 * Returns the mapping stack for the given mode.
214 * @param {Modes.Mode} mode The mode to search.
217 getStack: function getStack(mode) {
218 if (!(mode in this.stacks))
219 return this.stacks[mode] = MapHive.Stack();
220 return this.stacks[mode];
224 * Returns the map from *mode* named *cmd*.
226 * @param {Modes.Mode} mode The mode to search.
227 * @param {string} cmd The map name to match.
228 * @returns {Map|null}
230 get: function (mode, cmd) this.getStack(mode).mappings[cmd],
233 * Returns a count of maps with names starting with but not equal to
236 * @param {Modes.Mode} mode The mode to search.
237 * @param {string} prefix The map prefix string to match.
240 getCandidates: function (mode, prefix) this.getStack(mode).candidates[prefix] || 0,
243 * Returns whether there is a user-defined mapping *cmd* for the specified
246 * @param {Modes.Mode} mode The mode to search.
247 * @param {string} cmd The candidate key mapping.
250 has: function (mode, cmd) this.getStack(mode).mappings[cmd] != null,
253 * Remove the mapping named *cmd* for *mode*.
255 * @param {Modes.Mode} mode The mode to search.
256 * @param {string} cmd The map name to match.
258 remove: function (mode, cmd) {
259 let stack = this.getStack(mode);
260 for (let [i, map] in array.iterItems(stack)) {
261 let j = map.names.indexOf(cmd);
264 map.names.splice(j, 1);
265 if (map.names.length == 0) // FIX ME.
266 for (let [mode, stack] in Iterator(this.stacks))
267 this.stacks[mode] = MapHive.Stack(stack.filter(function (m) m != map));
274 * Remove all user-defined mappings for *mode*.
276 * @param {Modes.Mode} mode The mode to remove all mappings from.
278 clear: function (mode) {
279 this.stacks[mode] = MapHive.Stack([]);
282 Stack: Class("Stack", Array, {
283 init: function (ary) {
284 let self = ary || [];
285 self.__proto__ = this.__proto__;
289 __iterator__: function () array.iterValues(this),
291 get candidates() this.states.candidates,
292 get mappings() this.states.mappings,
294 add: function (map) {
299 states: Class.Memoize(function () {
305 for (let map in this)
306 for (let name in values(map.keys)) {
307 states.mappings[name] = map;
309 for (let key in DOM.Event.iterKeys(name)) {
312 states.candidates[state] = (states.candidates[state] || 0) + 1;
323 var Mappings = Module("mappings", {
326 this._watchStack = 0;
330 afterCommands: function afterCommands(count, cmd, self) {
331 this.watches.push([cmd, self, Math.max(this._watchStack - 1, 0), count || 1]);
334 pushCommand: function pushCommand(cmd) {
336 this._yielders = util.yielders;
338 popCommand: function popCommand(cmd) {
339 this._watchStack = Math.max(this._watchStack - 1, 0);
340 if (util.yielders > this._yielders)
341 this._watchStack = 0;
343 this.watches = this.watches.filter(function (elem) {
344 if (this._watchStack <= elem[2])
347 elem[0].call(elem[1] || null);
352 repeat: Modes.boundProperty(),
354 get allHives() contexts.allGroups.mappings,
356 get userHives() this.allHives.filter(function (h) h !== this.builtin, this),
358 expandLeader: deprecated("your brain", function expandLeader(keyString) keyString),
360 prefixes: Class.Memoize(function () {
361 let list = Array.map("CASM", function (s) s + "-");
363 return iter(util.range(0, 1 << list.length)).map(function (mask)
364 list.filter(function (p, i) mask & (1 << i)).join("")).toArray().concat("*-");
367 expand: function expand(keys) {
368 if (!/<\*-/.test(keys))
371 res = util.debrace(DOM.Event.iterKeys(keys).map(function (key) {
372 if (/^<\*-/.test(key))
373 return ["<", this.prefixes, key.slice(3)];
375 }, this).flatten().array).map(function (k) DOM.Event.canonicalKeys(k));
377 if (keys != arguments[0])
378 return [arguments[0]].concat(keys);
382 iterate: function (mode) {
384 for (let hive in this.hives.iterValues())
385 for (let map in array(hive.getStack(mode)).iterValues())
386 if (!Set.add(seen, map.name))
390 // NOTE: just normal mode for now
391 /** @property {Iterator(Map)} */
392 __iterator__: function () this.iterate(modes.NORMAL),
394 getDefault: deprecated("mappings.builtin.get", function getDefault(mode, cmd) this.builtin.get(mode, cmd)),
395 getUserIterator: deprecated("mappings.user.iterator", function getUserIterator(modes) this.user.iterator(modes)),
396 hasMap: deprecated("group.mappings.has", function hasMap(mode, cmd) this.user.has(mode, cmd)),
397 remove: deprecated("group.mappings.remove", function remove(mode, cmd) this.user.remove(mode, cmd)),
398 removeAll: deprecated("group.mappings.clear", function removeAll(mode) this.user.clear(mode)),
401 * Adds a new default key mapping.
403 * @param {[Modes.Mode]} modes The modes that this mapping applies to.
404 * @param {[string]} keys The key sequences which are bound to *action*.
405 * @param {string} description A description of the key mapping.
406 * @param {function} action The action invoked by each key sequence.
407 * @param {Object} extra An optional extra configuration hash.
410 add: function add() {
411 let group = this.builtin;
412 if (!util.isDactyl(Components.stack.caller)) {
413 deprecated.warn(add, "mappings.add", "group.mappings.add");
417 let map = group.add.apply(group, arguments);
418 map.definedAt = contexts.getCaller(Components.stack.caller);
423 * Adds a new user-defined key mapping.
425 * @param {[Modes.Mode]} modes The modes that this mapping applies to.
426 * @param {[string]} keys The key sequences which are bound to *action*.
427 * @param {string} description A description of the key mapping.
428 * @param {function} action The action invoked by each key sequence.
429 * @param {Object} extra An optional extra configuration hash (see
430 * {@link Map#extraInfo}).
433 addUserMap: deprecated("group.mappings.add", function addUserMap() {
434 let map = this.user.add.apply(this.user, arguments);
435 map.definedAt = contexts.getCaller(Components.stack.caller);
440 * Returns the map from *mode* named *cmd*.
442 * @param {Modes.Mode} mode The mode to search.
443 * @param {string} cmd The map name to match.
446 get: function get(mode, cmd) this.hives.map(function (h) h.get(mode, cmd)).compact()[0] || null,
449 * Returns a count of maps with names starting with but not equal to
452 * @param {Modes.Mode} mode The mode to search.
453 * @param {string} prefix The map prefix string to match.
456 getCandidates: function (mode, prefix)
457 this.hives.map(function (h) h.getCandidates(mode, prefix))
458 .reduce(function (a, b) a + b, 0),
461 * Lists all user-defined mappings matching *filter* for the specified
462 * *modes* in the specified *hives*.
464 * @param {[Modes.Mode]} modes An array of modes to search.
465 * @param {string} filter The filter string to match. @optional
466 * @param {[MapHive]} hives The map hives to list. @optional
468 list: function (modes, filter, hives) {
469 let modeSign = modes.map(function (m) m.char || "").join("")
470 + modes.map(function (m) !m.char ? " " + m.name : "").join("");
471 modeSign = modeSign.replace(/^ /, "");
473 hives = (hives || mappings.userHives).map(function (h) [h, maps(h)])
474 .filter(function ([h, m]) m.length);
476 function maps(hive) {
477 let maps = iter.toArray(hive.iterate(modes));
479 maps = maps.filter(function (m) m.names[0] === filter);
484 <tr highlight="Title">
486 <td style="padding-right: 1em;">{_("title.Mode")}</td>
487 <td style="padding-right: 1em;">{_("title.Command")}</td>
488 <td style="padding-right: 1em;">{_("title.Action")}</td>
490 <col style="min-width: 6em; padding-right: 1em;"/>
492 template.map(hives, function ([hive, maps]) let (i = 0)
493 <tr style="height: .5ex;"/> +
494 template.map(maps, function (map)
495 template.map(map.names, function (name)
497 <td highlight="Title">{!i++ ? hive.name : ""}</td>
500 <td>{map.rhs || map.action.toSource()}</td>
502 <tr style="height: .5ex;"/>)
506 // TODO: Move this to an ItemList to show this automatically
507 if (list.*.length() === list.text().length() + 2)
508 dactyl.echomsg(_("map.none"));
510 commandline.commandOutput(list);
514 contexts: function initContexts(dactyl, modules, window) {
515 update(Mappings.prototype, {
516 hives: contexts.Hives("mappings", MapHive),
517 user: contexts.hives.mappings.user,
518 builtin: contexts.hives.mappings.builtin
521 commands: function initCommands(dactyl, modules, window) {
522 function addMapCommands(ch, mapmodes, modeDescription) {
523 function map(args, noremap) {
524 let mapmodes = array.uniq(args["-modes"].map(findMode));
525 let hives = args.explicitOpts["-group"] ? [args["-group"]] : null;
528 mappings.list(mapmodes, null, hives);
532 if (args[1] && !/^<nop>$/i.test(args[1])
533 && !args["-count"] && !args["-ex"] && !args["-javascript"]
534 && mapmodes.every(function (m) m.count))
535 args[1] = "<count>" + args[1];
537 let [lhs, rhs] = args;
539 args["-builtin"] = true;
541 if (!rhs) // list the mapping
542 mappings.list(mapmodes, lhs, hives);
544 util.assert(args["-group"].modifiable,
545 _("map.builtinImmutable"));
547 args["-group"].add(mapmodes, [lhs],
548 args["-description"],
549 contexts.bindMacro(args, "-keys", function (params) params),
552 count: args["-count"] || !(args["-ex"] || args["-javascript"]),
553 noremap: args["-builtin"],
554 persist: !args["-nopersist"],
555 get rhs() String(this.action),
556 silent: args["-silent"]
563 completer: function (context, args) {
564 let mapmodes = array.uniq(args["-modes"].map(findMode));
565 if (args.length == 1)
566 return completion.userMapping(context, mapmodes, args["-group"]);
567 if (args.length == 2) {
568 if (args["-javascript"])
569 return completion.javascript(context);
571 return completion.ex(context);
578 names: ["-arg", "-a"],
579 description: "Accept an argument after the requisite key press",
582 names: ["-builtin", "-b"],
583 description: "Execute this mapping as if there were no user-defined mappings"
586 names: ["-count", "-c"],
587 description: "Accept a count before the requisite key press"
590 names: ["-description", "-desc", "-d"],
591 description: "A description of this mapping",
592 default: /*L*/"User-defined mapping",
593 type: CommandOption.STRING
596 names: ["-ex", "-e"],
597 description: "Execute this mapping as an Ex command rather than keys"
599 contexts.GroupFlag("mappings"),
601 names: ["-javascript", "-js", "-j"],
602 description: "Execute this mapping as JavaScript rather than keys"
604 update({}, modeFlag, {
605 names: ["-modes", "-mode", "-m"],
606 type: CommandOption.LIST,
607 description: "Create this mapping in the given modes",
608 default: mapmodes || ["n", "v"]
611 names: ["-nopersist", "-n"],
612 description: "Do not save this mapping to an auto-generated RC file"
615 names: ["-silent", "-s", "<silent>", "<Silent>"],
616 description: "Do not echo any generated keys to the command line"
619 serialize: function () {
620 return this.name != "map" ? [] :
621 array(mappings.userHives)
622 .filter(function (h) h.persist)
623 .map(function (hive) [
627 "-count": map.count ? null : undefined,
628 "-description": map.description,
629 "-group": hive.name == "user" ? undefined : hive.name,
630 "-modes": uniqueModes(map.modes),
631 "-silent": map.silent ? null : undefined
633 arguments: [map.names[0]],
637 for (map in userMappings(hive))
643 function userMappings(hive) {
645 for (let stack in values(hive.stacks))
646 for (let map in array.iterValues(stack))
647 if (!Set.add(seen, map.id))
651 modeDescription = modeDescription ? " in " + modeDescription + " mode" : "";
652 commands.add([ch ? ch + "m[ap]" : "map"],
653 "Map a key sequence" + modeDescription,
654 function (args) { map(args, false); },
657 commands.add([ch + "no[remap]"],
658 "Map a key sequence without remapping keys" + modeDescription,
659 function (args) { map(args, true); },
660 update({ deprecated: ":" + ch + "map -builtin" }, opts));
662 commands.add([ch + "unm[ap]"],
663 "Remove a mapping" + modeDescription,
665 util.assert(args["-group"].modifiable, _("map.builtinImmutable"));
667 util.assert(args.bang ^ !!args[0], _("error.argumentOrBang"));
669 let mapmodes = array.uniq(args["-modes"].map(findMode));
672 for (let mode in values(mapmodes))
674 args["-group"].clear(mode);
675 else if (args["-group"].has(mode, args[0])) {
676 args["-group"].remove(mode, args[0]);
680 if (!found && !args.bang)
681 dactyl.echoerr(_("map.noSuch", args[0]));
687 completer: opts.completer,
689 contexts.GroupFlag("mappings"),
690 update({}, modeFlag, {
691 names: ["-modes", "-mode", "-m"],
692 type: CommandOption.LIST,
693 description: "Remove mapping from the given modes",
694 default: mapmodes || ["n", "v"]
701 names: ["-mode", "-m"],
702 type: CommandOption.STRING,
703 validator: function (value) Array.concat(value).every(findMode),
704 completer: function () [[array.compact([mode.name.toLowerCase().replace(/_/g, "-"), mode.char]), mode.description]
705 for (mode in values(modes.all))
709 function findMode(name) {
711 for (let mode in values(modes.all))
712 if (name == mode || name == mode.char
713 || String.toLowerCase(name).replace(/-/g, "_") == mode.name.toLowerCase())
717 function uniqueModes(modes) {
718 let chars = [k for ([k, v] in Iterator(modules.modes.modeChars))
719 if (v.every(function (mode) modes.indexOf(mode) >= 0))];
720 return array.uniq(modes.filter(function (m) chars.indexOf(m.char) < 0)
721 .map(function (m) m.name.toLowerCase())
725 commands.add(["feedkeys", "fk"],
727 function (args) { events.feedkeys(args[0] || "", args.bang, false, findMode(args["-mode"])); },
733 update({}, modeFlag, {
734 description: "The mode in which to feed the keys"
739 addMapCommands("", [modes.NORMAL, modes.VISUAL], "");
741 for (let mode in modes.mainModes)
742 if (mode.char && !commands.get(mode.char + "map", true))
743 addMapCommands(mode.char,
744 [m.mask for (m in modes.mainModes) if (m.char == mode.char)],
748 getMode: function (args) findMode(args["-mode"]),
749 iterate: function (args, mainOnly) {
750 let modes = [this.getMode(args)];
752 modes = modes[0].allBases;
755 // Bloody hell. --Kris
756 for (let [i, mode] in Iterator(modes))
757 for (let hive in mappings.hives.iterValues())
758 for (let map in array.iterValues(hive.getStack(mode)))
759 for (let name in values(map.names))
760 if (!Set.add(seen, name)) {
764 i === 0 ? "" : <span highlight="Object" style="padding-right: 1em;">{mode.name}</span>,
765 hive == mappings.builtin ? "" : <span highlight="Object" style="padding-right: 1em;">{hive.name}</span>
772 description: function (map) (XML.ignoreWhitespace = false, XML.prettyPrinting = false, <>
773 {options.get("passkeys").has(map.name)
774 ? <span highlight="URLExtra">(passed by {template.helpLink("'passkeys'")})</span>
776 {template.linkifyHelp(map.description + (map.rhs ? ": " + map.rhs : ""))}
778 help: function (map) let (char = array.compact(map.modes.map(function (m) m.char))[0])
779 char === "n" ? map.name : char ? char + "_" + map.name : "",
780 headings: ["Command", "Mode", "Group", "Description"]
784 dactyl.addUsageCommand({
786 name: ["listk[eys]", "lk"],
787 description: "List all mappings along with their short descriptions",
789 update({}, modeFlag, {
791 description: "The mode for which to list mappings"
796 iter.forEach(modes.mainModes, function (mode) {
797 if (mode.char && !commands.get(mode.char + "listkeys", true))
798 dactyl.addUsageCommand({
800 name: [mode.char + "listk[eys]", mode.char + "lk"],
801 iterateIndex: function (args)
802 let (self = this, prefix = /^[bCmn]$/.test(mode.char) ? "" : mode.char + "_",
803 haveTag = Set.has(help.tags))
804 ({ helpTag: prefix + map.name, __proto__: map }
805 for (map in self.iterate(args, true))
806 if (map.hive === mappings.builtin || haveTag(prefix + map.name))),
807 description: "List all " + mode.displayName + " mode mappings along with their short descriptions",
808 index: mode.char + "-map",
809 getMode: function (args) mode,
814 completion: function initCompletion(dactyl, modules, window) {
815 completion.userMapping = function userMapping(context, modes_, hive) {
816 hive = hive || mappings.user;
817 modes_ = modes_ || [modes.NORMAL];
818 context.keys = { text: function (m) m.names[0], description: function (m) m.description + ": " + m.action };
819 context.completions = hive.iterate(modes_);
822 javascript: function initJavascript(dactyl, modules, window) {
823 JavaScript.setCompleter([Mappings.prototype.get, MapHive.prototype.get],
826 function (context, obj, args) [[m.names, m.description] for (m in this.iterate(args[0]))]
829 mappings: function initMappings(dactyl, modules, window) {
830 mappings.add([modes.COMMAND],
831 ["\\"], "Emits <Leader> pseudo-key",
832 function () { events.feedkeys("<Leader>") });
836 // vim: set fdm=marker sw=4 ts=4 et: