]> git.donarmstrong.com Git - dactyl.git/blob - common/content/abbreviations.js
finalize changelog for 7904
[dactyl.git] / common / content / abbreviations.js
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>
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 /**
12  * A user-defined input mode binding of a typed string to an automatically
13  * inserted expansion string.
14  *
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.
19  *
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
22  *     be replaced.
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.
26  * @private
27  */
28 var Abbreviation = Class("Abbreviation", {
29     init: function (modes, lhs, rhs) {
30         this.modes = modes.sort();
31         this.lhs = lhs;
32         this.rhs = rhs;
33     },
34
35     /**
36      * Returns true if this abbreviation's LHS and RHS are equal to those in
37      * *other*.
38      *
39      * @param {Abbreviation} other The abbreviation to test.
40      * @returns {boolean} The result of the comparison.
41      */
42     equals: function (other) this.lhs == other.lhs && this.rhs == other.rhs,
43
44     /**
45      * Returns the abbreviation's expansion text.
46      *
47      * @param {nsIEditor} editor The editor in which abbreviation expansion is
48      *     occurring.
49      * @returns {string}
50      */
51     expand: function (editor) String(callable(this.rhs) ? this.rhs(editor) : this.rhs),
52
53     /**
54      * Returns true if this abbreviation is defined for all *modes*.
55      *
56      * @param {[Mode]} modes The modes to test.
57      * @returns {boolean} The result of the comparison.
58      */
59     modesEqual: function (modes) array.equals(this.modes, modes),
60
61     /**
62      * Returns true if this abbreviation is defined for *mode*.
63      *
64      * @param {Mode} mode The mode to test.
65      * @returns {boolean} The result of the comparison.
66      */
67     inMode: function (mode) this.modes.some(m => m == mode),
68
69     /**
70      * Returns true if this abbreviation is defined in any of *modes*.
71      *
72      * @param {[Modes]} modes The modes to test.
73      * @returns {boolean} The result of the comparison.
74      */
75     inModes: function (modes) modes.some(mode => this.inMode(mode)),
76
77     /**
78      * Remove *mode* from the list of supported modes for this abbreviation.
79      *
80      * @param {Mode} mode The mode to remove.
81      */
82     removeMode: function (mode) {
83         this.modes = this.modes.filter(m => m != mode)
84                                .sort();
85     },
86
87     /**
88      * @property {string} The mode display characters associated with the
89      *     supported mode combination.
90      */
91     get modeChar() Abbreviation.modeChar(this.modes)
92 }, {
93     modeChar: function (_modes) {
94         let result = array.uniq(_modes.map(m => m.char)).join("");
95         if (result == "ci")
96             result = "!";
97         return result;
98     }
99 });
100
101 var AbbrevHive = Class("AbbrevHive", Contexts.Hive, {
102     init: function init(group) {
103         init.superapply(this, arguments);
104         this._store = {};
105     },
106
107     /** @property {boolean} True if there are no abbreviations. */
108     get empty() !values(this._store).find(util.identity),
109
110     /**
111      * Adds a new abbreviation.
112      *
113      * @param {Abbreviation} abbr The abbreviation to add.
114      */
115     add: function (abbr) {
116         if (!(abbr instanceof Abbreviation))
117             abbr = Abbreviation.apply(null, arguments);
118
119         for (let [, mode] in Iterator(abbr.modes)) {
120             if (!this._store[mode])
121                 this._store[mode] = {};
122             this._store[mode][abbr.lhs] = abbr;
123         }
124     },
125
126     /**
127      * Returns the abbreviation with *lhs* in the given *mode*.
128      *
129      * @param {Mode} mode The mode of the abbreviation.
130      * @param {string} lhs The LHS of the abbreviation.
131      * @returns {Abbreviation} The matching abbreviation.
132      */
133     get: function (mode, lhs) {
134         let abbrevs = this._store[mode];
135         return abbrevs && hasOwnProperty(abbrevs, lhs) ? abbrevs[lhs]
136                                                        : null;
137     },
138
139     /**
140      * @property {[Abbreviation]} The list of the abbreviations merged from
141      *     each mode.
142      */
143     get merged() {
144         // Wth? --Kris;
145         let map = values(this._store).map(Iterator).map(iter.toArray)
146                                      .flatten().toObject();
147         return Object.keys(map).sort().map(k => map[k]);
148     },
149
150     /**
151      * Remove the specified abbreviations.
152      *
153      * @param {Array} modes List of modes.
154      * @param {string} lhs The LHS of the abbreviation.
155      * @returns {boolean} Did the deleted abbreviation exist?
156      */
157     remove: function (modes, lhs) {
158         let result = false;
159         for (let [, mode] in Iterator(modes)) {
160             if ((mode in this._store) && (lhs in this._store[mode])) {
161                 result = true;
162                 this._store[mode][lhs].removeMode(mode);
163                 delete this._store[mode][lhs];
164             }
165         }
166         return result;
167     },
168
169     /**
170      * Removes all abbreviations specified in *modes*.
171      *
172      * @param {Array} modes List of modes.
173      */
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];
179         }
180     }
181 });
182
183 var Abbreviations = Module("abbreviations", {
184     init: function () {
185
186         // (summarized from Vim's ":help abbreviations")
187         //
188         // There are three types of abbreviations.
189         //
190         // full-id: Consists entirely of keyword characters.
191         //          ("foo", "g3", "-1")
192         //
193         // end-id: Ends in a keyword character, but all other
194         //         are not keyword characters.
195         //         ("#i", "..f", "$/7")
196         //
197         // non-id: Ends in a non-keyword character, but the
198         //         others can be of any type other than space
199         //         and tab.
200         //         ("def#", "4/7$")
201         //
202         // Example strings that cannot be abbreviations:
203         //         "a.b", "#def", "a b", "_$r"
204         //
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
208         // list.
209         //
210         // TODO: Make keyword definition closer to Vim's default keyword
211         //       definition (which differs across platforms).
212
213         let params = { // This is most definitely not Vim compatible.
214             keyword:    /[^\s"']/,
215             nonkeyword: /[   "']/
216         };
217
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
222         */), "x", params);
223         this._check = util.regexp(literal(/*
224             ^ (?:
225               <keyword>+              | // full-id
226               <nonkeyword>+ <keyword> | // end-id
227               \S* <nonkeyword>          // non-id
228             ) $
229         */), "x", params);
230     },
231
232     get allHives() contexts.allGroups.abbrevs,
233
234     get userHives() this.allHives.filter(h => h !== this.builtin),
235
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 }),
240
241     /**
242      * Returns the abbreviation for the given *mode* if *text* matches the
243      * abbreviation expansion criteria.
244      *
245      * @param {Mode} mode The mode to search.
246      * @param {string} text The string to test against the expansion criteria.
247      *
248      * @returns {Abbreviation}
249      */
250     match: function (mode, text) {
251         let match = this._match.exec(text);
252         if (match)
253             return this.hives.map(h => h.get(mode, match[2] || match[4] || match[6]))
254                        .find(util.identity);
255         return null;
256     },
257
258     /**
259      * Lists all abbreviations matching *modes*, *lhs* and optionally *hives*.
260      *
261      * @param {Array} modes List of modes.
262      * @param {string} lhs The LHS of the abbreviation.
263      * @param {[Hive]} hives List of hives.
264      * @optional
265      */
266     list: function (modes, lhs, hives) {
267         let hives = (hives || this.userHives).filter(h => !h.empty);
268
269         function abbrevs(hive)
270             hive.merged.filter(ab => (ab.inModes(modes) && ab.lhs.startsWith(lhs)));
271
272         let list = ["table", {},
273                 ["tr", { highlight: "Title" },
274                     ["td"],
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 =>
282                         ["tr", {},
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;" }]])];
288
289         // FIXME?
290         // // TODO: Move this to an ItemList to show this automatically
291         // if (list.*.length() === list.text().length() + 2)
292         //     dactyl.echomsg(_("abbreviation.none"));
293         // else
294         commandline.commandOutput(list);
295     }
296
297 }, {
298 }, {
299     contexts: function initContexts(dactyl, modules, window) {
300         update(Abbreviations.prototype, {
301             hives: contexts.Hives("abbrevs", AbbrevHive),
302             user: contexts.hives.abbrevs.user
303         });
304     },
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)
309                            : abbr => abbr;
310             context.keys = { text: "lhs" , description: "rhs" };
311             context.completions = group.merged.filter(fn);
312         };
313     },
314     commands: function initCommands() {
315         function addAbbreviationCommands(modes, ch, modeDescription) {
316             modes.sort();
317             modeDescription = modeDescription ? " in " + modeDescription + " mode" : "";
318
319             commands.add([ch ? ch + "a[bbreviate]" : "ab[breviate]"],
320                 "Abbreviate a key sequence" + modeDescription,
321                 function (args) {
322                     let [lhs, rhs] = args;
323                     dactyl.assert(!args.length || abbreviations._check.test(lhs),
324                                   _("error.invalidArgument"));
325
326                     if (!rhs) {
327                         let hives = args.explicitOpts["-group"] ? [args["-group"]] : null;
328                         abbreviations.list(modes, lhs || "", hives);
329                     }
330                     else {
331                         if (args["-javascript"])
332                             rhs = contexts.bindMacro({ literalArg: rhs }, "-javascript", ["editor"]);
333                         args["-group"].add(modes, lhs, rhs);
334                     }
335                 }, {
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);
342                     },
343                     hereDoc: true,
344                     literal: 1,
345                     options: [
346                         contexts.GroupFlag("abbrevs"),
347                         {
348                             names: ["-javascript", "-js", "-j"],
349                             description: "Expand this abbreviation by evaluating its right-hand-side as JavaScript"
350                         }
351                     ],
352                     serialize: function () array(abbreviations.userHives)
353                         .filter(h => h.persist)
354                         .map(hive => [
355                             {
356                                 command: this.name,
357                                 arguments: [abbr.lhs],
358                                 literalArg: abbr.rhs,
359                                 options: {
360                                     "-group": hive.name == "user" ? undefined : hive.name,
361                                     "-javascript": callable(abbr.rhs) ? null : undefined
362                                 }
363                             }
364                             for ([, abbr] in Iterator(hive.merged))
365                             if (abbr.modesEqual(modes))
366                         ]).
367                         flatten().array
368                 });
369
370             commands.add([ch + "una[bbreviate]"],
371                 "Remove an abbreviation" + modeDescription,
372                 function (args) {
373                     util.assert(args.bang ^ !!args[0], _("error.argumentOrBang"));
374
375                     if (args.bang)
376                         args["-group"].clear(modes);
377                     else if (!args["-group"].remove(modes, args[0]))
378                         return dactyl.echoerr(_("abbreviation.noSuch"));
379                 }, {
380                     argCount: "?",
381                     bang: true,
382                     completer: function (context, args) completion.abbreviation(context, modes, args["-group"]),
383                     literal: 0,
384                     options: [contexts.GroupFlag("abbrevs")]
385                 });
386         }
387
388         addAbbreviationCommands([modes.INSERT, modes.COMMAND_LINE], "", "");
389         [modes.INSERT, modes.COMMAND_LINE].forEach(function (mode) {
390             addAbbreviationCommands([mode], mode.char, mode.displayName);
391         });
392     }
393 });
394
395 // vim: set fdm=marker sw=4 sts=4 ts=8 et: