]> git.donarmstrong.com Git - dactyl.git/blob - common/modules/io.jsm
Import r6948 from upstream hg supporting Firefox up to 24.*
[dactyl.git] / common / modules / io.jsm
1 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2007-2012 by Doug Kearns <dougkearns@gmail.com>
3 // Copyright (c) 2008-2012 Kris Maglione <maglione.k@gmail.com>
4 // Some code based on Venkman
5 //
6 // This work is licensed for reuse under an MIT license. Details are
7 // given in the LICENSE.txt file included with this file.
8 "use strict";
9
10 try {
11
12 defineModule("io", {
13     exports: ["IO", "io"],
14     require: ["services"]
15 });
16
17 lazyRequire("config", ["config"]);
18 lazyRequire("contexts", ["Contexts", "contexts"]);
19 lazyRequire("storage", ["File", "storage"]);
20 lazyRequire("styles", ["styles"]);
21 lazyRequire("template", ["template"]);
22
23 // TODO: why are we passing around strings rather than file objects?
24 /**
25  * Provides a basic interface to common system I/O operations.
26  * @instance io
27  */
28 var IO = Module("io", {
29     init: function init() {
30         this._processDir = services.directory.get("CurWorkD", Ci.nsIFile);
31         this._cwd = this._processDir.path;
32         this._oldcwd = null;
33         lazyRequire("config", ["config"], this);
34     },
35
36     Local: function Local(dactyl, modules, window) let ({ io, plugins } = modules) ({
37
38         init: function init() {
39             this.config = modules.config;
40             this._processDir = services.directory.get("CurWorkD", Ci.nsIFile);
41             this._cwd = this._processDir.path;
42             this._oldcwd = null;
43
44             this._lastRunCommand = ""; // updated whenever the users runs a command with :!
45             this._scriptNames = [];
46         },
47
48         CommandFileMode: Class("CommandFileMode", modules.CommandMode, {
49             init: function init(prompt, params) {
50                 init.supercall(this);
51                 this.prompt = isArray(prompt) ? prompt : ["Question", prompt];
52                 update(this, params);
53             },
54
55             historyKey: "file",
56
57             get mode() modules.modes.FILE_INPUT,
58
59             complete: function (context) {
60                 if (this.completer)
61                     this.completer(context);
62
63                 context = context.fork("files", 0);
64                 modules.completion.file(context);
65                 context.filters = context.filters.concat(this.filters || []);
66             }
67         }),
68
69         /**
70          * Returns all directories named *name* in 'runtimepath'.
71          *
72          * @param {string} name
73          * @returns {nsIFile[])
74          */
75         getRuntimeDirectories: function getRuntimeDirectories(name) {
76             return modules.options.get("runtimepath").files
77                 .map(function (dir) dir.child(name))
78                 .filter(function (dir) dir.exists() && dir.isDirectory() && dir.isReadable());
79         },
80
81         // FIXME: multiple paths?
82         /**
83          * Sources files found in 'runtimepath'. For each relative path in *paths*
84          * each directory in 'runtimepath' is searched and if a matching file is
85          * found it is sourced. Only the first file found (per specified path) is
86          * sourced unless *all* is specified, then all found files are sourced.
87          *
88          * @param {[string]} paths An array of relative paths to source.
89          * @param {boolean} all Whether all found files should be sourced.
90          */
91         sourceFromRuntimePath: function sourceFromRuntimePath(paths, all) {
92             let dirs = modules.options.get("runtimepath").files;
93             let found = null;
94
95             dactyl.echomsg(_("io.searchingFor", paths.join(" ").quote(), modules.options.get("runtimepath").stringValue), 2);
96
97         outer:
98             for (let dir in values(dirs)) {
99                 for (let [, path] in Iterator(paths)) {
100                     let file = dir.child(path);
101
102                     dactyl.echomsg(_("io.searchingFor", file.path.quote()), 3);
103
104                     if (file.exists() && file.isFile() && file.isReadable()) {
105                         found = io.source(file.path, false) || true;
106
107                         if (!all)
108                             break outer;
109                     }
110                 }
111             }
112
113             if (!found)
114                 dactyl.echomsg(_("io.notInRTP", paths.join(" ").quote()), 1);
115
116             return found;
117         },
118
119         /**
120          * Reads Ex commands, JavaScript or CSS from *filename*.
121          *
122          * @param {string} filename The name of the file to source.
123          * @param {object} params Extra parameters:
124          *      group:  The group in which to execute commands.
125          *      silent: Whether errors should not be reported.
126          */
127         source: function source(filename, params) {
128             const { contexts } = modules;
129             defineModule.loadLog.push("sourcing " + filename);
130
131             if (!isObject(params))
132                 params = { silent: params };
133
134             let time = Date.now();
135             return contexts.withContext(null, function () {
136                 try {
137                     var file = util.getFile(filename) || io.File(filename);
138
139                     if (!file.exists() || !file.isReadable() || file.isDirectory()) {
140                         if (!params.silent)
141                             dactyl.echoerr(_("io.notReadable", filename.quote()));
142                         return;
143                     }
144
145                     dactyl.echomsg(_("io.sourcing", filename.quote()), 2);
146
147                     let uri = file.URI;
148
149                     let sourceJSM = function sourceJSM() {
150                         context = contexts.Module(uri);
151                         dactyl.triggerObserver("io.source", context, file, file.lastModifiedTime);
152                     };
153
154                     if (/\.jsm$/.test(filename))
155                         sourceJSM();
156                     else if (/\.js$/.test(filename)) {
157                         try {
158                             var context = contexts.Script(file, params.group);
159                             if (Set.has(this._scriptNames, file.path))
160                                 util.flushCache();
161
162                             dactyl.loadScript(uri.spec, context);
163                             dactyl.triggerObserver("io.source", context, file, file.lastModifiedTime);
164                         }
165                         catch (e) {
166                             if (e == Contexts) { // Hack;
167                                 context.unload();
168                                 sourceJSM();
169                             }
170                             else {
171                                 if (e instanceof Finished)
172                                     return;
173                                 if (e.fileName && !(e instanceof FailedAssertion))
174                                     try {
175                                         e.fileName = util.fixURI(e.fileName);
176                                         if (e.fileName == uri.spec)
177                                             e.fileName = filename;
178                                         e.echoerr = [e.fileName, ":", e.lineNumber, ": ", e].join("");
179                                     }
180                                     catch (e) {}
181                                 throw e;
182                             }
183                         }
184                     }
185                     else if (/\.css$/.test(filename))
186                         styles.registerSheet(uri.spec, false, true);
187                     else {
188                         context = contexts.Context(file, params.group);
189                         modules.commands.execute(file.read(), null, params.silent,
190                                                  null, {
191                             context: context,
192                             file: file.path,
193                             group: context.GROUP,
194                             line: 1
195                         });
196                         dactyl.triggerObserver("io.source", context, file, file.lastModifiedTime);
197                     }
198
199                     Set.add(this._scriptNames, file.path);
200
201                     dactyl.echomsg(_("io.sourcingEnd", filename.quote()), 2);
202                     dactyl.log(_("dactyl.sourced", filename), 3);
203
204                     return context;
205                 }
206                 catch (e) {
207                     util.reportError(e);
208                     let message = _("io.sourcingError", e.echoerr || (file ? file.path : filename) + ": " + e);
209                     if (!params.silent)
210                         dactyl.echoerr(message);
211                 }
212                 finally {
213                     defineModule.loadLog.push("done sourcing " + filename + ": " + (Date.now() - time) + "ms");
214                 }
215             }, this);
216         }
217     }),
218
219     // TODO: there seems to be no way, short of a new component, to change
220     // the process's CWD - see https://bugzilla.mozilla.org/show_bug.cgi?id=280953
221     /**
222      * Returns the current working directory.
223      *
224      * It's not possible to change the real CWD of the process so this
225      * state is maintained internally. External commands run via
226      * {@link #system} are executed in this directory.
227      *
228      * @returns {nsIFile}
229      */
230     get cwd() {
231         let dir = File(this._cwd);
232
233         // NOTE: the directory could have been deleted underneath us so
234         // fallback to the process's CWD
235         if (dir.exists() && dir.isDirectory())
236             return dir;
237         else
238             return this._processDir.clone();
239     },
240
241     /**
242      * Sets the current working directory.
243      *
244      * @param {string} newDir The new CWD. This may be a relative or
245      *     absolute path and is expanded by {@link #expandPath}.
246      */
247     set cwd(newDir) {
248         newDir = newDir && newDir.path || newDir || "~";
249
250         if (newDir == "-") {
251             util.assert(this._oldcwd != null, _("io.noPrevDir"));
252             [this._cwd, this._oldcwd] = [this._oldcwd, this.cwd];
253         }
254         else {
255             let dir = io.File(newDir);
256             util.assert(dir.exists() && dir.isDirectory(), _("io.noSuchDir", dir.path.quote()));
257             dir.normalize();
258             [this._cwd, this._oldcwd] = [dir.path, this.cwd];
259         }
260         return this.cwd;
261     },
262
263     /**
264      * @property {function} File class.
265      * @final
266      */
267     File: Class.Memoize(function () let (io = this)
268         Class("File", File, {
269             init: function init(path, checkCWD)
270                 init.supercall(this, path, (arguments.length < 2 || checkCWD) && io.cwd)
271         })),
272
273     /**
274      * @property {Object} The current file sourcing context. As a file is
275      *     being sourced the 'file' and 'line' properties of this context
276      *     object are updated appropriately.
277      */
278     sourcing: null,
279
280     expandPath: deprecated("File.expandPath", function expandPath() File.expandPath.apply(File, arguments)),
281
282     /**
283      * Returns the first user RC file found in *dir*.
284      *
285      * @param {File|string} dir The directory to search.
286      * @param {boolean} always When true, return a path whether
287      *     the file exists or not.
288      * @default $HOME.
289      * @returns {nsIFile} The RC file or null if none is found.
290      */
291     getRCFile: function getRCFile(dir, always) {
292         dir = this.File(dir || "~");
293
294         let rcFile1 = dir.child("." + config.name + "rc");
295         let rcFile2 = dir.child("_" + config.name + "rc");
296
297         if (config.OS.isWindows)
298             [rcFile1, rcFile2] = [rcFile2, rcFile1];
299
300         if (rcFile1.exists() && rcFile1.isFile())
301             return rcFile1;
302         else if (rcFile2.exists() && rcFile2.isFile())
303             return rcFile2;
304         else if (always)
305             return rcFile1;
306         return null;
307     },
308
309     /**
310      * Returns a temporary file.
311      *
312      * @param {string} ext The filename extension.
313      *     @default "txt"
314      * @param {string} label A metadata string appended to the filename. Useful
315      *     for identifying the file, beyond its extension, to external
316      *     applications.
317      *     @default ""
318      * @returns {File}
319      */
320     createTempFile: function createTempFile(ext = "txt", label = "") {
321         let file = services.directory.get("TmpD", Ci.nsIFile);
322         file.append(config.name + label + "." + ext);
323         file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, octal(666));
324
325         services.externalApp.deleteTemporaryFileOnExit(file);
326
327         return File(file);
328     },
329
330     /**
331      * Determines whether the given URL string resolves to a JAR URL and
332      * returns the matching nsIJARURI object if it does.
333      *
334      * @param {string} url The URL to check.
335      * @returns {nsIJARURI|null}
336      */
337     isJarURL: function isJarURL(url) {
338         try {
339             let uri = util.newURI(url);
340             if (uri instanceof Ci.nsIJARURI)
341                 return uri;
342
343             let channel = services.io.newChannelFromURI(uri);
344             try { channel.cancel(Cr.NS_BINDING_ABORTED); } catch (e) {}
345             if (channel instanceof Ci.nsIJARChannel)
346                 return channel.URI.QueryInterface(Ci.nsIJARURI);
347         }
348         catch (e) {}
349         return null;
350     },
351
352     /**
353      * Returns a list of the contents of the given JAR file which are
354      * children of the given path.
355      *
356      * @param {nsIURI|string} file The URI of the JAR file to list.
357      * @param {string} path The prefix path to search.
358      */
359     listJar: function listJar(file, path) {
360         file = util.getFile(file);
361         if (file && file.exists() && file.isFile() && file.isReadable()) {
362             // let jar = services.zipReader.getZip(file); Crashes.
363             let jar = services.ZipReader(file.file);
364             try {
365                 let filter = RegExp("^" + util.regexp.escape(decodeURI(path))
366                                     + "[^/]*/?$");
367
368                 for (let entry in iter(jar.findEntries("*")))
369                     if (filter.test(entry))
370                         yield entry;
371             }
372             finally {
373                 if (jar)
374                     jar.close();
375             }
376         }
377     },
378
379     readHeredoc: function readHeredoc(end) {
380         return "";
381     },
382
383     /**
384      * Searches for the given executable file in the system executable
385      * file paths as specified by the PATH environment variable.
386      *
387      * On Windows, if the unadorned filename cannot be found, the
388      * extensions in the semicolon-separated list in the PATHSEP
389      * environment variable are successively appended to the original
390      * name and searched for in turn.
391      *
392      * @param {string} bin The name of the executable to find.
393      * @returns {File|null}
394      */
395     pathSearch: function pathSearch(bin) {
396         if (bin instanceof File || File.isAbsolutePath(bin))
397             return this.File(bin);
398
399         let dirs = services.environment.get("PATH")
400                            .split(config.OS.pathListSep);
401         // Windows tries the CWD first TODO: desirable?
402         if (config.OS.isWindows)
403             dirs = [io.cwd].concat(dirs);
404
405         for (let [, dir] in Iterator(dirs))
406             try {
407                 dir = this.File(dir, true);
408
409                 let file = dir.child(bin);
410                 if (file.exists() && file.isFile() && file.isExecutable())
411                     return file;
412
413                 // TODO: couldn't we just palm this off to the start command?
414                 // automatically try to add the executable path extensions on windows
415                 if (config.OS.isWindows) {
416                     let extensions = services.environment.get("PATHEXT").split(";");
417                     for (let [, extension] in Iterator(extensions)) {
418                         file = dir.child(bin + extension);
419                         if (file.exists())
420                             return file;
421                     }
422                 }
423             }
424             catch (e) {}
425         return null;
426     },
427
428     /**
429      * Runs an external program.
430      *
431      * @param {File|string} program The program to run.
432      * @param {[string]} args An array of arguments to pass to *program*.
433      */
434     run: function run(program, args, blocking, self) {
435         args = args || [];
436
437         let file = this.pathSearch(program);
438
439         if (!file || !file.exists()) {
440             util.dactyl.echoerr(_("io.noCommand", program));
441             if (callable(blocking))
442                 util.trapErrors(blocking);
443             return -1;
444         }
445
446         let process = services.Process(file.file);
447         process.run(false, args.map(String), args.length);
448         try {
449             if (callable(blocking))
450                 var timer = services.Timer(
451                     function () {
452                         if (!process.isRunning) {
453                             timer.cancel();
454                             util.trapErrors(blocking, self, process.exitValue);
455                         }
456                     },
457                     100, services.Timer.TYPE_REPEATING_SLACK);
458             else if (blocking)
459                 while (process.isRunning)
460                     util.threadYield(false, true);
461         }
462         catch (e) {
463             process.kill();
464             throw e;
465         }
466
467         return process.exitValue;
468     },
469
470     // TODO: when https://bugzilla.mozilla.org/show_bug.cgi?id=68702 is
471     // fixed use that instead of a tmpfile
472     /**
473      * Runs *command* in a subshell and returns the output. The shell used is
474      * that specified by the 'shell' option.
475      *
476      * @param {string|[string]} command The command to run. This can be a shell
477      *      command string or an array of strings (a command and arguments)
478      *      which will be escaped and concatenated.
479      * @param {string} input Any input to be provided to the command on stdin.
480      * @param {function(object)} callback A callback to be called when
481      *      the command completes. @optional
482      * @returns {object|null}
483      */
484     system: function system(command, input, callback) {
485         util.dactyl.echomsg(_("io.callingShell", command), 4);
486
487         let { shellEscape } = util.closure;
488
489         return this.withTempFiles(function (stdin, stdout, cmd) {
490             if (input instanceof File)
491                 stdin = input;
492             else if (input)
493                 stdin.write(input);
494
495             function result(status, output) ({
496                 __noSuchMethod__: function (meth, args) this.output[meth].apply(this.output, args),
497                 valueOf: function () this.output,
498                 output: output.replace(/^(.*)\n$/, "$1"),
499                 returnValue: status,
500                 toString: function () this.output
501             });
502
503             function async(status) {
504                 let output = stdout.read();
505                 [stdin, stdout, cmd].forEach(function (f) f.exists() && f.remove(false));
506                 callback(result(status, output));
507             }
508
509             let shell = io.pathSearch(storage["options"].get("shell").value);
510             let shcf = storage["options"].get("shellcmdflag").value;
511             util.assert(shell, _("error.invalid", "'shell'"));
512
513             if (isArray(command))
514                 command = command.map(shellEscape).join(" ");
515
516             // TODO: implement 'shellredir'
517             if (config.OS.isWindows && !/sh/.test(shell.leafName)) {
518                 command = "cd /D " + this.cwd.path + " && " + command + " > " + stdout.path + " 2>&1" + " < " + stdin.path;
519                 var res = this.run(shell, shcf.split(/\s+/).concat(command), callback ? async : true);
520             }
521             else {
522                 cmd.write("cd " + shellEscape(this.cwd.path) + "\n" +
523                         ["exec", ">" + shellEscape(stdout.path), "2>&1", "<" + shellEscape(stdin.path),
524                          shellEscape(shell.path), shcf, shellEscape(command)].join(" "));
525                 res = this.run("/bin/sh", ["-e", cmd.path], callback ? async : true);
526             }
527
528             return callback ? true : result(res, stdout.read());
529         }, this, true);
530     },
531
532     /**
533      * Creates a temporary file context for executing external commands.
534      * *func* is called with a temp file, created with {@link #createTempFile},
535      * for each explicit argument. Ensures that all files are removed when
536      * *func* returns.
537      *
538      * @param {function} func The function to execute.
539      * @param {Object} self The 'this' object used when executing func.
540      * @returns {boolean} false if temp files couldn't be created,
541      *     otherwise, the return value of *func*.
542      */
543     withTempFiles: function withTempFiles(func, self, checked, ext, label) {
544         let args = array(util.range(0, func.length))
545                     .map(bind("createTempFile", this, ext, label)).array;
546         try {
547             if (!args.every(util.identity))
548                 return false;
549             var res = func.apply(self || this, args);
550         }
551         finally {
552             if (!checked || res !== true)
553                 args.forEach(function (f) f.remove(false));
554         }
555         return res;
556     }
557 }, {
558     /**
559      * @property {string} The value of the $PENTADACTYL_RUNTIME environment
560      *     variable.
561      */
562     get runtimePath() {
563         const rtpvar = config.idName + "_RUNTIME";
564         let rtp = services.environment.get(rtpvar);
565         if (!rtp) {
566             rtp = "~/" + (config.OS.isWindows ? "" : ".") + config.name;
567             services.environment.set(rtpvar, rtp);
568         }
569         return rtp;
570     },
571
572     /**
573      * @property {string} The current platform's path separator.
574      */
575     PATH_SEP: deprecated("File.PATH_SEP", { get: function PATH_SEP() File.PATH_SEP })
576 }, {
577     commands: function initCommands(dactyl, modules, window) {
578         const { commands, completion, io } = modules;
579
580         commands.add(["cd", "chd[ir]"],
581             "Change the current directory",
582             function (args) {
583                 let arg = args[0];
584
585                 if (!arg)
586                     arg = "~";
587
588                 arg = File.expandPath(arg);
589
590                 // go directly to an absolute path or look for a relative path
591                 // match in 'cdpath'
592                 if (File.isAbsolutePath(arg)) {
593                     io.cwd = arg;
594                     dactyl.echomsg(io.cwd.path);
595                 }
596                 else {
597                     let dirs = modules.options.get("cdpath").files;
598                     for (let dir in values(dirs)) {
599                         dir = dir.child(arg);
600
601                         if (dir.exists() && dir.isDirectory() && dir.isReadable()) {
602                             io.cwd = dir;
603                             dactyl.echomsg(io.cwd.path);
604                             return;
605                         }
606                     }
607
608                     dactyl.echoerr(_("io.noSuchDir", arg.quote()));
609                     dactyl.echoerr(_("io.commandFailed"));
610                 }
611             }, {
612                 argCount: "?",
613                 completer: function (context) completion.directory(context, true),
614                 literal: 0
615             });
616
617         commands.add(["pw[d]"],
618             "Print the current directory name",
619             function () { dactyl.echomsg(io.cwd.path); },
620             { argCount: "0" });
621
622         commands.add([config.name.replace(/(.)(.*)/, "mk$1[$2rc]")],
623             "Write current key mappings and changed options to the config file",
624             function (args) {
625                 dactyl.assert(args.length <= 1, _("io.oneFileAllowed"));
626
627                 let file = io.File(args[0] || io.getRCFile(null, true));
628
629                 dactyl.assert(!file.exists() || args.bang, _("io.exists", file.path.quote()));
630
631                 // TODO: Use a set/specifiable list here:
632                 let lines = [cmd.serialize().map(commands.commandToString, cmd) for (cmd in commands.iterator()) if (cmd.serialize)];
633                 lines = array.flatten(lines);
634
635                 lines.unshift('"' + config.version + "\n");
636                 lines.push("\n\" vim: set ft=" + config.name + ":");
637
638                 try {
639                     file.write(lines.join("\n").concat("\n"));
640                     dactyl.echomsg(_("io.writing", file.path.quote()), 2);
641                 }
642                 catch (e) {
643                     dactyl.echoerr(_("io.notWriteable", file.path.quote()));
644                     dactyl.log(_("error.notWriteable", file.path, e.message)); // XXX
645                 }
646             }, {
647                 argCount: "*", // FIXME: should be "?" but kludged for proper error message
648                 bang: true,
649                 completer: function (context) completion.file(context, true)
650             });
651
652         commands.add(["mkv[imruntime]"],
653             "Create and install Vim runtime files for " + config.appName,
654             function (args) {
655                 dactyl.assert(args.length <= 1, _("io.oneFileAllowed"));
656
657                 if (args.length) {
658                     var rtDir = io.File(args[0]);
659                     dactyl.assert(rtDir.exists(), _("io.noSuchDir", rtDir.path.quote()));
660                 }
661                 else
662                     rtDir = io.File(config.OS.isWindows ? "~/vimfiles/" : "~/.vim/");
663
664                 dactyl.assert(!rtDir.exists() || rtDir.isDirectory(), _("io.eNotDir", rtDir.path.quote()));
665
666                 let rtItems = { ftdetect: {}, ftplugin: {}, syntax: {} };
667
668                 // require bang if any of the paths exist
669                 for (let [type, item] in iter(rtItems)) {
670                     let file = io.File(rtDir).child(type, config.name + ".vim");
671                     dactyl.assert(!file.exists() || args.bang, _("io.exists", file.path.quote()));
672                     item.file = file;
673                 }
674
675                 rtItems.ftdetect.template = //{{{
676 literal(/*" Vim filetype detection file
677 <header>
678
679 au BufNewFile,BufRead *<name>rc*,*.<fileext> set filetype=<name>
680 */);//}}}
681                 rtItems.ftplugin.template = //{{{
682 literal(/*" Vim filetype plugin file
683 <header>
684
685 if exists("b:did_ftplugin")
686   finish
687 endif
688 let b:did_ftplugin = 1
689
690 let s:cpo_save = &cpo
691 set cpo&vim
692
693 let b:undo_ftplugin = "setl com< cms< fo< ofu< | unlet! b:browsefilter"
694
695 setlocal comments=:\"
696 setlocal commentstring=\"%s
697 setlocal formatoptions-=t formatoptions+=croql
698 setlocal omnifunc=syntaxcomplete#Complete
699
700 if has("gui_win32") && !exists("b:browsefilter")
701     let b:browsefilter = "<appname> Config Files (*.<fileext>)\t*.<fileext>\n" .
702         \ "All Files (*.*)\t*.*\n"
703 endif
704
705 let &cpo = s:cpo_save
706 unlet s:cpo_save
707 */);//}}}
708                 rtItems.syntax.template = //{{{
709 literal(/*" Vim syntax file
710 <header>
711
712 if exists("b:current_syntax")
713   finish
714 endif
715
716 let s:cpo_save = &cpo
717 set cpo&vim
718
719 syn include @javascriptTop syntax/javascript.vim
720 unlet b:current_syntax
721
722 syn include @cssTop syntax/css.vim
723 unlet b:current_syntax
724
725 syn match <name>CommandStart "\%(^\s*:\=\)\@<=" nextgroup=<name>Command,<name>AutoCmd
726
727 <commands>
728     \ contained
729
730 syn match <name>Command "!" contained
731
732 syn keyword <name>AutoCmd au[tocmd] contained nextgroup=<name>AutoEventList skipwhite
733
734 <autocommands>
735     \ contained
736
737 syn match <name>AutoEventList "\(\a\+,\)*\a\+" contained contains=<name>AutoEvent
738
739 syn region <name>Set matchgroup=<name>Command start="\%(^\s*:\=\)\@<=\<\%(setl\%[ocal]\|setg\%[lobal]\|set\=\)\=\>"
740     \ end="$" keepend oneline contains=<name>Option,<name>String
741
742 <options>
743     \ contained nextgroup=pentadactylSetMod
744
745 <toggleoptions>
746 execute 'syn match <name>Option "\<\%(no\|inv\)\=\%(' .
747     \ join(s:toggleOptions, '\|') .
748     \ '\)\>!\=" contained nextgroup=<name>SetMod'
749
750 syn match <name>SetMod "\%(\<[a-z_]\+\)\@<=&" contained
751
752 syn region <name>JavaScript start="\%(^\s*\%(javascript\|js\)\s\+\)\@<=" end="$" contains=@javascriptTop keepend oneline
753 syn region <name>JavaScript matchgroup=<name>JavaScriptDelimiter
754     \ start="\%(^\s*\%(javascript\|js\)\s\+\)\@<=<<\s*\z(\h\w*\)"hs=s+2 end="^\z1$" contains=@javascriptTop fold
755
756 let s:cssRegionStart = '\%(^\s*sty\%[le]!\=\s\+\%(-\%(n\|name\)\%(\s\+\|=\)\S\+\s\+\)\=[^-]\S\+\s\+\)\@<='
757 execute 'syn region <name>Css start="' . s:cssRegionStart . '" end="$" contains=@cssTop keepend oneline'
758 execute 'syn region <name>Css matchgroup=<name>CssDelimiter'
759     \ 'start="' . s:cssRegionStart . '<<\s*\z(\h\w*\)"hs=s+2 end="^\z1$" contains=@cssTop fold'
760
761 syn match <name>Notation "<[0-9A-Za-z-]\+>"
762
763 syn keyword <name>Todo FIXME NOTE TODO XXX contained
764
765 syn region <name>String start="\z(["']\)" end="\z1" skip="\\\\\|\\\z1" oneline
766
767 syn match <name>Comment +^\s*".*$+ contains=<name>Todo,@Spell
768
769 " NOTE: match vim.vim highlighting group names
770 hi def link <name>AutoCmd               <name>Command
771 hi def link <name>AutoEvent             Type
772 hi def link <name>Command               Statement
773 hi def link <name>JavaScriptDelimiter   Delimiter
774 hi def link <name>CssDelimiter          Delimiter
775 hi def link <name>Notation              Special
776 hi def link <name>Comment               Comment
777 hi def link <name>Option                PreProc
778 hi def link <name>SetMod                <name>Option
779 hi def link <name>String                String
780 hi def link <name>Todo                  Todo
781
782 let b:current_syntax = "<name>"
783
784 let &cpo = s:cpo_save
785 unlet s:cpo_save
786
787 " vim: tw=130 et ts=8 sts=4 sw=4:
788 */);//}}}
789
790                 const { options } = modules;
791
792                 const WIDTH = 80;
793                 function wrap(prefix, items, sep) {//{{{
794                     sep = sep || " ";
795                     let width = 0;
796                     let lines = [];
797                     lines.__defineGetter__("last", function () this[this.length - 1]);
798
799                     for (let item in values(items.array || items)) {
800                         if (item.length > width && (!lines.length || lines.last.length > 1)) {
801                             lines.push([prefix]);
802                             width = WIDTH - prefix.length;
803                             prefix = "    \\ ";
804                         }
805                         width -= item.length + sep.length;
806                         lines.last.push(item, sep);
807                     }
808                     lines.last.pop();
809                     return lines.map(function (l) l.join("")).join("\n").replace(/\s+\n/gm, "\n");
810                 }//}}}
811
812                 let params = { //{{{
813                     header: ['" Language:    ' + config.appName + ' configuration file',
814                              '" Maintainer:  Doug Kearns <dougkearns@gmail.com>',
815                              '" Version:     ' + config.version].join("\n"),
816                     name: config.name,
817                     appname: config.appName,
818                     fileext: config.fileExtension,
819                     maintainer: "Doug Kearns <dougkearns@gmail.com>",
820                     autocommands: wrap("syn keyword " + config.name + "AutoEvent ",
821                                        keys(config.autocommands)),
822                     commands: wrap("syn keyword " + config.name + "Command ",
823                                   array(c.specs for (c in commands.iterator())).flatten()),
824                     options: wrap("syn keyword " + config.name + "Option ",
825                                   array(o.names for (o in options) if (o.type != "boolean")).flatten()),
826                     toggleoptions: wrap("let s:toggleOptions = [",
827                                         array(o.realNames for (o in options) if (o.type == "boolean"))
828                                             .flatten().map(String.quote),
829                                         ", ") + "]"
830                 }; //}}}
831
832                 for (let { file, template } in values(rtItems)) {
833                     try {
834                         file.write(util.compileMacro(template, true)(params));
835                         dactyl.echomsg(_("io.writing", file.path.quote()), 2);
836                     }
837                     catch (e) {
838                         dactyl.echoerr(_("io.notWriteable", file.path.quote()));
839                         dactyl.log(_("error.notWriteable", file.path, e.message));
840                     }
841                 }
842             }, {
843                 argCount: "?",
844                 bang: true,
845                 completer: function (context) completion.directory(context, true),
846                 literal: 1
847             });
848
849         commands.add(["runt[ime]"],
850             "Source the specified file from each directory in 'runtimepath'",
851             function (args) { io.sourceFromRuntimePath(args, args.bang); },
852             {
853                 argCount: "+",
854                 bang: true,
855                 completer: function (context) completion.runtime(context)
856             }
857         );
858
859         commands.add(["scrip[tnames]"],
860             "List all sourced script names",
861             function () {
862                 let names = Object.keys(io._scriptNames);
863                 if (!names.length)
864                     dactyl.echomsg(_("command.scriptnames.none"));
865                 else
866                     modules.commandline.commandOutput(
867                         template.tabular(["<SNR>", "Filename"], ["text-align: right; padding-right: 1em;"],
868                             ([i + 1, file] for ([i, file] in Iterator(names)))));
869
870             },
871             { argCount: "0" });
872
873         commands.add(["so[urce]"],
874             "Read Ex commands, JavaScript or CSS from a file",
875             function (args) {
876                 if (args.length > 1)
877                     dactyl.echoerr(_("io.oneFileAllowed"));
878                 else
879                     io.source(args[0], { silent: args.bang });
880             }, {
881                 argCount: "+", // FIXME: should be "1" but kludged for proper error message
882                 bang: true,
883                 completer: function (context) completion.file(context, true)
884             });
885
886         commands.add(["!", "run"],
887             "Run a command",
888             function (args) {
889                 let arg = args[0] || "";
890
891                 // :!! needs to be treated specially as the command parser sets the
892                 // bang flag but removes the ! from arg
893                 if (args.bang)
894                     arg = "!" + arg;
895
896                 // This is an asinine and irritating "feature" when we have searchable
897                 // command-line history. --Kris
898                 if (modules.options["banghist"]) {
899                     // NOTE: Vim doesn't replace ! preceded by 2 or more backslashes and documents it - desirable?
900                     // pass through a raw bang when escaped or substitute the last command
901
902                     // replaceable bang and no previous command?
903                     dactyl.assert(!/((^|[^\\])(\\\\)*)!/.test(arg) || io._lastRunCommand,
904                         _("command.run.noPrevious"));
905
906                     arg = arg.replace(/(\\)*!/g,
907                         function (m) /^\\(\\\\)*!$/.test(m) ? m.replace("\\!", "!") : m.replace("!", io._lastRunCommand)
908                     );
909                 }
910
911                 io._lastRunCommand = arg;
912
913                 let result = io.system(arg);
914                 if (result.returnValue != 0)
915                     result.output += "\n" + _("io.shellReturn", result.returnValue);
916
917                 modules.commandline.command = args.commandName.replace("run", "$& ") + arg;
918                 modules.commandline.commandOutput(["span", { highlight: "CmdOutput" }, result.output]);
919
920                 modules.autocommands.trigger("ShellCmdPost", {});
921             }, {
922                 argCount: "?",
923                 bang: true,
924                 // This is abominably slow.
925                 // completer: function (context) completion.shellCommand(context),
926                 literal: 0
927             });
928     },
929     completion: function initCompletion(dactyl, modules, window) {
930         const { completion, io } = modules;
931
932         completion.charset = function (context) {
933             context.anchored = false;
934             context.keys = {
935                 text: util.identity,
936                 description: function (charset) {
937                     try {
938                         return services.charset.getCharsetTitle(charset);
939                     }
940                     catch (e) {
941                         return charset;
942                     }
943                 }
944             };
945             context.generate = function () iter(services.charset.getDecoderList());
946         };
947
948         completion.directory = function directory(context, full) {
949             this.file(context, full);
950             context.filters.push(function (item) item.isdir);
951         };
952
953         completion.environment = function environment(context) {
954             context.title = ["Environment Variable", "Value"];
955             context.generate = function ()
956                 io.system(config.OS.isWindows ? "set" : "env")
957                   .output.split("\n")
958                   .filter(function (line) line.indexOf("=") > 0)
959                   .map(function (line) line.match(/([^=]+)=(.*)/).slice(1));
960         };
961
962         completion.file = function file(context, full, dir) {
963             if (/^jar:[^!]*$/.test(context.filter))
964                 context.advance(4);
965
966             // dir == "" is expanded inside readDirectory to the current dir
967             function getDir(str) str.match(/^(?:.*[\/\\])?/)[0];
968             dir = getDir(dir || context.filter);
969
970             let file = util.getFile(dir);
971             if (file && (!file.exists() || !file.isDirectory()))
972                 file = file.parent;
973
974             if (!full)
975                 context.advance(dir.length);
976
977             context.title = [full ? "Path" : "Filename", "Type"];
978             context.keys = {
979                 text: !full ? "leafName" : function (f) this.path,
980                 path: function (f) dir + f.leafName,
981                 description: function (f) this.isdir ? "Directory" : "File",
982                 isdir: function (f) f.isDirectory(),
983                 icon: function (f) this.isdir ? "resource://gre/res/html/folder.png"
984                                               : "moz-icon://" + f.leafName
985             };
986             context.compare = function (a, b) b.isdir - a.isdir || String.localeCompare(a.text, b.text);
987
988             if (modules.options["wildignore"])
989                 context.filters.push(function (item) !modules.options.get("wildignore").getKey(item.path));
990
991             // context.background = true;
992             context.key = dir;
993             let uri = io.isJarURL(dir);
994             if (uri)
995                 context.generate = function generate_jar() {
996                     return [
997                         {
998                               isDirectory: function () s.substr(-1) == "/",
999                               leafName: /([^\/]*)\/?$/.exec(s)[1]
1000                         }
1001                         for (s in io.listJar(uri.JARFile, getDir(uri.JAREntry)))]
1002                 };
1003             else
1004                 context.generate = function generate_file() {
1005                     try {
1006                         return io.File(file || dir).readDirectory();
1007                     }
1008                     catch (e) {}
1009                     return [];
1010                 };
1011         };
1012
1013         completion.runtime = function (context) {
1014             for (let [, dir] in Iterator(modules.options["runtimepath"]))
1015                 context.fork(dir, 0, this, function (context) {
1016                     dir = dir.replace("/+$", "") + "/";
1017                     completion.file(context, true, dir + context.filter);
1018                     context.title[0] = dir;
1019                     context.keys.text = function (f) this.path.substr(dir.length);
1020                 });
1021         };
1022
1023         completion.shellCommand = function shellCommand(context) {
1024             context.title = ["Shell Command", "Path"];
1025             context.generate = function () {
1026                 let dirNames = services.environment.get("PATH").split(config.OS.pathListSep);
1027                 let commands = [];
1028
1029                 for (let [, dirName] in Iterator(dirNames)) {
1030                     let dir = io.File(dirName);
1031                     if (dir.exists() && dir.isDirectory())
1032                         commands.push([[file.leafName, dir.path] for (file in iter(dir.directoryEntries))
1033                                        if (file.isFile() && file.isExecutable())]);
1034                 }
1035
1036                 return array.flatten(commands);
1037             };
1038         };
1039
1040         completion.addUrlCompleter("file", "Local files", function (context, full) {
1041             let match = util.regexp(literal(/*
1042                 ^
1043                 (?P<prefix>
1044                     (?P<proto>
1045                         (?P<scheme> chrome|resource)
1046                         :\/\/
1047                     )
1048                     [^\/]*
1049                 )
1050                 (?P<path> \/[^\/]* )?
1051                 $
1052             */), "x").exec(context.filter);
1053             if (match) {
1054                 if (!match.path) {
1055                     context.key = match.proto;
1056                     context.advance(match.proto.length);
1057                     context.generate = function () config.chromePackages.map(function (p) [p, match.proto + p + "/"]);
1058                 }
1059                 else if (match.scheme === "chrome") {
1060                     context.key = match.prefix;
1061                     context.advance(match.prefix.length + 1);
1062                     context.generate = function () iter({
1063                         content: /*L*/"Chrome content",
1064                         locale: /*L*/"Locale-specific content",
1065                         skin: /*L*/"Theme-specific content"
1066                     });
1067                 }
1068             }
1069             if (!match || match.scheme === "resource" && match.path)
1070                 if (/^(\.{0,2}|~)\/|^file:/.test(context.filter)
1071                     || config.OS.isWindows && /^[a-z]:/i.test(context.filter)
1072                     || util.getFile(context.filter)
1073                     || io.isJarURL(context.filter))
1074                     completion.file(context, full);
1075         });
1076     },
1077     javascript: function initJavascript(dactyl, modules, window) {
1078         modules.JavaScript.setCompleter([File, File.expandPath],
1079             [function (context, obj, args) {
1080                 context.quote[2] = "";
1081                 modules.completion.file(context, true);
1082             }]);
1083
1084     },
1085     modes: function initModes(dactyl, modules, window) {
1086         initModes.require("commandline");
1087         const { modes } = modules;
1088
1089         modes.addMode("FILE_INPUT", {
1090             extended: true,
1091             description: "Active when selecting a file",
1092             bases: [modes.COMMAND_LINE],
1093             input: true
1094         });
1095     },
1096     options: function initOptions(dactyl, modules, window) {
1097         const { completion, options } = modules;
1098
1099         var shell, shellcmdflag;
1100         if (config.OS.isWindows) {
1101             shell = "cmd.exe";
1102             shellcmdflag = "/c";
1103         }
1104         else {
1105             shell = services.environment.get("SHELL") || "sh";
1106             shellcmdflag = "-c";
1107         }
1108
1109         options.add(["banghist", "bh"],
1110             "Replace occurrences of ! with the previous command when executing external commands",
1111             "boolean", false);
1112
1113         options.add(["fileencoding", "fenc"],
1114             "The character encoding used when reading and writing files",
1115             "string", "UTF-8", {
1116                 completer: function (context) completion.charset(context),
1117                 getter: function () File.defaultEncoding,
1118                 setter: function (value) (File.defaultEncoding = value)
1119             });
1120         options.add(["cdpath", "cd"],
1121             "List of directories searched when executing :cd",
1122             "stringlist", ["."].concat(services.environment.get("CDPATH").split(/[:;]/).filter(util.identity)).join(","),
1123             {
1124                 get files() this.value.map(function (path) File(path, modules.io.cwd))
1125                                 .filter(function (dir) dir.exists()),
1126                 setter: function (value) File.expandPathList(value)
1127             });
1128
1129         options.add(["runtimepath", "rtp"],
1130             "List of directories searched for runtime files",
1131             "stringlist", IO.runtimePath,
1132             {
1133                 get files() this.value.map(function (path) File(path, modules.io.cwd))
1134                                 .filter(function (dir) dir.exists())
1135             });
1136
1137         options.add(["shell", "sh"],
1138             "Shell to use for executing external commands with :! and :run",
1139             "string", shell,
1140             { validator: function (val) io.pathSearch(val) });
1141
1142         options.add(["shellcmdflag", "shcf"],
1143             "Flag passed to shell when executing external commands with :! and :run",
1144             "string", shellcmdflag,
1145             {
1146                 getter: function (value) {
1147                     if (this.hasChanged || !config.OS.isWindows)
1148                         return value;
1149                     return /sh/.test(options["shell"]) ? "-c" : "/c";
1150                 }
1151             });
1152         options["shell"]; // Make sure it's loaded into global storage.
1153         options["shellcmdflag"];
1154
1155         options.add(["wildignore", "wig"],
1156             "List of path name patterns to ignore when completing files and directories",
1157             "regexplist", "");
1158     }
1159 });
1160
1161 endModule();
1162
1163 } catch(e){ if (isString(e)) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
1164
1165 // vim: set fdm=marker sw=4 sts=4 ts=8 et ft=javascript: