1 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
3 // Copyright (c) 2008-2013 Kris Maglione <maglione.k@gmail.com>
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
11 var EVAL_ERROR = "__dactyl_eval_error";
12 var EVAL_RESULT = "__dactyl_eval_result";
13 var EVAL_STRING = "__dactyl_eval_string";
15 var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
18 // cheap attempt at compatibility
19 let prop = { get: deprecated("dactyl", function liberator() dactyl),
21 Object.defineProperty(window, "liberator", prop);
22 Object.defineProperty(modules, "liberator", prop);
25 this.modules = modules;
27 util.addObserver(this);
29 this.commands["dactyl.restart"] = function (event) {
33 styles.registerSheet("resource://dactyl-skin/dactyl.css");
36 this.cleanups.push(overlay.overlayObject(window, {
37 focusAndSelectUrlBar: function focusAndSelectUrlBar() {
38 switch (options.get("strictfocus").getKey(document.documentURIObject || util.newURI(document.documentURI), "moderate")) {
40 if (!Events.isHidden(window.gURLBar, true))
41 return focusAndSelectUrlBar.superapply(this, arguments);
49 cleanup: function () {
50 for (let cleanup in values(this.cleanups))
54 delete window.liberator;
56 // Prevents box ordering bugs after our stylesheet is removed.
57 styles.system.add("cleanup-sheet", config.styleableChrome, literal(/*
58 #TabsToolbar tab { display: none; }
60 styles.unregisterSheet("resource://dactyl-skin/dactyl.css");
61 DOM('#TabsToolbar tab', document).style.display;
64 destroy: function () {
65 this.observe.unregister();
66 autocommands.trigger("LeavePre", {});
67 dactyl.triggerObserver("shutdown", null);
68 util.dump("All dactyl modules destroyed\n");
69 autocommands.trigger("Leave", {});
72 // initially hide all GUI elements, they are later restored unless the user
73 // has :set go= or something similar in his config
74 hideGUI: function () {
75 let guioptions = config.guioptions;
76 for (let option in guioptions) {
77 guioptions[option].forEach(function (elem) {
79 document.getElementById(elem).collapsed = true;
87 "dactyl-cleanup": function dactyl_cleanup(subject, reason) {
88 let modules = dactyl.modules;
90 for (let mod in values(modules.moduleList.reverse())) {
93 this.trapErrors("cleanup", mod, reason);
95 this.trapErrors("destroy", mod, reason);
98 modules.moduleManager.initDependencies("cleanup");
100 for (let name in values(Object.getOwnPropertyNames(modules).reverse()))
102 delete modules[name];
105 modules.__proto__ = {};
110 "io.source": function ioSource(context, file, modTime) {
111 if (contexts.getDocs(context))
112 help.flush("help/plugins.xml", modTime);
116 profileName: deprecated("config.profileName", { get: function profileName() config.profileName }),
119 * @property {Modes.Mode} The current main mode.
120 * @see modes#mainModes
122 mode: deprecated("modes.main", {
123 get: function mode() modes.main,
124 set: function mode(val) modes.main = val
127 getMenuItems: function getMenuItems(targetPath) {
128 function addChildren(node, parent) {
129 DOM(node).createContents();
131 if (~["menu", "menupopup"].indexOf(node.localName) && node.children.length)
132 DOM(node).popupshowing({ bubbles: false });
134 for (let [, item] in Iterator(node.childNodes)) {
135 if (item.childNodes.length == 0 && item.localName == "menuitem"
137 && !/rdf:http:/.test(item.getAttribute("label"))) { // FIXME
138 item.dactylPath = parent + item.getAttribute("label");
139 if (!targetPath || targetPath.indexOf(item.dactylPath) == 0)
144 if (item.localName == "menu")
145 path += item.getAttribute("label") + ".";
146 if (!targetPath || targetPath.indexOf(path) == 0)
147 addChildren(item, path);
153 addChildren(document.getElementById(config.guioptions["m"][1]), "");
157 get menuItems() this.getMenuItems(),
162 NEW_BACKGROUND_TAB: "background-tab",
163 NEW_WINDOW: "window",
165 forceBackground: null,
169 get forceOpen() ({ background: this.forceBackground,
170 target: this.forceTarget }),
172 for (let [k, v] in Iterator({ background: "forceBackground", target: "forceTarget" }))
177 version: deprecated("config.version", { get: function version() config.version }),
180 * @property {Object} The map of command-line options. These are
181 * specified in the argument to the host application's -{config.name}
182 * option. E.g. $ firefox -pentadactyl '+u=/tmp/rcfile ++noplugin'
184 * +u RCFILE Use RCFILE instead of .pentadactylrc.
185 * ++noplugin Don't load plugins.
186 * These two can be specified multiple times:
187 * ++cmd CMD Execute an Ex command before initialization.
188 * +c CMD Execute an Ex command after initialization.
190 commandLineOptions: {
191 /** @property Whether plugin loading should be prevented. */
193 /** @property An RC file to use rather than the default. */
195 /** @property An Ex command to run before any initialization is performed. */
197 /** @property An Ex command to run after all initialization has been performed. */
201 registerObserver: function registerObserver(type, callback, weak) {
202 if (!(type in this._observers))
203 this._observers[type] = [];
204 this._observers[type].push(weak ? util.weakReference(callback) : { get: function () callback });
207 registerObservers: function registerObservers(obj, prop) {
208 for (let [signal, func] in Iterator(obj[prop || "signals"]))
209 this.registerObserver(signal, obj.closure(func), false);
212 unregisterObserver: function unregisterObserver(type, callback) {
213 if (type in this._observers)
214 this._observers[type] = this._observers[type].filter(c => c.get() != callback);
217 applyTriggerObserver: function triggerObserver(type, args) {
218 if (type in this._observers)
219 this._observers[type] = this._observers[type].filter(function (callback) {
220 if (callback.get()) {
223 callback.get().apply(null, args);
225 catch (e if e.message == "can't wrap XML objects") {
227 callback.get().apply(null, [String(args[0])].concat(args.slice(1)));
231 dactyl.reportError(e);
238 triggerObserver: function triggerObserver(type, ...args) {
239 return this.applyTriggerObserver(type, args);
242 addUsageCommand: function (params) {
243 function keys(item) (item.names || [item.name]).concat(item.description, item.columns || []);
245 let name = commands.add(params.name, params.description,
247 let results = array(params.iterate(args))
248 .sort((a, b) => String.localeCompare(a.name, b.name));
250 let filters = args.map(arg => let (re = util.regexp.escape(arg))
251 util.regexp("\\b" + re + "\\b|(?:^|[()\\s])" + re + "(?:$|[()\\s])", "i"));
253 results = results.filter(item => filters.every(re => keys(item).some(re.closure.test)));
255 commandline.commandOutput(
256 template.usage(results, params.format));
260 completer: function (context, args) {
261 context.keys.text = util.identity;
262 context.keys.description = function () seen[this.text] + /*L*/" matching items";
263 context.ignoreCase = true;
265 context.completions = array(keys(item).join(" ").toLowerCase().split(/[()\s]+/)
266 for (item in params.iterate(args)))
269 seen[k] = (seen[k] || 0) + 1;
273 options: params.options || []
277 this.indices[params.index] = function () {
278 let results = array((params.iterateIndex || params.iterate).call(params, commands.get(name).newArgs()))
279 .array.sort((a, b) => String.localeCompare(a.name, b.name));
281 let haveTag = Set.has(help.tags);
282 for (let obj in values(results)) {
283 let res = dactyl.generateHelp(obj, null, null, true);
284 if (!haveTag(obj.helpTag))
285 res[0][1].tag = obj.helpTag;
293 * Triggers the application bell to notify the user of an error. The
294 * bell may be either audible or visual depending on the value of the
295 * 'visualbell' option.
298 this.triggerObserver("beep");
299 if (options["visualbell"]) {
301 bell: document.getElementById("dactyl-bell"),
302 strut: document.getElementById("dactyl-bell-strut")
305 overlay.overlayWindow(window, {
308 ["window", { id: document.documentElement.id, xmlns: "xul" },
309 ["hbox", { style: "display: none", highlight: "Bell", id: "dactyl-bell", key: "bell" }]]],
311 ["window", { id: document.documentElement.id, xmlns: "xul" },
312 ["hbox", { style: "display: none", highlight: "Bell", id: "dactyl-bell-strut", key: "strut" }]]]
315 elems.bell.style.height = window.innerHeight + "px";
316 elems.strut.style.marginBottom = -window.innerHeight + "px";
317 elems.strut.style.display = elems.bell.style.display = "";
319 util.timeout(function () { elems.strut.style.display = elems.bell.style.display = "none"; }, 20);
322 let soundService = Cc["@mozilla.org/sound;1"].getService(Ci.nsISound);
328 * Reads a string from the system clipboard.
330 * This is same as Firefox's readFromClipboard function, but is needed for
331 * apps like Thunderbird which do not provide it.
333 * @param {string} which Which clipboard to write to. Either
334 * "global" or "selection". If not provided, both clipboards are
339 clipboardRead: function clipboardRead(which) {
341 const { clipboard } = services;
343 let transferable = services.Transferable();
344 transferable.addDataFlavor("text/unicode");
346 let source = clipboard[which == "global" || !clipboard.supportsSelectionClipboard() ?
347 "kGlobalClipboard" : "kSelectionClipboard"];
348 clipboard.getData(transferable, source);
350 let str = {}, len = {};
351 transferable.getTransferData("text/unicode", str, len);
354 return str.value.QueryInterface(Ci.nsISupportsString)
355 .data.substr(0, len.value / 2);
362 * Copies a string to the system clipboard. If *verbose* is specified the
363 * copied string is also echoed to the command line.
365 * @param {string} str The string to write.
366 * @param {boolean} verbose If true, the user is notified of the copied data.
367 * @param {string} which Which clipboard to write to. Either
368 * "global" or "selection". If not provided, both clipboards are
372 clipboardWrite: function clipboardWrite(str, verbose, which) {
373 if (which == null || which == "selection" && !services.clipboard.supportsSelectionClipboard())
374 services.clipboardHelper.copyString(str);
376 services.clipboardHelper.copyStringToClipboard(str,
377 services.clipboard["k" + util.capitalize(which) + "Clipboard"]);
380 let message = { message: _("dactyl.yank", str) };
382 message.domains = [util.newURI(str).host];
385 dactyl.echomsg(message);
389 dump: deprecated("util.dump",
390 { get: function dump() util.closure.dump }),
391 dumpStack: deprecated("util.dumpStack",
392 { get: function dumpStack() util.closure.dumpStack }),
395 * Outputs a plain message to the command line.
397 * @param {string} str The message to output.
398 * @param {number} flags These control the multi-line message behavior.
399 * See {@link CommandLine#echo}.
401 echo: function echo(str, flags) {
402 commandline.echo(str, commandline.HL_NORMAL, flags);
406 * Outputs an error message to the command line.
408 * @param {string} str The message to output.
409 * @param {number} flags These control the multi-line message behavior.
410 * See {@link CommandLine#echo}.
412 echoerr: function echoerr(str, flags) {
413 flags |= commandline.APPEND_TO_MESSAGES;
415 if (isinstance(str, ["DOMException", "Error", "Exception", ErrorBase])
416 || isinstance(str, ["XPCWrappedNative_NoHelper"]) && /^\[Exception/.test(str))
417 dactyl.reportError(str);
419 if (isObject(str) && "echoerr" in str)
421 else if (isinstance(str, ["Error", FailedAssertion]) && str.fileName)
422 str = [str.fileName.replace(/^.* -> /, ""), ": ", str.lineNumber, ": ", str].join("");
424 if (options["errorbells"])
427 commandline.echo(str, commandline.HL_ERRORMSG, flags);
431 * Outputs a warning message to the command line.
433 * @param {string} str The message to output.
434 * @param {number} flags These control the multi-line message behavior.
435 * See {@link CommandLine#echo}.
437 warn: function warn(str, flags) {
438 commandline.echo(str, "WarningMsg", flags | commandline.APPEND_TO_MESSAGES);
441 // TODO: add proper level constants
443 * Outputs an information message to the command line.
445 * @param {string} str The message to output.
446 * @param {number} verbosity The messages log level (0 - 15). Only
447 * messages with verbosity less than or equal to the value of the
448 * *verbosity* option will be output.
449 * @param {number} flags These control the multi-line message behavior.
450 * See {@link CommandLine#echo}.
452 echomsg: function echomsg(str, verbosity, flags) {
453 if (verbosity == null)
454 verbosity = 0; // verbosity level is exclusionary
456 if (options["verbose"] >= verbosity)
457 commandline.echo(str, commandline.HL_INFOMSG,
458 flags | commandline.APPEND_TO_MESSAGES);
462 * Loads and executes the script referenced by *uri* in the scope of the
465 * @param {string} uri The URI of the script to load. Should be a local
466 * chrome:, file:, or resource: URL.
467 * @param {Object} context The context object into which the script
470 loadScript: function loadScript(uri, context) {
471 JSMLoader.loadSubScript(uri, context, File.defaultEncoding);
474 userEval: function userEval(str, context, fileName, lineNumber) {
476 if (jsmodules.__proto__ != window && jsmodules.__proto__ != XPCNativeWrapper(window) &&
477 jsmodules.isPrototypeOf(context))
478 str = "with (window) { with (modules) { (this.eval || eval)(" + str.quote() + ") } }";
480 let info = contexts.context;
481 if (fileName == null)
483 ({ file: fileName, line: lineNumber, context: ctxt }) = info;
485 if (fileName && fileName[0] == "[")
486 fileName = "dactyl://command-line/";
488 context = ctxt || _userContext;
490 if (isinstance(context, ["Sandbox"]))
491 return Cu.evalInSandbox(str, context, "1.8", fileName, lineNumber);
494 context = userContext || ctxt;
496 if (services.has("dactyl") && services.dactyl.evalInContext)
497 return services.dactyl.evalInContext(str, context, fileName, lineNumber);
500 context[EVAL_ERROR] = null;
501 context[EVAL_STRING] = str;
502 context[EVAL_RESULT] = null;
504 this.loadScript("resource://dactyl-content/eval.js", context);
505 if (context[EVAL_ERROR]) {
507 context[EVAL_ERROR].fileName = info.file;
508 context[EVAL_ERROR].lineNumber += info.line;
511 throw context[EVAL_ERROR];
513 return context[EVAL_RESULT];
516 delete context[EVAL_ERROR];
517 delete context[EVAL_RESULT];
518 delete context[EVAL_STRING];
523 * Acts like the Function builtin, but the code executes in the
524 * userContext global.
526 userFunc: function userFunc(...args) {
527 return this.userEval(
528 "(function userFunction(" + args.slice(0, -1).join(", ") + ")" +
529 " { " + args.pop() + " })");
533 * Execute an Ex command string. E.g. ":zoom 300".
535 * @param {string} str The command to execute.
536 * @param {Object} modifiers Any modifiers to be passed to
537 * {@link Command#action}.
538 * @param {boolean} silent Whether the command should be echoed on the
541 execute: function execute(str, modifiers = {}, silent = false) {
542 // skip comments and blank lines
543 if (/^\s*("|$)/.test(str))
547 commands.lastCommand = str.replace(/^\s*:\s*/, "");
549 for (let [command, args] in commands.parseCommands(str.replace(/^'(.*)'$/, "$1"))) {
550 if (command === null)
551 throw FailedAssertion(_("dactyl.notCommand", config.appName, args.commandString));
553 res = res && command.execute(args, modifiers);
558 focus: function focus(elem, flags) {
559 DOM(elem).focus(flags);
563 * Focuses the content window.
565 * @param {boolean} clearFocusedElement Remove focus from any focused
568 focusContent: function focusContent(clearFocusedElement) {
569 if (window != services.focus.activeWindow)
572 let win = document.commandDispatcher.focusedWindow;
573 let elem = config.mainWidget || content;
575 // TODO: make more generic
577 if (this.has("mail") && !config.isComposeWindow) {
578 let i = gDBView.selection.currentIndex;
579 if (i == -1 && gDBView.rowCount >= 0)
581 gDBView.selection.select(i);
584 let frame = buffer.focusedFrame;
585 if (frame && frame.top == content && !Editor.getEditor(frame))
591 if (clearFocusedElement) {
592 if (dactyl.focusedElement)
593 dactyl.focusedElement.blur();
594 if (win && Editor.getEditor(win)) {
595 this.withSavedValues(["ignoreFocus"], function _focusContent() {
596 this.ignoreFocus = true;
597 if (win.frameElement)
598 win.frameElement.blur();
600 if (content.document.activeElement instanceof Ci.nsIDOMHTMLIFrameElement)
601 content.document.activeElement.blur();
606 if (elem instanceof Window && Editor.getEditor(elem))
609 if (elem && elem != dactyl.focusedElement)
613 /** @property {Element} The currently focused element. */
614 get focusedElement() services.focus.getFocusedElementForWindow(window, true, {}),
615 set focusedElement(elem) dactyl.focus(elem),
618 * Returns whether this Dactyl extension supports *feature*.
620 * @param {string} feature The feature name.
623 has: function has(feature) Set.has(config.features, feature),
628 initDocument: function initDocument(doc) {
630 if (doc.location.protocol === "dactyl:") {
640 help: deprecated("help.help", { get: function help() modules.help.closure.help }),
641 findHelp: deprecated("help.findHelp", { get: function findHelp() help.closure.findHelp }),
645 * Initialize the help system.
647 initHelp: function initHelp() {
648 if ("noscriptOverlay" in window)
649 window.noscriptOverlay.safeAllow("dactyl:", true, false);
655 * Generates a help entry and returns it as a string.
657 * @param {Command|Map|Option} obj A dactyl *Command*, *Map* or *Option*
659 * @param {XMLList} extraHelp Extra help text beyond the description.
662 generateHelp: function generateHelp(obj, extraHelp, str, specOnly) {
664 link = tag = spec = util.identity;
667 if (obj instanceof Command) {
668 link = cmd => ["ex", {}, cmd];
669 args = obj.parseArgs("", CompletionContext(str || ""));
670 tag = cmd => DOM.DOMString(":" + cmd);
672 obj.count ? ["oa", {}, "count"] : [],
674 obj.bang ? ["oa", {}, "!"] : []
677 else if (obj instanceof Map) {
678 spec = map => (obj.count ? [["oa", {}, "count"], map]
679 : DOM.DOMString(map));
681 let (c = obj.modes[0].char) c ? c + "_" : "",
685 let [, mode, name, extra] = /^(?:(.)_)?(?:<([^>]+)>)?(.*)$/.exec(map);
686 let k = ["k", {}, extra];
694 else if (obj instanceof Option) {
695 spec = () => template.map(obj.names, tag, " ");
696 tag = name => DOM.DOMString("'" + name + "'");
697 link = (opt, name) => ["o", {}, name];
698 args = { value: "", values: [] };
702 ["dt", {}, link(obj.helpTag || tag(obj.name), obj.name)],
704 template.linkifyHelp(obj.description ? obj.description.replace(/\.$/, "") : "", true)]];
708 let description = ["description", {},
709 obj.description ? ["p", {}, template.linkifyHelp(obj.description.replace(/\.?$/, "."), true)] : "",
710 extraHelp ? extraHelp : "",
711 !(extraHelp || obj.description) ? ["p", {}, /*L*/ "Sorry, no help available."] : ""];
715 ["tags", {}, template.map(obj.names.slice().reverse(),
719 let (name = (obj.specs || obj.names)[0])
720 spec(template.highlightRegexp(tag(name),
722 (m, n0) => ["oa", {}, n0]),
725 ["type", {}, obj.type],
726 ["default", {}, obj.stringDefaultValue]],
731 ["dl", {}, template.map(ary,
732 function ([a, b]) [["dt", {}, a], " ",
736 if (obj.completer && false)
737 add(completion._runCompleter(obj.closure.completer, "", null, args).items
738 .map(i => [i.text, i.description]));
740 if (obj.options && obj.options.some(o => o.description) && false)
741 add(obj.options.filter(o => o.description)
745 o.names.length == 1 ? "" :
746 ["", " (short name: ",
747 template.map(o.names.slice(1),
753 return DOM.toPrettyXML(res, true, null, { "": String(NS) });
757 * The map of global variables.
759 * These are set and accessed with the "g:" prefix.
761 _globalVariables: {},
762 globalVariables: deprecated(_("deprecated.for.theOptionsSystem"), {
763 get: function globalVariables() this._globalVariables
766 loadPlugins: function loadPlugins(args, force) {
767 function sourceDirectory(dir) {
768 dactyl.assert(dir.isReadable(), _("io.notReadable", dir.path));
770 dactyl.log(_("dactyl.sourcingPlugins", dir.path), 3);
772 let loadplugins = options.get("loadplugins");
774 loadplugins = { __proto__: loadplugins, value: args.map(Option.parseRegexp) };
776 dir.readDirectory(true).forEach(function (file) {
777 if (file.leafName[0] == ".")
779 else if (file.isFile() && loadplugins.getKey(file.path)
780 && !(!force && file.path in dactyl.pluginFiles && dactyl.pluginFiles[file.path] >= file.lastModifiedTime)) {
782 io.source(file.path);
783 dactyl.pluginFiles[file.path] = file.lastModifiedTime;
786 dactyl.reportError(e);
789 else if (file.isDirectory())
790 sourceDirectory(file);
794 let dirs = io.getRuntimeDirectories("plugins");
796 if (dirs.length == 0) {
797 dactyl.log(_("dactyl.noPluginDir"), 3);
802 _("plugin.searchingForIn",
803 ("plugins/**/*.{js," + config.fileExtension + "}").quote(),
804 [dir.path.replace(/.plugins$/, "") for ([, dir] in Iterator(dirs))]
808 dirs.forEach(function (dir) {
809 dactyl.echomsg(_("plugin.searchingFor", (dir.path + "/**/*.{js," + config.fileExtension + "}").quote()), 3);
810 sourceDirectory(dir);
814 // TODO: add proper level constants
816 * Logs a message to the JavaScript error console. Each message has an
817 * associated log level. Only messages with a log level less than or equal
818 * to *level* will be printed. If *msg* is an object, it is pretty printed.
820 * @param {string|Object} msg The message to print.
821 * @param {number} level The logging level 0 - 15.
823 log: function log(msg, level) {
824 let verbose = config.prefs.get("loglevel", 0);
826 if (!level || level <= verbose) {
827 if (isObject(msg) && !isinstance(msg, _))
828 msg = util.objectToString(msg, false);
830 services.console.logStringMessage(config.name + ": " + msg);
835 click: function onClick(event) {
836 let elem = event.originalTarget;
838 if (elem instanceof Element && services.security.isSystemPrincipal(elem.nodePrincipal)) {
839 let command = elem.getAttributeNS(NS, "command");
840 if (command && event.button == 0) {
841 event.preventDefault();
843 if (dactyl.commands[command])
844 dactyl.withSavedValues(["forceTarget"], function () {
845 if (event.ctrlKey || event.shiftKey || event.button == 1)
846 dactyl.forceTarget = dactyl.NEW_TAB;
847 dactyl.commands[command](event);
853 "dactyl.execute": function onExecute(event) {
854 let cmd = event.originalTarget.getAttribute("dactyl-execute");
855 commands.execute(cmd, null, false, null,
856 { file: /*L*/"[Command Line]", line: 1 });
861 * Opens one or more URLs. Returns true when load was initiated, or
864 * @param {string|Array} urls A representation of the URLs to open.
865 * A string will be passed to {@link Dactyl#parseURLs}. An array may
866 * contain elements of the following forms:
868 * • {string} A URL to open.
869 * • {[string, {string|Array}]} Pair of a URL and POST data.
870 * • {object} Object compatible with those returned
871 * by {@link DOM#formData}.
873 * @param {object} params A set of parameters specifying how to open the
874 * URLs. The following properties are recognized:
876 * • background If true, new tabs are opened in the background.
878 * • from The designation of the opener, as appears in
879 * 'activate' and 'newtab' options. If present,
880 * the newtab option provides the default 'where'
881 * parameter, and the value of the 'activate'
882 * parameter is inverted if 'background' is true.
884 * • where One of CURRENT_TAB, NEW_TAB, or NEW_WINDOW
886 * As a deprecated special case, the where parameter may be provided
887 * by itself, in which case it is transformed into { where: params }.
889 * @param {boolean} force Don't prompt whether to open more than 20
893 open: function open(urls, params = {}, force = false) {
894 if (typeof urls == "string")
895 urls = dactyl.parseURLs(urls);
897 if (urls.length > prefs.get("browser.tabs.maxOpenBeforeWarn", 20) && !force)
898 return commandline.input(_("dactyl.prompt.openMany", urls.length) + " ",
900 if (resp && resp.match(/^y(es)?$/i))
901 dactyl.open(urls, params, true);
904 if (isString(params))
905 params = { where: params };
908 for (let [opt, flag] in Iterator({ replace: "REPLACE_HISTORY", hide: "BYPASS_HISTORY" }))
909 flags |= params[opt] && Ci.nsIWebNavigation["LOAD_FLAGS_" + flag];
911 let where = params.where || dactyl.CURRENT_TAB;
912 let background = dactyl.forceBackground != null ? dactyl.forceBackground :
913 ("background" in params) ? params.background
914 : params.where == dactyl.NEW_BACKGROUND_TAB;
916 if (params.from && dactyl.has("tabs")) {
917 if (!params.where && options.get("newtab").has(params.from))
918 where = dactyl.NEW_TAB;
919 background ^= !options.get("activate").has(params.from);
922 if (urls.length == 0)
925 let browser = config.tabbrowser;
926 function open(loc, where) {
929 loc = { url: loc[0], postData: loc[1] };
930 else if (isString(loc))
933 loc = Object.create(loc);
935 if (isString(loc.postData))
936 loc.postData = ["application/x-www-form-urlencoded", loc.postData];
938 if (isArray(loc.postData)) {
939 let stream = services.MIMEStream(services.StringStream(loc.postData[1]));
940 stream.addHeader("Content-Type", loc.postData[0]);
941 stream.addContentLength = true;
942 loc.postData = stream;
945 // decide where to load the first url
949 if (!dactyl.has("tabs"))
950 return open(loc, dactyl.NEW_WINDOW);
952 return prefs.withContext(function () {
953 prefs.set("browser.tabs.loadInBackground", true);
954 return browser.loadOneTab(loc.url, null, null, loc.postData, background).linkedBrowser.contentDocument;
957 case dactyl.NEW_WINDOW:
958 let options = ["chrome", "all", "dialog=no"];
959 if (dactyl.forcePrivate)
960 options.push("private");
962 let win = window.openDialog(document.documentURI, "_blank", options.join(","));
963 util.waitFor(() => win.document.readyState === "complete");
964 browser = win.dactyl && win.dactyl.modules.config.tabbrowser || win.getBrowser();
966 case dactyl.CURRENT_TAB:
967 browser.loadURIWithFlags(loc.url, flags, null, null, loc.postData);
968 return browser.contentWindow;
972 // Unfortunately, failed page loads throw exceptions and
973 // cause a lot of unwanted noise. This solution means that
974 // any genuine errors go unreported.
977 if (dactyl.forceTarget)
978 where = dactyl.forceTarget;
980 where = dactyl.CURRENT_TAB;
982 return urls.map(function (url) {
983 let res = open(url, where);
984 where = dactyl.NEW_TAB;
991 * Returns an array of URLs parsed from *str*.
993 * Given a string like 'google bla, www.osnews.com' return an array
994 * ['www.google.com/search?q=bla', 'www.osnews.com']
996 * @param {string} str
997 * @returns {[string]}
999 parseURLs: function parseURLs(str) {
1002 if (options["urlseparator"])
1003 urls = util.splitLiteral(str, util.regexp("\\s*" + options["urlseparator"] + "\\s*"));
1007 return urls.map(function (url) {
1010 if (/^(\.{0,2}|~)(\/|$)/.test(url) || config.OS.isWindows && /^[a-z]:/i.test(url)) {
1012 // Try to find a matching file.
1013 let file = io.File(url);
1014 if (file.exists() && file.isReadable())
1015 return file.URI.spec;
1020 // If it starts with a valid protocol, pass it through.
1021 let proto = /^([-\w]+):/.exec(url);
1022 if (proto && services.PROTOCOL + proto[1] in Cc)
1025 // Check for a matching search keyword.
1026 let searchURL = this.has("bookmarks") && bookmarks.getSearchURL(url, false);
1030 // If it looks like URL-ish (foo.com/bar), let Gecko figure it out.
1031 if (this.urlish.test(url) || !this.has("bookmarks"))
1032 return util.createURI(url).spec;
1034 // Pass it off to the default search engine or, failing
1035 // that, let Gecko deal with it as is.
1036 return bookmarks.getSearchURL(url, true) || util.createURI(url).spec;
1039 stringToURLArray: deprecated("dactyl.parseURLs", "parseURLs"),
1040 urlish: Class.Memoize(() => util.regexp(literal(/*
1042 <domain>+ (:\d+)? (/ .*) |
1044 <domain>+ \. [a-z0-9]+ |
1048 domain: util.regexp(String.replace(literal(/*
1050 U0000-U002c // U002d-U002e --.
1053 U003a-U0040 // U0041-U005a a-z
1054 U005b-U0060 // U0061-U007a A-Z
1057 */), /U/g, "\\u"), "x")
1062 get plugins() plugins,
1064 setNodeVisible: function setNodeVisible(node, visible) {
1065 if (window.setToolbarVisibility && node.localName == "toolbar")
1066 window.setToolbarVisibility(node, visible);
1068 node.collapsed = !visible;
1071 confirmQuit: function confirmQuit()
1072 prefs.withContext(function () {
1073 prefs.set("browser.warnOnQuit", false);
1074 return window.canQuitApplication();
1078 * Quit the host application, no matter how many tabs/windows are open.
1080 * @param {boolean} saveSession If true the current session will be
1081 * saved and restored when the host application is restarted.
1082 * @param {boolean} force Forcibly quit irrespective of whether all
1083 * windows could be closed individually.
1085 quit: function quit(saveSession, force) {
1086 if (!force && !this.confirmQuit())
1089 let pref = "browser.startup.page";
1092 prefs.safeSet(pref, 3);
1093 if (!saveSession && prefs.get(pref) >= 2)
1094 prefs.safeSet(pref, 1);
1096 services.appStartup.quit(Ci.nsIAppStartup[force ? "eForceQuit" : "eAttemptQuit"]);
1100 * Restart the host application.
1102 restart: function restart(args) {
1103 if (!this.confirmQuit())
1106 config.prefs.set("commandline-args", args);
1108 services.appStartup.quit(Ci.nsIAppStartup.eAttemptQuit | Ci.nsIAppStartup.eRestart);
1111 get assert() util.assert,
1114 * Traps errors in the called function, possibly reporting them.
1116 * @param {function} func The function to call
1117 * @param {object} self The 'this' object for the function.
1119 trapErrors: function trapErrors(func, self, ...args) {
1123 return func.apply(self || this, args);
1127 dactyl.reportError(e, true);
1130 util.reportError(e);
1137 * Reports an error to both the console and the host application's
1140 * @param {Object} error The error object.
1142 reportError: function reportError(error, echo) {
1143 if (error instanceof FailedAssertion && error.noTrace || error.message === "Interrupted") {
1144 let context = contexts.context;
1145 let prefix = context ? context.file + ":" + context.line + ": " : "";
1146 if (error.message && error.message.indexOf(prefix) !== 0 &&
1147 prefix != "[Command Line]:1: ")
1148 error.message = prefix + error.message;
1151 dactyl.echoerr(template.linkifyHelp(error.message));
1156 util.reportError(error);
1160 if (error.result == Cr.NS_BINDING_ABORTED)
1164 dactyl.echoerr(error, commandline.FORCE_SINGLELINE);
1166 util.reportError(error);
1170 * Parses a Dactyl command-line string i.e. the value of the
1171 * -dactyl command-line option.
1173 * @param {string} cmdline The string to parse for command-line
1176 * @see Commands#parseArgs
1178 parseCommandLine: function parseCommandLine(cmdline) {
1180 return commands.get("rehash").parseArgs(cmdline);
1183 dactyl.reportError(e, true);
1187 wrapCallback: function wrapCallback(callback, self = this) {
1188 let save = ["forceOpen"];
1189 let saved = save.map(p => dactyl[p]);
1190 return function wrappedCallback() {
1191 let args = arguments;
1192 return dactyl.withSavedValues(save, function () {
1193 saved.forEach((p, i) => { dactyl[save[i]] = p; });
1195 return callback.apply(self, args);
1198 dactyl.reportError(e, true);
1205 * @property {[Window]} Returns an array of all the host application's
1208 get windows() [win for (win in iter(services.windowMediator.getEnumerator("navigator:browser"))) if (win.dactyl)],
1211 toolbarHidden: function hidden(elem) (elem.getAttribute("autohide") || elem.getAttribute("collapsed")) == "true"
1213 cache: function initCache() {
1214 cache.register("help/plugins.xml", function () {
1215 // Process plugin help entries.
1218 for (let [, context] in Iterator(plugins.contexts))
1220 let info = contexts.getDocs(context);
1221 if (DOM.isJSONXML(info)) {
1222 let langs = info.slice(2).filter(e => isArray(e) && isObject(e[1]) && e[1].lang);
1224 let lang = config.bestLocale(l[1].lang for each (l in langs));
1226 info = info.slice(0, 2).concat(
1227 info.slice(2).filter(e => !isArray(e)
1229 || e[1].lang == lang));
1231 for each (let elem in info.slice(2).filter(e => isArray(e) && e[0] == "info" && isObject(e[1])))
1232 for (let attr in values(["name", "summary", "href"]))
1233 if (attr in elem[1])
1234 info[attr] = elem[1][attr];
1236 body.push(["h2", { xmlns: "dactyl", tag: info[1].name + '-plugin' },
1237 String(info[1].summary)]);
1242 util.reportError(e);
1245 return '<?xml version="1.0"?>\n' +
1246 '<?xml-stylesheet type="text/xsl" href="dactyl://content/help.xsl"?>\n' +
1248 ["document", { xmlns: "dactyl", name: "plugins",
1249 title: config.appName + ", Plugins" },
1250 ["h1", { tag: "using-plugins" }, _("help.title.Using Plugins")],
1251 ["toc", { start: "2" }],
1256 cache.register("help/index.xml", function () {
1257 return '<?xml version="1.0"?>\n' +
1258 DOM.toXML(["overlay", { xmlns: "dactyl" },
1259 template.map(dactyl.indices, ([name, iter]) =>
1260 ["dl", { insertafter: name + "-index" },
1261 template.map(iter(), util.identity)],
1265 cache.register("help/gui.xml", function () {
1266 return '<?xml version="1.0"?>\n' +
1267 DOM.toXML(["overlay", { xmlns: "dactyl" },
1268 ["dl", { insertafter: "dialog-list" },
1269 template.map(config.dialogs, ([name, val]) =>
1270 (!val[2] || val[2]())
1271 ? [["dt", {}, name],
1277 cache.register("help/privacy.xml", function () {
1278 return '<?xml version="1.0"?>\n' +
1279 DOM.toXML(["overlay", { xmlns: "dactyl" },
1280 ["dl", { insertafter: "sanitize-items" },
1281 template.map(options.get("sanitizeitems").values
1282 .sort((a, b) => String.localeCompare(a.name,
1284 ({ name, description }) =>
1286 ["dd", {}, template.linkifyHelp(description, true)]],
1290 events: function initEvents() {
1291 events.listen(window, dactyl, "events", true);
1293 // Only general options are added here, which are valid for all Dactyl extensions
1294 options: function initOptions() {
1295 options.add(["errorbells", "eb"],
1296 "Ring the bell when an error message is displayed",
1299 options.add(["exrc", "ex"],
1300 "Enable automatic sourcing of an RC file in the current directory at startup",
1303 options.add(["fullscreen", "fs"],
1304 "Show the current window fullscreen",
1306 setter: function (value) window.fullScreen = value,
1307 getter: function () window.fullScreen
1313 c: ["Always show the command line, even when empty"],
1314 C: ["Always show the command line outside of the status line"],
1315 M: ["Always show messages outside of the status line"]
1317 setter: function (opts) {
1318 if (loaded.commandline || ~opts.indexOf("c"))
1319 commandline.widgets.updateVisibility();
1324 s: ["Status bar", [statusline.statusBar.id]]
1325 }, config.guioptions),
1326 setter: function (opts) {
1327 for (let [opt, [, ids]] in Iterator(this.opts)) {
1328 ids.map(id => document.getElementById(id))
1329 .forEach(function (elem) {
1331 dactyl.setNodeVisible(elem, opts.indexOf(opt) >= 0);
1338 r: ["Right Scrollbar", "vertical"],
1339 l: ["Left Scrollbar", "vertical"],
1340 b: ["Bottom Scrollbar", "horizontal"]
1342 setter: function (opts) {
1343 let dir = ["horizontal", "vertical"].filter(
1344 dir => !Array.some(opts,
1345 o => this.opts[o] && this.opts[o][1] == dir));
1346 let class_ = dir.map(dir => "html|html > xul|scrollbar[orient=" + dir + "]");
1348 styles.system.add("scrollbar", "*",
1349 class_.length ? class_.join(", ") + " { visibility: collapse !important; }" : "",
1352 prefs.safeSet("layout.scrollbar.side", opts.indexOf("l") >= 0 ? 3 : 2,
1353 _("option.guioptions.safeSet"));
1355 validator: function (opts) Option.validIf(!(opts.indexOf("l") >= 0 && opts.indexOf("r") >= 0),
1356 UTF8("Only one of ‘l’ or ‘r’ allowed"))
1361 n: ["Tab number", highlight.selector("TabNumber")],
1362 N: ["Tab number over icon", highlight.selector("TabIconNumber")]
1364 setter: function (opts) {
1365 let classes = [v[1] for ([k, v] in Iterator(this.opts)) if (opts.indexOf(k) < 0)];
1367 styles.system.add("taboptions", "chrome://*",
1368 classes.length ? classes.join(",") + "{ display: none; }" : "");
1370 if (!dactyl.has("Gecko2")) {
1371 tabs.tabBinding.enabled = Array.some(opts, k => k in this.opts);
1372 tabs.updateTabCount();
1374 if (config.tabbrowser.tabContainer._positionPinnedTabs)
1375 config.tabbrowser.tabContainer._positionPinnedTabs();
1378 validator: function (opts) dactyl.has("Gecko2") ||
1379 Option.validIf(!/[nN]/.test(opts), "Tab numbering not available in this " + config.host + " version")
1382 ].filter(group => !group.feature || dactyl.has(group.feature));
1384 options.add(["guioptions", "go"],
1385 "Show or hide certain GUI elements like the menu or toolbar",
1389 cleanupValue: config.cleanups.guioptions ||
1390 "rb" + [k for ([k, v] in iter(groups[1].opts))
1391 if (!Dactyl.toolbarHidden(document.getElementById(v[1][0])))].join(""),
1393 values: array(groups).map(g => [[k, v[0]] for ([k, v] in Iterator(g.opts))])
1396 setter: function (value) {
1397 for (let group in values(groups))
1398 group.setter(value);
1399 events.checkFocus();
1402 validator: function (val) Option.validateCompleter.call(this, val)
1403 && groups.every(g => !g.validator || g.validator(val))
1406 options.add(["loadplugins", "lpl"],
1407 "A regexp list that defines which plugins are loaded at startup and via :loadplugins",
1408 "regexplist", "'\\.(js|" + config.fileExtension + ")$'");
1410 options.add(["titlestring"],
1411 "The string shown at the end of the window title",
1412 "string", config.host,
1414 setter: function (value) {
1415 let win = document.documentElement;
1416 function updateTitle(old, current) {
1417 if (config.browser.updateTitlebar)
1418 config.browser.updateTitlebar();
1420 document.title = document.title.replace(RegExp("(.*)" + util.regexp.escape(old)), "$1" + current);
1423 if (win.hasAttribute("titlemodifier_privatebrowsing")) {
1424 let oldValue = win.getAttribute("titlemodifier_normal");
1425 let suffix = win.getAttribute("titlemodifier_privatebrowsing").substr(oldValue.length);
1427 win.setAttribute("titlemodifier_normal", value);
1428 win.setAttribute("titlemodifier_privatebrowsing", value + suffix);
1430 if (storage.privateMode) {
1431 updateTitle(oldValue + suffix, value + suffix);
1432 win.setAttribute("titlemodifier", value + suffix);
1437 updateTitle(win.getAttribute("titlemodifier"), value);
1438 win.setAttribute("titlemodifier", value);
1444 options.add(["urlseparator", "urlsep", "us"],
1445 "The regular expression used to separate multiple URLs in :open and friends",
1447 { validator: function (value) RegExp(value) });
1449 options.add(["verbose", "vbs"],
1450 "Define which info messages are displayed",
1452 { validator: function (value) Option.validIf(value >= 0 && value <= 15,
1453 "Value must be between 0 and 15") });
1455 options.add(["visualbell", "vb"],
1456 "Use visual bell instead of beeping on errors",
1459 setter: function (value) {
1460 prefs.safeSet("accessibility.typeaheadfind.enablesound", !value,
1461 _("option.safeSet", "visualbell"));
1467 mappings: function initMappings() {
1468 if (dactyl.has("session"))
1469 mappings.add([modes.NORMAL], ["ZQ"],
1470 "Quit and don't save the session",
1471 function () { dactyl.quit(false); });
1473 mappings.add([modes.NORMAL], ["ZZ"],
1474 "Quit and save the session",
1475 function () { dactyl.quit(true); });
1478 commands: function initCommands() {
1479 commands.add(["dia[log]"],
1480 "Open a " + config.appName + " dialog",
1482 let dialog = args[0];
1484 dactyl.assert(dialog in config.dialogs,
1485 _("error.invalidArgument", dialog));
1486 dactyl.assert(!config.dialogs[dialog][2] || config.dialogs[dialog][2](),
1487 _("dialog.notAvailable", dialog));
1489 config.dialogs[dialog][1]();
1492 dactyl.echoerr(_("error.cantOpen", dialog.quote(), e.message || e));
1496 completer: function (context) {
1497 context.ignoreCase = true;
1498 completion.dialog(context);
1502 commands.add(["em[enu]"],
1503 "Execute the specified menu item from the command line",
1505 let arg = args[0] || "";
1506 let items = dactyl.getMenuItems(arg);
1508 dactyl.assert(items.some(i => i.dactylPath == arg),
1509 _("emenu.notFound", arg));
1511 for (let [, item] in Iterator(items)) {
1512 if (item.dactylPath == arg) {
1513 dactyl.assert(!item.disabled, _("error.disabled", item.dactylPath));
1519 completer: function (context) completion.menuItem(context),
1523 commands.add(["exe[cute]"],
1524 "Execute the argument as an Ex command",
1527 let cmd = dactyl.userEval(args[0] || "");
1528 dactyl.execute(cmd || "", null, true);
1534 completer: function (context) completion.javascript(context),
1538 commands.add(["loadplugins", "lpl"],
1539 "Load all or matching plugins",
1541 dactyl.loadPlugins(args.length ? args : null, args.bang);
1548 serialize: function () [
1551 literalArg: options["loadplugins"].join(" ")
1556 commands.add(["norm[al]"],
1557 "Execute Normal mode commands",
1558 function (args) { events.feedkeys(args[0], args.bang, false, modes.NORMAL); },
1565 commands.add(["pr[ivate]", "pr0n", "porn"],
1566 "Enable privacy features of a command, when applicable, and do not save the invocation in command history",
1568 dactyl.withSavedValues(["forcePrivate"], function () {
1569 this.forcePrivate = true;
1570 dactyl.execute(args[0], null, true);
1574 completer: function (context) completion.ex(context),
1576 privateData: "never-save",
1580 commands.add(["exit", "x"],
1581 "Quit " + config.appName,
1583 dactyl.quit(false, args.bang);
1589 commands.add(["q[uit]"],
1590 dactyl.has("tabs") ? "Quit current tab" : "Quit application",
1592 if (dactyl.has("tabs") && tabs.remove(tabs.getTab(), 1, false))
1594 else if (dactyl.windows.length > 1)
1597 dactyl.quit(false, args.bang);
1603 let startupOptions = [
1606 description: "The initialization file to execute at startup",
1607 type: CommandOption.STRING
1610 names: ["++noplugin"],
1611 description: "Do not automatically load plugins"
1615 description: "Ex commands to execute prior to initialization",
1616 type: CommandOption.STRING,
1621 description: "Ex commands to execute after initialization",
1622 type: CommandOption.STRING,
1626 names: ["+purgecaches"],
1627 description: "Purge " + config.appName + " caches at startup",
1628 type: CommandOption.NOARG
1632 commands.add(["reh[ash]"],
1633 "Reload the " + config.appName + " add-on",
1636 storage.storeForSession("rehashCmd", args.trailing); // Hack.
1639 if (args["+purgecaches"])
1642 util.delay(function () { util.rehash(args) });
1645 argCount: "0", // FIXME
1646 options: startupOptions
1649 commands.add(["res[tart]"],
1650 "Force " + config.host + " to restart",
1652 if (args["+purgecaches"])
1655 dactyl.restart(args.string);
1659 options: startupOptions
1662 function findToolbar(name) DOM.XPath(
1663 "//*[@toolbarname=" + util.escapeString(name, "'") + " or " +
1664 "@toolbarname=" + util.escapeString(name.trim(), "'") + "]",
1665 document).snapshotItem(0);
1667 var toolbox = document.getElementById("navigator-toolbox");
1669 let toolbarCommand = function (names, desc, action, filter) {
1670 commands.add(names, desc,
1672 let toolbar = findToolbar(args[0] || "");
1673 dactyl.assert(toolbar, _("error.invalidArgument"));
1675 events.checkFocus();
1678 completer: function (context) {
1679 completion.toolbar(context);
1681 context.filters.push(filter);
1687 toolbarCommand(["toolbars[how]", "tbs[how]"], "Show the named toolbar",
1688 toolbar => dactyl.setNodeVisible(toolbar, true),
1689 ({ item }) => Dactyl.toolbarHidden(item));
1690 toolbarCommand(["toolbarh[ide]", "tbh[ide]"], "Hide the named toolbar",
1691 toolbar => dactyl.setNodeVisible(toolbar, false),
1692 ({ item }) => !Dactyl.toolbarHidden(item));
1693 toolbarCommand(["toolbart[oggle]", "tbt[oggle]"], "Toggle the named toolbar",
1694 toolbar => dactyl.setNodeVisible(toolbar, Dactyl.toolbarHidden(toolbar)));
1697 commands.add(["time"],
1698 "Profile a piece of code or run a command multiple times",
1700 let count = args.count;
1701 let special = args.bang;
1702 args = args[0] || "";
1705 var func = () => commands.execute(args, null, false);
1707 func = dactyl.userFunc(args);
1711 let each, eachUnits, totalUnits;
1714 for (let i in util.interruptibleRange(0, count, 500)) {
1715 let now = Date.now();
1717 total += Date.now() - now;
1723 if (total / count >= 100) {
1724 each = total / 1000.0 / count;
1728 each = total / count;
1733 total = total / 1000.0;
1737 totalUnits = "msec";
1739 commandline.commandOutput(
1741 ["tr", { highlight: "Title", align: "left" },
1742 ["th", { colspan: "3" }, _("title.Code execution summary")]],
1744 ["td", {}, _("title.Executed"), ":"],
1745 ["td", { align: "right" },
1746 ["span", { class: "times-executed" }, count]],
1747 ["td", {}, /*L*/"times"]],
1749 ["td", {}, _("title.Average time"), ":"],
1750 ["td", { align: "right" },
1751 ["span", { class: "time-average" }, each.toFixed(2)]],
1752 ["td", {}, eachUnits]],
1754 ["td", {}, _("title.Total time"), ":"],
1755 ["td", { align: "right" },
1756 ["span", { class: "time-total" }, total.toFixed(2)]],
1757 ["td", {}, totalUnits]]]);
1760 let beforeTime = Date.now();
1766 let afterTime = Date.now();
1768 if (afterTime - beforeTime >= 100)
1769 dactyl.echo(_("time.total", ((afterTime - beforeTime) / 1000.0).toFixed(2) + " sec"));
1771 dactyl.echo(_("time.total", (afterTime - beforeTime) + " msec"));
1780 completer: function (context) {
1781 if (/^:/.test(context.filter))
1782 return completion.ex(context);
1784 return completion.javascript(context);
1792 commands.add(["verb[ose]"],
1793 "Execute a command with 'verbose' set",
1795 let vbs = options.get("verbose");
1796 let value = vbs.value;
1797 let setFrom = vbs.setFrom;
1800 vbs.set(args.count || 1);
1802 dactyl.execute(args[0] || "", null, true);
1806 vbs.setFrom = setFrom;
1810 completer: function (context) completion.ex(context),
1816 commands.add(["ve[rsion]"],
1817 "Show version information",
1820 dactyl.open("about:");
1822 let date = config.buildDate;
1823 date = date ? " (" + date + ")" : "";
1825 commandline.commandOutput([
1826 ["div", {}, [config.appName, " ", config.version, date, " running on: "].join("")],
1827 ["div", {}, [window.navigator.userAgent].join("")]
1837 completion: function initCompletion() {
1838 completion.dialog = function dialog(context) {
1839 context.title = ["Dialog"];
1840 context.filters.push(({ item }) => !item[2] || item[2]());
1841 context.completions = [[k, v[0], v[2]] for ([k, v] in Iterator(config.dialogs))];
1844 completion.menuItem = function menuItem(context) {
1845 context.title = ["Menu Path", "Label"];
1846 context.anchored = false;
1849 description: function (item) item.getAttribute("label"),
1850 highlight: function (item) item.disabled ? "Disabled" : ""
1852 context.generate = () => dactyl.menuItems;
1855 var toolbox = document.getElementById("navigator-toolbox");
1856 completion.toolbar = function toolbar(context) {
1857 context.title = ["Toolbar"];
1858 context.keys = { text: function (item) item.getAttribute("toolbarname"), description: function () "" };
1859 context.completions = DOM.XPath("//*[@toolbarname]", document);
1862 completion.window = function window(context) {
1863 context.title = ["Window", "Title"];
1864 context.keys = { text: win => dactyl.windows.indexOf(win) + 1,
1865 description: win => win.document.title };
1866 context.completions = dactyl.windows;
1869 load: function initLoad() {
1870 dactyl.triggerObserver("load");
1872 dactyl.log(_("dactyl.modulesLoaded"), 3);
1874 userContext.DOM = Class("DOM", DOM, { init: function DOM_(sel, ctxt) DOM(sel, ctxt || buffer.focusedFrame.document) });
1875 userContext.$ = modules.userContext.DOM;
1877 // Hack: disable disabling of Personas in private windows.
1878 let root = document.documentElement;
1880 if (PrivateBrowsingUtils && PrivateBrowsingUtils.isWindowPrivate(window)
1881 && root._lightweightTheme
1882 && root._lightweightTheme._lastScreenWidth == null) {
1884 dactyl.withSavedValues.call(PrivateBrowsingUtils,
1885 ["isWindowPrivate"], function () {
1886 PrivateBrowsingUtils.isWindowPrivate = () => false;
1887 Cu.import("resource://gre/modules/LightweightThemeConsumer.jsm", {})
1888 .LightweightThemeConsumer.call(root._lightweightTheme, document);
1892 dactyl.timeout(function () {
1894 var args = config.prefs.get("commandline-args")
1895 || storage.session.commandlineArgs
1896 || services.commandLineHandler.optionValue;
1898 config.prefs.reset("commandline-args");
1901 args = dactyl.parseCommandLine(args);
1904 dactyl.commandLineOptions.rcFile = args["+u"];
1905 dactyl.commandLineOptions.noPlugins = "++noplugin" in args;
1906 dactyl.commandLineOptions.postCommands = args["+c"];
1907 dactyl.commandLineOptions.preCommands = args["++cmd"];
1908 util.dump("Processing command-line option: " + args.string);
1912 dactyl.echoerr(_("dactyl.parsingCommandLine", e));
1915 dactyl.log(_("dactyl.commandlineOpts", util.objectToString(dactyl.commandLineOptions)), 3);
1917 if (config.prefs.get("first-run", true))
1918 dactyl.timeout(function () {
1919 config.prefs.set("first-run", false);
1920 this.withSavedValues(["forceTarget"], function () {
1921 this.forceTarget = dactyl.NEW_TAB;
1926 // TODO: we should have some class where all this guioptions stuff fits well
1927 // dactyl.hideGUI();
1929 if (dactyl.userEval("typeof document", null, "test.js") === "undefined")
1930 jsmodules.__proto__ = XPCSafeJSObjectWrapper(window);
1932 if (dactyl.commandLineOptions.preCommands)
1933 dactyl.commandLineOptions.preCommands.forEach(function (cmd) {
1934 dactyl.execute(cmd);
1937 // finally, read the RC file and source plugins
1938 let init = services.environment.get(config.idName + "_INIT");
1939 let rcFile = io.getRCFile("~");
1942 if (dactyl.commandLineOptions.rcFile) {
1943 let filename = dactyl.commandLineOptions.rcFile;
1944 if (!/^(NONE|NORC)$/.test(filename))
1945 io.source(io.File(filename).path, { group: contexts.user });
1949 dactyl.execute(init);
1952 io.source(rcFile.path, { group: contexts.user });
1953 services.environment.set("MY_" + config.idName + "RC", rcFile.path);
1956 dactyl.log(_("dactyl.noRCFile"), 3);
1959 if (options["exrc"] && !dactyl.commandLineOptions.rcFile) {
1960 let localRCFile = io.getRCFile(io.cwd);
1961 if (localRCFile && !localRCFile.equals(rcFile))
1962 io.source(localRCFile.path, { group: contexts.user });
1966 if (dactyl.commandLineOptions.rcFile == "NONE" || dactyl.commandLineOptions.noPlugins)
1967 options["loadplugins"] = [];
1969 if (options["loadplugins"].length)
1970 dactyl.loadPlugins();
1973 dactyl.reportError(e, true);
1976 // after sourcing the initialization files, this function will set
1977 // all gui options to their default values, if they have not been
1978 // set before by any RC file
1979 for (let option in values(options.needInit))
1982 if (dactyl.commandLineOptions.postCommands)
1983 dactyl.commandLineOptions.postCommands.forEach(function (cmd) {
1984 dactyl.execute(cmd);
1987 if (storage.session.rehashCmd)
1988 dactyl.execute(storage.session.rehashCmd);
1989 storage.session.rehashCmd = null;
1991 dactyl.fullyInitialized = true;
1992 dactyl.triggerObserver("enter", null);
1993 autocommands.trigger("Enter", {});
1996 statusline.update();
1997 dactyl.log(_("dactyl.initialized", config.appName), 0);
1998 dactyl.initialized = true;
2002 // vim: set fdm=marker sw=4 sts=4 ts=8 et: