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

Death to E4X and stuff.

This commit is contained in:
Kris Maglione
2012-12-17 18:56:36 -08:00
parent 0d179d78bc
commit 3f483de547
24 changed files with 112 additions and 517 deletions

View File

@@ -37,7 +37,7 @@ var Bookmarks = Module("bookmarks", {
anchored: false, anchored: false,
title: ["URL", "Info"], title: ["URL", "Info"],
keys: { text: "url", description: "title", icon: "icon", extra: "extra", tags: "tags", isURI: function () true }, keys: { text: "url", description: "title", icon: "icon", extra: "extra", tags: "tags", isURI: function () true },
process: [template_.icon, template_.bookmarkDescription] process: [template.icon, template.bookmarkDescription]
}), }),
// TODO: why is this a filter? --djk // TODO: why is this a filter? --djk

View File

@@ -1578,7 +1578,7 @@ var CommandLine = Module("commandline", {
else if (callable(arg)) else if (callable(arg))
arg = String.replace(arg, "/* use strict */ \n", "/* use strict */ "); arg = String.replace(arg, "/* use strict */ \n", "/* use strict */ ");
else if (!isString(arg) && useColor) else if (!isString(arg) && useColor)
arg = template_.highlight(arg); arg = template.highlight(arg);
return arg; return arg;
} }
}, { }, {
@@ -1621,7 +1621,7 @@ var CommandLine = Module("commandline", {
} }
else if (commandline._messageHistory.length > 1) { else if (commandline._messageHistory.length > 1) {
commandline.commandOutput( commandline.commandOutput(
template_.map(commandline._messageHistory.messages, function (message) template.map(commandline._messageHistory.messages, function (message)
["div", { highlight: message.highlight + " Message" }, ["div", { highlight: message.highlight + " Message" },
message.message])); message.message]));
} }
@@ -1894,7 +1894,7 @@ var ItemList = Class("ItemList", {
["div", { key: "completions" }]], ["div", { key: "completions" }]],
["div", { highlight: "Completions" }, ["div", { highlight: "Completions" },
template_.map(util.range(0, options["maxitems"] * 2), function (i) template.map(util.range(0, options["maxitems"] * 2), function (i)
["div", { highlight: "CompItem NonText" }, ["div", { highlight: "CompItem NonText" },
"~"])]], "~"])]],

View File

@@ -253,7 +253,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
results = results.filter(function (item) filters.every(function (re) keys(item).some(re.closure.test))); results = results.filter(function (item) filters.every(function (re) keys(item).some(re.closure.test)));
commandline.commandOutput( commandline.commandOutput(
template_.usage(results, params.format)); template.usage(results, params.format));
}, },
{ {
argCount: "*", argCount: "*",
@@ -693,7 +693,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
}; };
} }
else if (obj instanceof Option) { else if (obj instanceof Option) {
spec = function () template_.map(obj.names, tag, " "); spec = function () template.map(obj.names, tag, " ");
tag = function (name) DOM.DOMString("'" + name + "'"); tag = function (name) DOM.DOMString("'" + name + "'");
link = function (opt, name) ["o", {}, name]; link = function (opt, name) ["o", {}, name];
args = { value: "", values: [] }; args = { value: "", values: [] };
@@ -702,23 +702,23 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
let res = [ let res = [
["dt", {}, link(obj.helpTag || tag(obj.name), obj.name)], ["dt", {}, link(obj.helpTag || tag(obj.name), obj.name)],
["dd", {}, ["dd", {},
template_.linkifyHelp(obj.description ? obj.description.replace(/\.$/, "") : "", true)]]; template.linkifyHelp(obj.description ? obj.description.replace(/\.$/, "") : "", true)]];
if (specOnly) if (specOnly)
return res; return res;
let description = ["description", {}, let description = ["description", {},
obj.description ? ["p", {}, template_.linkifyHelp(obj.description.replace(/\.?$/, "."), true)] : "", obj.description ? ["p", {}, template.linkifyHelp(obj.description.replace(/\.?$/, "."), true)] : "",
extraHelp ? extraHelp : "", extraHelp ? extraHelp : "",
!(extraHelp || obj.description) ? ["p", {}, /*L*/ "Sorry, no help available."] : ""] !(extraHelp || obj.description) ? ["p", {}, /*L*/ "Sorry, no help available."] : ""]
res.push( res.push(
["item", {}, ["item", {},
["tags", {}, template_.map(obj.names.slice().reverse(), ["tags", {}, template.map(obj.names.slice().reverse(),
tag, tag,
" ").join("")], " ").join("")],
["spec", {}, ["spec", {},
let (name = (obj.specs || obj.names)[0]) let (name = (obj.specs || obj.names)[0])
spec(template_.highlightRegexp(tag(name), spec(template.highlightRegexp(tag(name),
/\[(.*?)\]/g, /\[(.*?)\]/g,
function (m, n0) ["oa", {}, n0]), function (m, n0) ["oa", {}, n0]),
name)], name)],
@@ -729,7 +729,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
function add(ary) { function add(ary) {
description.push( description.push(
["dl", {}, template_.map(ary, ["dl", {}, template.map(ary,
function ([a, b]) [["dt", {}, a], " ", function ([a, b]) [["dt", {}, a], " ",
["dd", {}, b]])]); ["dd", {}, b]])]);
} }
@@ -745,7 +745,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
[o.description, [o.description,
o.names.length == 1 ? "" : o.names.length == 1 ? "" :
["", " (short name: ", ["", " (short name: ",
template_.map(o.names.slice(1), function (n) ["em", {}, n], ", "), template.map(o.names.slice(1), function (n) ["em", {}, n], ", "),
")"]] ")"]]
])); ]));
@@ -1144,7 +1144,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
error.message = prefix + error.message; error.message = prefix + error.message;
if (error.message) if (error.message)
dactyl.echoerr(template_.linkifyHelp(error.message)); dactyl.echoerr(template.linkifyHelp(error.message));
else else
dactyl.beep(); dactyl.beep();
@@ -1267,9 +1267,9 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
cache.register("help/index.xml", function () { cache.register("help/index.xml", function () {
return '<?xml version="1.0"?>\n' + return '<?xml version="1.0"?>\n' +
DOM.toXML(["overlay", { xmlns: "dactyl" }, DOM.toXML(["overlay", { xmlns: "dactyl" },
template_.map(dactyl.indices, function ([name, iter]) template.map(dactyl.indices, function ([name, iter])
["dl", { insertafter: name + "-index" }, ["dl", { insertafter: name + "-index" },
template_.map(iter(), util.identity)], template.map(iter(), util.identity)],
"\n\n")]); "\n\n")]);
}); });
@@ -1277,7 +1277,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
return '<?xml version="1.0"?>\n' + return '<?xml version="1.0"?>\n' +
DOM.toXML(["overlay", { xmlns: "dactyl" }, DOM.toXML(["overlay", { xmlns: "dactyl" },
["dl", { insertafter: "dialog-list" }, ["dl", { insertafter: "dialog-list" },
template_.map(config.dialogs, function ([name, val]) template.map(config.dialogs, function ([name, val])
(!val[2] || val[2]()) (!val[2] || val[2]())
? [["dt", {}, name], ? [["dt", {}, name],
["dd", {}, val[0]]] ["dd", {}, val[0]]]
@@ -1289,12 +1289,12 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
return '<?xml version="1.0"?>\n' + return '<?xml version="1.0"?>\n' +
DOM.toXML(["overlay", { xmlns: "dactyl" }, DOM.toXML(["overlay", { xmlns: "dactyl" },
["dl", { insertafter: "sanitize-items" }, ["dl", { insertafter: "sanitize-items" },
template_.map(options.get("sanitizeitems").values template.map(options.get("sanitizeitems").values
.sort(function (a, b) String.localeCompare(a.name, .sort(function (a, b) String.localeCompare(a.name,
b.name)), b.name)),
function ({ name, description }) function ({ name, description })
[["dt", {}, name], [["dt", {}, name],
["dd", {}, template_.linkifyHelp(description, true)]], ["dd", {}, template.linkifyHelp(description, true)]],
"\n")]]); "\n")]]);
}); });
}, },

View File

@@ -316,7 +316,7 @@ var History = Module("history", {
.concat(jumps) .concat(jumps)
.concat(sh.slice(sh.index + 1)); .concat(sh.slice(sh.index + 1));
commandline.commandOutput(template_.jumps(index, list)); commandline.commandOutput(template.jumps(index, list));
}, },
{ argCount: "0" }); { argCount: "0" });

View File

@@ -770,9 +770,9 @@ var Mappings = Module("mappings", {
description: function (map) [ description: function (map) [
options.get("passkeys").has(map.name) options.get("passkeys").has(map.name)
? ["span", { highlight: "URLExtra" }, ? ["span", { highlight: "URLExtra" },
"(", template_.linkifyHelp(_("option.passkeys.passedBy")), ")"] "(", template.linkifyHelp(_("option.passkeys.passedBy")), ")"]
: [], : [],
template_.linkifyHelp(map.description + (map.rhs ? ": " + map.rhs : "")) template.linkifyHelp(map.description + (map.rhs ? ": " + map.rhs : ""))
], ],
help: function (map) let (char = array.compact(map.modes.map(function (m) m.char))[0]) help: function (map) let (char = array.compact(map.modes.map(function (m) m.char))[0])
char === "n" ? map.name : char ? char + "_" + map.name : "", char === "n" ? map.name : char ? char + "_" + map.name : "",

View File

@@ -265,7 +265,7 @@ var Marks = Module("marks", {
} }
commandline.commandOutput( commandline.commandOutput(
template_.tabular( template.tabular(
["Mark", "HPos", "VPos", "File"], ["Mark", "HPos", "VPos", "File"],
["", "text-align: right", "text-align: right", "color: green"], ["", "text-align: right", "text-align: right", "color: green"],
([name, ([name,

View File

@@ -113,7 +113,7 @@ var QuickMarks = Module("quickmarks", {
dactyl.assert(marks.length >= 0, _("quickmark.noMatching", filter.quote())); dactyl.assert(marks.length >= 0, _("quickmark.noMatching", filter.quote()));
} }
commandline.commandOutput(template_.tabular(["QuickMark", "URL"], [], commandline.commandOutput(template.tabular(["QuickMark", "URL"], [],
([mark, quickmarks._qmarks.get(mark)] for ([k, mark] in Iterator(marks))))); ([mark, quickmarks._qmarks.get(mark)] for ([k, mark] in Iterator(marks)))));
} }
}, { }, {

View File

@@ -1044,7 +1044,7 @@ var Tabs = Module("tabs", {
item.indicator], item.indicator],
next.call(this, item, text) next.call(this, item, text)
]); ]);
context.process[1] = function (item, text) template_.bookmarkDescription(item, template_.highlightFilter(text, this.filter)); context.process[1] = function (item, text) template.bookmarkDescription(item, template.highlightFilter(text, this.filter));
context.anchored = false; context.anchored = false;
context.keys = { context.keys = {

View File

@@ -13,7 +13,7 @@ defineModule("addons", {
}); });
this.lazyRequire("completion", ["completion"]); this.lazyRequire("completion", ["completion"]);
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
var callResult = function callResult(method) { var callResult = function callResult(method) {
let args = Array.slice(arguments, 1); let args = Array.slice(arguments, 1);

View File

@@ -16,7 +16,7 @@ lazyRequire("io", ["io"]);
lazyRequire("finder", ["RangeFind"]); lazyRequire("finder", ["RangeFind"]);
lazyRequire("overlay", ["overlay"]); lazyRequire("overlay", ["overlay"]);
lazyRequire("storage", ["File", "storage"]); lazyRequire("storage", ["File", "storage"]);
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
/** /**
* A class to manage the primary web content buffer. The name comes * A class to manage the primary web content buffer. The name comes
@@ -909,7 +909,7 @@ var Buffer = Module("Buffer", {
let file = this.win.location.pathname.split("/").pop() || _("buffer.noName"); let file = this.win.location.pathname.split("/").pop() || _("buffer.noName");
let title = this.win.document.title || _("buffer.noTitle"); let title = this.win.document.title || _("buffer.noTitle");
let info = template_.map( let info = template.map(
(sections || options["pageinfo"]) (sections || options["pageinfo"])
.map(function (opt) Buffer.pageInfo[opt].action.call(self)), .map(function (opt) Buffer.pageInfo[opt].action.call(self)),
function (res) res && iter(res).join(", ") || undefined, function (res) res && iter(res).join(", ") || undefined,
@@ -923,9 +923,9 @@ var Buffer = Module("Buffer", {
return; return;
} }
let list = template_.map(sections || options["pageinfo"], function (option) { let list = template.map(sections || options["pageinfo"], function (option) {
let { action, title } = Buffer.pageInfo[option]; let { action, title } = Buffer.pageInfo[option];
return template_.table(title, action.call(self, true)); return template.table(title, action.call(self, true));
}, ["br"]); }, ["br"]);
commandline.commandOutput(list); commandline.commandOutput(list);
@@ -2430,7 +2430,7 @@ Buffer.addPageInfoSection("f", "Feeds", function (verbose) {
nFeed++; nFeed++;
let type = feedTypes[feed.type] || "RSS"; let type = feedTypes[feed.type] || "RSS";
if (verbose) if (verbose)
yield [feed.title, [template_.highlightURL(feed.href, true), yield [feed.title, [template.highlightURL(feed.href, true),
["span", { class: "extra-info" }, " (" + type + ")"]]]; ["span", { class: "extra-info" }, " (" + type + ")"]]];
} }
} }
@@ -2479,11 +2479,11 @@ Buffer.addPageInfoSection("g", "General Info", function (verbose) {
} }
yield ["Title", doc.title]; yield ["Title", doc.title];
yield ["URL", template_.highlightURL(doc.location.href, true)]; yield ["URL", template.highlightURL(doc.location.href, true)];
let ref = "referrer" in doc && doc.referrer; let ref = "referrer" in doc && doc.referrer;
if (ref) if (ref)
yield ["Referrer", template_.highlightURL(ref, true)]; yield ["Referrer", template.highlightURL(ref, true)];
if (pageSize[0]) if (pageSize[0])
yield ["File Size", pageSize[1] ? pageSize[1] + " (" + pageSize[0] + ")" yield ["File Size", pageSize[1] ? pageSize[1] + " (" + pageSize[0] + ")"
@@ -2504,7 +2504,7 @@ Buffer.addPageInfoSection("m", "Meta Tags", function (verbose) {
let metaNodes = this.focusedFrame.document.getElementsByTagName("meta"); let metaNodes = this.focusedFrame.document.getElementsByTagName("meta");
return Array.map(metaNodes, function (node) [(node.name || node.httpEquiv), return Array.map(metaNodes, function (node) [(node.name || node.httpEquiv),
template_.highlightURL(node.content)]) template.highlightURL(node.content)])
.sort(function (a, b) util.compareIgnoreCase(a[0], b[0])); .sort(function (a, b) util.compareIgnoreCase(a[0], b[0]));
}); });

View File

@@ -15,7 +15,7 @@ defineModule("commands", {
lazyRequire("help", ["help"]); lazyRequire("help", ["help"]);
lazyRequire("options", ["Option"]); lazyRequire("options", ["Option"]);
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
/** /**
* A structure representing the options available for a command. * A structure representing the options available for a command.
@@ -1712,7 +1712,7 @@ var Commands = Module("commands", {
this.iterate(args).filter(function (cmd) cmd.hive === commands.builtin || Set.has(tags, cmd.helpTag)), this.iterate(args).filter(function (cmd) cmd.hive === commands.builtin || Set.has(tags, cmd.helpTag)),
format: { format: {
headings: ["Command", "Group", "Description"], headings: ["Command", "Group", "Description"],
description: function (cmd) template_.linkifyHelp(cmd.description + (cmd.replacementText ? ": " + cmd.action : "")), description: function (cmd) template.linkifyHelp(cmd.description + (cmd.replacementText ? ": " + cmd.action : "")),
help: function (cmd) ":" + cmd.name help: function (cmd) ":" + cmd.name
} }
}); });

View File

@@ -12,7 +12,7 @@ defineModule("completion", {
lazyRequire("dom", ["DOM"]); lazyRequire("dom", ["DOM"]);
lazyRequire("messages", ["_", "messages"]); lazyRequire("messages", ["_", "messages"]);
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
/** /**
* Creates a new completion context. * Creates a new completion context.
@@ -321,7 +321,7 @@ var CompletionContext = Class("CompletionContext", {
util.trapErrors("onUpdate", this); util.trapErrors("onUpdate", this);
}, },
get createRow() this._createRow || template_.completionRow, // XXX get createRow() this._createRow || template.completionRow, // XXX
set createRow(createRow) this._createRow = createRow, set createRow(createRow) this._createRow = createRow,
get filterFunc() this._filterFunc || util.identity, get filterFunc() this._filterFunc || util.identity,
@@ -494,7 +494,7 @@ var CompletionContext = Class("CompletionContext", {
this.processor = Array.slice(this.process); this.processor = Array.slice(this.process);
if (!this.anchored) if (!this.anchored)
this.processor[0] = function (item, text) self.process[0].call(self, item, this.processor[0] = function (item, text) self.process[0].call(self, item,
template_.highlightFilter(item.text, self.filter, null, item.isURI)); template.highlightFilter(item.text, self.filter, null, item.isURI));
try { try {
// Item prototypes // Item prototypes
@@ -824,7 +824,7 @@ var CompletionContext = Class("CompletionContext", {
throw Error(); throw Error();
this.offset = 0; this.offset = 0;
this.process = [template_.icon, function (item, k) k]; this.process = [template.icon, function (item, k) k];
this.filters = [CompletionContext.Filter.text]; this.filters = [CompletionContext.Filter.text];
this.tabPressed = false; this.tabPressed = false;
this.title = ["Completions"]; this.title = ["Completions"];
@@ -937,9 +937,9 @@ var Completion = Module("completion", {
modules.commandline.commandOutput( modules.commandline.commandOutput(
["div", { highlight: "Completions" }, ["div", { highlight: "Completions" },
template_.map(contexts, function (context) template.map(contexts, function (context)
[template_.completionRow(context.title, "CompTitle"), [template.completionRow(context.title, "CompTitle"),
template_.map(context.items, function (item) context.createRow(item), null, 100)])]); template.map(context.items, function (item) context.createRow(item), null, 100)])]);
}, },
}), }),
@@ -1090,7 +1090,7 @@ 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) process[i].call(this, item, template.highlightRegexp(text, re));
let process = context.process; let process = context.process;
context.process = [ context.process = [
function (item, text) highlight.call(this, item, item.text, 0), function (item, text) highlight.call(this, item, item.text, 0),
@@ -1121,9 +1121,9 @@ var Completion = Module("completion", {
function (args) { function (args) {
modules.commandline.commandOutput( modules.commandline.commandOutput(
["div", { highlight: "Completions" }, ["div", { highlight: "Completions" },
template_.completionRow(["Context", "Title"], "CompTitle"), template.completionRow(["Context", "Title"], "CompTitle"),
template_.map(completion.contextList || [], template.map(completion.contextList || [],
function (item) template_.completionRow(item, "CompItem"))]); function (item) template.completionRow(item, "CompItem"))]);
}, },
{ {
argCount: "*", argCount: "*",

View File

@@ -13,7 +13,7 @@ lazyRequire("commands", ["ArgType", "CommandOption", "commands"]);
lazyRequire("options", ["Option"]); lazyRequire("options", ["Option"]);
lazyRequire("overlay", ["overlay"]); lazyRequire("overlay", ["overlay"]);
lazyRequire("storage", ["File"]); lazyRequire("storage", ["File"]);
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
var Const = function Const(val) Class.Property({ enumerable: true, value: val }); var Const = function Const(val) Class.Property({ enumerable: true, value: val });
@@ -79,7 +79,7 @@ var Group = Class("Group", {
toString: function () this.filters.join(","), toString: function () this.filters.join(","),
toJSONXML: function (modules) let (uri = modules && modules.buffer.uri) toJSONXML: function (modules) let (uri = modules && modules.buffer.uri)
template_.map(this.filters, template.map(this.filters,
function (f) ["span", { highlight: uri && f(uri) ? "Filter" : "" }, function (f) ["span", { highlight: uri && f(uri) ? "Filter" : "" },
"toJSONXML" in f ? f.toJSONXML() : String(f)], "toJSONXML" in f ? f.toJSONXML() : String(f)],
","), ","),

View File

@@ -11,7 +11,7 @@ defineModule("dom", {
lazyRequire("highlight", ["highlight"]); lazyRequire("highlight", ["highlight"]);
lazyRequire("messages", ["_"]); lazyRequire("messages", ["_"]);
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
var XBL = Namespace("xbl", "http://www.mozilla.org/xbl"); var XBL = Namespace("xbl", "http://www.mozilla.org/xbl");
var XHTML = Namespace("html", "http://www.w3.org/1999/xhtml"); var XHTML = Namespace("html", "http://www.w3.org/1999/xhtml");
@@ -579,7 +579,7 @@ var DOM = Class("DOM", {
res.push(["span", { highlight: "HelpXML" }, res.push(["span", { highlight: "HelpXML" },
["span", { highlight: "HelpXMLTagStart" }, ["span", { highlight: "HelpXMLTagStart" },
"<", namespaced(elem), " ", "<", namespaced(elem), " ",
template_.map(array.iterValues(elem.attributes), template.map(array.iterValues(elem.attributes),
function (attr) [ function (attr) [
["span", { highlight: "HelpXMLAttribute" }, namespaced(attr)], ["span", { highlight: "HelpXMLAttribute" }, namespaced(attr)],
["span", { highlight: "HelpXMLString" }, attr.value] ["span", { highlight: "HelpXMLString" }, attr.value]
@@ -603,7 +603,7 @@ var DOM = Class("DOM", {
res.push({}.toString.call(elem)); res.push({}.toString.call(elem));
} }
}, this); }, this);
res = template_.map(res, util.identity, ","); res = template.map(res, util.identity, ",");
return color ? res : res.join(""); return color ? res : res.join("");
}, },

View File

@@ -11,7 +11,7 @@ defineModule("help", {
lazyRequire("completion", ["completion"]); lazyRequire("completion", ["completion"]);
lazyRequire("overlay", ["overlay"]); lazyRequire("overlay", ["overlay"]);
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
var HelpBuilder = Class("HelpBuilder", { var HelpBuilder = Class("HelpBuilder", {
init: function init() { init: function init() {
@@ -166,7 +166,7 @@ var Help = Module("Help", {
if (level == 0 && /^.*:\n$/.test(match.par)) { if (level == 0 && /^.*:\n$/.test(match.par)) {
let text = par.slice(0, -1); let text = par.slice(0, -1);
res.push(["h2", { tag: "news-" + text }, res.push(["h2", { tag: "news-" + text },
template_.linkifyHelp(text, true)]); template.linkifyHelp(text, true)]);
} }
else { else {
let [, a, b] = /^(IMPORTANT:?)?([^]*)/.exec(par); let [, a, b] = /^(IMPORTANT:?)?([^]*)/.exec(par);
@@ -174,7 +174,7 @@ var Help = Module("Help", {
res.push(["p", { "dactyl:highlight": group + " HelpNews" }, res.push(["p", { "dactyl:highlight": group + " HelpNews" },
!tags.length ? "" : ["hl", { key: "HelpNewsTag" }, tags.join(" ")], !tags.length ? "" : ["hl", { key: "HelpNewsTag" }, tags.join(" ")],
a ? ["hl", { key: "HelpWarning" }, a] : "", a ? ["hl", { key: "HelpWarning" }, a] : "",
template_.linkifyHelp(b, true)]); template.linkifyHelp(b, true)]);
} }
} }
i++; i++;

View File

@@ -10,7 +10,7 @@ defineModule("highlight", {
}); });
lazyRequire("styles", ["Styles", "styles"]); lazyRequire("styles", ["Styles", "styles"]);
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
var Highlight = Struct("class", "selector", "sites", var Highlight = Struct("class", "selector", "sites",
"defaultExtends", "defaultValue", "defaultExtends", "defaultValue",
@@ -346,13 +346,13 @@ var Highlights = Module("Highlight", {
if (!modify) if (!modify)
modules.commandline.commandOutput( modules.commandline.commandOutput(
template_.tabular(["Key", "Sample", "Link", "CSS"], template.tabular(["Key", "Sample", "Link", "CSS"],
["padding: 0 1em 0 0; vertical-align: top; max-width: 16em; overflow: hidden;", ["padding: 0 1em 0 0; vertical-align: top; max-width: 16em; overflow: hidden;",
"text-align: center"], "text-align: center"],
([h.class, ([h.class,
["span", { style: "text-align: center; line-height: 1em;" + h.value + style }, "XXX"], ["span", { style: "text-align: center; line-height: 1em;" + h.value + style }, "XXX"],
template_.map(h.extends, function (s) template_.highlight(s), ","), template.map(h.extends, function (s) template.highlight(s), ","),
template_.highlightRegexp(h.value, /\b[-\w]+(?=:)|\/\*.*?\*\//g, template.highlightRegexp(h.value, /\b[-\w]+(?=:)|\/\*.*?\*\//g,
function (match) ["span", { highlight: match[0] == "/" ? "Comment" : "Key" }, match]) function (match) ["span", { highlight: match[0] == "/" ? "Comment" : "Key" }, match])
] ]
for (h in highlight) for (h in highlight)

View File

@@ -18,7 +18,7 @@ lazyRequire("config", ["config"]);
lazyRequire("contexts", ["Contexts", "contexts"]); lazyRequire("contexts", ["Contexts", "contexts"]);
lazyRequire("storage", ["File", "storage"]); lazyRequire("storage", ["File", "storage"]);
lazyRequire("styles", ["styles"]); lazyRequire("styles", ["styles"]);
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
// TODO: why are we passing around strings rather than file objects? // TODO: why are we passing around strings rather than file objects?
/** /**
@@ -865,7 +865,7 @@ unlet s:cpo_save
dactyl.echomsg(_("command.scriptnames.none")); dactyl.echomsg(_("command.scriptnames.none"));
else else
modules.commandline.commandOutput( modules.commandline.commandOutput(
template_.tabular(["<SNR>", "Filename"], ["text-align: right; padding-right: 1em;"], template.tabular(["<SNR>", "Filename"], ["text-align: right; padding-right: 1em;"],
([i + 1, file] for ([i, file] in Iterator(names))))); ([i + 1, file] for ([i, file] in Iterator(names)))));
}, },

View File

@@ -13,7 +13,7 @@ defineModule("javascript", {
require: ["util"] require: ["util"]
}); });
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
let isPrototypeOf = Object.prototype.isPrototypeOf; let isPrototypeOf = Object.prototype.isPrototypeOf;
@@ -354,7 +354,7 @@ var JavaScript = Module("javascript", {
if (!compl) { if (!compl) {
base.process[1] = function highlight(item, v) base.process[1] = function highlight(item, v)
template_.highlight(typeof v == "xml" ? new String(v.toXMLString()) : v, true, 200); template.highlight(typeof v == "xml" ? new String(v.toXMLString()) : v, true, 200);
// Sort in a logical fashion for object keys: // Sort in a logical fashion for object keys:
// Numbers are sorted as numbers, rather than strings, and appear first. // Numbers are sorted as numbers, rather than strings, and appear first.
@@ -490,7 +490,7 @@ var JavaScript = Module("javascript", {
if (callable(func)) { if (callable(func)) {
let [, prefix, args] = /^(function .*?)\((.*?)\)/.exec(Function.prototype.toString.call(func)); let [, prefix, args] = /^(function .*?)\((.*?)\)/.exec(Function.prototype.toString.call(func));
let n = this._get(i).comma.length; let n = this._get(i).comma.length;
args = template_.map(Iterator(args.split(", ")), args = template.map(Iterator(args.split(", ")),
function ([i, arg]) ["span", { highlight: i == n ? "Filter" : "" }, arg], function ([i, arg]) ["span", { highlight: i == n ? "Filter" : "" }, arg],
",\u00a0"); ",\u00a0");
this.context.message = ["", prefix + "(", args, ")"]; this.context.message = ["", prefix + "(", args, ")"];

View File

@@ -19,7 +19,7 @@ lazyRequire("commands", ["Commands"]);
lazyRequire("completion", ["CompletionContext"]); lazyRequire("completion", ["CompletionContext"]);
lazyRequire("prefs", ["prefs"]); lazyRequire("prefs", ["prefs"]);
lazyRequire("styles", ["Styles"]); lazyRequire("styles", ["Styles"]);
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
/** @scope modules */ /** @scope modules */
@@ -874,18 +874,18 @@ var Options = Module("options", {
} }
else if (isArray(opt.value) && opt.type != "charlist") else if (isArray(opt.value) && opt.type != "charlist")
option.value = ["", "=", option.value = ["", "=",
template_.map(opt.value, template.map(opt.value,
function (v) template_.highlight(String(v)), function (v) template.highlight(String(v)),
["", ",", ["", ",",
["span", { style: "width: 0; display: inline-block" }, " "]])]; ["span", { style: "width: 0; display: inline-block" }, " "]])];
else else
option.value = ["", "=", template_.highlight(opt.stringValue)]; option.value = ["", "=", template.highlight(opt.stringValue)];
yield option; yield option;
} }
}; };
modules.commandline.commandOutput( modules.commandline.commandOutput(
template_.options("Options", opts.call(this), this["verbose"] > 0)); template.options("Options", opts.call(this), this["verbose"] > 0));
}, },
cleanup: function cleanup() { cleanup: function cleanup() {
@@ -1082,7 +1082,7 @@ var Options = Module("options", {
? ["span", { highlight: "URLExtra" }, ? ["span", { highlight: "URLExtra" },
"(" + _("option.bufferLocal") + ")"] "(" + _("option.bufferLocal") + ")"]
: "", : "",
template_.linkifyHelp(opt.description) template.linkifyHelp(opt.description)
], ],
help: function (opt) "'" + opt.name + "'" help: function (opt) "'" + opt.name + "'"
} }

