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-2013 Kris Maglione <maglione.k@gmail.com>
4 // Some code based on Venkman
6 // This work is licensed for reuse under an MIT license. Details are
7 // given in the LICENSE.txt file included with this file.
13 exports: ["IO", "io"],
17 lazyRequire("config", ["config"]);
18 lazyRequire("contexts", ["Contexts", "contexts"]);
19 lazyRequire("storage", ["File", "storage"]);
20 lazyRequire("styles", ["styles"]);
21 lazyRequire("template", ["template"]);
23 // TODO: why are we passing around strings rather than file objects?
25 * Provides a basic interface to common system I/O operations.
28 var IO = Module("io", {
29 init: function init() {
30 this._processDir = services.directory.get("CurWorkD", Ci.nsIFile);
31 this._cwd = this._processDir.path;
33 lazyRequire("config", ["config"], this);
36 Local: function Local(dactyl, modules, window) let ({ io, plugins } = modules) ({
38 init: function init() {
39 this.config = modules.config;
40 this._processDir = services.directory.get("CurWorkD", Ci.nsIFile);
41 this._cwd = this._processDir.path;
44 this._lastRunCommand = ""; // updated whenever the users runs a command with :!
45 this._scriptNames = [];
48 CommandFileMode: Class("CommandFileMode", modules.CommandMode, {
49 init: function init(prompt, params) {
51 this.prompt = isArray(prompt) ? prompt : ["Question", prompt];
57 get mode() modules.modes.FILE_INPUT,
59 complete: function (context) {
61 this.completer(context);
63 context = context.fork("files", 0);
64 modules.completion.file(context);
65 context.filters = context.filters.concat(this.filters || []);
70 * Returns all directories named *name* in 'runtimepath'.
72 * @param {string} name
73 * @returns {nsIFile[])
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()));
81 // FIXME: multiple paths?
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.
88 * @param {[string]} paths An array of relative paths to source.
89 * @param {boolean} all Whether all found files should be sourced.
91 sourceFromRuntimePath: function sourceFromRuntimePath(paths, all) {
92 let dirs = modules.options.get("runtimepath").files;
95 dactyl.echomsg(_("io.searchingFor", paths.join(" ").quote(), modules.options.get("runtimepath").stringValue), 2);
98 for (let dir in values(dirs)) {
99 for (let [, path] in Iterator(paths)) {
100 let file = dir.child(path);
102 dactyl.echomsg(_("io.searchingFor", file.path.quote()), 3);
104 if (file.exists() && file.isFile() && file.isReadable()) {
105 found = io.source(file.path, false) || true;
114 dactyl.echomsg(_("io.notInRTP", paths.join(" ").quote()), 1);
120 * Reads Ex commands, JavaScript or CSS from *filename*.
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.
127 source: function source(filename, params) {
128 const { contexts } = modules;
129 defineModule.loadLog.push("sourcing " + filename);
131 if (!isObject(params))
132 params = { silent: params };
134 let time = Date.now();
135 return contexts.withContext(null, function () {
137 var file = util.getFile(filename) || io.File(filename);
139 if (!file.exists() || !file.isReadable() || file.isDirectory()) {
141 dactyl.echoerr(_("io.notReadable", filename.quote()));
145 dactyl.echomsg(_("io.sourcing", filename.quote()), 2);
149 let sourceJSM = function sourceJSM() {
150 context = contexts.Module(uri);
151 dactyl.triggerObserver("io.source", context, file, file.lastModifiedTime);
154 if (/\.jsm$/.test(filename))
156 else if (/\.js$/.test(filename)) {
158 var context = contexts.Script(file, params.group);
159 if (Set.has(this._scriptNames, file.path))
162 dactyl.loadScript(uri.spec, context);
163 dactyl.triggerObserver("io.source", context, file, file.lastModifiedTime);
166 if (e == Contexts) { // Hack;
171 if (e instanceof Finished)
173 if (e.fileName && !(e instanceof FailedAssertion))
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("");
185 else if (/\.css$/.test(filename))
186 styles.registerSheet(uri.spec, false, true);
188 context = contexts.Context(file, params.group);
189 modules.commands.execute(file.read(), null, params.silent,
193 group: context.GROUP,
196 dactyl.triggerObserver("io.source", context, file, file.lastModifiedTime);
199 Set.add(this._scriptNames, file.path);
201 dactyl.echomsg(_("io.sourcingEnd", filename.quote()), 2);
202 dactyl.log(_("dactyl.sourced", filename), 3);
208 let message = _("io.sourcingError", e.echoerr || (file ? file.path : filename) + ": " + e);
210 dactyl.echoerr(message);
213 defineModule.loadLog.push("done sourcing " + filename + ": " + (Date.now() - time) + "ms");
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
222 * Returns the current working directory.
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.
231 let dir = File(this._cwd);
233 // NOTE: the directory could have been deleted underneath us so
234 // fallback to the process's CWD
235 if (dir.exists() && dir.isDirectory())
238 return this._processDir.clone();
242 * Sets the current working directory.
244 * @param {File|string} newDir The new CWD. This may be a relative or
245 * absolute path and is expanded by {@link #expandPath}.
249 set cwd(newDir = "~") {
250 newDir = newDir.path || newDir;
253 util.assert(this._oldcwd != null, _("io.noPrevDir"));
254 [this._cwd, this._oldcwd] = [this._oldcwd, this.cwd];
257 let dir = io.File(newDir);
258 util.assert(dir.exists() && dir.isDirectory(), _("io.noSuchDir", dir.path.quote()));
260 [this._cwd, this._oldcwd] = [dir.path, this.cwd];
266 * @property {function} File class.
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)
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.
282 expandPath: deprecated("File.expandPath", function expandPath() File.expandPath.apply(File, arguments)),
285 * Returns the first user RC file found in *dir*.
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.
291 * @returns {nsIFile} The RC file or null if none is found.
293 getRCFile: function getRCFile(dir, always) {
294 dir = this.File(dir || "~");
296 let rcFile1 = dir.child("." + config.name + "rc");
297 let rcFile2 = dir.child("_" + config.name + "rc");
299 if (config.OS.isWindows)
300 [rcFile1, rcFile2] = [rcFile2, rcFile1];
302 if (rcFile1.exists() && rcFile1.isFile())
304 else if (rcFile2.exists() && rcFile2.isFile())
312 * Returns a temporary file.
314 * @param {string} ext The filename extension.
316 * @param {string} label A metadata string appended to the filename. Useful
317 * for identifying the file, beyond its extension, to external
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));
327 services.externalApp.deleteTemporaryFileOnExit(file);
333 * Determines whether the given URL string resolves to a JAR URL and
334 * returns the matching nsIJARURI object if it does.
336 * @param {string} url The URL to check.
337 * @returns {nsIJARURI|null}
339 isJarURL: function isJarURL(url) {
341 let uri = util.newURI(url);
342 if (uri instanceof Ci.nsIJARURI)
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);
355 * Returns a list of the contents of the given JAR file which are
356 * children of the given path.
358 * @param {nsIURI|string} file The URI of the JAR file to list.
359 * @param {string} path The prefix path to search.
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);
367 let filter = RegExp("^" + util.regexp.escape(decodeURI(path))
370 for (let entry in iter(jar.findEntries("*")))
371 if (filter.test(entry))
381 readHeredoc: function readHeredoc(end) {
386 * Searches for the given executable file in the system executable
387 * file paths as specified by the PATH environment variable.
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.
394 * @param {string} bin The name of the executable to find.
395 * @returns {File|null}
397 pathSearch: function pathSearch(bin) {
398 if (bin instanceof File || File.isAbsolutePath(bin))
399 return this.File(bin);
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);
407 for (let [, dir] in Iterator(dirs))
409 dir = this.File(dir, true);
411 let file = dir.child(bin);
412 if (file.exists() && file.isFile() && file.isExecutable())
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);
431 * Runs an external program.
433 * @param {File|string} program The program to run.
434 * @param {[string]} args An array of arguments to pass to *program*.
436 run: function run(program, args, blocking, self) {
439 let file = this.pathSearch(program);
441 if (!file || !file.exists()) {
442 util.dactyl.echoerr(_("io.noCommand", program));
443 if (callable(blocking))
444 util.trapErrors(blocking);
448 let process = services.Process(file.file);
449 process.run(false, args.map(String), args.length);
451 if (callable(blocking))
452 var timer = services.Timer(
454 if (!process.isRunning) {
456 util.trapErrors(blocking, self, process.exitValue);
459 100, services.Timer.TYPE_REPEATING_SLACK);
461 while (process.isRunning)
462 util.threadYield(false, true);
469 return process.exitValue;
472 // TODO: when https://bugzilla.mozilla.org/show_bug.cgi?id=68702 is
473 // fixed use that instead of a tmpfile
475 * Runs *command* in a subshell and returns the output. The shell used is
476 * that specified by the 'shell' option.
478 * @param {string|[string]} command The command to run. This can be a shell
479 * command string or an array of strings (a command and arguments)
480 * which will be escaped and concatenated.
481 * @param {string} input Any input to be provided to the command on stdin.
482 * @param {function(object)} callback A callback to be called when
483 * the command completes. @optional
484 * @returns {object|null}
486 system: function system(command, input, callback) {
487 util.dactyl.echomsg(_("io.callingShell", command), 4);
489 let { shellEscape } = util.closure;
491 return this.withTempFiles(function (stdin, stdout, cmd) {
492 if (input instanceof File)
497 function result(status, output) ({
498 __noSuchMethod__: function (meth, args) this.output[meth].apply(this.output, args),
499 valueOf: function () this.output,
500 output: output.replace(/^(.*)\n$/, "$1"),
502 toString: function () this.output
505 function async(status) {
506 let output = stdout.read();
507 for (let f of [stdin, stdout, cmd])
510 callback(result(status, output));
513 let shell = io.pathSearch(storage["options"].get("shell").value);
514 let shcf = storage["options"].get("shellcmdflag").value;
515 util.assert(shell, _("error.invalid", "'shell'"));
517 if (isArray(command))
518 command = command.map(shellEscape).join(" ");
520 // TODO: implement 'shellredir'
521 if (config.OS.isWindows && !/sh/.test(shell.leafName)) {
522 command = "cd /D " + this.cwd.path + " && " + command + " > " + stdout.path + " 2>&1" + " < " + stdin.path;
523 var res = this.run(shell, shcf.split(/\s+/).concat(command), callback ? async : true);
526 cmd.write("cd " + shellEscape(this.cwd.path) + "\n" +
527 ["exec", ">" + shellEscape(stdout.path), "2>&1", "<" + shellEscape(stdin.path),
528 shellEscape(shell.path), shcf, shellEscape(command)].join(" "));
529 res = this.run("/bin/sh", ["-e", cmd.path], callback ? async : true);
532 return callback ? true : result(res, stdout.read());
537 * Creates a temporary file context for executing external commands.
538 * *func* is called with a temp file, created with {@link #createTempFile},
539 * for each explicit argument. Ensures that all files are removed when
542 * @param {function} func The function to execute.
543 * @param {Object} self The 'this' object used when executing func.
544 * @returns {boolean} false if temp files couldn't be created,
545 * otherwise, the return value of *func*.
547 withTempFiles: function withTempFiles(func, self, checked, ext, label) {
548 let args = array(util.range(0, func.length))
549 .map(bind("createTempFile", this, ext, label)).array;
551 if (!args.every(util.identity))
553 var res = func.apply(self || this, args);
556 if (!checked || res !== true)
557 args.forEach(f => { f.remove(false); });
563 * @property {string} The value of the $PENTADACTYL_RUNTIME environment
567 const rtpvar = config.idName + "_RUNTIME";
568 let rtp = services.environment.get(rtpvar);
570 rtp = "~/" + (config.OS.isWindows ? "" : ".") + config.name;
571 services.environment.set(rtpvar, rtp);
577 * @property {string} The current platform's path separator.
579 PATH_SEP: deprecated("File.PATH_SEP", { get: function PATH_SEP() File.PATH_SEP })
581 commands: function initCommands(dactyl, modules, window) {
582 const { commands, completion, io } = modules;
584 commands.add(["cd", "chd[ir]"],
585 "Change the current directory",
592 arg = File.expandPath(arg);
594 // go directly to an absolute path or look for a relative path
596 if (File.isAbsolutePath(arg)) {
598 dactyl.echomsg(io.cwd.path);
601 let dirs = modules.options.get("cdpath").files;
602 for (let dir in values(dirs)) {
603 dir = dir.child(arg);
605 if (dir.exists() && dir.isDirectory() && dir.isReadable()) {
607 dactyl.echomsg(io.cwd.path);
612 dactyl.echoerr(_("io.noSuchDir", arg.quote()));
613 dactyl.echoerr(_("io.commandFailed"));
617 completer: function (context) completion.directory(context, true),
621 commands.add(["pw[d]"],
622 "Print the current directory name",
623 function () { dactyl.echomsg(io.cwd.path); },
626 commands.add([config.name.replace(/(.)(.*)/, "mk$1[$2rc]")],
627 "Write current key mappings and changed options to the config file",
629 dactyl.assert(args.length <= 1, _("io.oneFileAllowed"));
631 let file = io.File(args[0] || io.getRCFile(null, true));
633 dactyl.assert(!file.exists() || args.bang, _("io.exists", file.path.quote()));
635 // TODO: Use a set/specifiable list here:
636 let lines = [cmd.serialize().map(commands.commandToString, cmd) for (cmd in commands.iterator()) if (cmd.serialize)];
637 lines = array.flatten(lines);
639 lines.unshift('"' + config.version + "\n");
640 lines.push("\n\" vim: set ft=" + config.name + ":");
643 file.write(lines.join("\n").concat("\n"));
644 dactyl.echomsg(_("io.writing", file.path.quote()), 2);
647 dactyl.echoerr(_("io.notWriteable", file.path.quote()));
648 dactyl.log(_("error.notWriteable", file.path, e.message)); // XXX
651 argCount: "*", // FIXME: should be "?" but kludged for proper error message
653 completer: function (context) completion.file(context, true)
656 commands.add(["mkv[imruntime]"],
657 "Create and install Vim runtime files for " + config.appName,
659 dactyl.assert(args.length <= 1, _("io.oneFileAllowed"));
662 var rtDir = io.File(args[0]);
663 dactyl.assert(rtDir.exists(), _("io.noSuchDir", rtDir.path.quote()));
666 rtDir = io.File(config.OS.isWindows ? "~/vimfiles/" : "~/.vim/");
668 dactyl.assert(!rtDir.exists() || rtDir.isDirectory(), _("io.eNotDir", rtDir.path.quote()));
670 let rtItems = { ftdetect: {}, ftplugin: {}, syntax: {} };
672 // require bang if any of the paths exist
673 for (let [type, item] in iter(rtItems)) {
674 let file = io.File(rtDir).child(type, config.name + ".vim");
675 dactyl.assert(!file.exists() || args.bang, _("io.exists", file.path.quote()));
679 rtItems.ftdetect.template = //{{{
680 literal(/*" Vim filetype detection file
683 au BufNewFile,BufRead *<name>rc*,*.<fileext> set filetype=<name>
685 rtItems.ftplugin.template = //{{{
686 literal(/*" Vim filetype plugin file
689 if exists("b:did_ftplugin")
692 let b:did_ftplugin = 1
694 let s:cpo_save = &cpo
697 let b:undo_ftplugin = "setl com< cms< fo< ofu< | unlet! b:browsefilter"
699 setlocal comments=:\"
700 setlocal commentstring=\"%s
701 setlocal formatoptions-=t formatoptions+=croql
702 setlocal omnifunc=syntaxcomplete#Complete
704 if has("gui_win32") && !exists("b:browsefilter")
705 let b:browsefilter = "<appname> Config Files (*.<fileext>)\t*.<fileext>\n" .
706 \ "All Files (*.*)\t*.*\n"
709 let &cpo = s:cpo_save
712 rtItems.syntax.template = //{{{
713 literal(/*" Vim syntax file
716 if exists("b:current_syntax")
720 let s:cpo_save = &cpo
723 syn include @javascriptTop syntax/javascript.vim
724 unlet b:current_syntax
726 syn include @cssTop syntax/css.vim
727 unlet b:current_syntax
729 syn match <name>CommandStart "\%(^\s*:\=\)\@<=" nextgroup=<name>Command,<name>AutoCmd
734 syn match <name>Command "!" contained
736 syn keyword <name>AutoCmd au[tocmd] contained nextgroup=<name>AutoEventList skipwhite
741 syn match <name>AutoEventList "\(\a\+,\)*\a\+" contained contains=<name>AutoEvent
743 syn region <name>Set matchgroup=<name>Command start="\%(^\s*:\=\)\@<=\<\%(setl\%[ocal]\|setg\%[lobal]\|set\=\)\=\>"
744 \ end="$" keepend oneline contains=<name>Option,<name>String
747 \ contained nextgroup=pentadactylSetMod
750 execute 'syn match <name>Option "\<\%(no\|inv\)\=\%(' .
751 \ join(s:toggleOptions, '\|') .
752 \ '\)\>!\=" contained nextgroup=<name>SetMod'
754 syn match <name>SetMod "\%(\<[a-z_]\+\)\@<=&" contained
756 syn region <name>JavaScript start="\%(^\s*\%(javascript\|js\)\s\+\)\@<=" end="$" contains=@javascriptTop keepend oneline
757 syn region <name>JavaScript matchgroup=<name>JavaScriptDelimiter
758 \ start="\%(^\s*\%(javascript\|js\)\s\+\)\@<=<<\s*\z(\h\w*\)"hs=s+2 end="^\z1$" contains=@javascriptTop fold
760 let s:cssRegionStart = '\%(^\s*sty\%[le]!\=\s\+\%(-\%(n\|name\)\%(\s\+\|=\)\S\+\s\+\)\=[^-]\S\+\s\+\)\@<='
761 execute 'syn region <name>Css start="' . s:cssRegionStart . '" end="$" contains=@cssTop keepend oneline'
762 execute 'syn region <name>Css matchgroup=<name>CssDelimiter'
763 \ 'start="' . s:cssRegionStart . '<<\s*\z(\h\w*\)"hs=s+2 end="^\z1$" contains=@cssTop fold'
765 syn match <name>Notation "<[0-9A-Za-z-]\+>"
767 syn keyword <name>Todo FIXME NOTE TODO XXX contained
769 syn region <name>String start="\z(["']\)" end="\z1" skip="\\\\\|\\\z1" oneline
771 syn match <name>Comment +^\s*".*$+ contains=<name>Todo,@Spell
773 " NOTE: match vim.vim highlighting group names
774 hi def link <name>AutoCmd <name>Command
775 hi def link <name>AutoEvent Type
776 hi def link <name>Command Statement
777 hi def link <name>JavaScriptDelimiter Delimiter
778 hi def link <name>CssDelimiter Delimiter
779 hi def link <name>Notation Special
780 hi def link <name>Comment Comment
781 hi def link <name>Option PreProc
782 hi def link <name>SetMod <name>Option
783 hi def link <name>String String
784 hi def link <name>Todo Todo
786 let b:current_syntax = "<name>"
788 let &cpo = s:cpo_save
791 " vim: tw=130 et ts=8 sts=4 sw=4:
794 const { options } = modules;
797 function wrap(prefix, items, sep) {//{{{
801 lines.__defineGetter__("last", function () this[this.length - 1]);
803 for (let item in values(items.array || items)) {
804 if (item.length > width && (!lines.length || lines.last.length > 1)) {
805 lines.push([prefix]);
806 width = WIDTH - prefix.length;
809 width -= item.length + sep.length;
810 lines.last.push(item, sep);
813 return lines.map(l => l.join(""))
815 .replace(/\s+\n/gm, "\n");
819 header: ['" Language: ' + config.appName + ' configuration file',
820 '" Maintainer: Doug Kearns <dougkearns@gmail.com>',
821 '" Version: ' + config.version].join("\n"),
823 appname: config.appName,
824 fileext: config.fileExtension,
825 maintainer: "Doug Kearns <dougkearns@gmail.com>",
826 autocommands: wrap("syn keyword " + config.name + "AutoEvent ",
827 keys(config.autocommands)),
828 commands: wrap("syn keyword " + config.name + "Command ",
829 array(c.specs for (c in commands.iterator())).flatten()),
830 options: wrap("syn keyword " + config.name + "Option ",
831 array(o.names for (o in options) if (o.type != "boolean")).flatten()),
832 toggleoptions: wrap("let s:toggleOptions = [",
833 array(o.realNames for (o in options) if (o.type == "boolean"))
834 .flatten().map(String.quote),
838 for (let { file, template } in values(rtItems)) {
840 file.write(util.compileMacro(template, true)(params));
841 dactyl.echomsg(_("io.writing", file.path.quote()), 2);
844 dactyl.echoerr(_("io.notWriteable", file.path.quote()));
845 dactyl.log(_("error.notWriteable", file.path, e.message));
851 completer: function (context) completion.directory(context, true),
855 commands.add(["runt[ime]"],
856 "Source the specified file from each directory in 'runtimepath'",
857 function (args) { io.sourceFromRuntimePath(args, args.bang); },
861 completer: function (context) completion.runtime(context)
865 commands.add(["scrip[tnames]"],
866 "List all sourced script names",
868 let names = Object.keys(io._scriptNames);
870 dactyl.echomsg(_("command.scriptnames.none"));
872 modules.commandline.commandOutput(
873 template.tabular(["<SNR>", "Filename"], ["text-align: right; padding-right: 1em;"],
874 ([i + 1, file] for ([i, file] in Iterator(names)))));
879 commands.add(["so[urce]"],
880 "Read Ex commands, JavaScript or CSS from a file",
883 dactyl.echoerr(_("io.oneFileAllowed"));
885 io.source(args[0], { silent: args.bang });
887 argCount: "+", // FIXME: should be "1" but kludged for proper error message
889 completer: function (context) completion.file(context, true)
892 commands.add(["!", "run"],
895 let arg = args[0] || "";
897 // :!! needs to be treated specially as the command parser sets the
898 // bang flag but removes the ! from arg
902 // This is an asinine and irritating "feature" when we have searchable
903 // command-line history. --Kris
904 if (modules.options["banghist"]) {
905 // NOTE: Vim doesn't replace ! preceded by 2 or more backslashes and documents it - desirable?
906 // pass through a raw bang when escaped or substitute the last command
908 // replaceable bang and no previous command?
909 dactyl.assert(!/((^|[^\\])(\\\\)*)!/.test(arg) || io._lastRunCommand,
910 _("command.run.noPrevious"));
912 arg = arg.replace(/(\\)*!/g,
913 m => (/^\\(\\\\)*!$/.test(m) ? m.replace("\\!", "!")
914 : m.replace("!", io._lastRunCommand)));
917 io._lastRunCommand = arg;
919 let result = io.system(arg);
920 if (result.returnValue != 0)
921 result.output += "\n" + _("io.shellReturn", result.returnValue);
923 modules.commandline.command = args.commandName.replace("run", "$& ") + arg;
924 modules.commandline.commandOutput(["span", { highlight: "CmdOutput" }, result.output]);
926 modules.autocommands.trigger("ShellCmdPost", {});
930 // This is abominably slow.
931 // completer: function (context) completion.shellCommand(context),
935 completion: function initCompletion(dactyl, modules, window) {
936 const { completion, io } = modules;
938 completion.charset = function (context) {
939 context.anchored = false;
942 description: function (charset) {
944 return services.charset.getCharsetTitle(charset);
951 context.generate = () => iter(services.charset.getDecoderList());
954 completion.directory = function directory(context, full) {
955 this.file(context, full);
956 context.filters.push(item => item.isdir);
959 completion.environment = function environment(context) {
960 context.title = ["Environment Variable", "Value"];
961 context.generate = () =>
962 io.system(config.OS.isWindows ? "set" : "env")
964 .filter(line => line.indexOf("=") > 0)
965 .map(line => line.match(/([^=]+)=(.*)/).slice(1));
968 completion.file = function file(context, full, dir) {
969 if (/^jar:[^!]*$/.test(context.filter))
972 // dir == "" is expanded inside readDirectory to the current dir
973 function getDir(str) str.match(/^(?:.*[\/\\])?/)[0];
974 dir = getDir(dir || context.filter);
976 let file = util.getFile(dir);
977 if (file && (!file.exists() || !file.isDirectory()))
981 context.advance(dir.length);
983 context.title = [full ? "Path" : "Filename", "Type"];
985 text: !full ? "leafName" : function (f) this.path,
986 path: function (f) dir + f.leafName,
987 description: function (f) this.isdir ? "Directory" : "File",
988 isdir: function (f) f.isDirectory(),
989 icon: function (f) this.isdir ? "resource://gre/res/html/folder.png"
990 : "moz-icon://" + f.leafName
992 context.compare = (a, b) => b.isdir - a.isdir || String.localeCompare(a.text, b.text);
994 if (modules.options["wildignore"])
995 context.filters.push(item => !modules.options.get("wildignore").getKey(item.path));
997 // context.background = true;
999 let uri = io.isJarURL(dir);
1001 context.generate = function generate_jar() {
1004 isDirectory: function () s.substr(-1) == "/",
1005 leafName: /([^\/]*)\/?$/.exec(s)[1]
1007 for (s in io.listJar(uri.JARFile, getDir(uri.JAREntry)))]
1010 context.generate = function generate_file() {
1012 return io.File(file || dir).readDirectory();
1019 completion.runtime = function (context) {
1020 for (let [, dir] in Iterator(modules.options["runtimepath"]))
1021 context.fork(dir, 0, this, function (context) {
1022 dir = dir.replace("/+$", "") + "/";
1023 completion.file(context, true, dir + context.filter);
1024 context.title[0] = dir;
1025 context.keys.text = function (f) this.path.substr(dir.length);
1029 completion.shellCommand = function shellCommand(context) {
1030 context.title = ["Shell Command", "Path"];
1031 context.generate = function () {
1032 let dirNames = services.environment.get("PATH").split(config.OS.pathListSep);
1035 for (let [, dirName] in Iterator(dirNames)) {
1036 let dir = io.File(dirName);
1037 if (dir.exists() && dir.isDirectory())
1038 commands.push([[file.leafName, dir.path] for (file in iter(dir.directoryEntries))
1039 if (file.isFile() && file.isExecutable())]);
1042 return array.flatten(commands);
1046 completion.addUrlCompleter("file", "Local files", function (context, full) {
1047 let match = util.regexp(literal(/*
1051 (?P<scheme> chrome|resource)
1056 (?P<path> \/[^\/]* )?
1058 */), "x").exec(context.filter);
1061 context.key = match.proto;
1062 context.advance(match.proto.length);
1063 context.generate = () => config.chromePackages.map(p => [p, match.proto + p + "/"]);
1065 else if (match.scheme === "chrome") {
1066 context.key = match.prefix;
1067 context.advance(match.prefix.length + 1);
1068 context.generate = function () iter({
1069 content: /*L*/"Chrome content",
1070 locale: /*L*/"Locale-specific content",
1071 skin: /*L*/"Theme-specific content"
1075 if (!match || match.scheme === "resource" && match.path)
1076 if (/^(\.{0,2}|~)\/|^file:/.test(context.filter)
1077 || config.OS.isWindows && /^[a-z]:/i.test(context.filter)
1078 || util.getFile(context.filter)
1079 || io.isJarURL(context.filter))
1080 completion.file(context, full);
1083 javascript: function initJavascript(dactyl, modules, window) {
1084 modules.JavaScript.setCompleter([File, File.expandPath],
1085 [function (context, obj, args) {
1086 context.quote[2] = "";
1087 modules.completion.file(context, true);
1091 modes: function initModes(dactyl, modules, window) {
1092 initModes.require("commandline");
1093 const { modes } = modules;
1095 modes.addMode("FILE_INPUT", {
1097 description: "Active when selecting a file",
1098 bases: [modes.COMMAND_LINE],
1102 options: function initOptions(dactyl, modules, window) {
1103 const { completion, options } = modules;
1105 var shell, shellcmdflag;
1106 if (config.OS.isWindows) {
1108 shellcmdflag = "/c";
1111 shell = services.environment.get("SHELL") || "sh";
1112 shellcmdflag = "-c";
1115 options.add(["banghist", "bh"],
1116 "Replace occurrences of ! with the previous command when executing external commands",
1119 options.add(["fileencoding", "fenc"],
1120 "The character encoding used when reading and writing files",
1121 "string", "UTF-8", {
1122 completer: function (context) completion.charset(context),
1123 getter: function () File.defaultEncoding,
1124 setter: function (value) (File.defaultEncoding = value)
1126 options.add(["cdpath", "cd"],
1127 "List of directories searched when executing :cd",
1128 "stringlist", ["."].concat(services.environment.get("CDPATH").split(/[:;]/).filter(util.identity)).join(","),
1130 get files() this.value.map(path => File(path, modules.io.cwd))
1131 .filter(dir => dir.exists()),
1132 setter: function (value) File.expandPathList(value)
1135 options.add(["runtimepath", "rtp"],
1136 "List of directories searched for runtime files",
1137 "stringlist", IO.runtimePath,
1139 get files() this.value.map(path => File(path, modules.io.cwd))
1140 .filter(dir => dir.exists())
1143 options.add(["shell", "sh"],
1144 "Shell to use for executing external commands with :! and :run",
1146 { validator: function (val) io.pathSearch(val) });
1148 options.add(["shellcmdflag", "shcf"],
1149 "Flag passed to shell when executing external commands with :! and :run",
1150 "string", shellcmdflag,
1152 getter: function (value) {
1153 if (this.hasChanged || !config.OS.isWindows)
1155 return /sh/.test(options["shell"]) ? "-c" : "/c";
1158 options["shell"]; // Make sure it's loaded into global storage.
1159 options["shellcmdflag"];
1161 options.add(["wildignore", "wig"],
1162 "List of path name patterns to ignore when completing files and directories",
1169 } catch(e){ if (isString(e)) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
1171 // vim: set fdm=marker sw=4 sts=4 ts=8 et ft=javascript: