1
0
mirror of https://github.com/gryf/pentadactyl-pm.git synced 2025-12-22 22:08:00 +01:00

Replace expression closures (function declarations).

Expression closures are to be axed. See https://bugzil.la/1083458.
This commit is contained in:
Doug Kearns
2015-05-25 23:59:30 +10:00
parent 5ab1befbf7
commit c0b7c4c35d
31 changed files with 292 additions and 162 deletions

8
common/bootstrap.js vendored
View File

@@ -11,7 +11,9 @@ const global = this;
var { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components; var { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
function module(uri) Cu.import(uri, {}); function module(uri) {
return Cu.import(uri, {});
}
const DEBUG = true; const DEBUG = true;
@@ -316,7 +318,9 @@ function init() {
* Performs necessary migrations after a version change. * Performs necessary migrations after a version change.
*/ */
function updateVersion() { function updateVersion() {
function isDev(ver) /^hg|pre$/.test(ver); function isDev(ver) {
return /^hg|pre$/.test(ver);
}
try { try {
if (typeof require === "undefined" || addon === addonData) if (typeof require === "undefined" || addon === addonData)
return; return;

View File

@@ -287,7 +287,9 @@ var Bookmarks = Module("bookmarks", {
if (!queryURI) if (!queryURI)
return Promise.reject(); return Promise.reject();
function parse(req) JSON.parse(req.responseText)[1].filter(isString); function parse(req) {
return JSON.parse(req.responseText)[1].filter(isString);
}
return this.makeSuggestions(queryURI, parse, callback); return this.makeSuggestions(queryURI, parse, callback);
}, },

View File

@@ -243,9 +243,11 @@ var Browser = Module("browser", XPCOM(Ci.nsISupportsWeakReference, ModuleBase),
CommandExMode().open(mode + "open " + (args || "")); CommandExMode().open(mode + "open " + (args || ""));
} }
function decode(uri) util.losslessDecodeURI(uri) function decode(uri) {
.replace(/%20(?!(?:%20)*$)/g, " ") return util.losslessDecodeURI(uri)
.replace(RegExp(options["urlseparator"], "g"), encodeURIComponent); .replace(/%20(?!(?:%20)*$)/g, " ")
.replace(RegExp(options["urlseparator"], "g"), encodeURIComponent);
}
mappings.add([modes.NORMAL], mappings.add([modes.NORMAL],
["o"], "Open one or more URLs", ["o"], "Open one or more URLs",

View File

@@ -165,7 +165,9 @@ var CommandWidgets = Class("CommandWidgets", {
const self = this; const self = this;
this.elements[obj.name] = obj; this.elements[obj.name] = obj;
function get(prefix, map, id) (obj.getElement || util.identity)(map[id] || document.getElementById(prefix + id)); function get(prefix, map, id) {
return (obj.getElement || util.identity)(map[id] || document.getElementById(prefix + id));
}
this.active.__defineGetter__(obj.name, () => this.activeGroup[obj.name][obj.name]); this.active.__defineGetter__(obj.name, () => this.activeGroup[obj.name][obj.name]);
this.activeGroup.__defineGetter__(obj.name, () => this.getGroup(obj.name)); this.activeGroup.__defineGetter__(obj.name, () => this.getGroup(obj.name));

View File

@@ -231,7 +231,9 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
}, },
addUsageCommand: function (params) { addUsageCommand: function (params) {
function keys(item) (item.names || [item.name]).concat(item.description, item.columns || []); function keys(item) {
return (item.names || [item.name]).concat(item.description, item.columns || []);
}
let name = commands.add(params.name, params.description, let name = commands.add(params.name, params.description,
function (args) { function (args) {
@@ -1667,10 +1669,12 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
options: startupOptions options: startupOptions
}); });
function findToolbar(name) DOM.XPath( function findToolbar(name) {
"//*[@toolbarname=" + util.escapeString(name, "'") + " or " + return DOM.XPath(
"@toolbarname=" + util.escapeString(name.trim(), "'") + "]", "//*[@toolbarname=" + util.escapeString(name, "'") + " or " +
document).snapshotItem(0); "@toolbarname=" + util.escapeString(name.trim(), "'") + "]",
document).snapshotItem(0);
}
var toolbox = document.getElementById("navigator-toolbox"); var toolbox = document.getElementById("navigator-toolbox");
if (toolbox) { if (toolbox) {

View File

@@ -299,7 +299,9 @@ var Editor = Module("editor", XPCOM(Ci.nsIEditActionListener, ModuleBase), {
// Find the *count*th occurance of *char* before a non-collapsed // Find the *count*th occurance of *char* before a non-collapsed
// \n, ignoring the character at the caret. // \n, ignoring the character at the caret.
let i = 0; let i = 0;
function test(c) (collapse || c != "\n") && !!(!i++ || c != char || --count) function test(c) {
return (collapse || c != "\n") && !!(!i++ || c != char || --count);
}
Editor.extendRange(range, !backward, { test: test }, true); Editor.extendRange(range, !backward, { test: test }, true);
dactyl.assert(count == 0); dactyl.assert(count == 0);

View File

@@ -861,7 +861,10 @@ var Events = Module("events", {
// access to the real focus target // access to the real focus target
// Huh? --djk // Huh? --djk
onFocusChange: util.wrapCallback(function onFocusChange(event) { onFocusChange: util.wrapCallback(function onFocusChange(event) {
function hasHTMLDocument(win) win && win.document && win.document instanceof Ci.nsIDOMHTMLDocument function hasHTMLDocument(win) {
return win && win.document && win.document instanceof Ci.nsIDOMHTMLDocument;
}
if (dactyl.ignoreFocus) if (dactyl.ignoreFocus)
return; return;
@@ -1129,10 +1132,12 @@ var Events = Module("events", {
init: function init(values, map) { init: function init(values, map) {
this.name = "passkeys:" + map; this.name = "passkeys:" + map;
this.stack = MapHive.Stack(values.map(v => Map(v[map + "Keys"]))); this.stack = MapHive.Stack(values.map(v => Map(v[map + "Keys"])));
function Map(keys) ({ function Map(keys) {
execute: function () Events.PASS_THROUGH, return {
keys: keys execute: function () Events.PASS_THROUGH,
}); keys: keys
};
}
}, },
get active() this.stack.length, get active() this.stack.length,

View File

@@ -798,9 +798,11 @@ var Hints = Module("hints", {
this.addMode("i", "Show image", elem => dactyl.open(elem.src)); this.addMode("i", "Show image", elem => dactyl.open(elem.src));
this.addMode("I", "Show image in a new tab", elem => dactyl.open(elem.src, dactyl.NEW_TAB)); this.addMode("I", "Show image in a new tab", elem => dactyl.open(elem.src, dactyl.NEW_TAB));
function isScrollable(elem) isinstance(elem, [Ci.nsIDOMHTMLFrameElement, function isScrollable(elem) {
Ci.nsIDOMHTMLIFrameElement]) || return isinstance(elem, [Ci.nsIDOMHTMLFrameElement, Ci.nsIDOMHTMLIFrameElement]) ||
Buffer.isScrollable(elem, 0, true) || Buffer.isScrollable(elem, 0, false); Buffer.isScrollable(elem, 0, true) ||
Buffer.isScrollable(elem, 0, false);
}
}, },
hintSession: Modes.boundProperty(), hintSession: Modes.boundProperty(),
@@ -820,7 +822,9 @@ var Hints = Module("hints", {
* @optional * @optional
*/ */
addMode: function (mode, prompt, action, filter, tags) { addMode: function (mode, prompt, action, filter, tags) {
function toString(regexp) RegExp.prototype.toString.call(regexp); function toString(regexp) {
return RegExp.prototype.toString.call(regexp);
}
if (tags != null) { if (tags != null) {
let eht = options.get("extendedhinttags"); let eht = options.get("extendedhinttags");
@@ -912,7 +916,9 @@ var Hints = Module("hints", {
* @param {string} str The string to split. * @param {string} str The string to split.
* @returns {Array(string)} The lowercased splits of the splitting. * @returns {Array(string)} The lowercased splits of the splitting.
*/ */
function tokenize(pat, str) str.split(pat).map(String.toLowerCase); function tokenize(pat, str) {
return str.split(pat).map(String.toLowerCase);
}
/** /**
* Get a hint matcher for hintmatching=contains * Get a hint matcher for hintmatching=contains

View File

@@ -354,7 +354,9 @@ var History = Module("history", {
completion.addUrlCompleter("history", "History", completion.history); completion.addUrlCompleter("history", "History", completion.history);
}, },
mappings: function initMappings() { mappings: function initMappings() {
function bind(...args) apply(mappings, "add", [config.browserModes].concat(args)); function bind(...args) {
return apply(mappings, "add", [config.browserModes].concat(args));
}
bind(["<C-o>"], "Go to an older position in the jump list", bind(["<C-o>"], "Go to an older position in the jump list",
function ({ count }) { history.stepTo(-Math.max(count, 1), true); }, function ({ count }) { history.stepTo(-Math.max(count, 1), true); },

View File

@@ -373,7 +373,9 @@ var Marks = Module("marks", {
completion: function initCompletion() { completion: function initCompletion() {
completion.mark = function mark(context) { completion.mark = function mark(context) {
function percent(i) Math.round(i * 100); function percent(i) {
return Math.round(i * 100);
}
context.title = ["Mark", "HPos VPos File"]; context.title = ["Mark", "HPos VPos File"];
context.keys.description = ([, m]) => (m.offset ? Math.round(m.offset.x) + " " + Math.round(m.offset.y) context.keys.description = ([, m]) => (m.offset ? Math.round(m.offset.x) + " " + Math.round(m.offset.y)
@@ -388,10 +390,14 @@ var Marks = Module("marks", {
persistent: true, persistent: true,
contains: ["history"], contains: ["history"],
action: function (timespan, host) { action: function (timespan, host) {
function matchhost(url) !host || util.isDomainURL(url, host); function matchhost(url) {
function match(marks) (k return !host || util.isDomainURL(url, host);
for ([k, v] of iter(marks)) }
if (timespan.contains(v.timestamp) && matchhost(v.location))); function match(marks) {
return (k
for ([k, v] of iter(marks))
if (timespan.contains(v.timestamp) && matchhost(v.location)));
}
for (let [url, local] of marks._localMarks) for (let [url, local] of marks._localMarks)
if (matchhost(url)) { if (matchhost(url)) {

View File

@@ -409,7 +409,9 @@ var Addons = Module("addons", {
// TODO: handle extension dependencies // TODO: handle extension dependencies
values(actions).forEach(function (command) { values(actions).forEach(function (command) {
let perm = command.perm && AddonManager["PERM_CAN_" + command.perm.toUpperCase()]; let perm = command.perm && AddonManager["PERM_CAN_" + command.perm.toUpperCase()];
function ok(addon) (!perm || addon.permissions & perm) && (!command.filter || command.filter(addon)); function ok(addon) {
return (!perm || addon.permissions & perm) && (!command.filter || command.filter(addon));
}
commands.add(Array.concat(command.name), commands.add(Array.concat(command.name),
command.description, command.description,

View File

@@ -44,7 +44,9 @@ function lazyRequire(module, names, target) {
let jsmodules = { lazyRequire: lazyRequire }; let jsmodules = { lazyRequire: lazyRequire };
jsmodules.jsmodules = jsmodules; jsmodules.jsmodules = jsmodules;
function toString() "[module-global " + this.NAME + "]"; function toString() {
return "[module-global " + this.NAME + "]";
}
function objToString(obj) { function objToString(obj) {
try { try {
@@ -406,7 +408,7 @@ function keys(obj) {
* @param {object} obj The object to inspect. * @param {object} obj The object to inspect.
* @returns {Iter} * @returns {Iter}
*/ */
function values(obj) { function values(obj) {
if (isinstance(obj, ["Map"])) if (isinstance(obj, ["Map"]))
return iter(obj.values()); return iter(obj.values());
@@ -582,7 +584,9 @@ function curry(fn, length, self, acc) {
return fn; return fn;
// Close over function with 'this' // Close over function with 'this'
function close(self, fn) (...args) => fn.apply(self, args); function close(self, fn) {
return (...args) => fn.apply(self, args);
}
if (acc == null) if (acc == null)
acc = []; acc = [];
@@ -668,7 +672,9 @@ function isinstance(object, interfaces) {
/** /**
* Returns true if obj is a non-null object. * Returns true if obj is a non-null object.
*/ */
function isObject(obj) typeof obj === "object" && obj != null || obj instanceof Ci.nsISupports; function isObject(obj) {
return typeof obj === "object" && obj != null || obj instanceof Ci.nsISupports;
}
/** /**
* Returns true if and only if its sole argument is an * Returns true if and only if its sole argument is an
@@ -678,7 +684,9 @@ function isObject(obj) typeof obj === "object" && obj != null || obj instanceof
*/ */
var isArray = var isArray =
// This is bloody stupid. // This is bloody stupid.
function isArray(val) Array.isArray(val) || val && val.constructor && val.constructor.name === "Array"; function isArray(val) {
return Array.isArray(val) || val && val.constructor && val.constructor.name === "Array";
}
/** /**
* Returns true if and only if its sole argument is an * Returns true if and only if its sole argument is an
@@ -686,7 +694,9 @@ var isArray =
* functions containing the 'yield' statement and generator * functions containing the 'yield' statement and generator
* statements such as (x for (x in obj)). * statements such as (x for (x in obj)).
*/ */
function isGenerator(val) objToString(val) == "[object Generator]"; function isGenerator(val) {
return objToString(val) == "[object Generator]";
}
/** /**
* Returns true if and only if its sole argument is a String, * Returns true if and only if its sole argument is a String,
@@ -695,13 +705,17 @@ function isGenerator(val) objToString(val) == "[object Generator]";
* namespace, or execution context, which is not the case when * namespace, or execution context, which is not the case when
* using (obj instanceof String) or (typeof obj == "string"). * using (obj instanceof String) or (typeof obj == "string").
*/ */
function isString(val) objToString(val) == "[object String]"; function isString(val) {
return objToString(val) == "[object String]";
}
/** /**
* Returns true if and only if its sole argument may be called * Returns true if and only if its sole argument may be called
* as a function. This includes classes and function objects. * as a function. This includes classes and function objects.
*/ */
function callable(val) typeof val === "function" && !(val instanceof Ci.nsIDOMElement); function callable(val) {
return typeof val === "function" && !(val instanceof Ci.nsIDOMElement);
}
function call(fn, self, ...args) { function call(fn, self, ...args) {
fn.apply(self, args); fn.apply(self, args);

View File

@@ -6,7 +6,9 @@
var EXPORTED_SYMBOLS = ["require"]; var EXPORTED_SYMBOLS = ["require"];
function create(proto) Object.create(proto); function create(proto) {
return Object.create(proto);
}
this["import"] = function import_(obj) { this["import"] = function import_(obj) {
let res = {}; let res = {};
@@ -20,6 +22,8 @@ if (typeof TextEncoder == "undefined")
// Deal with subScriptLoader prepending crap to loaded URLs // Deal with subScriptLoader prepending crap to loaded URLs
Components.utils.import("resource://gre/modules/Services.jsm"); Components.utils.import("resource://gre/modules/Services.jsm");
function loadSubScript() Services.scriptloader.loadSubScript.apply(null, arguments); function loadSubScript() {
return Services.scriptloader.loadSubScript.apply(null, arguments);
}
// vim: set fdm=marker sw=4 sts=4 ts=8 et ft=javascript: // vim: set fdm=marker sw=4 sts=4 ts=8 et ft=javascript:

View File

@@ -515,11 +515,15 @@ var Buffer = Module("Buffer", {
for (let elem of iter(elems)) for (let elem of iter(elems))
yield elem; yield elem;
function a(regexp, elem) regexp.test(elem.textContent) === regexp.result || function a(regexp, elem) {
Array.some(elem.childNodes, return regexp.test(elem.textContent) === regexp.result ||
child => (regexp.test(child.alt) === regexp.result)); Array.some(elem.childNodes,
child => (regexp.test(child.alt) === regexp.result));
}
function b(regexp, elem) regexp.test(elem.title) === regexp.result; function b(regexp, elem) {
return regexp.test(elem.title) === regexp.result;
}
let res = Array.filter(frame.document.querySelectorAll(selector), let res = Array.filter(frame.document.querySelectorAll(selector),
Hints.isVisible); Hints.isVisible);
@@ -617,7 +621,9 @@ var Buffer = Module("Buffer", {
* viewport. * viewport.
*/ */
resetCaret: function resetCaret() { resetCaret: function resetCaret() {
function visible(range) util.intersection(DOM(range).rect, viewport); function visible(range) {
return util.intersection(DOM(range).rect, viewport);
}
function getRanges(rect) { function getRanges(rect) {
let nodes = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils) let nodes = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils)
@@ -2771,9 +2777,12 @@ Buffer.addPageInfoSection("s", "Security", function* (verbose) {
return; // For now return; // For now
// Modified from Firefox // Modified from Firefox
function location(data) Ary.compact([ function location(data) {
data.city, data.state, data.country return Ary.compact([data.city,
]).join(", "); data.state,
data.country])
.join(", ");
}
switch (statusline.security) { switch (statusline.security) {
case "secure": case "secure":

View File

@@ -767,7 +767,9 @@ var Commands = Module("commands", {
return ""; return "";
} }
// TODO: allow matching of aliases? // TODO: allow matching of aliases?
function cmds(hive) hive._list.filter(cmd => cmd.name.startsWith(filter || "")) function cmds(hive) {
return hive._list.filter(cmd => cmd.name.startsWith(filter || ""));
}
hives = (hives || this.userHives).map(h => [h, cmds(h)]) hives = (hives || this.userHives).map(h => [h, cmds(h)])
.filter(([h, c]) => c.length); .filter(([h, c]) => c.length);
@@ -1401,8 +1403,10 @@ var Commands = Module("commands", {
let quote = null; let quote = null;
let len = str.length; let len = str.length;
function fixEscapes(str) str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4}|(.))/g, function fixEscapes(str) {
(m, n1) => n1 || m); return str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4}|(.))/g,
(m, n1) => n1 || m);
}
// Fix me. // Fix me.
if (isString(sep)) if (isString(sep))
@@ -1798,8 +1802,10 @@ var Commands = Module("commands", {
let quote = function quote(q, list, map=Commands.quoteMap) { let quote = function quote(q, list, map=Commands.quoteMap) {
let re = RegExp("[" + list + "]", "g"); let re = RegExp("[" + list + "]", "g");
function quote(str) (q + String.replace(str, re, $0 => ($0 in map ? map[$0] : ("\\" + $0))) function quote(str) {
+ q); return (q + String.replace(str, re, $0 => ($0 in map ? map[$0] : ("\\" + $0)))
+ q);
}
quote.list = list; quote.list = list;
return quote; return quote;
}; };

View File

@@ -1095,7 +1095,9 @@ var Completion = Module("completion", {
contains(item.title, tok))); contains(item.title, tok)));
let re = RegExp(tokens.filter(util.identity).map(util.regexp.escape).join("|"), "g"); let re = RegExp(tokens.filter(util.identity).map(util.regexp.escape).join("|"), "g");
function highlight(item, text, i) process[i].call(this, item, template.highlightRegexp(text, re)); function highlight(item, text, i) {
return process[i].call(this, item, template.highlightRegexp(text, re));
}
let process = context.process; let process = context.process;
context.process = [ context.process = [
function process_0(item, text) highlight.call(this, item, item.text, 0), function process_0(item, text) highlight.call(this, item, item.text, 0),

View File

@@ -174,10 +174,12 @@ var ConfigBase = Class("ConfigBase", {
let hl = highlight.set("Find", ""); let hl = highlight.set("Find", "");
hl.onChange = function () { hl.onChange = function () {
function hex(val) ("#" + util.regexp.iterate(/\d+/g, val) function hex(val) {
.map(num => ("0" + Number(num).toString(16)).slice(-2)) return ("#" + util.regexp.iterate(/\d+/g, val)
.join("") .map(num => ("0" + Number(num).toString(16)).slice(-2))
).slice(0, 7); .join("")
).slice(0, 7);
}
let elem = services.appShell.hiddenDOMWindow.document.createElement("div"); let elem = services.appShell.hiddenDOMWindow.document.createElement("div");
elem.style.cssText = this.cssText; elem.style.cssText = this.cssText;
@@ -216,7 +218,9 @@ var ConfigBase = Class("ConfigBase", {
*/ */
locales: Class.Memoize(function () { locales: Class.Memoize(function () {
// TODO: Merge with completion.file code. // TODO: Merge with completion.file code.
function getDir(str) str.match(/^(?:.*[\/\\])?/)[0]; function getDir(str) {
return str.match(/^(?:.*[\/\\])?/)[0];
}
let uri = "resource://dactyl-locale/"; let uri = "resource://dactyl-locale/";
let jar = io.isJarURL(uri); let jar = io.isJarURL(uri);

View File

@@ -499,12 +499,14 @@ var Contexts = Module("contexts", {
bindMacro: function (args, default_, params) { bindMacro: function (args, default_, params) {
const { dactyl, events, modules } = this.modules; const { dactyl, events, modules } = this.modules;
function Proxy(obj, key) Class.Property({ function Proxy(obj, key) {
configurable: true, return Class.Property({
enumerable: true, configurable: true,
get: function Proxy_get() process(obj[key]), enumerable: true,
set: function Proxy_set(val) obj[key] = val get: function Proxy_get() process(obj[key]),
}) set: function Proxy_set(val) obj[key] = val
});
}
let process = util.identity; let process = util.identity;

View File

@@ -20,15 +20,17 @@ var XHTML = "http://www.w3.org/1999/xhtml";
var XUL = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var XUL = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
var NS = "http://vimperator.org/namespaces/liberator"; var NS = "http://vimperator.org/namespaces/liberator";
function BooleanAttribute(attr) ({ function BooleanAttribute(attr) {
get: function (elem) elem.getAttribute(attr) == "true", return {
set: function (elem, val) { get: function (elem) elem.getAttribute(attr) == "true",
if (val === "false" || !val) set: function (elem, val) {
elem.removeAttribute(attr); if (val === "false" || !val)
else elem.removeAttribute(attr);
elem.setAttribute(attr, true); else
} elem.setAttribute(attr, true);
}); }
};
}
/** /**
* @class * @class
@@ -549,7 +551,9 @@ var DOM = Class("DOM", {
* @returns {string} * @returns {string}
*/ */
get xpath() { get xpath() {
function quote(val) "'" + val.replace(/[\\']/g, "\\$&") + "'"; function quote(val) {
return "'" + val.replace(/[\\']/g, "\\$&") + "'";
}
if (!(this[0] instanceof Ci.nsIDOMElement)) if (!(this[0] instanceof Ci.nsIDOMElement))
return null; return null;
@@ -1575,7 +1579,9 @@ var DOM = Class("DOM", {
attr = attr || {}; attr = attr || {};
function parseNamespace(name) DOM.parseNamespace(name, namespaces); function parseNamespace(name) {
return DOM.parseNamespace(name, namespaces);
}
// FIXME: Surely we can do better. // FIXME: Surely we can do better.
for (var key in attr) { for (var key in attr) {
@@ -1652,7 +1658,9 @@ var DOM = Class("DOM", {
throw Error("No such namespace"); throw Error("No such namespace");
} }
function isFragment(args) !isString(args[0]) || args.length == 0 || args[0] === ""; function isFragment(args) {
return !isString(args[0]) || args.length == 0 || args[0] === "";
}
function hasString(args) { function hasString(args) {
return args.some(a => (isString(a) || isFragment(a) && hasString(a))); return args.some(a => (isString(a) || isFragment(a) && hasString(a)));

View File

@@ -12,9 +12,14 @@ defineModule("finder", {
lazyRequire("buffer", ["Buffer"]); lazyRequire("buffer", ["Buffer"]);
lazyRequire("overlay", ["overlay"]); lazyRequire("overlay", ["overlay"]);
function id(w) w.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils) function id(w) {
.outerWindowID; return w.QueryInterface(Ci.nsIInterfaceRequestor)
function equals(a, b) id(a) == id(b); .getInterface(Ci.nsIDOMWindowUtils)
.outerWindowID;
}
function equals(a, b) {
return id(a) == id(b);
}
/** @instance rangefinder */ /** @instance rangefinder */
var RangeFinder = Module("rangefinder", { var RangeFinder = Module("rangefinder", {

View File

@@ -242,7 +242,9 @@ var Help = Module("Help", {
let items = modules.completion._runCompleter("help", topic, null, !!consolidated).items; let items = modules.completion._runCompleter("help", topic, null, !!consolidated).items;
let partialMatch = null; let partialMatch = null;
function format(item) item.description + "#" + encodeURIComponent(item.text); function format(item) {
return item.description + "#" + encodeURIComponent(item.text);
}
for (let item of items) { for (let item of items) {
if (item.text == topic) if (item.text == topic)

View File

@@ -528,13 +528,15 @@ var IO = Module("io", {
else if (input) else if (input)
stdin.write(input); stdin.write(input);
function result(status, output) ({ function result(status, output) {
__noSuchMethod__: function (meth, args) apply(this.output, meth, args), return {
valueOf: function () this.output, __noSuchMethod__: function (meth, args) apply(this.output, meth, args),
output: output.replace(/^(.*)\n$/, "$1"), valueOf: function () this.output,
returnValue: status, output: output.replace(/^(.*)\n$/, "$1"),
toString: function () this.output returnValue: status,
}); toString: function () this.output
};
}
function async(status) { function async(status) {
let output = stdout.read(); let output = stdout.read();
@@ -1000,7 +1002,9 @@ unlet s:cpo_save
context.advance(4); context.advance(4);
// dir == "" is expanded inside readDirectory to the current dir // dir == "" is expanded inside readDirectory to the current dir
function getDir(str) str.match(/^(?:.*[\/\\])?/)[0]; function getDir(str) {
return str.match(/^(?:.*[\/\\])?/)[0];
}
dir = getDir(dir || context.filter); dir = getDir(dir || context.filter);
let file = util.getFile(dir); let file = util.getFile(dir);

View File

@@ -382,7 +382,10 @@ var JavaScript = Module("javascript", {
} }
// We've already listed anchored matches, so don't list them again here. // We've already listed anchored matches, so don't list them again here.
function unanchored(item) util.compareIgnoreCase(item.text.substr(0, this.filter.length), this.filter); function unanchored(item) {
return util.compareIgnoreCase(item.text.substr(0, this.filter.length),
this.filter);
}
objects.forEach(function (obj) { objects.forEach(function (obj) {
let context = base.fork(obj[1]); let context = base.fork(obj[1]);
@@ -856,7 +859,9 @@ var JavaScript = Module("javascript", {
mappings: function initMappings(dactyl, modules, window) { mappings: function initMappings(dactyl, modules, window) {
const { mappings, modes } = modules; const { mappings, modes } = modules;
function bind(...args) apply(mappings, "add", [[modes.REPL]].concat(args)) function bind(...args) {
return apply(mappings, "add", [[modes.REPL]].concat(args));
}
bind(["<Return>"], "Accept the current input", bind(["<Return>"], "Accept the current input",
function ({ self }) { self.accept(); }); function ({ self }) { self.accept(); });

View File

@@ -106,29 +106,33 @@ var Messages = Module("messages", {
let { Buffer, commands, hints, io, mappings, modes, options, sanitizer } = overlay.activeModules; let { Buffer, commands, hints, io, mappings, modes, options, sanitizer } = overlay.activeModules;
file = io.File(file); file = io.File(file);
function properties(base, iter_, prop="description") iter(function* _properties() { function properties(base, iter_, prop="description") {
function key(...args) [base, obj.identifier || obj.name].concat(args).join(".").replace(/[\\:=]/g, "\\$&"); return iter(function* _properties() {
function key(...args) {
for (var obj of iter_) { return [base, obj.identifier || obj.name].concat(args).join(".").replace(/[\\:=]/g, "\\$&");
if (!obj.hive || obj.hive.name !== "user") {
yield key(prop) + " = " + obj[prop];
if (iter_.values) {
let iter_ = isArray(obj.values) ? obj.values
: iter(obj.values);
for (let [k, v] of iter_)
yield key("values", k) + " = " + v;
}
for (let opt of values(obj.options))
yield key("options", opt.names[0]) + " = " + opt.description;
if (obj.deprecated)
yield key("deprecated") + " = " + obj.deprecated;
} }
}
}()).toArray(); for (var obj of iter_) {
if (!obj.hive || obj.hive.name !== "user") {
yield key(prop) + " = " + obj[prop];
if (iter_.values) {
let iter_ = isArray(obj.values) ? obj.values
: iter(obj.values);
for (let [k, v] of iter_)
yield key("values", k) + " = " + v;
}
for (let opt of values(obj.options))
yield key("options", opt.names[0]) + " = " + opt.description;
if (obj.deprecated)
yield key("deprecated") + " = " + obj.deprecated;
}
}
}()).toArray();
}
file.write( file.write(
Ary(commands.allHives.map(h => properties("command", h))) Ary(commands.allHives.map(h => properties("command", h)))
@@ -161,7 +165,9 @@ var Messages = Module("messages", {
get: function get() { get: function get() {
let value = this[_prop]; let value = this[_prop];
function getter(key, default_) function getter() messages.get([name, key].join("."), default_); function getter(key, default_) {
return function getter() messages.get([name, key].join("."), default_);
}
if (value != null) { if (value != null) {
var name = [this.constructor.className.toLowerCase(), var name = [this.constructor.className.toLowerCase(),

View File

@@ -1337,9 +1337,11 @@ var Options = Module("options", {
function (args) { function (args) {
let globalVariables = dactyl._globalVariables; let globalVariables = dactyl._globalVariables;
args = (args[0] || "").trim(); args = (args[0] || "").trim();
function fmt(value) (typeof value == "number" ? "#" : function fmt(value) {
typeof value == "function" ? "*" : return (typeof value == "number" ? "#" :
" ") + value; typeof value == "function" ? "*" :
" ") + value;
}
util.assert(!(!args || args == "g:")); util.assert(!(!args || args == "g:"));
let matches = args.match(/^([a-z]:)?([\w]+)(?:\s*([-+.])?=\s*(.*)?)?$/); let matches = args.match(/^([a-z]:)?([\w]+)(?:\s*([-+.])?=\s*(.*)?)?$/);

View File

@@ -162,10 +162,12 @@ var Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakRef
override: true override: true
}); });
function ourItems(persistent) [ function ourItems(persistent) {
item for (item of values(self.itemMap)) return [
if (!item.builtin && (!persistent || item.persistent) && item.name !== "all") item for (item of values(self.itemMap))
]; if (!item.builtin && (!persistent || item.persistent) && item.name !== "all")
];
}
function prefOverlay(branch, persistent, local) { function prefOverlay(branch, persistent, local) {
return update(Object.create(local), return update(Object.create(local),

View File

@@ -719,17 +719,21 @@ var File = Class("File", {
* @returns {string} * @returns {string}
*/ */
expandPath: function expandPath(path, relative) { expandPath: function expandPath(path, relative) {
function getenv(name) services.environment.get(name); function getenv(name) {
return services.environment.get(name);
}
// expand any $ENV vars - this is naive but so is Vim and we like to be compatible // expand any $ENV vars - this is naive but so is Vim and we like to be compatible
// TODO: Vim does not expand variables set to an empty string (and documents it). // TODO: Vim does not expand variables set to an empty string (and documents it).
// Kris reckons we shouldn't replicate this 'bug'. --djk // Kris reckons we shouldn't replicate this 'bug'. --djk
// TODO: should we be doing this for all paths? // TODO: should we be doing this for all paths?
// No. // No.
function expand(path) path.replace( function expand(path) {
win32 ? /\$(\w+)\b|\${(\w+)}|%(\w+)%/g return path.replace(
: /\$(\w+)\b|\${(\w+)}/g, win32 ? /\$(\w+)\b|\${(\w+)}|%(\w+)%/g
(m, n1, n2, n3) => (getenv(n1 || n2 || n3) || m)); : /\$(\w+)\b|\${(\w+)}/g,
(m, n1, n2, n3) => (getenv(n1 || n2 || n3) || m));
}
path = expand(path); path = expand(path);
// expand ~ // expand ~

View File

@@ -570,16 +570,18 @@ var Styles = Module("Styles", {
Styles.splitContext(context); Styles.splitContext(context);
} }
function nameFlag(filter) ({ function nameFlag(filter) {
names: ["-name", "-n"], return {
description: "The name of this stylesheet", names: ["-name", "-n"],
type: modules.CommandOption.STRING, description: "The name of this stylesheet",
completer: function (context, args) { type: modules.CommandOption.STRING,
context.keys.text = sheet => sheet.name; completer: function (context, args) {
context.filters.unshift(({ item }) => item.name); context.keys.text = sheet => sheet.name;
sheets(context, args, filter); context.filters.unshift(({ item }) => item.name);
} sheets(context, args, filter);
}); }
};
}
commands.add(["sty[le]"], commands.add(["sty[le]"],
"Add or list user styles", "Add or list user styles",

View File

@@ -259,17 +259,19 @@ var Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference]),
let stack = [frame()]; let stack = [frame()];
stack.__defineGetter__("top", function () this[this.length - 1]); stack.__defineGetter__("top", function () this[this.length - 1]);
function frame() update( function frame() {
function _frame(obj) return update(
_frame === stack.top || _frame.valid(obj) function _frame(obj)
? _frame.elements.map(e => callable(e) ? e(obj) : e) _frame === stack.top || _frame.valid(obj)
.join("") ? _frame.elements.map(e => callable(e) ? e(obj) : e)
: "", .join("")
{ : "",
elements: [], {
seen: {}, elements: [],
valid: function valid(obj) this.elements.every(e => !e.test || e.test(obj)) seen: {},
}); valid: function valid(obj) this.elements.every(e => !e.test || e.test(obj))
});
}
let end = 0; let end = 0;
for (let match of util.regexp.iterate(/(.*?)%(.)/gy, format)) { for (let match of util.regexp.iterate(/(.*?)%(.)/gy, format)) {
@@ -345,17 +347,19 @@ var Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference]),
if (!keepUnknown) if (!keepUnknown)
unknown = () => ""; unknown = () => "";
function frame() update( function frame() {
function _frame(obj) return update(
_frame === stack.top || _frame.valid(obj) function _frame(obj)
? _frame.elements.map(e => callable(e) ? e(obj) : e) _frame === stack.top || _frame.valid(obj)
.join("") ? _frame.elements.map(e => callable(e) ? e(obj) : e)
: "", .join("")
{ : "",
elements: [], {
seen: new RealSet, elements: [],
valid: function valid(obj) this.elements.every(e => (!e.test || e.test(obj))) seen: new RealSet,
}); valid: function valid(obj) this.elements.every(e => (!e.test || e.test(obj)))
});
}
let defaults = { lt: "<", gt: ">" }; let defaults = { lt: "<", gt: ">" };
@@ -655,8 +659,12 @@ var Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference]),
* @returns {string} * @returns {string}
*/ */
formatSeconds: function formatSeconds(seconds) { formatSeconds: function formatSeconds(seconds) {
function pad(n, val) ("0000000" + val).substr(-Math.max(n, String(val).length)); function pad(n, val) {
function div(num, denom) [Math.floor(num / denom), Math.round(num % denom)]; return ("0000000" + val).substr(-Math.max(n, String(val).length));
}
function div(num, denom) {
return [Math.floor(num / denom), Math.round(num % denom)];
}
let days, hours, minutes; let days, hours, minutes;
[minutes, seconds] = div(Math.round(seconds), 60); [minutes, seconds] = div(Math.round(seconds), 60);

View File

@@ -550,7 +550,9 @@ const Player = Module("player", {
dactyl.assert(/^[+-]?(\d+[smh]?|(\d+:\d\d:|\d+:)?\d{2})$/.test(arg), dactyl.assert(/^[+-]?(\d+[smh]?|(\d+:\d\d:|\d+:)?\d{2})$/.test(arg),
_("error.invalidArgument", arg)); _("error.invalidArgument", arg));
function ms(t, m) Math.abs(parseInt(t, 10) * { s: 1000, m: 60000, h: 3600000 }[m]) function ms(t, m) {
return Math.abs(parseInt(t, 10) * { s: 1000, m: 60000, h: 3600000 }[m]);
}
if (/:/.test(arg)) { if (/:/.test(arg)) {
let [seconds, minutes, hours] = arg.split(":").reverse(); let [seconds, minutes, hours] = arg.split(":").reverse();

View File

@@ -119,7 +119,9 @@ var Config = Module("config", ConfigBase, {
commands.add(["sideb[ar]", "sb[ar]", "sbop[en]"], commands.add(["sideb[ar]", "sb[ar]", "sbop[en]"],
"Open the sidebar window", "Open the sidebar window",
function (args) { function (args) {
function compare(a, b) util.compareIgnoreCase(a, b) == 0 function compare(a, b) {
return util.compareIgnoreCase(a, b) == 0;
}
let title = document.getElementById("sidebar-title"); let title = document.getElementById("sidebar-title");
dactyl.assert(args.length || title.value || args.bang && config.lastSidebar, dactyl.assert(args.length || title.value || args.bang && config.lastSidebar,