View File

@@ -14,7 +14,7 @@ defineModule("prefs", {
}); });
lazyRequire("messages", ["_"]); lazyRequire("messages", ["_"]);
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
var Prefs = Module("prefs", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference]), { var Prefs = Module("prefs", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference]), {
ORIGINAL: "extensions.dactyl.original.", ORIGINAL: "extensions.dactyl.original.",
@@ -169,7 +169,7 @@ var Prefs = Module("prefs", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
if (saved == null && curval != defval || saved != null && curval != saved) { if (saved == null && curval != defval || saved != null && curval != saved) {
let msg = _("pref.safeSet.warnChanged", name); let msg = _("pref.safeSet.warnChanged", name);
if (message) if (message)
msg = template_.linkifyHelp(msg + " " + message); msg = template.linkifyHelp(msg + " " + message);
util.dactyl.warn(msg); util.dactyl.warn(msg);
} }
}, },
@@ -404,7 +404,7 @@ var Prefs = Module("prefs", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
let option = { let option = {
isDefault: !userValue, isDefault: !userValue,
default: this.defaults.get(pref, null), default: this.defaults.get(pref, null),
value: ["", "=", template_.highlight(value, true, 100)], value: ["", "=", template.highlight(value, true, 100)],
name: pref, name: pref,
pre: "\u00a0\u00a0" // Unicode nonbreaking space. pre: "\u00a0\u00a0" // Unicode nonbreaking space.
}; };
@@ -413,7 +413,7 @@ var Prefs = Module("prefs", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
} }
}; };
return template_.options(_("pref.hostPreferences", config.host), prefs.call(this)); return template.options(_("pref.hostPreferences", config.host), prefs.call(this));
}, },
}, { }, {
}, { }, {

View File

@@ -20,7 +20,7 @@ defineModule("sanitizer", {
lazyRequire("messages", ["_"]); lazyRequire("messages", ["_"]);
lazyRequire("overlay", ["overlay"]); lazyRequire("overlay", ["overlay"]);
lazyRequire("storage", ["storage"]); lazyRequire("storage", ["storage"]);
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
let tmp = Object.create(this); let tmp = Object.create(this);
JSMLoader.loadSubScript("chrome://browser/content/sanitize.js", tmp); JSMLoader.loadSubScript("chrome://browser/content/sanitize.js", tmp);
@@ -168,7 +168,7 @@ var Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakRef
before: [ before: [
["preferences", { id: branch.substr(Item.PREFIX.length) + "history", ["preferences", { id: branch.substr(Item.PREFIX.length) + "history",
xmlns: "xul" }, xmlns: "xul" },
template_.map(ourItems(persistent), function (item) template.map(ourItems(persistent), function (item)
["preference", { type: "bool", id: branch + item.name, name: branch + item.name }])] ["preference", { type: "bool", id: branch + item.name, name: branch + item.name }])]
], ],
init: function init(win) { init: function init(win) {
@@ -194,9 +194,9 @@ var Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakRef
["column", { flex: "1" }]], ["column", { flex: "1" }]],
["rows", {}, ["rows", {},
let (items = ourItems(true)) let (items = ourItems(true))
template_.map(util.range(0, Math.ceil(items.length / 2)), function (i) template.map(util.range(0, Math.ceil(items.length / 2)), function (i)
["row", {}, ["row", {},
template_.map(items.slice(i * 2, i * 2 + 2), function (item) template.map(items.slice(i * 2, i * 2 + 2), function (item)
["checkbox", { xmlns: XUL, label: item.description, preference: branch + item.name }])])]]], ["checkbox", { xmlns: XUL, label: item.description, preference: branch + item.name }])])]]],
} }
})); }));
@@ -208,7 +208,7 @@ var Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakRef
itemList: [ itemList: [
["listitem", { xmlns: "xul", label: /*L*/"See :help privacy for the following:", ["listitem", { xmlns: "xul", label: /*L*/"See :help privacy for the following:",
disabled: "true", style: "font-style: italic; font-weight: bold;" }], disabled: "true", style: "font-style: italic; font-weight: bold;" }],
template_.map(ourItems(), function ([item, desc]) template.map(ourItems(), function ([item, desc])
["listitem", { xmlns: "xul", preference: branch + item, ["listitem", { xmlns: "xul", preference: branch + item,
type: "checkbox", label: config.appName + ", " + desc, type: "checkbox", label: config.appName + ", " + desc,
onsyncfrompreference: "return gSanitizePromptDialog.onReadGeneric();" }]), onsyncfrompreference: "return gSanitizePromptDialog.onReadGeneric();" }]),
@@ -524,7 +524,7 @@ var Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakRef
return; return;
case "list": case "list":
modules.commandline.commandOutput(template_.tabular( modules.commandline.commandOutput(template.tabular(
["Host", "Expiry (UTC)", "Path", "Name", "Value"], ["Host", "Expiry (UTC)", "Path", "Name", "Value"],
["padding-right: 1em", "padding-right: 1em", "padding-right: 1em", "max-width: 12em; overflow: hidden;", "padding-left: 1ex;"], ["padding-right: 1em", "padding-right: 1em", "padding-right: 1em", "max-width: 12em; overflow: hidden;", "padding-left: 1ex;"],
([c.host, ([c.host,

View File

@@ -10,7 +10,7 @@ defineModule("styles", {
}); });
lazyRequire("contexts", ["Contexts"]); lazyRequire("contexts", ["Contexts"]);
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
function cssUri(css) "chrome-data:text/css," + encodeURI(css); function cssUri(css) "chrome-data:text/css," + encodeURI(css);
var namespace = "@namespace html " + XHTML.uri.quote() + ";\n" + var namespace = "@namespace html " + XHTML.uri.quote() + ";\n" +
@@ -35,7 +35,7 @@ Sheet.liveProperty("css");
Sheet.liveProperty("sites"); Sheet.liveProperty("sites");
update(Sheet.prototype, { update(Sheet.prototype, {
formatSites: function (uris) formatSites: function (uris)
template_.map(this.sites, template.map(this.sites,
function (filter) ["span", { highlight: uris.some(Styles.matchFilter(filter)) ? "Filter" : "" }, filter], function (filter) ["span", { highlight: uris.some(Styles.matchFilter(filter)) ? "Filter" : "" }, filter],
","), ","),
@@ -327,9 +327,9 @@ var Styles = Module("Styles", {
["col", { style: "min-width: 1em; text-align: center; color: red; font-weight: bold;" }], ["col", { style: "min-width: 1em; text-align: center; color: red; font-weight: bold;" }],
["col", { style: "padding: 0 1em 0 1ex; vertical-align: top;" }], ["col", { style: "padding: 0 1em 0 1ex; vertical-align: top;" }],
["col", { style: "padding: 0 1em 0 0; vertical-align: top;" }], ["col", { style: "padding: 0 1em 0 0; vertical-align: top;" }],
template_.map(hives, function (hive) let (i = 0) [ template.map(hives, function (hive) let (i = 0) [
["tr", { style: "height: .5ex;" }], ["tr", { style: "height: .5ex;" }],
template_.map(sheets(hive), function (sheet) template.map(sheets(hive), function (sheet)
["tr", {}, ["tr", {},
["td", { highlight: "Title" }, !i++ ? hive.name : ""], ["td", { highlight: "Title" }, !i++ ? hive.name : ""],
["td", {}, sheet.enabled ? "" : UTF8("×")], ["td", {}, sheet.enabled ? "" : UTF8("×")],
@@ -744,19 +744,19 @@ var Styles = Module("Styles", {
return this.highlightRegexp(css, patterns.property, function (match) { return this.highlightRegexp(css, patterns.property, function (match) {
if (!match.length) if (!match.length)
return []; return [];
return ["", match.preSpace, template_.filter(match.name), ": ", return ["", match.preSpace, template.filter(match.name), ": ",
template_.highlightRegexp(match.value, patterns.token, function (match) { template.highlightRegexp(match.value, patterns.token, function (match) {
if (match.function) if (match.function)
return ["", template_.filter(match.word), return ["", template.filter(match.word),
template_.highlightRegexp(match.function, patterns.string, template.highlightRegexp(match.function, patterns.string,
function (match) ["span", { highlight: "String" }, match.string]) function (match) ["span", { highlight: "String" }, match.string])
]; ];
if (match.important == "!important") if (match.important == "!important")
return ["span", { highlight: "String" }, match.important]; return ["span", { highlight: "String" }, match.important];
if (match.string) if (match.string)
return ["span", { highlight: "String" }, match.string]; return ["span", { highlight: "String" }, match.string];
return template.highlightRegexp(match.wholeMatch, /^(\d+)(em|ex|px|in|cm|mm|pt|pc)?/g, return template._highlightRegexp(match.wholeMatch, /^(\d+)(em|ex|px|in|cm|mm|pt|pc)?/g,
function (m, n, u) [ function (m, n, u) [
["span", { highlight: "Number" }, n], ["span", { highlight: "Number" }, n],
["span", { highlight: "Object" }, u || ""] ["span", { highlight: "Object" }, u || ""]

View File

@@ -2,18 +2,16 @@
// //
// This work is licensed for reuse under an MIT license. Details are // This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file. // given in the LICENSE.txt file included with this file.
/* use strict */ "use strict";
let global = this; let global = this;
defineModule("template", { defineModule("template", {
exports: ["Binding", "Template", "template", "template_"], exports: ["Binding", "Template", "template"],
require: ["util"] require: ["util"]
}); });
lazyRequire("help", ["help"]); lazyRequire("help", ["help"]);
default xml namespace = XHTML;
var Binding = Class("Binding", { var Binding = Class("Binding", {
init: function (node, nodes) { init: function (node, nodes) {
this.node = node; this.node = node;
@@ -93,27 +91,6 @@ var Binding = Class("Binding", {
}); });
var Template = Module("Template", { var Template = Module("Template", {
add: function add(a, b) a + b,
join: function join(c) function (a, b) a + c + b,
map: function map(iter, func, sep, interruptable) {
XML.ignoreWhitespace = XML.prettyPrinting = false;
if (typeof iter.length == "number") // FIXME: Kludge?
iter = array.iterValues(iter);
let res = <></>;
let n = 0;
for each (let i in Iterator(iter)) {
let val = func(i, n);
if (val == undefined)
continue;
if (n++ && sep)
res += sep;
if (interruptable && n % interruptable == 0)
util.threadYield(true, true);
res += val;
}
return res;
},
bindings: { bindings: {
Button: Class("Button", Binding, { Button: Class("Button", Binding, {
@@ -172,388 +149,6 @@ var Template = Module("Template", {
}) })
}, },
bookmarkDescription: function (item, text)
<>
{
!(item.extra && item.extra.length) ? "" :
<span highlight="URLExtra">
({
template.map(item.extra, function (e)
<>{e[0]}: <span highlight={e[2]}>{e[1]}</span></>,
<>&#xa0;</>)
})&#xa0;</span>
}
<a xmlns:dactyl={NS} identifier={item.id == null ? "" : item.id} dactyl:command={item.command || ""}
href={item.item.url} highlight="URL">{text || ""}</a>
</>,
filter: function (str) <span highlight="Filter">{str}</span>,
completionRow: function completionRow(item, highlightGroup) {
if (typeof icon == "function")
icon = icon();
if (highlightGroup) {
var text = item[0] || "";
var desc = item[1] || "";
}
else {
var text = this.processor[0].call(this, item, item.result);
var desc = this.processor[1].call(this, item, item.description);
}
return ["div", { highlight: highlightGroup || "CompItem", style: "white-space: nowrap" },
/* The non-breaking spaces prevent empty elements
* from pushing the baseline down and enlarging
* the row.
*/
["li", { highlight: "CompResult " + item.highlight },
text, "\u00a0"],
["li", { highlight: "CompDesc" },
desc, "\u00a0"]];
},
helpLink: function (token, text, type) {
if (!help.initialized)
util.dactyl.initHelp();
let topic = token; // FIXME: Evil duplication!
if (/^\[.*\]$/.test(topic))
topic = topic.slice(1, -1);
else if (/^n_/.test(topic))
topic = topic.slice(2);
if (help.initialized && !Set.has(help.tags, topic))
return <span highlight={type || ""}>{text || token}</span>;
XML.ignoreWhitespace = XML.prettyPrinting = false;
type = type || (/^'.*'$/.test(token) ? "HelpOpt" :
/^\[.*\]$|^E\d{3}$/.test(token) ? "HelpTopic" :
/^:\w/.test(token) ? "HelpEx" : "HelpKey");
return <a highlight={"InlineHelpLink " + type} tag={topic} href={"dactyl://help-tag/" + topic} dactyl:command="dactyl.help" xmlns:dactyl={NS}>{text || topic}</a>;
},
HelpLink: function (token) {
if (!help.initialized)
util.dactyl.initHelp();
let topic = token; // FIXME: Evil duplication!
if (/^\[.*\]$/.test(topic))
topic = topic.slice(1, -1);
else if (/^n_/.test(topic))
topic = topic.slice(2);
if (help.initialized && !Set.has(help.tags, topic))
return <>{token}</>;
XML.ignoreWhitespace = XML.prettyPrinting = false;
let tag = (/^'.*'$/.test(token) ? "o" :
/^\[.*\]$|^E\d{3}$/.test(token) ? "t" :
/^:\w/.test(token) ? "ex" : "k");
topic = topic.replace(/^'(.*)'$/, "$1");
return <{tag} xmlns={NS}>{topic}</{tag}>;
},
linkifyHelp: function linkifyHelp(str, help) {
let re = util.regexp(literal(/*
(?P<pre> [/\s]|^)
(?P<tag> '[\w-]+' | :(?:[\w-]+!?|!) | (?:._)?<[\w-]+>\w* | \b[a-zA-Z]_(?:[\w[\]]+|.) | \[[\w-;]+\] | E\d{3} )
(?= [[\)!,:;./\s]|$)
*/), "gx");
return this.highlightSubstrings(str, (function () {
for (let res in re.iterate(str))
yield [res.index + res.pre.length, res.tag.length];
})(), template[help ? "HelpLink" : "helpLink"]);
},
// Fixes some strange stack rewinds on NS_ERROR_OUT_OF_MEMORY
// exceptions that we can't catch.
stringify: function stringify(arg) {
if (!callable(arg))
return String(arg);
try {
this._sandbox.arg = arg;
return Cu.evalInSandbox("String(arg)", this._sandbox);
}
finally {
this._sandbox.arg = null;
}
},
_sandbox: Class.Memoize(function () Cu.Sandbox(Cu.getGlobalForObject(global),
{ wantXrays: false })),
// if "processStrings" is true, any passed strings will be surrounded by " and
// any line breaks are displayed as \n
highlight: function highlight(arg, processStrings, clip, bw) {
XML.ignoreWhitespace = XML.prettyPrinting = false;
// some objects like window.JSON or getBrowsers()._browsers need the try/catch
try {
let str = this.stringify(arg);
if (clip)
str = util.clip(str, clip);
switch (arg == null ? "undefined" : typeof arg) {
case "number":
return <span highlight="Number">{str}</span>;
case "string":
if (processStrings)
str = str.quote();
return <span highlight="String">{str}</span>;
case "boolean":
return <span highlight="Boolean">{str}</span>;
case "function":
if (arg instanceof Ci.nsIDOMElement) // wtf?
return util.objectToString(arg, !bw);
str = str.replace("/* use strict */ \n", "/* use strict */ ");
if (processStrings)
return <span highlight="Function">{str.replace(/\{(.|\n)*(?:)/g, "{ ... }")}</span>;
<>}</>; /* Vim */
arg = String(arg).replace("/* use strict */ \n", "/* use strict */ ");
return <>{arg}</>;
case "undefined":
return <span highlight="Null">{arg}</span>;
case "object":
if (arg instanceof Ci.nsIDOMElement)
return util.objectToString(arg, !bw);
if (arg instanceof util.Magic)
return <>{arg}</>;
// for java packages value.toString() would crash so badly
// that we cannot even try/catch it
if (/^\[JavaPackage.*\]$/.test(arg))
return <>[JavaPackage]</>;
if (processStrings && false)
str = template.highlightFilter(str, "\n", function () <span highlight="NonText">^J</span>);
return <span highlight="Object">{str}</span>;
case "xml":
return arg;
default:
return <![CDATA[<unknown type>]]>;
}
}
catch (e) {
return <![CDATA[<unknown>]]>;
}
},
highlightFilter: function highlightFilter(str, filter, highlight, isURI) {
if (isURI)
str = util.losslessDecodeURI(str);
return this.highlightSubstrings(str, (function () {
if (filter.length == 0)
return;
XML.ignoreWhitespace = XML.prettyPrinting = false;
let lcstr = String.toLowerCase(str);
let lcfilter = filter.toLowerCase();
let start = 0;
while ((start = lcstr.indexOf(lcfilter, start)) > -1) {
yield [start, filter.length];
start += filter.length;
}
})(), highlight || template.filter);
},
highlightRegexp: function highlightRegexp(str, re, highlight) {
return this.highlightSubstrings(str, (function () {
for (let res in util.regexp.iterate(re, str))
yield [res.index, res[0].length, res.wholeMatch ? [res] : res];
})(), highlight || template.filter);
},
highlightSubstrings: function highlightSubstrings(str, iter, highlight) {
XML.ignoreWhitespace = XML.prettyPrinting = false;
if (typeof str == "xml")
return str;
if (str == "")
return <>{str}</>;
str = String(str).replace(" ", "\u00a0");
let s = <></>;
let start = 0;
let n = 0, _i;
for (let [i, length, args] in iter) {
if (i == _i || i < _i)
break;
_i = i;
XML.ignoreWhitespace = false;
s += <>{str.substring(start, i)}</>;
s += highlight.apply(this, Array.concat(args || str.substr(i, length)));
start = i + length;
}
return s + <>{str.substr(start)}</>;
},
highlightURL: function highlightURL(str, force) {
if (force || /^[a-zA-Z]+:\/\//.test(str))
return <a highlight="URL" href={str}>{util.losslessDecodeURI(str)}</a>;
else
return str;
},
icon: function (item, text) <>
<span highlight="CompIcon">{item.icon ? <img src={item.icon}/> : <></>}</span><span class="td-strut"/>{text}
</>,
jumps: function jumps(index, elems) {
XML.ignoreWhitespace = XML.prettyPrinting = false;
// <e4x>
return <table>
<tr style="text-align: left;" highlight="Title">
<th colspan="2">{_("title.Jump")}</th>
<th>{_("title.HPos")}</th>
<th>{_("title.VPos")}</th>
<th>{_("title.Title")}</th>
<th>{_("title.URI")}</th>
</tr>
{
this.map(Iterator(elems), function ([idx, val])
<tr>
<td class="indicator">{idx == index ? ">" : ""}</td>
<td>{Math.abs(idx - index)}</td>
<td>{val.offset ? val.offset.x : ""}</td>
<td>{val.offset ? val.offset.y : ""}</td>
<td style="width: 250px; max-width: 500px; overflow: hidden;">{val.title}</td>
<td><a href={val.URI.spec} highlight="URL jump-list">{util.losslessDecodeURI(val.URI.spec)}</a></td>
</tr>)
}
</table>;
// </e4x>
},
options: function options(title, opts, verbose) {
XML.ignoreWhitespace = XML.prettyPrinting = false;
// <e4x>
return <table>
<tr highlight="Title" align="left">
<th>--- {title} ---</th>
</tr>
{
this.map(opts, function (opt)
<tr>
<td>
<div highlight="Message"
><span style={opt.isDefault ? "" : "font-weight: bold"}>{opt.pre}{opt.name}</span><span>{opt.value}</span>{
opt.isDefault || opt.default == null ? "" : <span class="extra-info"> (default: {opt.default})</span>
}</div>{
verbose && opt.setFrom ? <div highlight="Message"> Last set from {template.sourceLink(opt.setFrom)}</div> : <></>
}
</td>
</tr>)
}
</table>;
// </e4x>
},
sourceLink: function (frame) {
let url = util.fixURI(frame.filename || "unknown");
let path = util.urlPath(url);
XML.ignoreWhitespace = XML.prettyPrinting = false;
return <a xmlns:dactyl={NS} dactyl:command="buffer.viewSource"
href={url} path={path} line={frame.lineNumber}
highlight="URL">{
path + ":" + frame.lineNumber
}</a>;
},
table: function table(title, data, indent) {
XML.ignoreWhitespace = XML.prettyPrinting = false;
let table = // <e4x>
<table>
<tr highlight="Title" align="left">
<th colspan="2">{title}</th>
</tr>
{
this.map(data, function (datum)
<tr>
<td style={"font-weight: bold; min-width: 150px; padding-left: " + (indent || "2ex")}>{datum[0]}</td>
<td>{datum[1]}</td>
</tr>)
}
</table>;
// </e4x>
if (table.tr.length() > 1)
return table;
},
tabular: function tabular(headings, style, iter) {
// TODO: This might be mind-bogglingly slow. We'll see.
XML.ignoreWhitespace = XML.prettyPrinting = false;
// <e4x>
return <table>
<tr highlight="Title" align="left">
{
this.map(headings, function (h)
<th>{h}</th>)
}
</tr>
{
this.map(iter, function (row)
<tr>
{
template.map(Iterator(row), function ([i, d])
<td style={style[i] || ""}>{d}</td>)
}
</tr>)
}
</table>;
// </e4x>
},
usage: function usage(iter, format) {
XML.ignoreWhitespace = XML.prettyPrinting = false;
format = format || {};
let desc = format.description || function (item) template.linkifyHelp(item.description);
let help = format.help || function (item) item.name;
function sourceLink(frame) {
let source = template.sourceLink(frame);
source.@NS::hint = source.text();
return source;
}
// <e4x>
return <table>
{ format.headings ?
<thead highlight="UsageHead">
<tr highlight="Title" align="left">
{
this.map(format.headings, function (h) <th>{h}</th>)
}
</tr>
</thead> : ""
}
{ format.columns ?
<colgroup>
{
this.map(format.columns, function (c) <col style={c}/>)
}
</colgroup> : ""
}
<tbody highlight="UsageBody">{
this.map(iter, function (item)
<tr highlight="UsageItem">
<td style="padding-right: 2em;">
<span highlight="Usage Link">{
let (name = item.name || item.names[0], frame = item.definedAt)
!frame ? name :
template.helpLink(help(item), name, "Title") +
<span highlight="LinkInfo" xmlns:dactyl={NS}>{_("io.definedAt")} {sourceLink(frame)}</span>
}</span>
</td>
{ item.columns ? template.map(item.columns, function (c) <td>{c}</td>) : "" }
<td>{desc(item)}</td>
</tr>)
}</tbody>
</table>;
// </e4x>
}
});
var Template_ = Module("Template_", {
map: function map(iter, func, sep, interruptable) { map: function map(iter, func, sep, interruptable) {
if (typeof iter.length == "number") // FIXME: Kludge? if (typeof iter.length == "number") // FIXME: Kludge?
iter = array.iterValues(iter); iter = array.iterValues(iter);
@@ -626,7 +221,7 @@ var Template_ = Module("Template_", {
topic = topic.slice(2); topic = topic.slice(2);
if (help.initialized && !Set.has(help.tags, topic)) if (help.initialized && !Set.has(help.tags, topic))
return <span highlight={type || ""}>{text || token}</span>; return ["span", { highlight: type || ""}, text || token];
type = type || (/^'.*'$/.test(token) ? "HelpOpt" : type = type || (/^'.*'$/.test(token) ? "HelpOpt" :
/^\[.*\]$|^E\d{3}$/.test(token) ? "HelpTopic" : /^\[.*\]$|^E\d{3}$/.test(token) ? "HelpTopic" :

View File

@@ -15,7 +15,7 @@ defineModule("util", {
lazyRequire("overlay", ["overlay"]); lazyRequire("overlay", ["overlay"]);
lazyRequire("storage", ["File", "storage"]); lazyRequire("storage", ["File", "storage"]);
lazyRequire("template", ["template", "template_"]); lazyRequire("template", ["template"]);
var Magic = Class("Magic", { var Magic = Class("Magic", {
init: function init(str) { init: function init(str) {
@@ -987,7 +987,7 @@ var Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference]),
} }
if (color) { if (color) {
obj = template_.highlightFilter(util.clip(obj, 150), "\n", obj = template.highlightFilter(util.clip(obj, 150), "\n",
function () ["span", { highlight: "NonText" }, "^J"]); function () ["span", { highlight: "NonText" }, "^J"]);
var head = ["span", { highlight: "Title Object" }, obj, "::\n"]; var head = ["span", { highlight: "Title Object" }, obj, "::\n"];
} }
@@ -1029,7 +1029,7 @@ var Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference]),
i = ""; i = "";
if (color) if (color)
value = template_.highlight(value, true, 150, !color); value = template.highlight(value, true, 150, !color);
else else
value = util.clip(String(value).replace(/\n/g, "^J"), 150); value = util.clip(String(value).replace(/\n/g, "^J"), 150);
@@ -1053,7 +1053,7 @@ var Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference]),
return String.localeCompare(a[0], b[0]); return String.localeCompare(a[0], b[0]);
} }
let vals = template_.map(keys.sort(compare), function (f) f[1], "\n"); let vals = template.map(keys.sort(compare), function (f) f[1], "\n");
if (color) { if (color) {
return ["div", { style: "white-space: pre-wrap" }, head, vals]; return ["div", { style: "white-space: pre-wrap" }, head, vals];
} }