]> git.donarmstrong.com Git - dactyl.git/blob - common/content/autocommands.js
2d960c835be66b75f59a9c4fb274eea449fe38d3
[dactyl.git] / common / content / autocommands.js
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>
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 var AutoCommand = Struct("event", "filter", "command");
12 update(AutoCommand.prototype, {
13     eventName: Class.memoize(function () this.event.toLowerCase()),
14
15     match: function (event, pattern) {
16         return (!event || this.eventName == event.toLowerCase()) && (!pattern || String(this.filter) === pattern);
17     }
18 });
19
20 var AutoCmdHive = Class("AutoCmdHive", Contexts.Hive, {
21     init: function init(group) {
22         init.supercall(this, group);
23         this._store = [];
24     },
25
26     __iterator__: function () array.iterValues(this._store),
27
28     /**
29      * Adds a new autocommand. *cmd* will be executed when one of the specified
30      * *events* occurs and the URL of the applicable buffer matches *regexp*.
31      *
32      * @param {Array} events The array of event names for which this
33      *     autocommand should be executed.
34      * @param {string} pattern The URL pattern to match against the buffer URL.
35      * @param {string} cmd The Ex command to run.
36      */
37     add: function (events, pattern, cmd) {
38         if (!callable(pattern))
39             pattern = Group.compileFilter(pattern);
40
41         for (let event in values(events))
42             this._store.push(AutoCommand(event, pattern, cmd));
43     },
44
45     /**
46      * Returns all autocommands with a matching *event* and *regexp*.
47      *
48      * @param {string} event The event name filter.
49      * @param {string} pattern The URL pattern filter.
50      * @returns {AutoCommand[]}
51      */
52     get: function (event, pattern) {
53         return this._store.filter(function (autoCmd) autoCmd.match(event, regexp));
54     },
55
56     /**
57      * Deletes all autocommands with a matching *event* and *regexp*.
58      *
59      * @param {string} event The event name filter.
60      * @param {string} regexp The URL pattern filter.
61      */
62     remove: function (event, regexp) {
63         this._store = this._store.filter(function (autoCmd) !autoCmd.match(event, regexp));
64     },
65 });
66
67 /**
68  * @instance autocommands
69  */
70 var AutoCommands = Module("autocommands", {
71     init: function () {
72         update(this, {
73             hives: contexts.Hives("autocmd", AutoCmdHive),
74             user: contexts.hives.autocmd.user,
75             allHives: contexts.allGroups.autocmd,
76             matchingHives: function matchingHives(uri, doc) contexts.matchingGroups(uri, doc).autocmd
77         });
78     },
79
80     get activeHives() contexts.allGroups.autocmd.filter(function (h) h._store.length),
81
82     add: deprecated("group.autocmd.add", { get: function add() autocommands.user.closure.add }),
83     get: deprecated("group.autocmd.get", { get: function get() autocommands.user.closure.get }),
84     remove: deprecated("group.autocmd.remove", { get: function remove() autocommands.user.closure.remove }),
85
86     /**
87      * Lists all autocommands with a matching *event* and *regexp*.
88      *
89      * @param {string} event The event name filter.
90      * @param {string} regexp The URL pattern filter.
91      */
92     list: function (event, regexp) {
93
94         function cmds(hive) {
95             let cmds = {};
96             hive._store.forEach(function (autoCmd) {
97                 if (autoCmd.match(event, regexp)) {
98                     cmds[autoCmd.event] = cmds[autoCmd.event] || [];
99                     cmds[autoCmd.event].push(autoCmd);
100                 }
101             });
102             return cmds;
103         }
104
105         commandline.commandOutput(
106             <table>
107                 <tr highlight="Title">
108                     <td colspan="3">----- Auto Commands -----</td>
109                 </tr>
110                 {
111                     template.map(this.activeHives, function (hive)
112                         <tr highlight="Title">
113                             <td colspan="3">{hive.name}</td>
114                         </tr> +
115                         <tr style="height: .5ex;"/> +
116                         template.map(cmds(hive), function ([event, items])
117                             <tr style="height: .5ex;"/> +
118                             template.map(items, function (item, i)
119                                 <tr>
120                                     <td highlight="Title" style="padding-right: 1em;">{i == 0 ? event : ""}</td>
121                                     <td>{item.filter.toXML ? item.filter.toXML() : item.filter}</td>
122                                     <td>{item.command}</td>
123                                 </tr>) +
124                             <tr style="height: .5ex;"/>) +
125                         <tr style="height: .5ex;"/>)
126                 }
127             </table>);
128     },
129
130     /**
131      * Triggers the execution of all autocommands registered for *event*. A map
132      * of *args* is passed to each autocommand when it is being executed.
133      *
134      * @param {string} event The event to fire.
135      * @param {Object} args The args to pass to each autocommand.
136      */
137     trigger: function (event, args) {
138         if (options.get("eventignore").has(event))
139             return;
140
141         dactyl.echomsg(_("autocmd.executing", event, "*".quote()), 8);
142
143         let lastPattern = null;
144         var { url, doc } = args;
145         if (url)
146             uri = util.newURI(url);
147         else
148             var { uri, doc } = buffer;
149
150         event = event.toLowerCase();
151         for (let hive in values(this.matchingHives(uri, doc))) {
152             let args = update({},
153                               hive.argsExtra(arguments[1]),
154                               arguments[1]);
155
156             for (let autoCmd in values(hive._store))
157                 if (autoCmd.eventName === event && autoCmd.filter(uri, doc)) {
158                     if (!lastPattern || lastPattern !== String(autoCmd.filter))
159                         dactyl.echomsg(_("autocmd.executing", event, autoCmd.filter), 8);
160
161                     lastPattern = String(autoCmd.filter);
162                     dactyl.echomsg(_("autocmd.autocommand", autoCmd.command), 9);
163
164                     dactyl.trapErrors(autoCmd.command, autoCmd, args);
165                 }
166         }
167     }
168 }, {
169 }, {
170     commands: function () {
171         commands.add(["au[tocmd]"],
172             "Execute commands automatically on events",
173             function (args) {
174                 let [event, regexp, cmd] = args;
175                 let events = [];
176
177                 if (event) {
178                     // NOTE: event can only be a comma separated list for |:au {event} {pat} {cmd}|
179                     let validEvents = Object.keys(config.autocommands).map(String.toLowerCase);
180                     validEvents.push("*");
181
182                     events = Option.parse.stringlist(event);
183                     dactyl.assert(events.every(function (event) validEvents.indexOf(event.toLowerCase()) >= 0),
184                                   _("autocmd.noGroup", event));
185                 }
186
187                 if (args.length > 2) { // add new command, possibly removing all others with the same event/pattern
188                     if (args.bang)
189                         args["-group"].remove(event, regexp);
190                     cmd = contexts.bindMacro(args, "-ex", function (params) params);
191                     args["-group"].add(events, regexp, cmd);
192                 }
193                 else {
194                     if (event == "*")
195                         event = null;
196
197                     if (args.bang) {
198                         // TODO: "*" only appears to work in Vim when there is a {group} specified
199                         if (args[0] != "*" || args.length > 1)
200                             args["-group"].remove(event, regexp); // remove all
201                     }
202                     else
203                         autocommands.list(event, regexp); // list all
204                 }
205             }, {
206                 bang: true,
207                 completer: function (context, args) {
208                     if (args.length == 1)
209                         return completion.autocmdEvent(context);
210                     if (args.length == 3)
211                         return args["-javascript"] ? completion.javascript(context) : completion.ex(context);
212                 },
213                 hereDoc: true,
214                 keepQuotes: true,
215                 literal: 2,
216                 options: [
217                     contexts.GroupFlag("autocmd"),
218                     {
219                         names: ["-javascript", "-js"],
220                         description: "Interpret the action as JavaScript code rather than an Ex command"
221                     }
222                 ]
223             });
224
225         [
226             {
227                 name: "do[autocmd]",
228                 description: "Apply the autocommands matching the specified URL pattern to the current buffer"
229             }, {
230                 name: "doautoa[ll]",
231                 description: "Apply the autocommands matching the specified URL pattern to all buffers"
232             }
233         ].forEach(function (command) {
234             commands.add([command.name],
235                 command.description,
236                 // TODO: Perhaps this should take -args to pass to the command?
237                 function (args) {
238                     // Vim compatible
239                     if (args.length == 0)
240                         return void dactyl.echomsg(_("autocmd.noMatching"));
241
242                     let [event, url] = args;
243                     let defaultURL = url || buffer.uri.spec;
244                     let validEvents = Object.keys(config.autocommands);
245
246                     // TODO: add command validators
247                     dactyl.assert(event != "*",
248                                   _("autocmd.cantExecuteAll"));
249                     dactyl.assert(validEvents.indexOf(event) >= 0,
250                                   _("autocmd.noGroup", args));
251                     dactyl.assert(autocommands.get(event).some(function (c) c.patterns.some(function (re) re.test(defaultURL) ^ !re.result)),
252                                   _("autocmd.noMatching"));
253
254                     if (this.name == "doautoall" && dactyl.has("tabs")) {
255                         let current = tabs.index();
256
257                         for (let i = 0; i < tabs.count; i++) {
258                             tabs.select(i);
259                             // if no url arg is specified use the current buffer's URL
260                             autocommands.trigger(event, { url: url || buffer.uri.spec });
261                         }
262
263                         tabs.select(current);
264                     }
265                     else
266                         autocommands.trigger(event, { url: defaultURL });
267                 }, {
268                     argCount: "*", // FIXME: kludged for proper error message should be "1".
269                     completer: function (context) completion.autocmdEvent(context),
270                     keepQuotes: true
271                 });
272         });
273     },
274     completion: function () {
275         completion.autocmdEvent = function autocmdEvent(context) {
276             context.completions = Iterator(config.autocommands);
277         };
278     },
279     javascript: function () {
280         JavaScript.setCompleter(autocommands.user.get, [function () Iterator(config.autocommands)]);
281     },
282     options: function () {
283         options.add(["eventignore", "ei"],
284             "List of autocommand event names which should be ignored",
285             "stringlist", "",
286             {
287                 values: iter(update({ all: "All Events" }, config.autocommands)).toArray(),
288                 has: Option.has.toggleAll
289             });
290     }
291 });
292
293 // vim: set fdm=marker sw=4 ts=4 et: