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