1 // Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2010 by anekos <anekos@snca.net>
3 // Copyright (c) 2010-2014 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 user-defined input mode binding of a typed string to an automatically
13 * inserted expansion string.
15 * Abbreviations have a left-hand side (LHS) whose text is replaced by that of
16 * the right-hand side (RHS) when triggered by an Input mode expansion key.
17 * E.g. an abbreviation with a LHS of "gop" and RHS of "Grand Old Party" will
18 * replace the former with the latter.
20 * @param {[Mode]} modes The modes in which this abbreviation is active.
21 * @param {string} lhs The left hand side of the abbreviation; the text to
23 * @param {string|function(nsIEditor):string} rhs The right hand side of
24 * the abbreviation; the replacement text. This may either be a string
25 * literal or a function that will be passed the appropriate nsIEditor.
28 var Abbreviation = Class("Abbreviation", {
29 init: function (modes, lhs, rhs) {
30 this.modes = modes.sort();
36 * Returns true if this abbreviation's LHS and RHS are equal to those in
39 * @param {Abbreviation} other The abbreviation to test.
40 * @returns {boolean} The result of the comparison.
42 equals: function (other) this.lhs == other.lhs && this.rhs == other.rhs,
45 * Returns the abbreviation's expansion text.
47 * @param {nsIEditor} editor The editor in which abbreviation expansion is
51 expand: function (editor) String(callable(this.rhs) ? this.rhs(editor) : this.rhs),
54 * Returns true if this abbreviation is defined for all *modes*.
56 * @param {[Mode]} modes The modes to test.
57 * @returns {boolean} The result of the comparison.
59 modesEqual: function (modes) array.equals(this.modes, modes),
62 * Returns true if this abbreviation is defined for *mode*.
64 * @param {Mode} mode The mode to test.
65 * @returns {boolean} The result of the comparison.
67 inMode: function (mode) this.modes.some(m => m == mode),
70 * Returns true if this abbreviation is defined in any of *modes*.
72 * @param {[Modes]} modes The modes to test.
73 * @returns {boolean} The result of the comparison.
75 inModes: function (modes) modes.some(mode => this.inMode(mode)),
78 * Remove *mode* from the list of supported modes for this abbreviation.
80 * @param {Mode} mode The mode to remove.
82 removeMode: function (mode) {
83 this.modes = this.modes.filter(m => m != mode)
88 * @property {string} The mode display characters associated with the
89 * supported mode combination.
91 get modeChar() Abbreviation.modeChar(this.modes)
93 modeChar: function (_modes) {
94 let result = array.uniq(_modes.map(m => m.char)).join("");
101 var AbbrevHive = Class("AbbrevHive", Contexts.Hive, {
102 init: function init(group) {
103 init.superapply(this, arguments);
107 /** @property {boolean} True if there are no abbreviations. */
108 get empty() !values(this._store).find(util.identity),
111 * Adds a new abbreviation.
113 * @param {Abbreviation} abbr The abbreviation to add.
115 add: function (abbr) {
116 if (!(abbr instanceof Abbreviation))
117 abbr = Abbreviation.apply(null, arguments);
119 for (let [, mode] in Iterator(abbr.modes)) {
120 if (!this._store[mode])
121 this._store[mode] = {};
122 this._store[mode][abbr.lhs] = abbr;
127 * Returns the abbreviation with *lhs* in the given *mode*.
129 * @param {Mode} mode The mode of the abbreviation.
130 * @param {string} lhs The LHS of the abbreviation.
131 * @returns {Abbreviation} The matching abbreviation.
133 get: function (mode, lhs) {
134 let abbrevs = this._store[mode];
135 return abbrevs && hasOwnProperty(abbrevs, lhs) ? abbrevs[lhs]
140 * @property {[Abbreviation]} The list of the abbreviations merged from
145 let map = values(this._store).map(Iterator).map(iter.toArray)
146 .flatten().toObject();
147 return Object.keys(map).sort().map(k => map[k]);
151 * Remove the specified abbreviations.
153 * @param {Array} modes List of modes.
154 * @param {string} lhs The LHS of the abbreviation.
155 * @returns {boolean} Did the deleted abbreviation exist?
157 remove: function (modes, lhs) {
159 for (let [, mode] in Iterator(modes)) {
160 if ((mode in this._store) && (lhs in this._store[mode])) {
162 this._store[mode][lhs].removeMode(mode);
163 delete this._store[mode][lhs];
170 * Removes all abbreviations specified in *modes*.
172 * @param {Array} modes List of modes.
174 clear: function (modes) {
175 for (let mode in values(modes)) {
176 for (let abbr in values(this._store[mode]))
177 abbr.removeMode(mode);
178 delete this._store[mode];
183 var Abbreviations = Module("abbreviations", {
186 // (summarized from Vim's ":help abbreviations")
188 // There are three types of abbreviations.
190 // full-id: Consists entirely of keyword characters.
191 // ("foo", "g3", "-1")
193 // end-id: Ends in a keyword character, but all other
194 // are not keyword characters.
195 // ("#i", "..f", "$/7")
197 // non-id: Ends in a non-keyword character, but the
198 // others can be of any type other than space
202 // Example strings that cannot be abbreviations:
203 // "a.b", "#def", "a b", "_$r"
205 // For now, a keyword character is anything except for \s, ", or '
206 // (i.e., whitespace and quotes). In Vim, a keyword character is
207 // specified by the 'iskeyword' setting and is a much less inclusive
210 // TODO: Make keyword definition closer to Vim's default keyword
211 // definition (which differs across platforms).
213 let params = { // This is most definitely not Vim compatible.
218 this._match = util.regexp(literal(/*
219 (^ | \s | <nonkeyword>) (<keyword>+ )$ | // full-id
220 (^ | \s | <keyword> ) (<nonkeyword>+ <keyword>)$ | // end-id
221 (^ | \s ) (\S* <nonkeyword> )$ // non-id
223 this._check = util.regexp(literal(/*
225 <keyword>+ | // full-id
226 <nonkeyword>+ <keyword> | // end-id
227 \S* <nonkeyword> // non-id
232 get allHives() contexts.allGroups.abbrevs,
234 get userHives() this.allHives.filter(h => h !== this.builtin),
236 get: deprecated("group.abbrevs.get", { get: function get() this.user.bound.get }),
237 set: deprecated("group.abbrevs.set", { get: function set() this.user.bound.set }),
238 remove: deprecated("group.abbrevs.remove", { get: function remove() this.user.bound.remove }),
239 removeAll: deprecated("group.abbrevs.clear", { get: function removeAll() this.user.bound.clear }),
242 * Returns the abbreviation for the given *mode* if *text* matches the
243 * abbreviation expansion criteria.
245 * @param {Mode} mode The mode to search.
246 * @param {string} text The string to test against the expansion criteria.
248 * @returns {Abbreviation}
250 match: function (mode, text) {
251 let match = this._match.exec(text);
253 return this.hives.map(h => h.get(mode, match[2] || match[4] || match[6]))
254 .find(util.identity);
259 * Lists all abbreviations matching *modes*, *lhs* and optionally *hives*.
261 * @param {Array} modes List of modes.
262 * @param {string} lhs The LHS of the abbreviation.
263 * @param {[Hive]} hives List of hives.
266 list: function (modes, lhs, hives) {
267 let hives = (hives || this.userHives).filter(h => !h.empty);
269 function abbrevs(hive)
270 hive.merged.filter(ab => (ab.inModes(modes) && ab.lhs.startsWith(lhs)));
272 let list = ["table", {},
273 ["tr", { highlight: "Title" },
275 ["td", { style: "padding-right: 1em;" }, _("title.Mode")],
276 ["td", { style: "padding-right: 1em;" }, _("title.Abbrev")],
277 ["td", { style: "padding-right: 1em;" }, _("title.Replacement")]],
278 ["col", { style: "min-width: 6em; padding-right: 1em;" }],
279 hives.map(hive => let (i = 0) [
280 ["tr", { style: "height: .5ex;" }],
281 abbrevs(hive).map(abbrev =>
283 ["td", { highlight: "Title" }, !i++ ? String(hive.name) : ""],
284 ["td", {}, abbrev.modeChar],
285 ["td", {}, abbrev.lhs],
286 ["td", {}, abbrev.rhs]]),
287 ["tr", { style: "height: .5ex;" }]])];
290 // // TODO: Move this to an ItemList to show this automatically
291 // if (list.*.length() === list.text().length() + 2)
292 // dactyl.echomsg(_("abbreviation.none"));
294 commandline.commandOutput(list);
299 contexts: function initContexts(dactyl, modules, window) {
300 update(Abbreviations.prototype, {
301 hives: contexts.Hives("abbrevs", AbbrevHive),
302 user: contexts.hives.abbrevs.user
305 completion: function initCompletion() {
306 completion.abbreviation = function abbreviation(context, modes, group) {
307 group = group || abbreviations.user;
308 let fn = modes ? abbr => abbr.inModes(modes)
310 context.keys = { text: "lhs" , description: "rhs" };
311 context.completions = group.merged.filter(fn);
314 commands: function initCommands() {
315 function addAbbreviationCommands(modes, ch, modeDescription) {
317 modeDescription = modeDescription ? " in " + modeDescription + " mode" : "";
319 commands.add([ch ? ch + "a[bbreviate]" : "ab[breviate]"],
320 "Abbreviate a key sequence" + modeDescription,
322 let [lhs, rhs] = args;
323 dactyl.assert(!args.length || abbreviations._check.test(lhs),
324 _("error.invalidArgument"));
327 let hives = args.explicitOpts["-group"] ? [args["-group"]] : null;
328 abbreviations.list(modes, lhs || "", hives);
331 if (args["-javascript"])
332 rhs = contexts.bindMacro({ literalArg: rhs }, "-javascript", ["editor"]);
333 args["-group"].add(modes, lhs, rhs);
336 identifier: "abbreviate",
337 completer: function (context, args) {
338 if (args.length == 1)
339 return completion.abbreviation(context, modes, args["-group"]);
340 else if (args["-javascript"])
341 return completion.javascript(context);
346 contexts.GroupFlag("abbrevs"),
348 names: ["-javascript", "-js", "-j"],
349 description: "Expand this abbreviation by evaluating its right-hand-side as JavaScript"
352 serialize: function () array(abbreviations.userHives)
353 .filter(h => h.persist)
357 arguments: [abbr.lhs],
358 literalArg: abbr.rhs,
360 "-group": hive.name == "user" ? undefined : hive.name,
361 "-javascript": callable(abbr.rhs) ? null : undefined
364 for ([, abbr] in Iterator(hive.merged))
365 if (abbr.modesEqual(modes))
370 commands.add([ch + "una[bbreviate]"],
371 "Remove an abbreviation" + modeDescription,
373 util.assert(args.bang ^ !!args[0], _("error.argumentOrBang"));
376 args["-group"].clear(modes);
377 else if (!args["-group"].remove(modes, args[0]))
378 return dactyl.echoerr(_("abbreviation.noSuch"));
382 completer: function (context, args) completion.abbreviation(context, modes, args["-group"]),
384 options: [contexts.GroupFlag("abbrevs")]
388 addAbbreviationCommands([modes.INSERT, modes.COMMAND_LINE], "", "");
389 [modes.INSERT, modes.COMMAND_LINE].forEach(function (mode) {
390 addAbbreviationCommands([mode], mode.char, mode.displayName);
395 // vim: set fdm=marker sw=4 sts=4 ts=8 et: