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

with (liberator)

This commit is contained in:
Kris Maglione
2008-10-13 00:50:03 +00:00
parent 45a1334cc0
commit cd0fb01dd4
21 changed files with 2024 additions and 2046 deletions

View File

@@ -26,7 +26,7 @@ the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL. the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/ }}} ***** END LICENSE BLOCK *****/
liberator.Addressbook = function () //{{{ with (liberator) liberator.Addressbook = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -71,9 +71,9 @@ liberator.Addressbook = function () //{{{
////////////////////// MAPPINGS //////////////////////////////////////////////// ////////////////////// MAPPINGS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
var modes = liberator.config.mailModes || [liberator.modes.NORMAL]; var myModes = config.mailModes || [modes.NORMAL];
liberator.mappings.add(modes, ["a"], mappings.add(myModes, ["a"],
"Open a prompt to save a new addressbook entry for the sender of the selected message", "Open a prompt to save a new addressbook entry for the sender of the selected message",
function () function ()
{ {
@@ -84,7 +84,7 @@ liberator.Addressbook = function () //{{{
} }
catch (e) catch (e)
{ {
liberator.beep(); beep();
} }
if (!to) if (!to)
@@ -104,14 +104,14 @@ liberator.Addressbook = function () //{{{
displayName = "-name=\"" + displayName.replace(/"/g, "") + "\""; displayName = "-name=\"" + displayName.replace(/"/g, "") + "\"";
} }
liberator.commandline.open(":", "contact " + address + " " + displayName, liberator.modes.EX); commandline.open(":", "contact " + address + " " + displayName, modes.EX);
}); });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// COMMANDS //////////////////////////////////////////////// ////////////////////// COMMANDS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.commands.add(["con[tact]"], commands.add(["con[tact]"],
"Add an address book entry", "Add an address book entry",
function (args) function (args)
{ {
@@ -122,22 +122,22 @@ liberator.Addressbook = function () //{{{
if (!displayName) if (!displayName)
displayName = generateDisplayName(firstName, lastName); displayName = generateDisplayName(firstName, lastName);
if (liberator.addressbook.add(mailAddr, firstName, lastName, displayName)) if (addressbook.add(mailAddr, firstName, lastName, displayName))
liberator.echo("Added address: " + displayName + " <" + mailAddr + ">", liberator.commandline.FORCE_SINGLELINE); echo("Added address: " + displayName + " <" + mailAddr + ">", commandline.FORCE_SINGLELINE);
else else
liberator.echoerr("Exxx: Could not add bookmark `" + mailAddr + "'", liberator.commandline.FORCE_SINGLELINE); echoerr("Exxx: Could not add bookmark `" + mailAddr + "'", commandline.FORCE_SINGLELINE);
}, },
{ {
argCount: "+", argCount: "+",
options: [[["-firstname", "-f"], liberator.commands.OPTION_STRING], options: [[["-firstname", "-f"], commands.OPTION_STRING],
[["-lastname", "-l"], liberator.commands.OPTION_STRING], [["-lastname", "-l"], commands.OPTION_STRING],
[["-name", "-n"], liberator.commands.OPTION_STRING]] [["-name", "-n"], commands.OPTION_STRING]]
}); });
liberator.commands.add(["contacts", "addr[essbook]"], commands.add(["contacts", "addr[essbook]"],
"List or open multiple addresses", "List or open multiple addresses",
function (args, special) { liberator.addressbook.list(args, special); }, function (args, special) { addressbook.list(args, special); },
{ bang: true }); { bang: true });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
@@ -189,7 +189,7 @@ liberator.Addressbook = function () //{{{
} }
if (addresses.length < 1) if (addresses.length < 1)
{ {
liberator.echoerr("E94: No matching contact for " + filter, liberator.commandline.FORCE_SINGLELINE); echoerr("E94: No matching contact for " + filter, commandline.FORCE_SINGLELINE);
return false; return false;
} }
@@ -201,21 +201,21 @@ liberator.Addressbook = function () //{{{
function (address) "\"" + address[0].replace(/"/g, "") + " <" + address[1] + ">\"" function (address) "\"" + address[0].replace(/"/g, "") + " <" + address[1] + ">\""
).join(", "); ).join(", ");
liberator.mail.composeNewMail(args); mail.composeNewMail(args);
} }
else else
{ {
var list = ":" + liberator.util.escapeHTML(liberator.commandline.getCommand()) + "<br/>" + var list = ":" + util.escapeHTML(commandline.getCommand()) + "<br/>" +
"<table><tr class=\"hl-Title\" align=\"left\"><th>Name</th><th>Address</th></tr>"; "<table><tr class=\"hl-Title\" align=\"left\"><th>Name</th><th>Address</th></tr>";
for (let i = 0; i < addresses.length; i++) for (let i = 0; i < addresses.length; i++)
{ {
var displayName = liberator.util.escapeHTML(liberator.util.clip(addresses[i][0], 50)); var displayName = util.escapeHTML(util.clip(addresses[i][0], 50));
var mailAddr = liberator.util.escapeHTML(addresses[i][1]); var mailAddr = util.escapeHTML(addresses[i][1]);
list += "<tr><td>" + displayName + "</td><td style=\"width: 100%\"><a href=\"#\" class=\"hl-URL\">" + mailAddr + "</a></td></tr>"; list += "<tr><td>" + displayName + "</td><td style=\"width: 100%\"><a href=\"#\" class=\"hl-URL\">" + mailAddr + "</a></td></tr>";
} }
list += "</table>"; list += "</table>";
liberator.commandline.echo(list, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
} }
return true; return true;
} }

View File

@@ -27,7 +27,7 @@ the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/ }}} ***** END LICENSE BLOCK *****/
// also includes methods for dealing with keywords and search engines // also includes methods for dealing with keywords and search engines
liberator.Bookmarks = function () //{{{ with (liberator) liberator.Bookmarks = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -43,8 +43,8 @@ liberator.Bookmarks = function () //{{{
const faviconService = Components.classes["@mozilla.org/browser/favicon-service;1"] const faviconService = Components.classes["@mozilla.org/browser/favicon-service;1"]
.getService(Components.interfaces.nsIFaviconService); .getService(Components.interfaces.nsIFaviconService);
const Bookmark = new liberator.util.Struct("url", "title", "icon", "keyword", "tags", "id"); const Bookmark = new util.Struct("url", "title", "icon", "keyword", "tags", "id");
const Keyword = new liberator.util.Struct("keyword", "title", "icon", "url"); const Keyword = new util.Struct("keyword", "title", "icon", "url");
const storage = liberator.storage; const storage = liberator.storage;
function Cache(name, store, serial) function Cache(name, store, serial)
@@ -100,7 +100,7 @@ liberator.Bookmarks = function () //{{{
this.load = function load() this.load = function load()
{ {
// liberator.dump("cache.load()\n"); // dump("cache.load()\n");
// update our bookmark cache // update our bookmark cache
bookmarks = []; bookmarks = [];
this.__defineGetter__("bookmarks", function () bookmarks); this.__defineGetter__("bookmarks", function () bookmarks);
@@ -141,7 +141,7 @@ liberator.Bookmarks = function () //{{{
onItemMoved: function () {}, onItemMoved: function () {},
onItemAdded: function (itemId, folder, index) onItemAdded: function (itemId, folder, index)
{ {
// liberator.dump("onItemAdded(" + itemId + ", " + folder + ", " + index + ")\n"); // dump("onItemAdded(" + itemId + ", " + folder + ", " + index + ")\n");
if (bookmarksService.getItemType(itemId) == bookmarksService.TYPE_BOOKMARK) if (bookmarksService.getItemType(itemId) == bookmarksService.TYPE_BOOKMARK)
{ {
if (rootFolders.indexOf(findRoot(itemId)) >= 0) if (rootFolders.indexOf(findRoot(itemId)) >= 0)
@@ -153,7 +153,7 @@ liberator.Bookmarks = function () //{{{
}, },
onItemRemoved: function (itemId, folder, index) onItemRemoved: function (itemId, folder, index)
{ {
// liberator.dump("onItemRemoved(" + itemId + ", " + folder + ", " + index + ")\n"); // dump("onItemRemoved(" + itemId + ", " + folder + ", " + index + ")\n");
if (deleteBookmark(itemId)) if (deleteBookmark(itemId))
storage.fireEvent(name, "remove", itemId); storage.fireEvent(name, "remove", itemId);
}, },
@@ -161,7 +161,7 @@ liberator.Bookmarks = function () //{{{
{ {
if (isAnnotation) if (isAnnotation)
return; return;
// liberator.dump("onItemChanged(" + itemId + ", " + property + ", " + value + ")\n"); // dump("onItemChanged(" + itemId + ", " + property + ", " + value + ")\n");
var bookmark = bookmarks.filter(function (item) item.id == itemId)[0]; var bookmark = bookmarks.filter(function (item) item.id == itemId)[0];
if (bookmark) if (bookmark)
{ {
@@ -186,18 +186,18 @@ liberator.Bookmarks = function () //{{{
let bookmarkObserver = function (key, event, arg) let bookmarkObserver = function (key, event, arg)
{ {
if (event == "add") if (event == "add")
liberator.autocommands.trigger("BookmarkAdd", arg); autocommands.trigger("BookmarkAdd", arg);
liberator.statusline.updateUrl(); statusline.updateUrl();
} }
var cache = liberator.storage.newObject("bookmark-cache", Cache, false); var cache = storage.newObject("bookmark-cache", Cache, false);
liberator.storage.addObserver("bookmark-cache", bookmarkObserver); storage.addObserver("bookmark-cache", bookmarkObserver);
liberator.registerObserver("shutdown", function () { registerObserver("shutdown", function () {
liberator.storage.removeObserver("bookmark-cache", bookmarkObserver) storage.removeObserver("bookmark-cache", bookmarkObserver)
}); });
liberator.registerObserver("enter", function () { registerObserver("enter", function () {
if (liberator.options["preload"]) if (options["preload"])
cache.bookmarks; // Forces a load, if not already loaded. cache.bookmarks; // Forces a load, if not already loaded.
}); });
@@ -205,18 +205,18 @@ liberator.Bookmarks = function () //{{{
////////////////////// OPTIONS ///////////////////////////////////////////////// ////////////////////// OPTIONS /////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.options.add(["defsearch", "ds"], options.add(["defsearch", "ds"],
"Set the default search engine", "Set the default search engine",
"string", "google", "string", "google",
{ {
completer: function (filter) liberator.completion.url("", "s")[1], completer: function (filter) completion.url("", "s")[1],
validator: function (value) validator: function (value)
{ {
return liberator.completion.url("", "s")[1].some(function (s) s[0] == value); return completion.url("", "s")[1].some(function (s) s[0] == value);
} }
}); });
liberator.options.add(["preload"], options.add(["preload"],
"Speed up first time history/bookmark completion", "Speed up first time history/bookmark completion",
"boolean", true); "boolean", true);
@@ -224,87 +224,87 @@ liberator.Bookmarks = function () //{{{
////////////////////// MAPPINGS //////////////////////////////////////////////// ////////////////////// MAPPINGS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
var modes = liberator.config.browserModes || [liberator.modes.NORMAL]; var myModes = config.browserModes || [modes.NORMAL];
liberator.mappings.add(modes, ["a"], mappings.add(myModes, ["a"],
"Open a prompt to bookmark the current URL", "Open a prompt to bookmark the current URL",
function () function ()
{ {
var title = ""; var title = "";
if (liberator.buffer.title != liberator.buffer.URL) if (buffer.title != buffer.URL)
title = " -title=\"" + liberator.buffer.title + "\""; title = " -title=\"" + buffer.title + "\"";
liberator.commandline.open(":", "bmark " + liberator.buffer.URL + title, liberator.modes.EX); commandline.open(":", "bmark " + buffer.URL + title, modes.EX);
}); });
liberator.mappings.add(modes, ["A"], mappings.add(myModes, ["A"],
"Toggle bookmarked state of current URL", "Toggle bookmarked state of current URL",
function () { liberator.bookmarks.toggle(liberator.buffer.URL); }); function () { bookmarks.toggle(buffer.URL); });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// COMMANDS //////////////////////////////////////////////// ////////////////////// COMMANDS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.commands.add(["ju[mps]"], commands.add(["ju[mps]"],
"Show jumplist", "Show jumplist",
function () function ()
{ {
var sh = getWebNavigation().sessionHistory; var sh = getWebNavigation().sessionHistory;
let entries = [sh.getEntryAtIndex(i, false) for (i in liberator.util.range(0, sh.count))]; let entries = [sh.getEntryAtIndex(i, false) for (i in util.range(0, sh.count))];
let list = liberator.template.jumps(sh.index, entries); let list = template.jumps(sh.index, entries);
liberator.commandline.echo(list, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
}, },
{ argCount: "0" }); { argCount: "0" });
liberator.commands.add(["bma[rk]"], commands.add(["bma[rk]"],
"Add a bookmark", "Add a bookmark",
function (args, special) function (args, special)
{ {
var url = args.arguments.length == 0 ? liberator.buffer.URL : args.arguments[0]; var url = args.arguments.length == 0 ? buffer.URL : args.arguments[0];
var title = args["-title"] || (args.arguments.length == 0 ? liberator.buffer.title : null); var title = args["-title"] || (args.arguments.length == 0 ? buffer.title : null);
var keyword = args["-keyword"] || null; var keyword = args["-keyword"] || null;
var tags = args["-tags"] || []; var tags = args["-tags"] || [];
if (liberator.bookmarks.add(false, title, url, keyword, tags, special)) if (bookmarks.add(false, title, url, keyword, tags, special))
{ {
var extra = ""; var extra = "";
if (title != url) if (title != url)
extra = " (" + title + ")"; extra = " (" + title + ")";
liberator.echo("Added bookmark: " + url + extra, liberator.commandline.FORCE_SINGLELINE); echo("Added bookmark: " + url + extra, commandline.FORCE_SINGLELINE);
} }
else else
liberator.echoerr("Exxx: Could not add bookmark `" + title + "'", liberator.commandline.FORCE_SINGLELINE); echoerr("Exxx: Could not add bookmark `" + title + "'", commandline.FORCE_SINGLELINE);
}, },
{ {
argCount: "?", argCount: "?",
bang: true, bang: true,
options: [[["-title", "-t"], liberator.commands.OPTION_STRING], options: [[["-title", "-t"], commands.OPTION_STRING],
[["-tags", "-T"], liberator.commands.OPTION_LIST], [["-tags", "-T"], commands.OPTION_LIST],
[["-keyword", "-k"], liberator.commands.OPTION_STRING, function (arg) /\w/.test(arg)]] [["-keyword", "-k"], commands.OPTION_STRING, function (arg) /\w/.test(arg)]]
}); });
liberator.commands.add(["bmarks"], commands.add(["bmarks"],
"List or open multiple bookmarks", "List or open multiple bookmarks",
function (args, special) function (args, special)
{ {
liberator.bookmarks.list(args.arguments.join(" "), args["-tags"] || [], special); bookmarks.list(args.arguments.join(" "), args["-tags"] || [], special);
}, },
{ {
bang: true, bang: true,
completer: function (filter) liberator.completion.bookmark(filter), completer: function (filter) completion.bookmark(filter),
options: [[["-tags", "-T"], liberator.commands.OPTION_LIST]] options: [[["-tags", "-T"], commands.OPTION_LIST]]
}); });
liberator.commands.add(["delbm[arks]"], commands.add(["delbm[arks]"],
"Delete a bookmark", "Delete a bookmark",
function (args) function (args)
{ {
let url = args || liberator.buffer.URL; let url = args || buffer.URL;
let deletedCount = liberator.bookmarks.remove(url); let deletedCount = bookmarks.remove(url);
liberator.echo(deletedCount + " bookmark(s) with url `" + url + "' deleted", liberator.commandline.FORCE_SINGLELINE); echo(deletedCount + " bookmark(s) with url `" + url + "' deleted", commandline.FORCE_SINGLELINE);
}, },
{ completer: function (filter) liberator.completion.bookmark(filter) }); { completer: function (filter) completion.bookmark(filter) });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// PUBLIC SECTION ////////////////////////////////////////// ////////////////////// PUBLIC SECTION //////////////////////////////////////////
@@ -319,7 +319,7 @@ liberator.Bookmarks = function () //{{{
{ {
if (bypassCache) // Is this really necessary anymore? if (bypassCache) // Is this really necessary anymore?
cache.load(); cache.load();
return liberator.completion.cached("bookmarks", filter, function () cache.bookmarks, return completion.cached("bookmarks", filter, function () cache.bookmarks,
"filterURLArray", tags); "filterURLArray", tags);
}, },
@@ -328,7 +328,7 @@ liberator.Bookmarks = function () //{{{
{ {
try try
{ {
var uri = liberator.util.createURI(url); var uri = util.createURI(url);
if (!force) if (!force)
{ {
for (let bmark in cache) for (let bmark in cache)
@@ -356,7 +356,7 @@ liberator.Bookmarks = function () //{{{
} }
catch (e) catch (e)
{ {
liberator.log(e, 0); log(e, 0);
return false; return false;
} }
@@ -371,16 +371,16 @@ liberator.Bookmarks = function () //{{{
var count = this.remove(url); var count = this.remove(url);
if (count > 0) if (count > 0)
{ {
liberator.commandline.echo("Removed bookmark: " + url, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_SINGLELINE); commandline.echo("Removed bookmark: " + url, commandline.HL_NORMAL, commandline.FORCE_SINGLELINE);
} }
else else
{ {
var title = liberator.buffer.title || url; var title = buffer.title || url;
var extra = ""; var extra = "";
if (title != url) if (title != url)
extra = " (" + title + ")"; extra = " (" + title + ")";
this.add(true, title, url); this.add(true, title, url);
liberator.commandline.echo("Added bookmark: " + url + extra, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_SINGLELINE); commandline.echo("Added bookmark: " + url + extra, commandline.HL_NORMAL, commandline.FORCE_SINGLELINE);
} }
}, },
@@ -415,12 +415,12 @@ liberator.Bookmarks = function () //{{{
} }
catch (e) catch (e)
{ {
liberator.log(e, 0); log(e, 0);
return i; return i;
} }
// update the display of our "bookmarked" symbol // update the display of our "bookmarked" symbol
liberator.statusline.updateUrl(); statusline.updateUrl();
return count.value; return count.value;
}, },
@@ -474,7 +474,7 @@ liberator.Bookmarks = function () //{{{
{ {
var url = null; var url = null;
var aPostDataRef = {}; var aPostDataRef = {};
var searchString = (useDefsearch? liberator.options["defsearch"] + " " : "") + text; var searchString = (useDefsearch? options["defsearch"] + " " : "") + text;
// we need to make sure our custom alias have been set, even if the user // we need to make sure our custom alias have been set, even if the user
// did not :open <tab> once before // did not :open <tab> once before
@@ -497,21 +497,21 @@ liberator.Bookmarks = function () //{{{
if (items.length == 0) if (items.length == 0)
{ {
if (filter.length > 0 && tags.length > 0) if (filter.length > 0 && tags.length > 0)
liberator.echoerr("E283: No bookmarks matching tags: \"" + tags + "\" and string: \"" + filter + "\""); echoerr("E283: No bookmarks matching tags: \"" + tags + "\" and string: \"" + filter + "\"");
else if (filter.length > 0) else if (filter.length > 0)
liberator.echoerr("E283: No bookmarks matching string: \"" + filter + "\""); echoerr("E283: No bookmarks matching string: \"" + filter + "\"");
else if (tags.length > 0) else if (tags.length > 0)
liberator.echoerr("E283: No bookmarks matching tags: \"" + tags + "\""); echoerr("E283: No bookmarks matching tags: \"" + tags + "\"");
else else
liberator.echoerr("No bookmarks set"); echoerr("No bookmarks set");
return; return;
} }
if (openItems) if (openItems)
return liberator.open([i.url for each (i in items)], liberator.NEW_TAB); return open([i.url for each (i in items)], NEW_TAB);
let list = liberator.template.bookmarks("title", ( let list = template.bookmarks("title", (
{ {
url: item.url, url: item.url,
title: item.title, title: item.title,
@@ -519,13 +519,13 @@ liberator.Bookmarks = function () //{{{
['tags', item.tags.join(', '), "hl-Tag"] ['tags', item.tags.join(', '), "hl-Tag"]
].filter(function (i) i[1]) ].filter(function (i) i[1])
} for each (item in items))); } for each (item in items)));
liberator.commandline.echo(list, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
}, },
}; };
//}}} //}}}
}; //}}} }; //}}}
liberator.History = function () //{{{ with (liberator) liberator.History = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -562,7 +562,7 @@ liberator.History = function () //{{{
for (let i = 0; i < rootNode.childCount; i++) for (let i = 0; i < rootNode.childCount; i++)
{ {
var node = rootNode.getChild(i); var node = rootNode.getChild(i);
// liberator.dump("History child " + node.itemId + ": " + node.title + " - " + node.type); // dump("History child " + node.itemId + ": " + node.title + " - " + node.type);
if (node.type == node.RESULT_TYPE_URI) // just make sure it's a bookmark if (node.type == node.RESULT_TYPE_URI) // just make sure it's a bookmark
history.push([node.uri, node.title || "[No title]", getIcon(node.uri)]); history.push([node.uri, node.title || "[No title]", getIcon(node.uri)]);
} }
@@ -571,8 +571,8 @@ liberator.History = function () //{{{
rootNode.containerOpen = false; rootNode.containerOpen = false;
} }
liberator.registerObserver("enter", function () { registerObserver("enter", function () {
if (liberator.options["preload"]) if (options["preload"])
load(); load();
}); });
@@ -580,39 +580,39 @@ liberator.History = function () //{{{
////////////////////// MAPPINGS //////////////////////////////////////////////// ////////////////////// MAPPINGS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
var modes = liberator.config.browserModes || [liberator.modes.NORMAL]; var myModes = config.browserModes || [modes.NORMAL];
liberator.mappings.add(modes, mappings.add(myModes,
["<C-o>"], "Go to an older position in the jump list", ["<C-o>"], "Go to an older position in the jump list",
function (count) { liberator.history.stepTo(-(count > 1 ? count : 1)); }, function (count) { history.stepTo(-(count > 1 ? count : 1)); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, mappings.add(myModes,
["<C-i>"], "Go to a newer position in the jump list", ["<C-i>"], "Go to a newer position in the jump list",
function (count) { liberator.history.stepTo(count > 1 ? count : 1); }, function (count) { history.stepTo(count > 1 ? count : 1); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, mappings.add(myModes,
["H", "<A-Left>", "<M-Left>"], "Go back in the browser history", ["H", "<A-Left>", "<M-Left>"], "Go back in the browser history",
function (count) { liberator.history.stepTo(-(count > 1 ? count : 1)); }, function (count) { history.stepTo(-(count > 1 ? count : 1)); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, mappings.add(myModes,
["L", "<A-Right>", "<M-Right>"], "Go forward in the browser history", ["L", "<A-Right>", "<M-Right>"], "Go forward in the browser history",
function (count) { liberator.history.stepTo(count > 1 ? count : 1); }, function (count) { history.stepTo(count > 1 ? count : 1); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// COMMANDS //////////////////////////////////////////////// ////////////////////// COMMANDS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.commands.add(["ba[ck]"], commands.add(["ba[ck]"],
"Go back in the browser history", "Go back in the browser history",
function (args, special, count) function (args, special, count)
{ {
if (special) if (special)
{ {
liberator.history.goToStart(); history.goToStart();
} }
else else
{ {
@@ -627,11 +627,11 @@ liberator.History = function () //{{{
return; return;
} }
} }
liberator.echoerr("Exxx: URL not found in history"); echoerr("Exxx: URL not found in history");
} }
else else
{ {
liberator.history.stepTo(count > 0 ? -1 * count : -1); history.stepTo(count > 0 ? -1 * count : -1);
} }
} }
}, },
@@ -646,7 +646,7 @@ liberator.History = function () //{{{
var entry = sh.getEntryAtIndex(i, false); var entry = sh.getEntryAtIndex(i, false);
var url = entry.URI.spec; var url = entry.URI.spec;
var title = entry.title; var title = entry.title;
if (liberator.completion.match([url, title], filter, false)) if (completion.match([url, title], filter, false))
completions.push([url, title]); completions.push([url, title]);
} }
return [0, completions]; return [0, completions];
@@ -654,13 +654,13 @@ liberator.History = function () //{{{
count: true count: true
}); });
liberator.commands.add(["fo[rward]", "fw"], commands.add(["fo[rward]", "fw"],
"Go forward in the browser history", "Go forward in the browser history",
function (args, special, count) function (args, special, count)
{ {
if (special) if (special)
{ {
liberator.history.goToEnd(); history.goToEnd();
} }
else else
{ {
@@ -675,11 +675,11 @@ liberator.History = function () //{{{
return; return;
} }
} }
liberator.echoerr("Exxx: URL not found in history"); echoerr("Exxx: URL not found in history");
} }
else else
{ {
liberator.history.stepTo(count > 0 ? count : 1); history.stepTo(count > 0 ? count : 1);
} }
} }
}, },
@@ -694,7 +694,7 @@ liberator.History = function () //{{{
var entry = sh.getEntryAtIndex(i, false); var entry = sh.getEntryAtIndex(i, false);
var url = entry.URI.spec; var url = entry.URI.spec;
var title = entry.title; var title = entry.title;
if (liberator.completion.match([url, title], filter, false)) if (completion.match([url, title], filter, false))
completions.push([url, title]); completions.push([url, title]);
} }
return [0, completions]; return [0, completions];
@@ -702,12 +702,12 @@ liberator.History = function () //{{{
count: true count: true
}); });
liberator.commands.add(["hist[ory]", "hs"], commands.add(["hist[ory]", "hs"],
"Show recently visited URLs", "Show recently visited URLs",
function (args, special) { liberator.history.list(args, special); }, function (args, special) { history.list(args, special); },
{ {
bang: true, bang: true,
completer: function (filter) liberator.completion.history(filter) completer: function (filter) completion.history(filter)
}); });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
@@ -723,7 +723,7 @@ liberator.History = function () //{{{
if (!filter) if (!filter)
return cachedHistory.concat(history); return cachedHistory.concat(history);
return liberator.completion.cached("history", filter, function () cachedHistory.concat(history), return completion.cached("history", filter, function () cachedHistory.concat(history),
"filterURLArray"); "filterURLArray");
}, },
@@ -751,7 +751,7 @@ liberator.History = function () //{{{
}, },
// TODO: better names? // TODO: better names?
// and move to liberator.buffer.? // and move to buffer.?
stepTo: function (steps) stepTo: function (steps)
{ {
var index = getWebNavigation().sessionHistory.index + steps; var index = getWebNavigation().sessionHistory.index + steps;
@@ -762,7 +762,7 @@ liberator.History = function () //{{{
} }
else else
{ {
liberator.beep(); beep();
} }
}, },
@@ -772,7 +772,7 @@ liberator.History = function () //{{{
if (index == 0) if (index == 0)
{ {
liberator.beep(); beep();
return; return;
} }
@@ -786,7 +786,7 @@ liberator.History = function () //{{{
if (index == max) if (index == max)
{ {
liberator.beep(); beep();
return; return;
} }
@@ -800,129 +800,129 @@ liberator.History = function () //{{{
if (items.length == 0) if (items.length == 0)
{ {
if (filter.length > 0) if (filter.length > 0)
liberator.echoerr("E283: No history matching \"" + filter + "\""); echoerr("E283: No history matching \"" + filter + "\"");
else else
liberator.echoerr("No history set"); echoerr("No history set");
return; return;
} }
if (openItems) if (openItems)
{ {
return liberator.open([i[0] for each (i in items)], liberator.NEW_TAB); return open([i[0] for each (i in items)], NEW_TAB);
} }
else else
{ {
let list = liberator.template.bookmarks("title", ( let list = template.bookmarks("title", (
{ {
title: item[1], title: item[1],
url: item[0], url: item[0],
} for each (item in items))); } for each (item in items)));
liberator.commandline.echo(list, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
} }
} }
}; };
//}}} //}}}
}; //}}} }; //}}}
liberator.QuickMarks = function () //{{{ with (liberator) liberator.QuickMarks = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
var qmarks = liberator.storage.newMap("quickmarks", true); var qmarks = storage.newMap("quickmarks", true);
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// MAPPINGS //////////////////////////////////////////////// ////////////////////// MAPPINGS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
var modes = liberator.config.browserModes || [liberator.modes.NORMAL]; var myModes = config.browserModes || [modes.NORMAL];
liberator.mappings.add(modes, mappings.add(myModes,
["go"], "Jump to a QuickMark", ["go"], "Jump to a QuickMark",
function (arg) { liberator.quickmarks.jumpTo(arg, liberator.CURRENT_TAB); }, function (arg) { quickmarks.jumpTo(arg, CURRENT_TAB); },
{ flags: liberator.Mappings.flags.ARGUMENT }); { flags: Mappings.flags.ARGUMENT });
liberator.mappings.add(modes, mappings.add(myModes,
["gn"], "Jump to a QuickMark in a new tab", ["gn"], "Jump to a QuickMark in a new tab",
function (arg) function (arg)
{ {
liberator.quickmarks.jumpTo(arg, quickmarks.jumpTo(arg,
/\bquickmark\b/.test(liberator.options["activate"]) ? /\bquickmark\b/.test(options["activate"]) ?
liberator.NEW_TAB : liberator.NEW_BACKGROUND_TAB); NEW_TAB : NEW_BACKGROUND_TAB);
}, },
{ flags: liberator.Mappings.flags.ARGUMENT }); { flags: Mappings.flags.ARGUMENT });
liberator.mappings.add(modes, mappings.add(myModes,
["M"], "Add new QuickMark for current URL", ["M"], "Add new QuickMark for current URL",
function (arg) function (arg)
{ {
if (/[^a-zA-Z0-9]/.test(arg)) if (/[^a-zA-Z0-9]/.test(arg))
{ {
liberator.beep(); beep();
return; return;
} }
liberator.quickmarks.add(arg, liberator.buffer.URL); quickmarks.add(arg, buffer.URL);
}, },
{ flags: liberator.Mappings.flags.ARGUMENT }); { flags: Mappings.flags.ARGUMENT });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// COMMANDS //////////////////////////////////////////////// ////////////////////// COMMANDS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.commands.add(["delqm[arks]"], commands.add(["delqm[arks]"],
"Delete the specified QuickMarks", "Delete the specified QuickMarks",
function (args, special) function (args, special)
{ {
// TODO: finish arg parsing - we really need a proper way to do this. :) // TODO: finish arg parsing - we really need a proper way to do this. :)
if (!special && !args) if (!special && !args)
{ {
liberator.echoerr("E471: Argument required"); echoerr("E471: Argument required");
return; return;
} }
if (special && args) if (special && args)
{ {
liberator.echoerr("E474: Invalid argument"); echoerr("E474: Invalid argument");
return; return;
} }
if (special) if (special)
liberator.quickmarks.removeAll(); quickmarks.removeAll();
else else
liberator.quickmarks.remove(args); quickmarks.remove(args);
}, },
{ bang: true }); { bang: true });
liberator.commands.add(["qma[rk]"], commands.add(["qma[rk]"],
"Mark a URL with a letter for quick access", "Mark a URL with a letter for quick access",
function (args) function (args)
{ {
var matches = args.string.match(/^([a-zA-Z0-9])(?:\s+(.+))?$/); var matches = args.string.match(/^([a-zA-Z0-9])(?:\s+(.+))?$/);
if (!matches) if (!matches)
liberator.echoerr("E488: Trailing characters"); echoerr("E488: Trailing characters");
else if (!matches[2]) else if (!matches[2])
liberator.quickmarks.add(matches[1], liberator.buffer.URL); quickmarks.add(matches[1], buffer.URL);
else else
liberator.quickmarks.add(matches[1], matches[2]); quickmarks.add(matches[1], matches[2]);
}, },
{ argCount: "+" }); { argCount: "+" });
liberator.commands.add(["qmarks"], commands.add(["qmarks"],
"Show all QuickMarks", "Show all QuickMarks",
function (args) function (args)
{ {
// ignore invalid qmark characters unless there are no valid qmark chars // ignore invalid qmark characters unless there are no valid qmark chars
if (args && !/[a-zA-Z0-9]/.test(args)) if (args && !/[a-zA-Z0-9]/.test(args))
{ {
liberator.echoerr("E283: No QuickMarks matching \"" + args + "\""); echoerr("E283: No QuickMarks matching \"" + args + "\"");
return; return;
} }
var filter = args.replace(/[^a-zA-Z0-9]/g, ""); var filter = args.replace(/[^a-zA-Z0-9]/g, "");
liberator.quickmarks.list(filter); quickmarks.list(filter);
}); });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
@@ -957,9 +957,9 @@ liberator.QuickMarks = function () //{{{
var url = qmarks.get(qmark); var url = qmarks.get(qmark);
if (url) if (url)
liberator.open(url, where); open(url, where);
else else
liberator.echoerr("E20: QuickMark not set"); echoerr("E20: QuickMark not set");
}, },
list: function (filter) list: function (filter)
@@ -974,7 +974,7 @@ liberator.QuickMarks = function () //{{{
if (marks.length == 0) if (marks.length == 0)
{ {
liberator.echoerr("No QuickMarks set"); echoerr("No QuickMarks set");
return; return;
} }
@@ -983,14 +983,14 @@ liberator.QuickMarks = function () //{{{
marks = marks.filter(function (qmark) filter.indexOf(qmark) >= 0); marks = marks.filter(function (qmark) filter.indexOf(qmark) >= 0);
if (marks.length == 0) if (marks.length == 0)
{ {
liberator.echoerr("E283: No QuickMarks matching \"" + filter + "\""); echoerr("E283: No QuickMarks matching \"" + filter + "\"");
return; return;
} }
} }
let items = ({title: mark, url: qmarks.get(mark)} for each (mark in marks)); let items = ({title: mark, url: qmarks.get(mark)} for each (mark in marks));
let list = liberator.template.bookmarks("QuickMark", items); let list = template.bookmarks("QuickMark", items);
liberator.commandline.echo(list, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
} }
}; };
//}}} //}}}

File diff suppressed because it is too large Load Diff

View File

@@ -27,8 +27,8 @@ the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/ }}} ***** END LICENSE BLOCK *****/
// Do NOT create instances of this class yourself, use the helper method // Do NOT create instances of this class yourself, use the helper method
// liberator.commands.add() instead // commands.add() instead
liberator.Command = function (specs, description, action, extraInfo) //{{{ with (liberator) liberator.Command = function (specs, description, action, extraInfo) //{{{
{ {
if (!specs || !action) if (!specs || !action)
return null; return null;
@@ -86,7 +86,7 @@ liberator.Command = function (specs, description, action, extraInfo) //{{{
this.replacementText = extraInfo.replacementText || null; this.replacementText = extraInfo.replacementText || null;
}; };
liberator.Command.prototype = { with (liberator) liberator.Command.prototype = {
execute: function (args, special, count, modifiers) execute: function (args, special, count, modifiers)
{ {
@@ -100,7 +100,7 @@ liberator.Command.prototype = {
// we use our args parser instead of passing a string to the callback // we use our args parser instead of passing a string to the callback
if (this.options.length > 0 || this.argCount) if (this.options.length > 0 || this.argCount)
{ {
args = liberator.commands.parseArgs(args, this.options, this.argCount, false, this.literal); args = commands.parseArgs(args, this.options, this.argCount, false, this.literal);
if (args == null) if (args == null)
return false; return false;
} }
@@ -109,7 +109,7 @@ liberator.Command.prototype = {
let matches = args.match(/(.*)<<\s*(\S+)$/); let matches = args.match(/(.*)<<\s*(\S+)$/);
if (matches && matches[2]) if (matches && matches[2])
{ {
liberator.commandline.inputMultiline(new RegExp("^" + matches[2] + "$", "m"), commandline.inputMultiline(new RegExp("^" + matches[2] + "$", "m"),
function (args) self.action.call(self, matches[1] + "\n" + args, special, count, modifiers)); function (args) self.action.call(self, matches[1] + "\n" + args, special, count, modifiers));
return; return;
} }
@@ -151,7 +151,7 @@ liberator.Command.prototype = {
}; //}}} }; //}}}
liberator.Commands = function () //{{{ with (liberator) liberator.Commands = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -195,7 +195,7 @@ liberator.Commands = function () //{{{
return NaN; return NaN;
} }
const ArgType = new liberator.util.Struct("description", "parse"); const ArgType = new util.Struct("description", "parse");
const argTypes = [ const argTypes = [
null, null,
["no arg", function (arg) !arg], ["no arg", function (arg) !arg],
@@ -237,7 +237,7 @@ liberator.Commands = function () //{{{
add: function (names, description, action, extra) add: function (names, description, action, extra)
{ {
var command = new liberator.Command(names, description, action, extra); var command = new Command(names, description, action, extra);
if (!command) if (!command)
return false; return false;
@@ -246,7 +246,7 @@ liberator.Commands = function () //{{{
if (exCommands[i].name == command.name) if (exCommands[i].name == command.name)
{ {
// never replace for now // never replace for now
liberator.log("Warning: :" + names[0] + " already exists, NOT replacing existing command.", 1); log("Warning: :" + names[0] + " already exists, NOT replacing existing command.", 1);
return false; return false;
} }
} }
@@ -261,7 +261,7 @@ liberator.Commands = function () //{{{
extra.isUserCommand = true; extra.isUserCommand = true;
description = description || "User defined command"; description = description || "User defined command";
var command = new liberator.Command(names, description, action, extra); var command = new Command(names, description, action, extra);
// FIXME: shouldn't this be testing for an existing command by name? // FIXME: shouldn't this be testing for an existing command by name?
// Requiring uppercase user command names like Vim would be easier // Requiring uppercase user command names like Vim would be easier
if (!command) if (!command)
@@ -479,7 +479,7 @@ liberator.Commands = function () //{{{
} }
var sub = str.substr(i); var sub = str.substr(i);
//liberator.dump(i + ": " + sub + " - " + onlyArgumentsRemaining + "\n"); //dump(i + ": " + sub + " - " + onlyArgumentsRemaining + "\n");
if ((!onlyArgumentsRemaining) && /^--(\s|$)/.test(sub)) if ((!onlyArgumentsRemaining) && /^--(\s|$)/.test(sub))
{ {
onlyArgumentsRemaining = true; onlyArgumentsRemaining = true;
@@ -536,14 +536,14 @@ liberator.Commands = function () //{{{
{ {
if (!complete) if (!complete)
{ {
liberator.echoerr("Invalid argument for option " + optname); echoerr("Invalid argument for option " + optname);
return null; return null;
} }
let compl = opt[3] || []; let compl = opt[3] || [];
if (typeof compl == "function") if (typeof compl == "function")
compl = compl(); compl = compl();
let filter = quoteArg(sub[optname.length + 1]) let filter = quoteArg(sub[optname.length + 1])
return [i + optname.length + 1, liberator.completion.filter(compl.map(filter), filter(arg))]; return [i + optname.length + 1, completion.filter(compl.map(filter), filter(arg))];
} }
if (!invalid) if (!invalid)
@@ -554,7 +554,7 @@ liberator.Commands = function () //{{{
arg = type.parse(arg); arg = type.parse(arg);
if (arg == null || arg == NaN) if (arg == null || arg == NaN)
{ {
liberator.echoerr("Invalid argument for " + type.description + "option: " + optname); echoerr("Invalid argument for " + type.description + "option: " + optname);
return null; return null;
} }
} }
@@ -564,7 +564,7 @@ liberator.Commands = function () //{{{
{ {
if (opt[2].call(this, arg) == false) if (opt[2].call(this, arg) == false)
{ {
liberator.echoerr("Invalid argument for option: " + optname); echoerr("Invalid argument for option: " + optname);
return null; return null;
} }
} }
@@ -589,12 +589,12 @@ liberator.Commands = function () //{{{
var [count, arg] = getNextArg(sub); var [count, arg] = getNextArg(sub);
if (count == -1) if (count == -1)
{ {
liberator.echoerr("Error parsing arguments: " + arg); echoerr("Error parsing arguments: " + arg);
return null; return null;
} }
else if (!onlyArgumentsRemaining && /^-/.test(arg)) else if (!onlyArgumentsRemaining && /^-/.test(arg))
{ {
liberator.echoerr("Invalid option: " + arg); echoerr("Invalid option: " + arg);
return null; return null;
} }
@@ -610,13 +610,13 @@ liberator.Commands = function () //{{{
// check for correct number of arguments // check for correct number of arguments
if (args.arguments.length == 0 && (argCount == "1" || argCount == "+")) if (args.arguments.length == 0 && (argCount == "1" || argCount == "+"))
{ {
liberator.echoerr("E471: Argument required"); echoerr("E471: Argument required");
return null; return null;
} }
else if (args.arguments.length == 1 && (argCount == "0") || else if (args.arguments.length == 1 && (argCount == "0") ||
args.arguments.length > 1 && (argCount == "0" || argCount == "1" || argCount == "?")) args.arguments.length > 1 && (argCount == "0" || argCount == "1" || argCount == "?"))
{ {
liberator.echoerr("E488: Trailing characters"); echoerr("E488: Trailing characters");
return null; return null;
} }
@@ -705,7 +705,7 @@ liberator.Commands = function () //{{{
count: this.count && count count: this.count && count
}; };
liberator.execute(liberator.commands.replaceTokens(this.replacementText, tokens)); execute(commands.replaceTokens(this.replacementText, tokens));
} }
// TODO: Vim allows commands to be defined without {rep} if there are {attr}s // TODO: Vim allows commands to be defined without {rep} if there are {attr}s
@@ -717,7 +717,7 @@ liberator.Commands = function () //{{{
let cmd = args.arguments[0]; let cmd = args.arguments[0];
if (cmd != null && /\W/.test(cmd)) if (cmd != null && /\W/.test(cmd))
{ {
liberator.echoerr("E182: Invalid command name"); echoerr("E182: Invalid command name");
return; return;
} }
@@ -727,7 +727,7 @@ liberator.Commands = function () //{{{
let bangOpt = "-bang" in args; let bangOpt = "-bang" in args;
let countOpt = "-count" in args; let countOpt = "-count" in args;
if (!liberator.commands.addUserCommand( if (!commands.addUserCommand(
[cmd], [cmd],
"User defined command", "User defined command",
userCommand, userCommand,
@@ -740,7 +740,7 @@ liberator.Commands = function () //{{{
special) special)
) )
{ {
liberator.echoerr("E174: Command already exists: add ! to replace it"); echoerr("E174: Command already exists: add ! to replace it");
} }
} }
else else
@@ -754,18 +754,18 @@ liberator.Commands = function () //{{{
if (cmds.length > 0) if (cmds.length > 0)
{ {
let str = liberator.template.tabular(["", "Name", "Args", "Range", "Definition"], ["padding-right: 2em;"], let str = template.tabular(["", "Name", "Args", "Range", "Definition"], ["padding-right: 2em;"],
([cmd.bang ? "!" : " ", ([cmd.bang ? "!" : " ",
cmd.name, cmd.name,
cmd.argCount, cmd.argCount,
cmd.count ? "0c" : "", cmd.count ? "0c" : "",
cmd.replacementText || "function () { ... }"] for each (cmd in cmds))); cmd.replacementText || "function () { ... }"] for each (cmd in cmds)));
liberator.commandline.echo(str, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE); commandline.echo(str, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
} }
else else
{ {
liberator.echo("No user-defined commands found"); echo("No user-defined commands found");
} }
} }
}, },
@@ -773,7 +773,7 @@ liberator.Commands = function () //{{{
literal: true, literal: true,
argCount: 1, argCount: 1,
bang: true, bang: true,
completer: function (filter) liberator.completion.userCommand(filter), completer: function (filter) completion.userCommand(filter),
options: [ options: [
[["-nargs"], commandManager.OPTION_STRING, function (arg) /^[01*?+]$/.test(arg), ["0", "1", "*", "?", "+"]], [["-nargs"], commandManager.OPTION_STRING, function (arg) /^[01*?+]$/.test(arg), ["0", "1", "*", "?", "+"]],
[["-bang"], commandManager.OPTION_NOARG], [["-bang"], commandManager.OPTION_NOARG],
@@ -785,7 +785,7 @@ liberator.Commands = function () //{{{
"Delete all user-defined commands", "Delete all user-defined commands",
function () function ()
{ {
liberator.commands.getUserCommands().forEach(function (cmd) { liberator.commands.removeUserCommand(cmd.name); }); commands.getUserCommands().forEach(function (cmd) { commands.removeUserCommand(cmd.name); });
}, },
{ argCount: "0" }); { argCount: "0" });
@@ -794,22 +794,22 @@ liberator.Commands = function () //{{{
function (args) function (args)
{ {
var name = args.arguments[0]; var name = args.arguments[0];
var cmdlist = liberator.commands.getUserCommands(); var cmdlist = commands.getUserCommands();
for (let i = 0; i < cmdlist.length; i++) for (let i = 0; i < cmdlist.length; i++)
{ {
if (cmdlist[i].name == name) if (cmdlist[i].name == name)
{ {
liberator.commands.removeUserCommand(name); commands.removeUserCommand(name);
return; return;
} }
} }
liberator.echoerr("E184: No such user-defined command: " + name); echoerr("E184: No such user-defined command: " + name);
}, },
{ {
argCount: "1", argCount: "1",
completer: function (filter) liberator.completion.userCommand(filter) completer: function (filter) completion.userCommand(filter)
}); });
//}}} //}}}

View File

@@ -26,7 +26,7 @@ the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL. the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/ }}} ***** END LICENSE BLOCK *****/
liberator.Completion = function () //{{{ with (liberator) liberator.Completion = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -49,9 +49,9 @@ liberator.Completion = function () //{{{
var historyResult = null; var historyResult = null;
var completionCache = []; var completionCache = [];
var historyTimer = new liberator.util.Timer(50, 100, function () { var historyTimer = new util.Timer(50, 100, function () {
let comp = []; let comp = [];
for (let i in liberator.util.range(0, historyResult.matchCount)) for (let i in util.range(0, historyResult.matchCount))
comp.push([historyResult.getValueAt(i), comp.push([historyResult.getValueAt(i),
historyResult.getCommentAt(i), historyResult.getCommentAt(i),
historyResult.getImageAt(i)]); historyResult.getImageAt(i)]);
@@ -59,7 +59,7 @@ liberator.Completion = function () //{{{
//let foo = ["", "IGNORED", "FAILURE", "NOMATCH", "SUCCESS", "NOMATCH_ONGOING", "SUCCESS_ONGOING"]; //let foo = ["", "IGNORED", "FAILURE", "NOMATCH", "SUCCESS", "NOMATCH_ONGOING", "SUCCESS_ONGOING"];
historyCache = comp; historyCache = comp;
liberator.commandline.setCompletions(completionCache.concat(historyCache)); commandline.setCompletions(completionCache.concat(historyCache));
}); });
function Javascript() function Javascript()
@@ -153,7 +153,7 @@ liberator.Completion = function () //{{{
obj = obj.wrappedJSObject; obj = obj.wrappedJSObject;
for (let [k, v] in this.iter(obj)) for (let [k, v] in this.iter(obj))
compl.push([k, liberator.template.highlight(v, true)]); compl.push([k, template.highlight(v, true)]);
} }
return compl; return compl;
} }
@@ -161,9 +161,9 @@ liberator.Completion = function () //{{{
this.filter = function filter(compl, key, last, offset) this.filter = function filter(compl, key, last, offset)
{ {
if (last != undefined) // Escaping the key (without adding quotes), so it matches the escaped completions. if (last != undefined) // Escaping the key (without adding quotes), so it matches the escaped completions.
key = liberator.util.escapeString(key.substr(offset), ""); key = util.escapeString(key.substr(offset), "");
liberator.completion.filterString = key; completion.filterString = key;
let res = buildLongestStartingSubstring(compl, key); let res = buildLongestStartingSubstring(compl, key);
if (res.length == 0) if (res.length == 0)
{ {
@@ -176,7 +176,7 @@ liberator.Completion = function () //{{{
if (last != undefined) // We're looking for a quoted string, so, strip whatever prefix we have and quote the rest if (last != undefined) // We're looking for a quoted string, so, strip whatever prefix we have and quote the rest
{ {
res.forEach(function (a) a[0] = liberator.util.escapeString(a[0].substr(offset), last)); res.forEach(function (a) a[0] = util.escapeString(a[0].substr(offset), last));
} }
else // We're not looking for a quoted string, so filter out anything that's not a valid identifier else // We're not looking for a quoted string, so filter out anything that's not a valid identifier
{ {
@@ -190,8 +190,8 @@ liberator.Completion = function () //{{{
{ {
try try
{ {
// liberator.dump("eval(" + liberator.util.escapeString(arg) + ")\n"); // dump("eval(" + util.escapeString(arg) + ")\n");
return liberator.eval(arg); return eval(arg);
} }
catch (e) catch (e)
{ {
@@ -226,7 +226,7 @@ liberator.Completion = function () //{{{
if (top[CHAR] != arg) if (top[CHAR] != arg)
throw new Error("Invalid JS"); throw new Error("Invalid JS");
if (i == str.length - 1) if (i == str.length - 1)
liberator.completion.parenMatch = top[OFFSET]; completion.parenMatch = top[OFFSET];
// The closing character of this stack frame will have pushed a new // The closing character of this stack frame will have pushed a new
// statement, leaving us with an empty statement. This doesn't matter, // statement, leaving us with an empty statement. This doesn't matter,
// now, as we simply throw away the frame when we pop it, but it may later. // now, as we simply throw away the frame when we pop it, but it may later.
@@ -339,7 +339,7 @@ liberator.Completion = function () //{{{
} }
catch (e) catch (e)
{ {
liberator.dump(liberator.util.escapeString(string) + ": " + e + "\n" + e.stack); dump(util.escapeString(string) + ": " + e + "\n" + e.stack);
lastIdx = 0; lastIdx = 0;
return [0, []]; return [0, []];
} }
@@ -490,7 +490,7 @@ liberator.Completion = function () //{{{
let idx; let idx;
while ((idx = str.indexOf(filter, start)) > -1) while ((idx = str.indexOf(filter, start)) > -1)
{ {
for (let end in liberator.util.range(idx + length, str.length + 1)) for (let end in util.range(idx + length, str.length + 1))
substrings.push(str.substring(idx, end)); substrings.push(str.substring(idx, end));
start = idx + 1; start = idx + 1;
} }
@@ -500,7 +500,7 @@ liberator.Completion = function () //{{{
// list = [ [['com1', 'com2'], 'text'], [['com3', 'com4'], 'text'] ] // list = [ [['com1', 'com2'], 'text'], [['com3', 'com4'], 'text'] ]
function buildLongestCommonSubstring(list, filter, favicon) function buildLongestCommonSubstring(list, filter, favicon)
{ {
liberator.completion.filterString = filter; completion.filterString = filter;
var filtered = []; var filtered = [];
var ignorecase = false; var ignorecase = false;
@@ -508,7 +508,7 @@ liberator.Completion = function () //{{{
ignorecase = true; ignorecase = true;
var longest = false; var longest = false;
if (liberator.options["wildmode"].indexOf("longest") >= 0) if (options["wildmode"].indexOf("longest") >= 0)
longest = true; longest = true;
for (let [,item] in Iterator(list)) for (let [,item] in Iterator(list))
@@ -534,8 +534,8 @@ liberator.Completion = function () //{{{
break; break;
} }
} }
if (liberator.options.get("wildoptions").has("sort")) if (options.get("wildoptions").has("sort"))
filtered = filtered.sort(function (a, b) liberator.util.ciCompare(a[0], b[0]));; filtered = filtered.sort(function (a, b) util.ciCompare(a[0], b[0]));;
return filtered; return filtered;
} }
@@ -545,7 +545,7 @@ liberator.Completion = function () //{{{
var filtered = []; var filtered = [];
var longest = false; var longest = false;
if (liberator.options["wildmode"].indexOf("longest") >= 0) if (options["wildmode"].indexOf("longest") >= 0)
longest = true; longest = true;
for (let [,item] in Iterator(list)) for (let [,item] in Iterator(list))
@@ -575,8 +575,8 @@ liberator.Completion = function () //{{{
break; break;
} }
} }
if (liberator.options.get("wildoptions").has("sort")) if (options.get("wildoptions").has("sort"))
filtered = filtered.sort(function (a, b) liberator.util.ciCompare(a[0], b[0]));; filtered = filtered.sort(function (a, b) util.ciCompare(a[0], b[0]));;
return filtered; return filtered;
} }
@@ -696,8 +696,8 @@ liberator.Completion = function () //{{{
} }
filtered = filtered.concat(additionalCompletions); filtered = filtered.concat(additionalCompletions);
if (liberator.options.get("wildoptions").has("sort")) if (options.get("wildoptions").has("sort"))
filtered = filtered.sort(function (a, b) liberator.util.ciCompare(a[0], b[0]));; filtered = filtered.sort(function (a, b) util.ciCompare(a[0], b[0]));;
return filtered; return filtered;
}, },
@@ -725,7 +725,7 @@ liberator.Completion = function () //{{{
////////////////////// COMPLETION TYPES //////////////////////////////////////// ////////////////////// COMPLETION TYPES ////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
bookmark: function bookmark(filter) [0, liberator.bookmarks.get(filter)], bookmark: function bookmark(filter) [0, bookmarks.get(filter)],
// FIXME: items shouldn't be [[[a], b]], but [[a, b]] and only mapped if at all for bLCS --mst // FIXME: items shouldn't be [[[a], b]], but [[a, b]] and only mapped if at all for bLCS --mst
buffer: function buffer(filter) buffer: function buffer(filter)
@@ -772,23 +772,23 @@ liberator.Completion = function () //{{{
if (!filter) if (!filter)
{ {
for (let command in liberator.commands) for (let command in commands)
completions.push([command.name, command.description]); completions.push([command.name, command.description]);
return [0, completions]; return [0, completions];
} }
for (let command in liberator.commands) for (let command in commands)
completions.push([command.longNames, command.description]); completions.push([command.longNames, command.description]);
return [0, buildLongestStartingSubstring(completions, filter)]; return [0, buildLongestStartingSubstring(completions, filter)];
}, },
dialog: function dialog(filter) [0, this.filter(liberator.config.dialogs || [], filter)], dialog: function dialog(filter) [0, this.filter(config.dialogs || [], filter)],
environment: function environment(filter) environment: function environment(filter)
{ {
let command = WINDOWS ? "set" : "export"; let command = WINDOWS ? "set" : "export";
let lines = liberator.io.system(command).split("\n"); let lines = io.system(command).split("\n");
lines.splice(lines.length - 1, 1); lines.splice(lines.length - 1, 1);
@@ -800,7 +800,7 @@ liberator.Completion = function () //{{{
return [0, this.filter(vars, filter)]; return [0, this.filter(vars, filter)];
}, },
event: function event(filter) [0, this.filter(liberator.config.autocommands, filter)], event: function event(filter) [0, this.filter(config.autocommands, filter)],
// provides completions for ex commands, including their arguments // provides completions for ex commands, including their arguments
ex: function ex(str) ex: function ex(str)
@@ -815,7 +815,7 @@ liberator.Completion = function () //{{{
} }
cacheFilter["ex"] = str; cacheFilter["ex"] = str;
var [count, cmd, special, args] = liberator.commands.parseCommand(str); var [count, cmd, special, args] = commands.parseCommand(str);
var completions = []; var completions = [];
var start = 0; var start = 0;
var exLength = 0; var exLength = 0;
@@ -827,7 +827,7 @@ liberator.Completion = function () //{{{
return [matches[1].length, this.command(cmd)[1]]; return [matches[1].length, this.command(cmd)[1]];
// dynamically get completions as specified with the command's completer function // dynamically get completions as specified with the command's completer function
var command = liberator.commands.get(cmd); var command = commands.get(cmd);
if (command && command.completer) if (command && command.completer)
{ {
matches = str.match(/^:*\d*\w+[\s!]\s*/); matches = str.match(/^:*\d*\w+[\s!]\s*/);
@@ -850,11 +850,11 @@ liberator.Completion = function () //{{{
try try
{ {
files = liberator.io.readDirectory(dir, true); files = io.readDirectory(dir, true);
if (liberator.options["wildignore"]) if (options["wildignore"])
{ {
var wigRegexp = new RegExp("(^" + liberator.options["wildignore"].replace(",", "|", "g") + ")$"); var wigRegexp = new RegExp("(^" + options["wildignore"].replace(",", "|", "g") + ")$");
files = files.filter(function (f) f.isDirectory() || !wigRegexp.test(f.leafName)) files = files.filter(function (f) f.isDirectory() || !wigRegexp.test(f.leafName))
} }
@@ -871,12 +871,12 @@ liberator.Completion = function () //{{{
return [dir.length, this.cached("file-" + dir, compl, generate, "filter", [true])]; return [dir.length, this.cached("file-" + dir, compl, generate, "filter", [true])];
else else
return [0, this.cached("file", filter, generate, "filter", [true])]; return [0, this.cached("file", filter, generate, "filter", [true])];
}catch(e){liberator.dump(e)} }catch(e){dump(e)}
}, },
help: function help(filter) help: function help(filter)
{ {
var files = liberator.config.helpFiles || []; var files = config.helpFiles || [];
var res = []; var res = [];
for (let i = 0; i < files.length; i++) for (let i = 0; i < files.length; i++)
@@ -889,7 +889,7 @@ liberator.Completion = function () //{{{
} }
catch (e) catch (e)
{ {
liberator.log("Error opening chrome://liberator/locale/" + files[i], 1); log("Error opening chrome://liberator/locale/" + files[i], 1);
continue; continue;
} }
var doc = xmlhttp.responseXML; var doc = xmlhttp.responseXML;
@@ -901,7 +901,7 @@ liberator.Completion = function () //{{{
return [0, this.filter(res, filter)]; return [0, this.filter(res, filter)];
}, },
history: function history(filter) [0, liberator.history.get(filter)], history: function history(filter) [0, history.get(filter)],
get javascriptCompleter() javascript, get javascriptCompleter() javascript,
@@ -913,14 +913,14 @@ liberator.Completion = function () //{{{
} }
catch (e) catch (e)
{ {
liberator.dump(e); dump(e);
return [0, []]; return [0, []];
} }
}, },
macro: function macro(filter) macro: function macro(filter)
{ {
var macros = [item for (item in liberator.events.getMacros())]; var macros = [item for (item in events.getMacros())];
return [0, this.filter(macros, filter)]; return [0, this.filter(macros, filter)];
}, },
@@ -928,8 +928,8 @@ liberator.Completion = function () //{{{
search: function search(filter) search: function search(filter)
{ {
let [, keyword, args] = filter.match(/^\s*(\S*)\s*(.*)/); let [, keyword, args] = filter.match(/^\s*(\S*)\s*(.*)/);
let keywords = liberator.bookmarks.getKeywords(); let keywords = bookmarks.getKeywords();
let engines = this.filter(keywords.concat(liberator.bookmarks.getSearchEngines()), filter, false, true); let engines = this.filter(keywords.concat(bookmarks.getSearchEngines()), filter, false, true);
let generate = function () { let generate = function () {
let history = liberator.history.get(); let history = liberator.history.get();
@@ -964,7 +964,7 @@ liberator.Completion = function () //{{{
if (!filter) if (!filter)
return [0, []]; return [0, []];
var engineList = (engineAliases || liberator.options["suggestengines"]).split(","); var engineList = (engineAliases || options["suggestengines"]).split(",");
var responseType = "application/x-suggestions+json"; var responseType = "application/x-suggestions+json";
var ss = Components.classes["@mozilla.org/browser/search-service;1"] var ss = Components.classes["@mozilla.org/browser/search-service;1"]
.getService(Components.interfaces.nsIBrowserSearchService); .getService(Components.interfaces.nsIBrowserSearchService);
@@ -1021,7 +1021,7 @@ liberator.Completion = function () //{{{
stylesheet: function stylesheet(filter) stylesheet: function stylesheet(filter)
{ {
var completions = liberator.buffer.alternateStyleSheets.map( var completions = buffer.alternateStyleSheets.map(
function (stylesheet) [stylesheet.title, stylesheet.href || "inline"] function (stylesheet) [stylesheet.title, stylesheet.href || "inline"]
); );
@@ -1050,17 +1050,17 @@ liberator.Completion = function () //{{{
this.filterString = filter; this.filterString = filter;
var completions = []; var completions = [];
var start = 0; var start = 0;
var skip = filter.match("^(.*" + liberator.options["urlseparator"] + ")(.*)"); // start after the last 'urlseparator' var skip = filter.match("^(.*" + options["urlseparator"] + ")(.*)"); // start after the last 'urlseparator'
if (skip) if (skip)
{ {
start += skip[1].length; start += skip[1].length;
filter = skip[2]; filter = skip[2];
} }
var cpt = complete || liberator.options["complete"]; var cpt = complete || options["complete"];
var suggestEngineAlias = liberator.options["suggestengines"] || "google"; var suggestEngineAlias = options["suggestengines"] || "google";
// join all completion arrays together // join all completion arrays together
for (let c in liberator.util.arrayIter(cpt)) for (let c in util.arrayIter(cpt))
{ {
if (c == "s") if (c == "s")
completions.push(this.search(filter)[1]); completions.push(this.search(filter)[1]);
@@ -1069,9 +1069,9 @@ liberator.Completion = function () //{{{
else if (c == "S") else if (c == "S")
completions.push(this.searchEngineSuggest(filter, suggestEngineAlias)[1]); completions.push(this.searchEngineSuggest(filter, suggestEngineAlias)[1]);
else if (c == "b") else if (c == "b")
completions.push(liberator.bookmarks.get(filter)); completions.push(bookmarks.get(filter));
else if (c == "h") else if (c == "h")
completions.push(liberator.history.get(filter)); completions.push(history.get(filter));
else if (c == "l" && completionService) // add completions like Firefox's smart location bar else if (c == "l" && completionService) // add completions like Firefox's smart location bar
{ {
completionService.stopSearch(); completionService.stopSearch();
@@ -1086,26 +1086,22 @@ liberator.Completion = function () //{{{
} }
} }
completionCache = liberator.util.flatten(completions); completionCache = util.flatten(completions);
return [start, completionCache.concat(historyCache)]; return [start, completionCache.concat(historyCache)];
}, },
userCommand: function userCommand(filter) userCommand: function userCommand(filter)
{ {
var commands = liberator.commands.getUserCommands(); let cmds = commands.getUserCommands();
commands = commands.map(function (command) [command.name, ""]); cmds = cmds.map(function (cmd) [cmd.name, ""]);
return [0, this.filter(commands, filter)]; return [0, this.filter(cmds, filter)];
}, },
userMapping: function userMapping(filter, modes) userMapping: function userMapping(filter, modes)
{ {
// TODO: add appropriate getters to l.mappings // TODO: add appropriate getters to l.mappings
var mappings = []; let maps = [[m.names[0], ""] for (m in mappings.getUserIterator(modes))];
return [0, this.filter(maps, filter)];
for (let map in liberator.mappings.getUserIterator(modes))
mappings.push([map.names[0], ""]);
return [0, this.filter(mappings, filter)];
} }
// }}} // }}}
}; };

View File

@@ -29,7 +29,7 @@ the terms of any one of the MPL, the GPL or the LGPL.
// command names taken from: // command names taken from:
// http://developer.mozilla.org/en/docs/Editor_Embedding_Guide // http://developer.mozilla.org/en/docs/Editor_Embedding_Guide
liberator.Editor = function () //{{{ with (liberator) liberator.Editor = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -56,15 +56,15 @@ liberator.Editor = function () //{{{
function selectPreviousLine() function selectPreviousLine()
{ {
liberator.editor.executeCommand("cmd_selectLinePrevious"); editor.executeCommand("cmd_selectLinePrevious");
if ((liberator.modes.extended & liberator.modes.LINE) && !liberator.editor.selectedText()) if ((modes.extended & modes.LINE) && !editor.selectedText())
liberator.editor.executeCommand("cmd_selectLinePrevious"); editor.executeCommand("cmd_selectLinePrevious");
} }
function selectNextLine() function selectNextLine()
{ {
liberator.editor.executeCommand("cmd_selectLineNext"); editor.executeCommand("cmd_selectLineNext");
if ((liberator.modes.extended & liberator.modes.LINE) && !liberator.editor.selectedText()) if ((modes.extended & modes.LINE) && !editor.selectedText())
liberator.editor.executeCommand("cmd_selectLineNext"); editor.executeCommand("cmd_selectLineNext");
} }
// add mappings for commands like h,j,k,l,etc. in CARET, VISUAL and TEXTAREA mode // add mappings for commands like h,j,k,l,etc. in CARET, VISUAL and TEXTAREA mode
@@ -72,9 +72,9 @@ liberator.Editor = function () //{{{
{ {
var extraInfo = {}; var extraInfo = {};
if (hasCount) if (hasCount)
extraInfo.flags = liberator.Mappings.flags.COUNT; extraInfo.flags = Mappings.flags.COUNT;
liberator.mappings.add([liberator.modes.CARET], keys, "", mappings.add([modes.CARET], keys, "",
function (count) function (count)
{ {
if (typeof count != "number" || count < 1) if (typeof count != "number" || count < 1)
@@ -90,7 +90,7 @@ liberator.Editor = function () //{{{
}, },
extraInfo); extraInfo);
liberator.mappings.add([liberator.modes.VISUAL], keys, "", mappings.add([modes.VISUAL], keys, "",
function (count) function (count)
{ {
if (typeof count != "number" || count < 1 || !hasCount) if (typeof count != "number" || count < 1 || !hasCount)
@@ -103,12 +103,12 @@ liberator.Editor = function () //{{{
while (count--) while (count--)
{ {
if (liberator.modes.extended & liberator.modes.TEXTAREA) if (modes.extended & modes.TEXTAREA)
{ {
if (typeof visualTextareaCommand == "function") if (typeof visualTextareaCommand == "function")
visualTextareaCommand(); visualTextareaCommand();
else else
liberator.editor.executeCommand(visualTextareaCommand); editor.executeCommand(visualTextareaCommand);
} }
else else
controller[caretModeMethod](caretModeArg, true); controller[caretModeMethod](caretModeArg, true);
@@ -116,13 +116,13 @@ liberator.Editor = function () //{{{
}, },
extraInfo); extraInfo);
liberator.mappings.add([liberator.modes.TEXTAREA], keys, "", mappings.add([modes.TEXTAREA], keys, "",
function (count) function (count)
{ {
if (typeof count != "number" || count < 1) if (typeof count != "number" || count < 1)
count = 1; count = 1;
liberator.editor.executeCommand(textareaCommand, count); editor.executeCommand(textareaCommand, count);
}, },
extraInfo); extraInfo);
} }
@@ -130,22 +130,21 @@ liberator.Editor = function () //{{{
// add mappings for commands like i,a,s,c,etc. in TEXTAREA mode // add mappings for commands like i,a,s,c,etc. in TEXTAREA mode
function addBeginInsertModeMap(keys, commands) function addBeginInsertModeMap(keys, commands)
{ {
liberator.mappings.add([liberator.modes.TEXTAREA], keys, "", mappings.add([modes.TEXTAREA], keys, "",
function (count) function (count)
{ {
for (let c = 0; c < commands.length; c++) commands.forEach(function (cmd)
liberator.editor.executeCommand(commands[c], 1); editor.executeCommand(cmd, 1));
modes.set(modes.INSERT, modes.TEXTAREA);
liberator.modes.set(liberator.modes.INSERT, liberator.modes.TEXTAREA);
}); });
} }
function addMotionMap(key) function addMotionMap(key)
{ {
liberator.mappings.add([liberator.modes.TEXTAREA], [key], mappings.add([modes.TEXTAREA], [key],
"Motion command", "Motion command",
function (motion, count) { liberator.editor.executeCommandWithMotion(key, motion, count); }, function (motion, count) { editor.executeCommandWithMotion(key, motion, count); },
{ flags: liberator.Mappings.flags.MOTION | liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.MOTION | Mappings.flags.COUNT });
} }
// mode = "i" -> add :iabbrev, :iabclear and :iunabbrev commands // mode = "i" -> add :iabbrev, :iabclear and :iunabbrev commands
@@ -154,31 +153,31 @@ liberator.Editor = function () //{{{
var mode = ch || "!"; var mode = ch || "!";
modeDescription = modeDescription ? " in " + modeDescription + " mode" : ""; modeDescription = modeDescription ? " in " + modeDescription + " mode" : "";
liberator.commands.add([ch ? ch + "a[bbrev]" : "ab[breviate]"], commands.add([ch ? ch + "a[bbrev]" : "ab[breviate]"],
"Abbreviate a key sequence" + modeDescription, "Abbreviate a key sequence" + modeDescription,
function (args) function (args)
{ {
if (!args) if (!args)
{ {
liberator.editor.listAbbreviations(mode, ""); editor.listAbbreviations(mode, "");
return; return;
} }
var matches = args.match(/^(\S+)(?:\s+(.+))?$/); var matches = args.match(/^(\S+)(?:\s+(.+))?$/);
var [lhs, rhs] = [matches[1], matches[2]]; var [lhs, rhs] = [matches[1], matches[2]];
if (rhs) if (rhs)
liberator.editor.addAbbreviation(mode, lhs, rhs); editor.addAbbreviation(mode, lhs, rhs);
else else
liberator.editor.listAbbreviations(mode, lhs); editor.listAbbreviations(mode, lhs);
}); });
liberator.commands.add([ch ? ch + "una[bbrev]" : "una[bbreviate]"], commands.add([ch ? ch + "una[bbrev]" : "una[bbreviate]"],
"Remove an abbreviation" + modeDescription, "Remove an abbreviation" + modeDescription,
function (args) { liberator.editor.removeAbbreviation(mode, args); }); function (args) { editor.removeAbbreviation(mode, args); });
liberator.commands.add([ch + "abc[lear]"], commands.add([ch + "abc[lear]"],
"Remove all abbreviations" + modeDescription, "Remove all abbreviations" + modeDescription,
function () { liberator.editor.removeAllAbbreviations(mode); }, function () { editor.removeAllAbbreviations(mode); },
{ argCount: "0" }); { argCount: "0" });
} }
@@ -186,11 +185,11 @@ liberator.Editor = function () //{{{
////////////////////// OPTIONS ///////////////////////////////////////////////// ////////////////////// OPTIONS /////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.options.add(["editor"], options.add(["editor"],
"Set the external text editor", "Set the external text editor",
"string", "gvim -f"); "string", "gvim -f");
liberator.options.add(["insertmode", "im"], options.add(["insertmode", "im"],
"Use Insert mode as the default for text areas", "Use Insert mode as the default for text areas",
"boolean", true); "boolean", true);
@@ -198,7 +197,7 @@ liberator.Editor = function () //{{{
////////////////////// MAPPINGS //////////////////////////////////////////////// ////////////////////// MAPPINGS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
var modes = [liberator.modes.INSERT, liberator.modes.COMMAND_LINE]; var myModes = [modes.INSERT, modes.COMMAND_LINE];
/* KEYS COUNT CARET TEXTAREA VISUAL_TEXTAREA */ /* KEYS COUNT CARET TEXTAREA VISUAL_TEXTAREA */
addMovementMap(["k", "<Up>"], true, "lineMove", false, "cmd_linePrevious", selectPreviousLine); addMovementMap(["k", "<Up>"], true, "lineMove", false, "cmd_linePrevious", selectPreviousLine);
@@ -227,253 +226,253 @@ liberator.Editor = function () //{{{
addMotionMap("y"); // yank addMotionMap("y"); // yank
// insert mode mappings // insert mode mappings
liberator.mappings.add(modes, mappings.add(myModes,
["<C-o>", "<C-f>", "<C-g>", "<C-n>", "<C-p>"], ["<C-o>", "<C-f>", "<C-g>", "<C-n>", "<C-p>"],
"Ignore certain " + liberator.config.hostApplication + " key bindings", "Ignore certain " + config.hostApplication + " key bindings",
function () { /*liberator.beep();*/ }); function () { /*beep();*/ });
liberator.mappings.add(modes, mappings.add(myModes,
["<C-w>"], "Delete previous word", ["<C-w>"], "Delete previous word",
function () { liberator.editor.executeCommand("cmd_deleteWordBackward", 1); }); function () { editor.executeCommand("cmd_deleteWordBackward", 1); });
liberator.mappings.add(modes, mappings.add(myModes,
["<C-u>"], "Delete until beginning of current line", ["<C-u>"], "Delete until beginning of current line",
function () function ()
{ {
// broken in FF3, deletes the whole line: // broken in FF3, deletes the whole line:
// liberator.editor.executeCommand("cmd_deleteToBeginningOfLine", 1); // editor.executeCommand("cmd_deleteToBeginningOfLine", 1);
liberator.editor.executeCommand("cmd_selectBeginLine", 1); editor.executeCommand("cmd_selectBeginLine", 1);
if (getController().isCommandEnabled("cmd_delete")) if (getController().isCommandEnabled("cmd_delete"))
liberator.editor.executeCommand("cmd_delete", 1); editor.executeCommand("cmd_delete", 1);
}); });
liberator.mappings.add(modes, mappings.add(myModes,
["<C-k>"], "Delete until end of current line", ["<C-k>"], "Delete until end of current line",
function () { liberator.editor.executeCommand("cmd_deleteToEndOfLine", 1); }); function () { editor.executeCommand("cmd_deleteToEndOfLine", 1); });
liberator.mappings.add(modes, mappings.add(myModes,
["<C-a>"], "Move cursor to beginning of current line", ["<C-a>"], "Move cursor to beginning of current line",
function () { liberator.editor.executeCommand("cmd_beginLine", 1); }); function () { editor.executeCommand("cmd_beginLine", 1); });
liberator.mappings.add(modes, mappings.add(myModes,
["<C-e>"], "Move cursor to end of current line", ["<C-e>"], "Move cursor to end of current line",
function () { liberator.editor.executeCommand("cmd_endLine", 1); }); function () { editor.executeCommand("cmd_endLine", 1); });
liberator.mappings.add(modes, mappings.add(myModes,
["<C-h>"], "Delete character to the left", ["<C-h>"], "Delete character to the left",
function () { liberator.editor.executeCommand("cmd_deleteCharBackward", 1); }); function () { editor.executeCommand("cmd_deleteCharBackward", 1); });
liberator.mappings.add(modes, mappings.add(myModes,
["<C-d>"], "Delete character to the right", ["<C-d>"], "Delete character to the right",
function () { liberator.editor.executeCommand("cmd_deleteCharForward", 1); }); function () { editor.executeCommand("cmd_deleteCharForward", 1); });
/*liberator.mappings.add(modes, /*mappings.add(myModes,
["<C-Home>"], "Move cursor to beginning of text field", ["<C-Home>"], "Move cursor to beginning of text field",
function () { liberator.editor.executeCommand("cmd_moveTop", 1); }); function () { editor.executeCommand("cmd_moveTop", 1); });
liberator.mappings.add(modes, mappings.add(myModes,
["<C-End>"], "Move cursor to end of text field", ["<C-End>"], "Move cursor to end of text field",
function () { liberator.editor.executeCommand("cmd_moveBottom", 1); });*/ function () { editor.executeCommand("cmd_moveBottom", 1); });*/
liberator.mappings.add(modes, mappings.add(myModes,
["<S-Insert>"], "Insert clipboard/selection", ["<S-Insert>"], "Insert clipboard/selection",
function () { liberator.editor.pasteClipboard(); }); function () { editor.pasteClipboard(); });
liberator.mappings.add([liberator.modes.INSERT, liberator.modes.TEXTAREA, liberator.modes.COMPOSE], mappings.add([modes.INSERT, modes.TEXTAREA, modes.COMPOSE],
["<C-i>"], "Edit text field with an external editor", ["<C-i>"], "Edit text field with an external editor",
function () { liberator.editor.editWithExternalEditor(); }); function () { editor.editWithExternalEditor(); });
// FIXME: <esc> does not work correctly // FIXME: <esc> does not work correctly
liberator.mappings.add([liberator.modes.INSERT], mappings.add([modes.INSERT],
["<C-t>"], "Edit text field in vi mode", ["<C-t>"], "Edit text field in vi mode",
function () { liberator.mode = liberator.modes.TEXTAREA; }); function () { liberator.mode = liberator.modes.TEXTAREA; });
liberator.mappings.add([liberator.modes.INSERT], mappings.add([modes.INSERT],
["<Space>", "<Return>"], "Expand insert mode abbreviation", ["<Space>", "<Return>"], "Expand insert mode abbreviation",
function () { liberator.editor.expandAbbreviation("i"); }, function () { editor.expandAbbreviation("i"); },
{ flags: liberator.Mappings.flags.ALLOW_EVENT_ROUTING }); { flags: Mappings.flags.ALLOW_EVENT_ROUTING });
liberator.mappings.add([liberator.modes.INSERT], mappings.add([modes.INSERT],
["<Tab>"], "Expand insert mode abbreviation", ["<Tab>"], "Expand insert mode abbreviation",
function () { liberator.editor.expandAbbreviation("i"); document.commandDispatcher.advanceFocus(); }); function () { editor.expandAbbreviation("i"); document.commandDispatcher.advanceFocus(); });
liberator.mappings.add([liberator.modes.INSERT], mappings.add([modes.INSERT],
["<C-]>", "<C-5>"], "Expand insert mode abbreviation", ["<C-]>", "<C-5>"], "Expand insert mode abbreviation",
function () { liberator.editor.expandAbbreviation("i"); }); function () { editor.expandAbbreviation("i"); });
// textarea mode // textarea mode
liberator.mappings.add([liberator.modes.TEXTAREA], mappings.add([modes.TEXTAREA],
["u"], "Undo", ["u"], "Undo",
function (count) function (count)
{ {
liberator.editor.executeCommand("cmd_undo", count); editor.executeCommand("cmd_undo", count);
liberator.mode = liberator.modes.TEXTAREA; liberator.mode = liberator.modes.TEXTAREA;
}, },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.TEXTAREA], mappings.add([modes.TEXTAREA],
["<C-r>"], "Redo", ["<C-r>"], "Redo",
function (count) function (count)
{ {
liberator.editor.executeCommand("cmd_redo", count); editor.executeCommand("cmd_redo", count);
liberator.mode = liberator.modes.TEXTAREA; liberator.mode = liberator.modes.TEXTAREA;
}, },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.TEXTAREA], mappings.add([modes.TEXTAREA],
["D"], "Delete the characters under the cursor until the end of the line", ["D"], "Delete the characters under the cursor until the end of the line",
function () { liberator.editor.executeCommand("cmd_deleteToEndOfLine"); }); function () { editor.executeCommand("cmd_deleteToEndOfLine"); });
liberator.mappings.add([liberator.modes.TEXTAREA], mappings.add([modes.TEXTAREA],
["o"], "Open line below current", ["o"], "Open line below current",
function (count) function (count)
{ {
liberator.editor.executeCommand("cmd_endLine", 1); editor.executeCommand("cmd_endLine", 1);
liberator.modes.set(liberator.modes.INSERT, liberator.modes.TEXTAREA); modes.set(modes.INSERT, modes.TEXTAREA);
liberator.events.feedkeys("<Return>"); events.feedkeys("<Return>");
}); });
liberator.mappings.add([liberator.modes.TEXTAREA], mappings.add([modes.TEXTAREA],
["O"], "Open line above current", ["O"], "Open line above current",
function (count) function (count)
{ {
liberator.editor.executeCommand("cmd_beginLine", 1); editor.executeCommand("cmd_beginLine", 1);
liberator.modes.set(liberator.modes.INSERT, liberator.modes.TEXTAREA); modes.set(modes.INSERT, modes.TEXTAREA);
liberator.events.feedkeys("<Return>"); events.feedkeys("<Return>");
liberator.editor.executeCommand("cmd_linePrevious", 1); editor.executeCommand("cmd_linePrevious", 1);
}); });
liberator.mappings.add([liberator.modes.TEXTAREA], mappings.add([modes.TEXTAREA],
["X"], "Delete character to the left", ["X"], "Delete character to the left",
function (count) { liberator.editor.executeCommand("cmd_deleteCharBackward", count); }, function (count) { editor.executeCommand("cmd_deleteCharBackward", count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.TEXTAREA], mappings.add([modes.TEXTAREA],
["x"], "Delete character to the right", ["x"], "Delete character to the right",
function (count) { liberator.editor.executeCommand("cmd_deleteCharForward", count); }, function (count) { editor.executeCommand("cmd_deleteCharForward", count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
// visual mode // visual mode
liberator.mappings.add([liberator.modes.CARET, liberator.modes.TEXTAREA, liberator.modes.VISUAL], mappings.add([modes.CARET, modes.TEXTAREA, modes.VISUAL],
["v"], "Start visual mode", ["v"], "Start visual mode",
function (count) { liberator.modes.set(liberator.modes.VISUAL, liberator.mode); }); function (count) { modes.set(modes.VISUAL, mode); });
liberator.mappings.add([liberator.modes.TEXTAREA], mappings.add([modes.TEXTAREA],
["V"], "Start visual line mode", ["V"], "Start visual line mode",
function (count) function (count)
{ {
liberator.modes.set(liberator.modes.VISUAL, liberator.modes.TEXTAREA | liberator.modes.LINE); modes.set(modes.VISUAL, modes.TEXTAREA | modes.LINE);
liberator.editor.executeCommand("cmd_beginLine", 1); editor.executeCommand("cmd_beginLine", 1);
liberator.editor.executeCommand("cmd_selectLineNext", 1); editor.executeCommand("cmd_selectLineNext", 1);
}); });
liberator.mappings.add([liberator.modes.VISUAL], mappings.add([modes.VISUAL],
["c", "s"], "Change selected text", ["c", "s"], "Change selected text",
function (count) function (count)
{ {
if (liberator.modes.extended & liberator.modes.TEXTAREA) if (modes.extended & modes.TEXTAREA)
{ {
liberator.editor.executeCommand("cmd_cut"); editor.executeCommand("cmd_cut");
liberator.modes.set(liberator.modes.INSERT, liberator.modes.TEXTAREA); modes.set(modes.INSERT, modes.TEXTAREA);
} }
else else
liberator.beep(); beep();
}); });
liberator.mappings.add([liberator.modes.VISUAL], mappings.add([modes.VISUAL],
["d"], "Delete selected text", ["d"], "Delete selected text",
function (count) function (count)
{ {
if (liberator.modes.extended & liberator.modes.TEXTAREA) if (modes.extended & modes.TEXTAREA)
{ {
liberator.editor.executeCommand("cmd_cut"); editor.executeCommand("cmd_cut");
liberator.modes.set(liberator.modes.TEXTAREA); modes.set(modes.TEXTAREA);
} }
else else
liberator.beep(); beep();
}); });
liberator.mappings.add([liberator.modes.VISUAL], mappings.add([modes.VISUAL],
["y"], "Yank selected text", ["y"], "Yank selected text",
function (count) function (count)
{ {
if (liberator.modes.extended & liberator.modes.TEXTAREA) if (modes.extended & modes.TEXTAREA)
{ {
liberator.editor.executeCommand("cmd_copy"); editor.executeCommand("cmd_copy");
liberator.modes.set(liberator.modes.TEXTAREA); modes.set(modes.TEXTAREA);
} }
else else
{ {
var sel = window.content.document.getSelection(); var sel = window.content.document.getSelection();
if (sel) if (sel)
liberator.util.copyToClipboard(sel, true); util.copyToClipboard(sel, true);
else else
liberator.beep(); beep();
} }
}); });
liberator.mappings.add([liberator.modes.VISUAL, liberator.modes.TEXTAREA], mappings.add([modes.VISUAL, modes.TEXTAREA],
["p"], "Paste clipboard contents", ["p"], "Paste clipboard contents",
function (count) function (count)
{ {
if (!(liberator.modes.extended & liberator.modes.CARET)) if (!(modes.extended & modes.CARET))
{ {
if (!count) count = 1; if (!count) count = 1;
while (count--) while (count--)
liberator.editor.executeCommand("cmd_paste"); editor.executeCommand("cmd_paste");
liberator.mode = liberator.modes.TEXTAREA; liberator.mode = liberator.modes.TEXTAREA;
} }
else else
liberator.beep(); beep();
}); });
// finding characters // finding characters
liberator.mappings.add([liberator.modes.TEXTAREA, liberator.modes.VISUAL], mappings.add([modes.TEXTAREA, modes.VISUAL],
["f"], "Move to a character on the current line after the cursor", ["f"], "Move to a character on the current line after the cursor",
function (count, arg) function (count, arg)
{ {
var pos = liberator.editor.findCharForward(arg, count); var pos = editor.findCharForward(arg, count);
if (pos >= 0) if (pos >= 0)
liberator.editor.moveToPosition(pos, true, liberator.mode == liberator.modes.VISUAL); editor.moveToPosition(pos, true, mode == modes.VISUAL);
}, },
{ flags: liberator.Mappings.flags.ARGUMENT | liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.ARGUMENT | Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.TEXTAREA, liberator.modes.VISUAL], mappings.add([modes.TEXTAREA, modes.VISUAL],
["F"], "Move to a charater on the current line before the cursor", ["F"], "Move to a charater on the current line before the cursor",
function (count, arg) function (count, arg)
{ {
var pos = liberator.editor.findCharBackward(arg, count); var pos = editor.findCharBackward(arg, count);
if (pos >= 0) if (pos >= 0)
liberator.editor.moveToPosition(pos, false, liberator.mode == liberator.modes.VISUAL); editor.moveToPosition(pos, false, mode == modes.VISUAL);
}, },
{ flags: liberator.Mappings.flags.ARGUMENT | liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.ARGUMENT | Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.TEXTAREA, liberator.modes.VISUAL], mappings.add([modes.TEXTAREA, modes.VISUAL],
["t"], "Move before a character on the current line", ["t"], "Move before a character on the current line",
function (count, arg) function (count, arg)
{ {
var pos = liberator.editor.findCharForward(arg, count); var pos = editor.findCharForward(arg, count);
if (pos >= 0) if (pos >= 0)
liberator.editor.moveToPosition(pos - 1, true, liberator.mode == liberator.modes.VISUAL); editor.moveToPosition(pos - 1, true, mode == modes.VISUAL);
}, },
{ flags: liberator.Mappings.flags.ARGUMENT | liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.ARGUMENT | Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.TEXTAREA, liberator.modes.VISUAL], mappings.add([modes.TEXTAREA, modes.VISUAL],
["T"], "Move before a character on the current line, backwards", ["T"], "Move before a character on the current line, backwards",
function (count, arg) function (count, arg)
{ {
var pos = liberator.editor.findCharBackward(arg, count); var pos = editor.findCharBackward(arg, count);
if (pos >= 0) if (pos >= 0)
liberator.editor.moveToPosition(pos + 1, false, liberator.mode == liberator.modes.VISUAL); editor.moveToPosition(pos + 1, false, mode == modes.VISUAL);
}, },
{ flags: liberator.Mappings.flags.ARGUMENT | liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.ARGUMENT | Mappings.flags.COUNT });
// textarea and visual mode // textarea and visual mode
liberator.mappings.add([liberator.modes.TEXTAREA, liberator.modes.VISUAL], mappings.add([modes.TEXTAREA, modes.VISUAL],
["~"], "Switch case of the character under the cursor and move the cursor to the right", ["~"], "Switch case of the character under the cursor and move the cursor to the right",
function (count) function (count)
{ {
if (liberator.modes.main == liberator.modes.VISUAL) if (modes.main == modes.VISUAL)
{ {
count = editor().selectionEnd - editor().selectionStart; count = editor().selectionEnd - editor().selectionStart;
} }
@@ -488,18 +487,18 @@ liberator.Editor = function () //{{{
var pos = editor().selectionStart; var pos = editor().selectionStart;
if (pos >= text.length) if (pos >= text.length)
{ {
liberator.beep(); beep();
return; return;
} }
var chr = text[pos]; var chr = text[pos];
editor().value = text.substring(0, pos) + editor().value = text.substring(0, pos) +
(chr == chr.toLocaleLowerCase() ? chr.toLocaleUpperCase() : chr.toLocaleLowerCase()) + (chr == chr.toLocaleLowerCase() ? chr.toLocaleUpperCase() : chr.toLocaleLowerCase()) +
text.substring(pos + 1); text.substring(pos + 1);
liberator.editor.moveToPosition(pos + 1, true, false); editor.moveToPosition(pos + 1, true, false);
} }
liberator.modes.set(liberator.modes.TEXTAREA); modes.set(modes.TEXTAREA);
}, },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// COMMANDS //////////////////////////////////////////////// ////////////////////// COMMANDS ////////////////////////////////////////////////
@@ -555,14 +554,14 @@ liberator.Editor = function () //{{{
{ {
var elt = window.document.commandDispatcher.focusedElement; var elt = window.document.commandDispatcher.focusedElement;
if (elt.setSelectionRange && liberator.util.readFromClipboard()) if (elt.setSelectionRange && util.readFromClipboard())
// readFromClipboard would return 'undefined' if not checked // readFromClipboard would return 'undefined' if not checked
// dunno about .setSelectionRange // dunno about .setSelectionRange
{ {
var rangeStart = elt.selectionStart; // caret position var rangeStart = elt.selectionStart; // caret position
var rangeEnd = elt.selectionEnd; var rangeEnd = elt.selectionEnd;
var tempStr1 = elt.value.substring(0, rangeStart); var tempStr1 = elt.value.substring(0, rangeStart);
var tempStr2 = liberator.util.readFromClipboard(); var tempStr2 = util.readFromClipboard();
var tempStr3 = elt.value.substring(rangeEnd); var tempStr3 = elt.value.substring(rangeEnd);
elt.value = tempStr1 + tempStr2 + tempStr3; elt.value = tempStr1 + tempStr2 + tempStr3;
elt.selectionStart = rangeStart + tempStr2.length; elt.selectionStart = rangeStart + tempStr2.length;
@@ -576,7 +575,7 @@ liberator.Editor = function () //{{{
var controller = getController(); var controller = getController();
if (!controller || !controller.supportsCommand(cmd) || !controller.isCommandEnabled(cmd)) if (!controller || !controller.supportsCommand(cmd) || !controller.isCommandEnabled(cmd))
{ {
liberator.beep(); beep();
return false; return false;
} }
@@ -597,7 +596,7 @@ liberator.Editor = function () //{{{
catch (e) catch (e)
{ {
if (!didCommand) if (!didCommand)
liberator.beep(); beep();
return false; return false;
} }
} }
@@ -618,7 +617,7 @@ liberator.Editor = function () //{{{
count--; count--;
} }
liberator.modes.set(liberator.modes.VISUAL, liberator.modes.TEXTAREA); modes.set(modes.VISUAL, modes.TEXTAREA);
switch (motion) switch (motion)
{ {
@@ -663,7 +662,7 @@ liberator.Editor = function () //{{{
break; break;
default: default:
liberator.beep(); beep();
return false; return false;
} }
@@ -672,11 +671,11 @@ liberator.Editor = function () //{{{
case "d": case "d":
this.executeCommand("cmd_delete", 1); this.executeCommand("cmd_delete", 1);
// need to reset the mode as the visual selection changes it // need to reset the mode as the visual selection changes it
liberator.modes.main = liberator.modes.TEXTAREA; modes.main = modes.TEXTAREA;
break; break;
case "c": case "c":
this.executeCommand("cmd_delete", 1); this.executeCommand("cmd_delete", 1);
liberator.modes.set(liberator.modes.INSERT, liberator.modes.TEXTAREA); modes.set(modes.INSERT, modes.TEXTAREA);
break; break;
case "y": case "y":
this.executeCommand("cmd_copy", 1); this.executeCommand("cmd_copy", 1);
@@ -684,7 +683,7 @@ liberator.Editor = function () //{{{
break; break;
default: default:
liberator.beep(); beep();
return false; return false;
} }
return true; return true;
@@ -749,7 +748,7 @@ liberator.Editor = function () //{{{
return i + 1; // always position the cursor after the char return i + 1; // always position the cursor after the char
} }
liberator.beep(); beep();
return -1; return -1;
}, },
@@ -776,7 +775,7 @@ liberator.Editor = function () //{{{
return i; return i;
} }
liberator.beep(); beep();
return -1; return -1;
}, },
@@ -784,7 +783,7 @@ liberator.Editor = function () //{{{
editWithExternalEditor: function () editWithExternalEditor: function ()
{ {
var textBox = null; var textBox = null;
if (!(liberator.config.isComposeWindow)) if (!(config.isComposeWindow))
textBox = document.commandDispatcher.focusedElement; textBox = document.commandDispatcher.focusedElement;
var text = ""; var text = "";
@@ -795,30 +794,30 @@ liberator.Editor = function () //{{{
else else
return false; return false;
var editor = liberator.options["editor"]; var editor = options["editor"];
var args = liberator.commands.parseArgs(editor, [], "*", true).arguments; var args = commands.parseArgs(editor, [], "*", true).arguments;
if (args.length < 1) if (args.length < 1)
{ {
liberator.echoerr("No editor specified"); echoerr("No editor specified");
return false; return false;
} }
try try
{ {
var tmpfile = liberator.io.createTempFile(); var tmpfile = io.createTempFile();
} }
catch (e) catch (e)
{ {
liberator.echoerr("Could not create temporary file: " + e.message); echoerr("Could not create temporary file: " + e.message);
return false; return false;
} }
try try
{ {
liberator.io.writeFile(tmpfile, text); io.writeFile(tmpfile, text);
} }
catch (e) catch (e)
{ {
liberator.echoerr("Could not write to temporary file " + tmpfile.path + ": " + e.message); echoerr("Could not write to temporary file " + tmpfile.path + ": " + e.message);
return false; return false;
} }
@@ -834,7 +833,7 @@ liberator.Editor = function () //{{{
} }
// TODO: save return value in v:shell_error // TODO: save return value in v:shell_error
liberator.callFunctionInThread(null, liberator.io.run, [prog, args, true]); callFunctionInThread(null, io.run, [prog, args, true]);
if (textBox) if (textBox)
textBox.removeAttribute("readonly"); textBox.removeAttribute("readonly");
@@ -842,13 +841,13 @@ liberator.Editor = function () //{{{
// if (v:shell_error != 0) // if (v:shell_error != 0)
// { // {
// tmpBg = "red"; // tmpBg = "red";
// liberator.echoerr("External editor returned with exit code " + retcode); // echoerr("External editor returned with exit code " + retcode);
// } // }
// else // else
// { // {
try try
{ {
var val = liberator.io.readFile(tmpfile); var val = io.readFile(tmpfile);
if (textBox) if (textBox)
textBox.value = val; textBox.value = val;
else else
@@ -869,7 +868,7 @@ liberator.Editor = function () //{{{
catch (e) catch (e)
{ {
tmpBg = "red"; tmpBg = "red";
liberator.echoerr("Could not read from temporary file " + tmpfile.path + ": " + e.message); echoerr("Could not read from temporary file " + tmpfile.path + ": " + e.message);
} }
// } // }
@@ -916,11 +915,11 @@ liberator.Editor = function () //{{{
for (let i = 0; i < abbrev[lhs].length; i++) for (let i = 0; i < abbrev[lhs].length; i++)
{ {
if (abbrev[lhs][i][0] == filter) if (abbrev[lhs][i][0] == filter)
liberator.echo(abbrev[lhs][i][0] + " " + lhs + " " + abbrev[lhs][i][1]); echo(abbrev[lhs][i][0] + " " + lhs + " " + abbrev[lhs][i][1]);
return true; return true;
} }
} }
liberator.echoerr("No abbreviations found"); echoerr("No abbreviations found");
return false; return false;
} }
else // list all (for that filter {i,c,!}) else // list all (for that filter {i,c,!})
@@ -931,8 +930,8 @@ liberator.Editor = function () //{{{
let list = let list =
<table> <table>
{ {
liberator.template.map(abbrev, function ([lhs, rhs]) template.map(abbrev, function ([lhs, rhs])
liberator.template.map(rhs, function (abbr) template.map(rhs, function (abbr)
searchFilter.indexOf(abbr[0]) < 0 ? undefined : searchFilter.indexOf(abbr[0]) < 0 ? undefined :
<tr> <tr>
<td>{abbr[0]}</td> <td>{abbr[0]}</td>
@@ -942,9 +941,9 @@ liberator.Editor = function () //{{{
} }
</table>; </table>;
if (list.*.length()) if (list.*.length())
liberator.commandline.echo(list, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
else else
liberator.echoerr("No abbreviations found"); echoerr("No abbreviations found");
} }
}, },
@@ -1034,7 +1033,7 @@ liberator.Editor = function () //{{{
{ {
if (!lhs) if (!lhs)
{ {
liberator.echoerr("E474: Invalid argument"); echoerr("E474: Invalid argument");
return false; return false;
} }
@@ -1072,7 +1071,7 @@ liberator.Editor = function () //{{{
} }
} }
liberator.echoerr("E24: No such abbreviation"); echoerr("E24: No such abbreviation");
return false; return false;
}, },

File diff suppressed because it is too large Load Diff

View File

@@ -37,7 +37,7 @@ the terms of any one of the MPL, the GPL or the LGPL.
// : incremental searches shouldn't permanently update search modifiers // : incremental searches shouldn't permanently update search modifiers
// make sure you only create this object when the "liberator" object is ready // make sure you only create this object when the "liberator" object is ready
liberator.Search = function () //{{{ with (liberator) liberator.Search = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -56,13 +56,13 @@ liberator.Search = function () //{{{
var linksOnly = false; // search is limited to link text only var linksOnly = false; // search is limited to link text only
// Event handlers for search - closure is needed // Event handlers for search - closure is needed
liberator.registerCallback("change", liberator.modes.SEARCH_FORWARD, function (command) { liberator.search.searchKeyPressed(command); }); registerCallback("change", modes.SEARCH_FORWARD, function (command) { search.searchKeyPressed(command); });
liberator.registerCallback("submit", liberator.modes.SEARCH_FORWARD, function (command) { liberator.search.searchSubmitted(command); }); registerCallback("submit", modes.SEARCH_FORWARD, function (command) { search.searchSubmitted(command); });
liberator.registerCallback("cancel", liberator.modes.SEARCH_FORWARD, function () { liberator.search.searchCanceled(); }); registerCallback("cancel", modes.SEARCH_FORWARD, function () { search.searchCanceled(); });
// TODO: allow advanced modes in register/triggerCallback // TODO: allow advanced myModes in register/triggerCallback
liberator.registerCallback("change", liberator.modes.SEARCH_BACKWARD, function (command) { liberator.search.searchKeyPressed(command); }); registerCallback("change", modes.SEARCH_BACKWARD, function (command) { search.searchKeyPressed(command); });
liberator.registerCallback("submit", liberator.modes.SEARCH_BACKWARD, function (command) { liberator.search.searchSubmitted(command); }); registerCallback("submit", modes.SEARCH_BACKWARD, function (command) { search.searchSubmitted(command); });
liberator.registerCallback("cancel", liberator.modes.SEARCH_BACKWARD, function () { liberator.search.searchCanceled(); }); registerCallback("cancel", modes.SEARCH_BACKWARD, function () { search.searchCanceled(); });
// set searchString, searchPattern, caseSensitive, linksOnly // set searchString, searchPattern, caseSensitive, linksOnly
function processUserPattern(pattern) function processUserPattern(pattern)
@@ -80,7 +80,7 @@ liberator.Search = function () //{{{
linksOnly = true; linksOnly = true;
else if (/\L/.test(pattern)) else if (/\L/.test(pattern))
linksOnly = false; linksOnly = false;
else if (liberator.options["linksearch"]) else if (options["linksearch"])
linksOnly = true; linksOnly = true;
else else
linksOnly = false; linksOnly = false;
@@ -93,9 +93,9 @@ liberator.Search = function () //{{{
caseSensitive = false; caseSensitive = false;
else if (/\C/.test(pattern)) else if (/\C/.test(pattern))
caseSensitive = true; caseSensitive = true;
else if (liberator.options["ignorecase"] && liberator.options["smartcase"] && /[A-Z]/.test(pattern)) else if (options["ignorecase"] && options["smartcase"] && /[A-Z]/.test(pattern))
caseSensitive = true; caseSensitive = true;
else if (liberator.options["ignorecase"]) else if (options["ignorecase"])
caseSensitive = false; caseSensitive = false;
else else
caseSensitive = true; caseSensitive = true;
@@ -177,7 +177,7 @@ liberator.Search = function () //{{{
} }
var baseNode = <span class="__liberator-search"/> var baseNode = <span class="__liberator-search"/>
baseNode = liberator.util.xmlToDom(baseNode, window.content.document); baseNode = util.xmlToDom(baseNode, window.content.document);
var body = doc.body; var body = doc.body;
var count = body.childNodes.length; var count = body.childNodes.length;
@@ -204,8 +204,8 @@ liberator.Search = function () //{{{
this.startPt.setStart(node, node.childNodes.length); this.startPt.setStart(node, node.childNodes.length);
this.startPt.setEnd(node, node.childNodes.length); this.startPt.setEnd(node, node.childNodes.length);
if (n++ % 20 == 0) if (n++ % 20 == 0)
liberator.threadYield(); threadYield();
if (liberator.interrupted) if (interrupted)
break; break;
} }
}, },
@@ -228,34 +228,34 @@ liberator.Search = function () //{{{
////////////////////// OPTIONS ///////////////////////////////////////////////// ////////////////////// OPTIONS /////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.options.add(["hlsearch", "hls"], options.add(["hlsearch", "hls"],
"Highlight previous search pattern matches", "Highlight previous search pattern matches",
"boolean", "false", "boolean", "false",
{ {
setter: function (value) setter: function (value)
{ {
if (value) if (value)
liberator.search.highlight(); search.highlight();
else else
liberator.search.clear(); search.clear();
return value; return value;
} }
}); });
liberator.options.add(["ignorecase", "ic"], options.add(["ignorecase", "ic"],
"Ignore case in search patterns", "Ignore case in search patterns",
"boolean", true); "boolean", true);
liberator.options.add(["incsearch", "is"], options.add(["incsearch", "is"],
"Show where the search pattern matches as it is typed", "Show where the search pattern matches as it is typed",
"boolean", true); "boolean", true);
liberator.options.add(["linksearch", "lks"], options.add(["linksearch", "lks"],
"Limit the search to hyperlink text", "Limit the search to hyperlink text",
"boolean", false); "boolean", false);
liberator.options.add(["smartcase", "scs"], options.add(["smartcase", "scs"],
"Override the 'ignorecase' option if the pattern contains uppercase characters", "Override the 'ignorecase' option if the pattern contains uppercase characters",
"boolean", true); "boolean", true);
@@ -263,48 +263,48 @@ liberator.Search = function () //{{{
////////////////////// MAPPINGS //////////////////////////////////////////////// ////////////////////// MAPPINGS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
var modes = liberator.config.browserModes || [liberator.modes.NORMAL]; var myModes = config.browserModes || [modes.NORMAL];
modes = modes.concat([liberator.modes.CARET]); myModes = myModes.concat([modes.CARET]);
liberator.mappings.add(modes, mappings.add(myModes,
["/"], "Search forward for a pattern", ["/"], "Search forward for a pattern",
function () { liberator.search.openSearchDialog(liberator.modes.SEARCH_FORWARD); }); function () { search.openSearchDialog(modes.SEARCH_FORWARD); });
liberator.mappings.add(modes, mappings.add(myModes,
["?"], "Search backwards for a pattern", ["?"], "Search backwards for a pattern",
function () { liberator.search.openSearchDialog(liberator.modes.SEARCH_BACKWARD); }); function () { search.openSearchDialog(modes.SEARCH_BACKWARD); });
liberator.mappings.add(modes, mappings.add(myModes,
["n"], "Find next", ["n"], "Find next",
function () { liberator.search.findAgain(false); }); function () { search.findAgain(false); });
liberator.mappings.add(modes, mappings.add(myModes,
["N"], "Find previous", ["N"], "Find previous",
function () { liberator.search.findAgain(true); }); function () { search.findAgain(true); });
liberator.mappings.add(modes.concat([liberator.modes.CARET, liberator.modes.TEXTAREA]), ["*"], mappings.add(myModes.concat([modes.CARET, modes.TEXTAREA]), ["*"],
"Find word under cursor", "Find word under cursor",
function () function ()
{ {
liberator.search.searchSubmitted(liberator.buffer.getCurrentWord(), false); search.searchSubmitted(buffer.getCurrentWord(), false);
liberator.search.findAgain(); search.findAgain();
}); });
liberator.mappings.add(modes.concat([liberator.modes.CARET, liberator.modes.TEXTAREA]), ["#"], mappings.add(myModes.concat([modes.CARET, modes.TEXTAREA]), ["#"],
"Find word under cursor backwards", "Find word under cursor backwards",
function () function ()
{ {
liberator.search.searchSubmitted(liberator.buffer.getCurrentWord(), true); search.searchSubmitted(buffer.getCurrentWord(), true);
liberator.search.findAgain(); search.findAgain();
}); });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// COMMANDS //////////////////////////////////////////////// ////////////////////// COMMANDS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.commands.add(["noh[lsearch]"], commands.add(["noh[lsearch]"],
"Remove the search highlighting", "Remove the search highlighting",
function () { liberator.search.clear(); }, function () { search.clear(); },
{ argCount: "0" }); { argCount: "0" });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
@@ -317,14 +317,14 @@ liberator.Search = function () //{{{
// If you omit "mode", it will default to forward searching // If you omit "mode", it will default to forward searching
openSearchDialog: function (mode) openSearchDialog: function (mode)
{ {
if (mode == liberator.modes.SEARCH_BACKWARD) if (mode == modes.SEARCH_BACKWARD)
{ {
liberator.commandline.open("?", "", liberator.modes.SEARCH_BACKWARD); commandline.open("?", "", modes.SEARCH_BACKWARD);
backwards = true; backwards = true;
} }
else else
{ {
liberator.commandline.open("/", "", liberator.modes.SEARCH_FORWARD); commandline.open("/", "", modes.SEARCH_FORWARD);
backwards = false; backwards = false;
} }
@@ -343,7 +343,7 @@ liberator.Search = function () //{{{
found = fastFind.find(searchString, linksOnly) != Components.interfaces.nsITypeAheadFind.FIND_NOTFOUND; found = fastFind.find(searchString, linksOnly) != Components.interfaces.nsITypeAheadFind.FIND_NOTFOUND;
if (!found) if (!found)
setTimeout(function () { liberator.echoerr("E486: Pattern not found: " + searchPattern); }, 0); setTimeout(function () { echoerr("E486: Pattern not found: " + searchPattern); }, 0);
return found; return found;
}, },
@@ -362,7 +362,7 @@ liberator.Search = function () //{{{
if (result == Components.interfaces.nsITypeAheadFind.FIND_NOTFOUND) if (result == Components.interfaces.nsITypeAheadFind.FIND_NOTFOUND)
{ {
liberator.echoerr("E486: Pattern not found: " + lastSearchPattern); echoerr("E486: Pattern not found: " + lastSearchPattern);
} }
else if (result == Components.interfaces.nsITypeAheadFind.FIND_WRAPPED) else if (result == Components.interfaces.nsITypeAheadFind.FIND_WRAPPED)
{ {
@@ -370,18 +370,18 @@ liberator.Search = function () //{{{
// our command line // our command line
setTimeout(function () { setTimeout(function () {
if (up) if (up)
liberator.commandline.echo("search hit TOP, continuing at BOTTOM", commandline.echo("search hit TOP, continuing at BOTTOM",
liberator.commandline.HL_WARNINGMSG, liberator.commandline.APPEND_TO_MESSAGES); commandline.HL_WARNINGMSG, commandline.APPEND_TO_MESSAGES);
else else
liberator.commandline.echo("search hit BOTTOM, continuing at TOP", commandline.echo("search hit BOTTOM, continuing at TOP",
liberator.commandline.HL_WARNINGMSG, liberator.commandline.APPEND_TO_MESSAGES); commandline.HL_WARNINGMSG, commandline.APPEND_TO_MESSAGES);
}, 0); }, 0);
} }
else else
{ {
liberator.echo((up ? "?" : "/") + lastSearchPattern, null, liberator.commandline.FORCE_SINGLELINE); echo((up ? "?" : "/") + lastSearchPattern, null, commandline.FORCE_SINGLELINE);
if (liberator.options["hlsearch"]) if (options["hlsearch"])
this.highlight(lastSearchString); this.highlight(lastSearchString);
} }
}, },
@@ -389,7 +389,7 @@ liberator.Search = function () //{{{
// Called when the user types a key in the search dialog. Triggers a find attempt if 'incsearch' is set // Called when the user types a key in the search dialog. Triggers a find attempt if 'incsearch' is set
searchKeyPressed: function (command) searchKeyPressed: function (command)
{ {
if (liberator.options["incsearch"]) if (options["incsearch"])
this.find(command, backwards); this.find(command, backwards);
}, },
@@ -405,7 +405,7 @@ liberator.Search = function () //{{{
command = lastSearchPattern; command = lastSearchPattern;
this.clear(); this.clear();
if (!liberator.options["incsearch"] || !found) if (!options["incsearch"] || !found)
this.find(command, backwards); this.find(command, backwards);
lastSearchBackwards = backwards; lastSearchBackwards = backwards;
@@ -416,12 +416,12 @@ liberator.Search = function () //{{{
// TODO: move to find() when reverse incremental searching is kludged in // TODO: move to find() when reverse incremental searching is kludged in
// need to find again for reverse searching // need to find again for reverse searching
if (backwards) if (backwards)
setTimeout(function () { liberator.search.findAgain(false); }, 0); setTimeout(function () { search.findAgain(false); }, 0);
if (liberator.options["hlsearch"]) if (options["hlsearch"])
this.highlight(searchString); this.highlight(searchString);
liberator.modes.reset(); modes.reset();
}, },
// Called when the search is canceled - for example if someone presses // Called when the search is canceled - for example if someone presses
@@ -436,7 +436,7 @@ liberator.Search = function () //{{{
// this is not dependent on the value of 'hlsearch' // this is not dependent on the value of 'hlsearch'
highlight: function (text) highlight: function (text)
{ {
if (liberator.config.name == "Muttator") if (config.name == "Muttator")
return; return;
// already highlighted? // already highlighted?

View File

@@ -26,13 +26,13 @@ the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL. the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/ }}} ***** END LICENSE BLOCK *****/
liberator.Hints = function () //{{{ with (liberator) liberator.Hints = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
var modes = liberator.config.browserModes || [liberator.modes.NORMAL]; var myModes = config.browserModes || [modes.NORMAL];
var submode = ""; // used for extended mode, can be "o", "t", "y", etc. var submode = ""; // used for extended mode, can be "o", "t", "y", etc.
var hintString = ""; // the typed string part of the hint is in this string var hintString = ""; // the typed string part of the hint is in this string
@@ -54,7 +54,7 @@ liberator.Hints = function () //{{{
// reset all important variables // reset all important variables
function reset() function reset()
{ {
liberator.statusline.updateInputBuffer(""); statusline.updateInputBuffer("");
hintString = ""; hintString = "";
hintNumber = 0; hintNumber = 0;
usedTabKey = false; usedTabKey = false;
@@ -71,7 +71,7 @@ liberator.Hints = function () //{{{
function updateStatusline() function updateStatusline()
{ {
liberator.statusline.updateInputBuffer((escapeNumbers ? liberator.mappings.getMapLeader() + " " : "") + // sign for escapeNumbers statusline.updateInputBuffer((escapeNumbers ? mappings.getMapLeader() + " " : "") + // sign for escapeNumbers
(hintString ? "\"" + hintString + "\"" : "") + (hintString ? "\"" + hintString + "\"" : "") +
(hintNumber > 0 ? " <" + hintNumber + ">" : "")); (hintNumber > 0 ? " <" + hintNumber + ">" : ""));
} }
@@ -87,11 +87,11 @@ liberator.Hints = function () //{{{
var scrollX = doc.defaultView.scrollX; var scrollX = doc.defaultView.scrollX;
var scrollY = doc.defaultView.scrollY; var scrollY = doc.defaultView.scrollY;
var baseNodeAbsolute = liberator.util.xmlToDom( var baseNodeAbsolute = util.xmlToDom(
<span class="liberator-hint"/>, doc); <span class="liberator-hint"/>, doc);
var elem, tagname, text, span, rect; var elem, tagname, text, span, rect;
var res = liberator.buffer.evaluateXPath(liberator.options["hinttags"], doc, null, true); var res = buffer.evaluateXPath(options["hinttags"], doc, null, true);
var fragment = doc.createDocumentFragment(); var fragment = doc.createDocumentFragment();
var start = hints.length; var start = hints.length;
@@ -147,19 +147,19 @@ liberator.Hints = function () //{{{
{ {
var oldElem = validHints[oldID - 1]; var oldElem = validHints[oldID - 1];
if (oldElem) if (oldElem)
oldElem.style.backgroundColor = liberator.options["linkbgcolor"]; oldElem.style.backgroundColor = options["linkbgcolor"];
var newElem = validHints[newID - 1]; var newElem = validHints[newID - 1];
if (newElem) if (newElem)
newElem.style.backgroundColor = liberator.options["activelinkbgcolor"]; newElem.style.backgroundColor = options["activelinkbgcolor"];
} }
function showHints() function showHints()
{ {
var linkfgcolor = liberator.options["linkfgcolor"]; var linkfgcolor = options["linkfgcolor"];
var linkbgcolor = liberator.options["linkbgcolor"]; var linkbgcolor = options["linkbgcolor"];
var activelinkfgcolor = liberator.options["activelinkfgcolor"]; var activelinkfgcolor = options["activelinkfgcolor"];
var activelinkbgcolor = liberator.options["activelinkbgcolor"]; var activelinkbgcolor = options["activelinkbgcolor"];
var elem, tagname, text, rect, span, imgspan; var elem, tagname, text, rect, span, imgspan;
var hintnum = 1; var hintnum = 1;
@@ -176,12 +176,10 @@ liberator.Hints = function () //{{{
var scrollY = doc.defaultView.scrollY; var scrollY = doc.defaultView.scrollY;
inner: inner:
for (let i = start; i <= end; i++) for (let i in (util.rangeInterruptable(start, end + 1, 500)))
{ {
elem = hints[i][0]; let hint = hints[i];
text = hints[i][1]; [elem, text, span, imgspan] = hint;
span = hints[i][2];
imgspan = hints[i][3];
if (!validHint(text)) if (!validHint(text))
{ {
@@ -190,8 +188,8 @@ liberator.Hints = function () //{{{
imgspan.style.display = "none"; imgspan.style.display = "none";
// reset background color // reset background color
elem.style.backgroundColor = hints[i][4]; elem.style.backgroundColor = hint[4];
elem.style.color = hints[i][5]; elem.style.color = hint[5];
continue inner; continue inner;
} }
@@ -212,7 +210,7 @@ liberator.Hints = function () //{{{
imgspan.style.width = (rect.right - rect.left) + "px"; imgspan.style.width = (rect.right - rect.left) + "px";
imgspan.style.height = (rect.bottom - rect.top) + "px"; imgspan.style.height = (rect.bottom - rect.top) + "px";
imgspan.className = "liberator-hint"; imgspan.className = "liberator-hint";
hints[i][3] = imgspan; hint[3] = imgspan;
doc.body.appendChild(imgspan); doc.body.appendChild(imgspan);
} }
imgspan.style.backgroundColor = (activeHint == hintnum) ? activelinkbgcolor : linkbgcolor; imgspan.style.backgroundColor = (activeHint == hintnum) ? activelinkbgcolor : linkbgcolor;
@@ -245,22 +243,23 @@ liberator.Hints = function () //{{{
for (let i = start; i <= end; i++) for (let i = start; i <= end; i++)
{ {
let hint = hits[i];
// remove the span for the numeric display part // remove the span for the numeric display part
doc.body.removeChild(hints[i][2]); doc.body.removeChild(hint[2]);
if (hints[i][3]) // a transparent span for images if (hint[3]) // a transparent span for images
doc.body.removeChild(hints[i][3]); doc.body.removeChild(hint[3]);
if (timeout && firstElem == hints[i][0]) if (timeout && firstElem == hint[0])
{ {
firstElemBgColor = hints[i][4]; firstElemBgColor = hint[4];
firstElemColor = hints[i][5]; firstElemColor = hint[5];
} }
else else
{ {
// restore colors // restore colors
var elem = hints[i][0]; var elem = hint[0];
elem.style.backgroundColor = hints[i][4]; elem.style.backgroundColor = hint[4];
elem.style.color = hints[i][5]; elem.style.color = hint[5];
} }
} }
@@ -304,7 +303,7 @@ liberator.Hints = function () //{{{
{ {
if (validHints.length == 0) if (validHints.length == 0)
{ {
liberator.beep(); beep();
return false; return false;
} }
@@ -326,50 +325,50 @@ liberator.Hints = function () //{{{
var loc = elem.href || ""; var loc = elem.href || "";
switch (submode) switch (submode)
{ {
case ";": liberator.buffer.focusElement(elem); break; case ";": buffer.focusElement(elem); break;
case "?": liberator.buffer.showElementInfo(elem); break; case "?": buffer.showElementInfo(elem); break;
case "a": liberator.buffer.saveLink(elem, false); break; case "a": buffer.saveLink(elem, false); break;
case "s": liberator.buffer.saveLink(elem, true); break; case "s": buffer.saveLink(elem, true); break;
case "o": liberator.buffer.followLink(elem, liberator.CURRENT_TAB); break; case "o": buffer.followLink(elem, CURRENT_TAB); break;
case "O": liberator.commandline.open(":", "open " + loc, liberator.modes.EX); break; case "O": commandline.open(":", "open " + loc, modes.EX); break;
case "t": liberator.buffer.followLink(elem, liberator.NEW_TAB); break; case "t": buffer.followLink(elem, NEW_TAB); break;
case "b": liberator.buffer.followLink(elem, liberator.NEW_BACKGROUND_TAB); break; case "b": buffer.followLink(elem, NEW_BACKGROUND_TAB); break;
case "T": liberator.commandline.open(":", "tabopen " + loc, liberator.modes.EX); break; case "T": commandline.open(":", "tabopen " + loc, modes.EX); break;
case "v": liberator.buffer.viewSource(loc, false); break; case "v": buffer.viewSource(loc, false); break;
case "V": liberator.buffer.viewSource(loc, true); break; case "V": buffer.viewSource(loc, true); break;
case "w": liberator.buffer.followLink(elem, liberator.NEW_WINDOW); break; case "w": buffer.followLink(elem, NEW_WINDOW); break;
case "W": liberator.commandline.open(":", "winopen " + loc, liberator.modes.EX); break; case "W": commandline.open(":", "winopen " + loc, modes.EX); break;
case "y": setTimeout(function () { liberator.util.copyToClipboard(loc, true); }, timeout + 50); break; case "y": setTimeout(function () { util.copyToClipboard(loc, true); }, timeout + 50); break;
case "Y": setTimeout(function () { liberator.util.copyToClipboard(elem.textContent || "", true); }, timeout + 50); break; case "Y": setTimeout(function () { util.copyToClipboard(elem.textContent || "", true); }, timeout + 50); break;
default: default:
liberator.echoerr("INTERNAL ERROR: unknown submode: " + submode); echoerr("INTERNAL ERROR: unknown submode: " + submode);
} }
removeHints(timeout); removeHints(timeout);
if (liberator.modes.extended & liberator.modes.ALWAYS_HINT) if (modes.extended & modes.ALWAYS_HINT)
{ {
setTimeout(function () { setTimeout(function () {
canUpdate = true; canUpdate = true;
hintString = ""; hintString = "";
hintNumber = 0; hintNumber = 0;
liberator.statusline.updateInputBuffer(""); statusline.updateInputBuffer("");
}, timeout); }, timeout);
} }
else else
{ {
if (timeout == 0 || liberator.modes.isReplaying) if (timeout == 0 || modes.isReplaying)
{ {
// force a possible mode change, based on wheter an input field has focus // force a possible mode change, based on wheter an input field has focus
liberator.events.onFocusChange(); events.onFocusChange();
if (liberator.mode == liberator.modes.HINTS) if (mode == modes.HINTS)
liberator.modes.reset(false); modes.reset(false);
} }
else else
{ {
liberator.modes.add(liberator.modes.INACTIVE_HINT); modes.add(modes.INACTIVE_HINT);
setTimeout(function () { setTimeout(function () {
if (liberator.mode == liberator.modes.HINTS) if (mode == modes.HINTS)
liberator.modes.pop(); modes.pop();
}, timeout); }, timeout);
} }
} }
@@ -400,7 +399,7 @@ liberator.Hints = function () //{{{
function wordStartsWithMatcher(hintString, allowWordOverleaping) //{{{ function wordStartsWithMatcher(hintString, allowWordOverleaping) //{{{
{ {
var hintStrings = hintString.split(/ +/); var hintStrings = hintString.split(/ +/);
var wordSplitRegex = new RegExp(liberator.options["wordseparators"]); var wordSplitRegex = new RegExp(options["wordseparators"]);
function charsAtBeginningOfWords(chars, words, allowWordOverleaping) function charsAtBeginningOfWords(chars, words, allowWordOverleaping)
{ {
@@ -530,14 +529,14 @@ liberator.Hints = function () //{{{
return wordStartsWith; return wordStartsWith;
} //}}} } //}}}
var hintMatching = liberator.options["hintmatching"]; var hintMatching = options["hintmatching"];
switch (hintMatching) switch (hintMatching)
{ {
case "contains" : return containsMatcher(hintString); case "contains" : return containsMatcher(hintString);
case "wordstartswith": return wordStartsWithMatcher(hintString, /*allowWordOverleaping=*/ true); case "wordstartswith": return wordStartsWithMatcher(hintString, /*allowWordOverleaping=*/ true);
case "firstletters" : return wordStartsWithMatcher(hintString, /*allowWordOverleaping=*/ false); case "firstletters" : return wordStartsWithMatcher(hintString, /*allowWordOverleaping=*/ false);
case "custom" : return liberator.plugins.customHintMatcher(hintString); case "custom" : return plugins.customHintMatcher(hintString);
default : liberator.echoerr("Invalid hintmatching type: " + hintMatching); default : echoerr("Invalid hintmatching type: " + hintMatching);
} }
return null; return null;
} //}}} } //}}}
@@ -551,36 +550,36 @@ liberator.Hints = function () //{{{
"//xhtml:*[@onclick or @onmouseover or @onmousedown or @onmouseup or @oncommand or @class='lk' or @class='s'] | " + "//xhtml:*[@onclick or @onmouseover or @onmousedown or @onmouseup or @oncommand or @class='lk' or @class='s'] | " +
"//xhtml:input[not(@type='hidden')] | //xhtml:a | //xhtml:area | //xhtml:iframe | //xhtml:textarea | //xhtml:button | //xhtml:select"; "//xhtml:input[not(@type='hidden')] | //xhtml:a | //xhtml:area | //xhtml:iframe | //xhtml:textarea | //xhtml:button | //xhtml:select";
liberator.options.add(["extendedhinttags", "eht"], options.add(["extendedhinttags", "eht"],
"XPath string of hintable elements activated by ';'", "XPath string of hintable elements activated by ';'",
"string", DEFAULT_HINTTAGS); "string", DEFAULT_HINTTAGS);
liberator.options.add(["hinttags", "ht"], options.add(["hinttags", "ht"],
"XPath string of hintable elements activated by 'f' and 'F'", "XPath string of hintable elements activated by 'f' and 'F'",
"string", DEFAULT_HINTTAGS); "string", DEFAULT_HINTTAGS);
liberator.options.add(["hinttimeout", "hto"], options.add(["hinttimeout", "hto"],
"Automatically follow non unique numerical hint", "Automatically follow non unique numerical hint",
"number", 0, "number", 0,
{ validator: function (value) value >= 0 }); { validator: function (value) value >= 0 });
liberator.options.add(["linkfgcolor", "lfc"], options.add(["linkfgcolor", "lfc"],
"Foreground color of a link during hint mode", "Foreground color of a link during hint mode",
"string", "black"); "string", "black");
liberator.options.add(["linkbgcolor", "lbc"], options.add(["linkbgcolor", "lbc"],
"Background color of a link during hint mode", "Background color of a link during hint mode",
"string", "yellow"); "string", "yellow");
liberator.options.add(["activelinkfgcolor", "alfc"], options.add(["activelinkfgcolor", "alfc"],
"Foreground color of the current active link during hint mode", "Foreground color of the current active link during hint mode",
"string", "black"); "string", "black");
liberator.options.add(["activelinkbgcolor", "albc"], options.add(["activelinkbgcolor", "albc"],
"Background color of the current active link during hint mode", "Background color of the current active link during hint mode",
"string", "#88FF00"); "string", "#88FF00");
liberator.options.add(["hintmatching", "hm"], options.add(["hintmatching", "hm"],
"How links are matched", "How links are matched",
"string", "contains", "string", "contains",
{ {
@@ -591,7 +590,7 @@ liberator.Hints = function () //{{{
validator: function (value) /^(contains|wordstartswith|firstletters|custom)$/.test(value) validator: function (value) /^(contains|wordstartswith|firstletters|custom)$/.test(value)
}); });
liberator.options.add(["wordseparators", "wsp"], options.add(["wordseparators", "wsp"],
"How words are split for hintmatching", "How words are split for hintmatching",
"string", '[\\.,!\\?:;/\\\"\\^\\$%&?\\(\\)\\[\\]\\{\\}<>#\\*\\+\\|=~ _\\-]'); "string", '[\\.,!\\?:;/\\\"\\^\\$%&?\\(\\)\\[\\]\\{\\}<>#\\*\\+\\|=~ _\\-]');
@@ -599,26 +598,26 @@ liberator.Hints = function () //{{{
////////////////////// MAPPINGS //////////////////////////////////////////////// ////////////////////// MAPPINGS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.mappings.add(modes, ["f"], mappings.add(myModes, ["f"],
"Start QuickHint mode", "Start QuickHint mode",
function () { liberator.hints.show(liberator.modes.QUICK_HINT); }); function () { hints.show(modes.QUICK_HINT); });
liberator.mappings.add(modes, ["F"], mappings.add(myModes, ["F"],
"Start QuickHint mode, but open link in a new tab", "Start QuickHint mode, but open link in a new tab",
function () { liberator.hints.show(liberator.modes.QUICK_HINT, "t"); }); function () { hints.show(modes.QUICK_HINT, "t"); });
liberator.mappings.add(modes, [";"], mappings.add(myModes, [";"],
"Start an extended hint mode", "Start an extended hint mode",
function (arg) function (arg)
{ {
if (arg == "f") if (arg == "f")
liberator.hints.show(liberator.modes.ALWAYS_HINT, "o"); hints.show(modes.ALWAYS_HINT, "o");
else if (arg == "F") else if (arg == "F")
liberator.hints.show(liberator.modes.ALWAYS_HINT, "t"); hints.show(modes.ALWAYS_HINT, "t");
else else
liberator.hints.show(liberator.modes.EXTENDED_HINT, arg); hints.show(modes.EXTENDED_HINT, arg);
}, },
{ flags: liberator.Mappings.flags.ARGUMENT }); { flags: Mappings.flags.ARGUMENT });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// PUBLIC SECTION ////////////////////////////////////////// ////////////////////// PUBLIC SECTION //////////////////////////////////////////
@@ -628,13 +627,13 @@ liberator.Hints = function () //{{{
show: function (mode, minor, filter, win) show: function (mode, minor, filter, win)
{ {
if (mode == liberator.modes.EXTENDED_HINT && !/^[;?asoOtbTvVwWyY]$/.test(minor)) if (mode == modes.EXTENDED_HINT && !/^[;?asoOtbTvVwWyY]$/.test(minor))
{ {
liberator.beep(); beep();
return; return;
} }
liberator.modes.push(liberator.modes.HINTS, mode, win != undefined); modes.push(modes.HINTS, mode, win != undefined);
submode = minor || "o"; // open is the default mode submode = minor || "o"; // open is the default mode
hintString = filter || ""; hintString = filter || "";
hintNumber = 0; hintNumber = 0;
@@ -643,15 +642,15 @@ liberator.Hints = function () //{{{
generate(win); generate(win);
// get all keys from the input queue // get all keys from the input queue
liberator.threadYield(true); threadYield(true);
canUpdate = true; canUpdate = true;
showHints(); showHints();
if (validHints.length == 0) if (validHints.length == 0)
{ {
liberator.beep(); beep();
liberator.modes.reset(); modes.reset();
return false; return false;
} }
else if (validHints.length == 1) else if (validHints.length == 1)
@@ -670,7 +669,7 @@ liberator.Hints = function () //{{{
onEvent: function (event) onEvent: function (event)
{ {
var key = liberator.events.toString(event); var key = events.toString(event);
var followFirst = false; var followFirst = false;
// clear any timeout which might be active after pressing a number // clear any timeout which might be active after pressing a number
@@ -726,7 +725,7 @@ liberator.Hints = function () //{{{
{ {
usedTabKey = false; usedTabKey = false;
hintNumber = 0; hintNumber = 0;
liberator.beep(); beep();
return; return;
} }
break; break;
@@ -737,7 +736,7 @@ liberator.Hints = function () //{{{
hintNumber = 0; hintNumber = 0;
break; break;
case liberator.mappings.getMapLeader(): case mappings.getMapLeader():
escapeNumbers = !escapeNumbers; escapeNumbers = !escapeNumbers;
if (escapeNumbers && usedTabKey) // hintNumber not used normally, but someone may wants to toggle if (escapeNumbers && usedTabKey) // hintNumber not used normally, but someone may wants to toggle
hintNumber = 0; // <tab>s ? reset. Prevent to show numbers not entered. hintNumber = 0; // <tab>s ? reset. Prevent to show numbers not entered.
@@ -750,14 +749,14 @@ liberator.Hints = function () //{{{
if (/^<./.test(key) || key == ":") if (/^<./.test(key) || key == ":")
{ {
var map = null; var map = null;
if ((map = liberator.mappings.get(liberator.modes.NORMAL, key)) || if ((map = mappings.get(modes.NORMAL, key)) ||
(map = liberator.mappings.get(liberator.modes.HINTS, key))) (map = mappings.get(modes.HINTS, key)))
{ {
map.execute(null, -1); map.execute(null, -1);
return; return;
} }
liberator.beep(); beep();
return; return;
} }
@@ -786,7 +785,7 @@ liberator.Hints = function () //{{{
if (hintNumber == 0 || hintNumber > validHints.length) if (hintNumber == 0 || hintNumber > validHints.length)
{ {
liberator.beep(); beep();
return; return;
} }
@@ -794,7 +793,7 @@ liberator.Hints = function () //{{{
// the hint after a timeout, as the user might have wanted to follow link 34 // the hint after a timeout, as the user might have wanted to follow link 34
if (hintNumber > 0 && hintNumber * 10 <= validHints.length) if (hintNumber > 0 && hintNumber * 10 <= validHints.length)
{ {
var timeout = liberator.options["hinttimeout"]; var timeout = options["hinttimeout"];
if (timeout > 0) if (timeout > 0)
activeTimeout = setTimeout(function () { processHints(true); }, timeout); activeTimeout = setTimeout(function () { processHints(true); }, timeout);

View File

@@ -28,14 +28,14 @@ the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/ }}} ***** END LICENSE BLOCK *****/
// TODO: why are we passing around strings rather than file objects? // TODO: why are we passing around strings rather than file objects?
liberator.IO = function () //{{{ with (liberator) liberator.IO = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
const WINDOWS = navigator.platform == "Win32"; const WINDOWS = navigator.platform == "Win32";
const EXTENSION_NAME = liberator.config.name.toLowerCase(); // "vimperator" or "muttator" const EXTENSION_NAME = config.name.toLowerCase(); // "vimperator" or "muttator"
var environmentService = Components.classes["@mozilla.org/process/environment;1"] var environmentService = Components.classes["@mozilla.org/process/environment;1"]
.getService(Components.interfaces.nsIEnvironment); .getService(Components.interfaces.nsIEnvironment);
@@ -69,7 +69,7 @@ liberator.IO = function () //{{{
function expandPathList(list) function expandPathList(list)
{ {
return list.split(",").map(liberator.io.expandPath).join(","); return list.split(",").map(io.expandPath).join(",");
} }
// TODO: why are we passing around so many strings? I know that the XPCOM // TODO: why are we passing around so many strings? I know that the XPCOM
@@ -89,22 +89,22 @@ liberator.IO = function () //{{{
////////////////////// OPTIONS //////////////////////////////////////////////// ////////////////////// OPTIONS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.options.add(["cdpath", "cd"], options.add(["cdpath", "cd"],
"List of directories searched when executing :cd", "List of directories searched when executing :cd",
"stringlist", cdpath, "stringlist", cdpath,
{ setter: function (value) expandPathList(value) }); { setter: function (value) expandPathList(value) });
liberator.options.add(["runtimepath", "rtp"], options.add(["runtimepath", "rtp"],
"List of directories searched for runtime files", "List of directories searched for runtime files",
"stringlist", runtimepath, "stringlist", runtimepath,
{ setter: function (value) expandPathList(value) }); { setter: function (value) expandPathList(value) });
liberator.options.add(["shell", "sh"], options.add(["shell", "sh"],
"Shell to use for executing :! and :run commands", "Shell to use for executing :! and :run commands",
"string", shell, "string", shell,
{ setter: function (value) liberator.io.expandPath(value) }); { setter: function (value) io.expandPath(value) });
liberator.options.add(["shellcmdflag", "shcf"], options.add(["shellcmdflag", "shcf"],
"Flag passed to shell when executing :! and :run commands", "Flag passed to shell when executing :! and :run commands",
"string", shellcmdflag); "string", shellcmdflag);
@@ -112,7 +112,7 @@ liberator.IO = function () //{{{
////////////////////// COMMANDS //////////////////////////////////////////////// ////////////////////// COMMANDS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.commands.add(["cd", "chd[ir]"], commands.add(["cd", "chd[ir]"],
"Change the current directory", "Change the current directory",
function (args) function (args)
{ {
@@ -128,28 +128,28 @@ liberator.IO = function () //{{{
} }
else else
{ {
liberator.echoerr("E186: No previous directory"); echoerr("E186: No previous directory");
return; return;
} }
} }
args = liberator.io.expandPath(args); args = io.expandPath(args);
// go directly to an absolute path or look for a relative path // go directly to an absolute path or look for a relative path
// match in 'cdpath' // match in 'cdpath'
if (/^(~|\/|[a-z]:|\.\/|\.\.\/)/i.test(args)) if (/^(~|\/|[a-z]:|\.\/|\.\.\/)/i.test(args))
{ {
// TODO: apparently we don't handle ../ or ./ paths yet // TODO: apparently we don't handle ../ or ./ paths yet
if (liberator.io.setCurrentDirectory(args)) if (io.setCurrentDirectory(args))
liberator.echo(liberator.io.getCurrentDirectory()); echo(io.getCurrentDirectory());
} }
else else
{ {
var directories = liberator.options["cdpath"].replace(/^,$|^,,|,,$/, "").split(","); var directories = options["cdpath"].replace(/^,$|^,,|,,$/, "").split(",");
// empty 'cdpath' items mean the current directory // empty 'cdpath' items mean the current directory
directories = directories.map( directories = directories.map(
function (directory) directory == "" ? liberator.io.getCurrentDirectory() : directory function (directory) directory == "" ? io.getCurrentDirectory() : directory
); );
var directoryFound = false; var directoryFound = false;
@@ -157,11 +157,11 @@ liberator.IO = function () //{{{
for (let i = 0; i < directories.length; i++) for (let i = 0; i < directories.length; i++)
{ {
var dir = joinPaths(directories[i], args); var dir = joinPaths(directories[i], args);
if (liberator.io.setCurrentDirectory(dir)) if (io.setCurrentDirectory(dir))
{ {
// FIXME: we're just overwriting the error message from // FIXME: we're just overwriting the error message from
// setCurrentDirectory here // setCurrentDirectory here
liberator.echo(liberator.io.getCurrentDirectory()); echo(io.getCurrentDirectory());
directoryFound = true; directoryFound = true;
break; break;
} }
@@ -169,27 +169,27 @@ liberator.IO = function () //{{{
if (!directoryFound) if (!directoryFound)
{ {
liberator.echoerr("E344: Can't find directory \"" + args + "\" in cdpath" echoerr("E344: Can't find directory \"" + args + "\" in cdpath"
+ "\n" + "\n"
+ "E472: Command failed"); + "E472: Command failed");
} }
} }
}, },
{ completer: function (filter) liberator.completion.file(filter, true) }); { completer: function (filter) completion.file(filter, true) });
// NOTE: this command is only used in :source // NOTE: this command is only used in :source
liberator.commands.add(["fini[sh]"], commands.add(["fini[sh]"],
"Stop sourcing a script file", "Stop sourcing a script file",
function () { liberator.echoerr("E168: :finish used outside of a sourced file"); }, function () { echoerr("E168: :finish used outside of a sourced file"); },
{ argCount: "0" }); { argCount: "0" });
liberator.commands.add(["pw[d]"], commands.add(["pw[d]"],
"Print the current directory name", "Print the current directory name",
function () { liberator.echo(liberator.io.getCurrentDirectory()); }, function () { echo(io.getCurrentDirectory()); },
{ argCount: "0" }); { argCount: "0" });
// "mkv[imperatorrc]" or "mkm[uttatorrc]" // "mkv[imperatorrc]" or "mkm[uttatorrc]"
liberator.commands.add([EXTENSION_NAME.replace(/(.)(.*)/, "mk$1[$2rc]")], commands.add([EXTENSION_NAME.replace(/(.)(.*)/, "mk$1[$2rc]")],
"Write current key mappings and changed options to the config file", "Write current key mappings and changed options to the config file",
function (args, special) function (args, special)
{ {
@@ -200,27 +200,26 @@ liberator.IO = function () //{{{
else else
filename = "~/" + (WINDOWS ? "_" : ".") + EXTENSION_NAME + "rc"; filename = "~/" + (WINDOWS ? "_" : ".") + EXTENSION_NAME + "rc";
var file = liberator.io.getFile(filename); var file = io.getFile(filename);
if (file.exists() && !special) if (file.exists() && !special)
{ {
liberator.echoerr("E189: \"" + filename + "\" exists (add ! to override)"); echoerr("E189: \"" + filename + "\" exists (add ! to override)");
return; return;
} }
var line = "\" " + liberator.version + "\n"; var line = "\" " + version + "\n";
line += "\" Mappings\n"; line += "\" Mappings\n";
var modes = [[[liberator.modes.NORMAL], ""], [[liberator.modes.COMMAND_LINE], "c"], [[[modes.NORMAL], ""],
[[liberator.modes.INSERT, liberator.modes.TEXTAREA], "i"]]; [[modes.COMMAND_LINE], "c"],
for (let i = 0; i < modes.length; i++) [[modes.INSERT, modes.TEXTAREA], "i"]].forEach(function ([modes, modechar]) {
{
// NOTE: names.length is always 1 on user maps. If that changes, also fix getUserIterator and v.m.list // NOTE: names.length is always 1 on user maps. If that changes, also fix getUserIterator and v.m.list
for (let map in liberator.mappings.getUserIterator(modes[i][0])) for (let map in mappings.getUserIterator(modes))
line += modes[i][1] + (map.noremap ? "nore" : "") + "map " + map.names[0] + " " + map.rhs + "\n"; line += modechar + (map.noremap ? "noremap" : "map") + " " + map.names[0] + " " + map.rhs + "\n";
} });
line += "\n\" Options\n"; line += "\n\" Options\n";
for (let option in liberator.options) for (let option in options)
{ {
// TODO: options should be queried for this info // TODO: options should be queried for this info
// TODO: string/list options might need escaping in future // TODO: string/list options might need escaping in future
@@ -235,15 +234,15 @@ liberator.IO = function () //{{{
// :mkvimrc doesn't save autocommands, so we don't either - remove this code at some point // :mkvimrc doesn't save autocommands, so we don't either - remove this code at some point
// line += "\n\" Auto-Commands\n"; // line += "\n\" Auto-Commands\n";
// for (let item in liberator.autocommands) // for (let item in autocommands)
// line += "autocmd " + item.event + " " + item.pattern.source + " " + item.command + "\n"; // line += "autocmd " + item.event + " " + item.pattern.source + " " + item.command + "\n";
line += "\n\" Abbreviations\n"; line += "\n\" Abbreviations\n";
for (let abbrCmd in liberator.editor.abbreviations) for (let abbrCmd in editor.abbreviations)
line += abbrCmd; line += abbrCmd;
// if (liberator.mappings.getMapLeader() != "\\") // if (mappings.getMapLeader() != "\\")
// line += "\nlet mapleader = \"" + liberator.mappings.getMapLeader() + "\"\n"; // line += "\nlet mapleader = \"" + mappings.getMapLeader() + "\"\n";
// source a user .vimperatorrc file // source a user .vimperatorrc file
line += "\nsource! " + filename + ".local\n"; line += "\nsource! " + filename + ".local\n";
@@ -251,20 +250,20 @@ liberator.IO = function () //{{{
try try
{ {
liberator.io.writeFile(file, line); io.writeFile(file, line);
} }
catch (e) catch (e)
{ {
liberator.echoerr("E190: Cannot open \"" + filename + "\" for writing"); echoerr("E190: Cannot open \"" + filename + "\" for writing");
liberator.log("Could not write to " + file.path + ": " + e.message); // XXX log("Could not write to " + file.path + ": " + e.message); // XXX
} }
}, },
{ {
bang: true, bang: true,
completer: function (filter) liberator.completion.file(filter, true) completer: function (filter) completion.file(filter, true)
}); });
liberator.commands.add(["ru[ntime]"], commands.add(["ru[ntime]"],
"Source the specified file from each directory in 'runtimepath'", "Source the specified file from each directory in 'runtimepath'",
function (args, special) function (args, special)
{ {
@@ -272,25 +271,25 @@ liberator.IO = function () //{{{
// : wildcards/regexp // : wildcards/regexp
// : unify with startup sourcing loop // : unify with startup sourcing loop
let paths = args.arguments; let paths = args.arguments;
let runtimeDirs = liberator.options["runtimepath"].split(","); let runtimeDirs = options["runtimepath"].split(",");
let found = false; let found = false;
// FIXME: should use original arg string // FIXME: should use original arg string
liberator.echomsg("Searching for \"" + paths.join(" ") + "\" in \"" + liberator.options["runtimepath"] + "\"", 2); echomsg("Searching for \"" + paths.join(" ") + "\" in \"" + options["runtimepath"] + "\"", 2);
outer: outer:
for (let [,runtimeDir] in Iterator(runtimeDirs)) for (let [,runtimeDir] in Iterator(runtimeDirs))
{ {
for (let [,path] in Iterator(paths)) for (let [,path] in Iterator(paths))
{ {
let file = liberator.io.getFile(joinPaths(runtimeDir, path)); let file = io.getFile(joinPaths(runtimeDir, path));
liberator.echomsg("Searching for \"" + file.path + "\" in \"", 3); echomsg("Searching for \"" + file.path + "\" in \"", 3);
if (file.exists() && file.isReadable() && !file.isDirectory()) // XXX if (file.exists() && file.isReadable() && !file.isDirectory()) // XXX
{ {
found = true; found = true;
liberator.io.source(file.path, false); io.source(file.path, false);
if (!special) if (!special)
break outer; break outer;
@@ -299,7 +298,7 @@ liberator.IO = function () //{{{
} }
if (!found) if (!found)
liberator.echomsg("not found in 'runtimepath': \"" + paths.join(" ") + "\"", 1); // FIXME: should use original arg string echomsg("not found in 'runtimepath': \"" + paths.join(" ") + "\"", 1); // FIXME: should use original arg string
}, },
{ {
argCount: "+", argCount: "+",
@@ -307,36 +306,36 @@ liberator.IO = function () //{{{
} }
); );
liberator.commands.add(["scrip[tnames]"], commands.add(["scrip[tnames]"],
"List all sourced script names", "List all sourced script names",
function () function ()
{ {
var list = liberator.template.tabular(["<SNR>", "Filename"], ["text-align: right; padding-right: 1em;"], var list = template.tabular(["<SNR>", "Filename"], ["text-align: right; padding-right: 1em;"],
([i + 1, file] for ([i, file] in Iterator(scriptNames)))); // TODO: add colon? ([i + 1, file] for ([i, file] in Iterator(scriptNames)))); // TODO: add colon?
liberator.commandline.echo(list, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
}, },
{ argCount: "0" }); { argCount: "0" });
liberator.commands.add(["so[urce]"], commands.add(["so[urce]"],
"Read Ex commands from a file", "Read Ex commands from a file",
function (args, special) function (args, special)
{ {
// FIXME: implement proper filename quoting - "E172: Only one file name allowed" // FIXME: implement proper filename quoting - "E172: Only one file name allowed"
if (!args) if (!args)
{ {
liberator.echoerr("E471: Argument required"); echoerr("E471: Argument required");
return; return;
} }
liberator.io.source(args, special); io.source(args, special);
}, },
{ {
bang: true, bang: true,
completer: function (filter) liberator.completion.file(filter, true) completer: function (filter) completion.file(filter, true)
}); });
liberator.commands.add(["!", "run"], commands.add(["!", "run"],
"Run a command", "Run a command",
function (args, special) function (args, special)
{ {
@@ -349,12 +348,12 @@ liberator.IO = function () //{{{
args = args.replace(/(^|[^\\])!/g, "$1" + lastRunCommand); args = args.replace(/(^|[^\\])!/g, "$1" + lastRunCommand);
lastRunCommand = args; lastRunCommand = args;
var output = liberator.io.system(args); var output = io.system(args);
var command = ":" + liberator.util.escapeHTML(liberator.commandline.getCommand()) + "<br/>"; var command = ":" + util.escapeHTML(commandline.getCommand()) + "<br/>";
liberator.echo(command + liberator.util.escapeHTML(output)); echo(command + util.escapeHTML(output));
liberator.autocommands.trigger("ShellCmdPost", {}); autocommands.trigger("ShellCmdPost", {});
}, },
{ bang: true }); { bang: true });
@@ -440,7 +439,7 @@ liberator.IO = function () //{{{
if (!dir.exists() || !dir.isDirectory()) if (!dir.exists() || !dir.isDirectory())
{ {
liberator.echoerr("E344: Can't find directory \"" + dir.path + "\" in path"); echoerr("E344: Can't find directory \"" + dir.path + "\" in path");
return null; return null;
} }
@@ -452,9 +451,9 @@ liberator.IO = function () //{{{
getRuntimeDirectories: function (specialDirectory) getRuntimeDirectories: function (specialDirectory)
{ {
let dirs = liberator.options["runtimepath"].split(","); let dirs = options["runtimepath"].split(",");
dirs = dirs.map(function (dir) liberator.io.getFile(joinPaths(dir, specialDirectory))) dirs = dirs.map(function (dir) io.getFile(joinPaths(dir, specialDirectory)))
.filter(function (dir) dir.exists() && dir.isDirectory() && dir.isReadable()); .filter(function (dir) dir.exists() && dir.isDirectory() && dir.isReadable());
return dirs; return dirs;
@@ -671,7 +670,7 @@ lookup:
if (!file.exists()) if (!file.exists())
{ {
liberator.echoerr("Command not found: " + program); echoerr("Command not found: " + program);
return -1; return -1;
} }
@@ -688,7 +687,7 @@ lookup:
// is fixed, should use that instead of a tmpfile // is fixed, should use that instead of a tmpfile
system: function (command, input) system: function (command, input)
{ {
liberator.echomsg("Calling shell to execute: " + command, 4); echomsg("Calling shell to execute: " + command, 4);
var stdoutFile = ioManager.createTempFile(); var stdoutFile = ioManager.createTempFile();
var stderrFile = ioManager.createTempFile(); var stderrFile = ioManager.createTempFile();
@@ -714,7 +713,7 @@ lookup:
command += " < \"" + escapeQuotes(stdinFile.path) + "\""; command += " < \"" + escapeQuotes(stdinFile.path) + "\"";
} }
var res = ioManager.run(liberator.options["shell"], [liberator.options["shellcmdflag"], command], true); var res = ioManager.run(options["shell"], [options["shellcmdflag"], command], true);
if (res > 0) if (res > 0)
var output = ioManager.readFile(stderrFile) + "\nshell returned " + res; var output = ioManager.readFile(stderrFile) + "\nshell returned " + res;
@@ -747,20 +746,20 @@ lookup:
if (!silent) if (!silent)
{ {
if (file.exists() && file.isDirectory()) if (file.exists() && file.isDirectory())
liberator.echomsg("Cannot source a directory: \"" + filename + "\"", 0); echomsg("Cannot source a directory: \"" + filename + "\"", 0);
else else
liberator.echomsg("could not source: \"" + filename + "\"", 1); echomsg("could not source: \"" + filename + "\"", 1);
liberator.echoerr("E484: Can't open file " + filename); echoerr("E484: Can't open file " + filename);
} }
return; return;
} }
liberator.echomsg("sourcing \"" + filename + "\"", 2); echomsg("sourcing \"" + filename + "\"", 2);
let str = ioManager.readFile(file); let str = ioManager.readFile(file);
let uri = liberator.util.createURI(file.path); let uri = util.createURI(file.path);
// handle pure javascript files specially // handle pure javascript files specially
if (/\.js$/.test(filename)) if (/\.js$/.test(filename))
@@ -779,7 +778,7 @@ lookup:
} }
else if (/\.css$/.test(filename)) else if (/\.css$/.test(filename))
{ {
liberator.storage.styles.registerSheet(uri.spec, !silent, true); storage.styles.registerSheet(uri.spec, !silent, true);
} }
else else
{ {
@@ -808,8 +807,8 @@ lookup:
if (/^\s*(".*)?$/.test(line)) if (/^\s*(".*)?$/.test(line))
continue; continue;
var [count, cmd, special, args] = liberator.commands.parseCommand(line); var [count, cmd, special, args] = commands.parseCommand(line);
var command = liberator.commands.get(cmd); var command = commands.get(cmd);
if (!command) if (!command)
{ {
@@ -818,11 +817,11 @@ lookup:
// FIXME: messages need to be able to specify // FIXME: messages need to be able to specify
// whether they can be cleared/overwritten or // whether they can be cleared/overwritten or
// should be appended to and the MOW opened // should be appended to and the MOW opened
liberator.echoerr("Error detected while processing " + file.path, echoerr("Error detected while processing " + file.path,
liberator.commandline.FORCE_MULTILINE); commandline.FORCE_MULTILINE);
liberator.commandline.echo("line " + lineNumber + ":", liberator.commandline.HL_LINENR, commandline.echo("line " + lineNumber + ":", commandline.HL_LINENR,
liberator.commandline.APPEND_TO_MESSAGES); commandline.APPEND_TO_MESSAGES);
liberator.echoerr("E492: Not an editor command: " + line); echoerr("E492: Not an editor command: " + line);
} }
else else
{ {
@@ -850,7 +849,7 @@ lookup:
else else
{ {
// execute a normal liberator command // execute a normal liberator command
liberator.execute(line); execute(line);
} }
} }
} }
@@ -858,15 +857,15 @@ lookup:
// if no heredoc-end delimiter is found before EOF then // if no heredoc-end delimiter is found before EOF then
// process the heredoc anyway - Vim compatible ;-) // process the heredoc anyway - Vim compatible ;-)
liberator.eval(heredoc); eval(heredoc);
} }
if (scriptNames.indexOf(file.path) == -1) if (scriptNames.indexOf(file.path) == -1)
scriptNames.push(file.path); scriptNames.push(file.path);
liberator.echomsg("finished sourcing \"" + filename + "\"", 2); echomsg("finished sourcing \"" + filename + "\"", 2);
liberator.log("Sourced: " + file.path, 3); log("Sourced: " + file.path, 3);
} }
catch (e) catch (e)
{ {
@@ -874,7 +873,7 @@ lookup:
if (Components.utils.reportError) if (Components.utils.reportError)
Components.utils.reportError(e); Components.utils.reportError(e);
if (!silent) if (!silent)
liberator.echoerr(message); echoerr(message);
} }
} }
}; //}}} }; //}}}

View File

@@ -398,8 +398,8 @@ const liberator = (function () //{{{
{ {
if (count > 1) if (count > 1)
{ {
let each, eachUnits, totalUnits;
let total = 0; let total = 0;
var beforeTime = Date.now();
for (let i in liberator.util.rangeInterruptable(0, count, 500)) for (let i in liberator.util.rangeInterruptable(0, count, 500))
{ {
@@ -413,23 +413,23 @@ const liberator = (function () //{{{
if (total / count >= 100) if (total / count >= 100)
{ {
var each = (total / 1000.0) / count; each = total / 1000.0 / count;
var eachUnits = "sec"; eachUnits = "sec";
} }
else else
{ {
var each = total / count; each = total / count;
var eachUnits = "msec"; eachUnits = "msec";
} }
if (total >= 100) if (total >= 100)
{ {
var total = total / 1000.0; total = total / 1000.0;
var totalUnits = "sec"; totalUnits = "sec";
} }
else else
{ {
var totalUnits = "msec"; totalUnits = "msec";
} }
var str = liberator.template.generic( var str = liberator.template.generic(

View File

@@ -26,7 +26,7 @@ the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL. the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/ }}} ***** END LICENSE BLOCK *****/
liberator.Mail = function () //{{{ with (liberator) liberator.Mail = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -54,7 +54,7 @@ liberator.Mail = function () //{{{
if (folder) if (folder)
{ {
var msgFolder = folder.QueryInterface(Components.interfaces.nsIMsgFolder); var msgFolder = folder.QueryInterface(Components.interfaces.nsIMsgFolder);
liberator.autocommands.trigger("FolderLoaded", {url: msgFolder}); autocommands.trigger("FolderLoaded", {url: msgFolder});
// Jump to a message when requested // Jump to a message when requested
var indices = []; var indices = [];
@@ -92,7 +92,7 @@ liberator.Mail = function () //{{{
function getFolderCompletions(filter) function getFolderCompletions(filter)
{ {
var completions = []; var completions = [];
var folders = liberator.mail.getFolders(); var folders = mail.getFolders();
for (let folder = 0; folder < folders.length; folder++) for (let folder = 0; folder < folders.length; folder++)
{ {
@@ -101,7 +101,7 @@ liberator.Mail = function () //{{{
"Unread: " + folders[folder].getNumUnread(false)]); "Unread: " + folders[folder].getNumUnread(false)]);
} }
return [0, liberator.completion.filter(completions, filter)]; return [0, completion.filter(completions, filter)];
} }
function getRSSUrl() function getRSSUrl()
@@ -113,38 +113,38 @@ liberator.Mail = function () //{{{
{ {
if (!destinationFolder) if (!destinationFolder)
{ {
liberator.echoerr("E471: Argument required"); echoerr("E471: Argument required");
return false; return false;
} }
var folders = liberator.mail.getFolders(destinationFolder); var folders = mail.getFolders(destinationFolder);
if (folders.length == 0) if (folders.length == 0)
{ {
liberator.echoerr("E94: No matching folder for " + destinationFolder); echoerr("E94: No matching folder for " + destinationFolder);
return false; return false;
} }
else if (folders.length > 1) else if (folders.length > 1)
{ {
liberator.echoerr("E93: More than one match for " + destinationFolder); echoerr("E93: More than one match for " + destinationFolder);
return false; return false;
} }
var count = gDBView.selection.count; var count = gDBView.selection.count;
if (!count) if (!count)
{ {
liberator.beep(); beep();
return false; return false;
} }
if (copy) if (copy)
{ {
MsgCopyMessage(folders[0]); MsgCopyMessage(folders[0]);
setTimeout(function () { liberator.echo(count + " message(s) copied to " + folders[0].prettyName); }, 100); setTimeout(function () { echo(count + " message(s) copied to " + folders[0].prettyName); }, 100);
} }
else else
{ {
MsgMoveMessage(folders[0]); MsgMoveMessage(folders[0]);
setTimeout(function () { liberator.echo(count + " message(s) moved to " + folders[0].prettyName); }, 100); setTimeout(function () { echo(count + " message(s) moved to " + folders[0].prettyName); }, 100);
} }
return true; return true;
} }
@@ -184,7 +184,7 @@ liberator.Mail = function () //{{{
i += direction; i += direction;
} }
if (!folder || count > 0) if (!folder || count > 0)
liberator.beep(); beep();
else else
tree.view.selection.timedSelect(c + folder, tree._selectDelay); tree.view.selection.timedSelect(c + folder, tree._selectDelay);
} }
@@ -199,11 +199,11 @@ liberator.Mail = function () //{{{
////////////////////// OPTIONS ///////////////////////////////////////////////// ////////////////////// OPTIONS /////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
// liberator.options.add(["editor"], // options.add(["editor"],
// "Set the external text editor", // "Set the external text editor",
// "string", "gvim -f"); // "string", "gvim -f");
liberator.options.add(["layout"], options.add(["layout"],
"Set the layout of the mail window", "Set the layout of the mail window",
"string", "inherit", "string", "inherit",
{ {
@@ -222,7 +222,7 @@ liberator.Mail = function () //{{{
validator: function (value) /^(classic|wide|vertical|inherit)$/.test(value) validator: function (value) /^(classic|wide|vertical|inherit)$/.test(value)
}); });
/*liberator.options.add(["threads"], /*options.add(["threads"],
"Use threading to group messages", "Use threading to group messages",
"boolean", true, "boolean", true,
{ {
@@ -241,232 +241,232 @@ liberator.Mail = function () //{{{
////////////////////// MAPPINGS //////////////////////////////////////////////// ////////////////////// MAPPINGS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
var modes = liberator.config.mailModes || [liberator.modes.NORMAL]; var myModes = config.mailModes || [modes.NORMAL];
liberator.mappings.add(modes, ["<Return>", "i"], mappings.add(myModes, ["<Return>", "i"],
"Inspect (focus) message", "Inspect (focus) message",
function () { content.focus(); }); function () { content.focus(); });
liberator.mappings.add(modes, ["I"], mappings.add(myModes, ["I"],
"Open the message in new tab", "Open the message in new tab",
function () function ()
{ {
if (gDBView && gDBView.selection.count < 1) if (gDBView && gDBView.selection.count < 1)
return liberator.beep(); return beep();
MsgOpenNewTabForMessage(); MsgOpenNewTabForMessage();
}); });
/*liberator.mappings.add([liberator.modes.NORMAL], /*mappings.add([modes.NORMAL],
["o"], "Open a message", ["o"], "Open a message",
function () { liberator.commandline.open(":", "open ", liberator.modes.EX); });*/ function () { commandline.open(":", "open ", modes.EX); });*/
liberator.mappings.add(modes, ["<Space>"], mappings.add(myModes, ["<Space>"],
"Scroll message or select next unread one", "Scroll message or select next unread one",
function () true, function () true,
{ flags: liberator.Mappings.flags.ALLOW_EVENT_ROUTING }); { flags: Mappings.flags.ALLOW_EVENT_ROUTING });
liberator.mappings.add(modes, ["t"], mappings.add(myModes, ["t"],
"Select thread", "Select thread",
function () { gDBView.ExpandAndSelectThreadByIndex(GetThreadTree().currentIndex, false); }); function () { gDBView.ExpandAndSelectThreadByIndex(GetThreadTree().currentIndex, false); });
liberator.mappings.add(modes, ["d", "<Del>"], mappings.add(myModes, ["d", "<Del>"],
"Move mail to Trash folder", "Move mail to Trash folder",
function () { goDoCommand("cmd_delete"); }); function () { goDoCommand("cmd_delete"); });
liberator.mappings.add(modes, ["j", "<Right>"], mappings.add(myModes, ["j", "<Right>"],
"Select next message", "Select next message",
function (count) { liberator.mail.selectMessage(function (msg) true, false, false, false, count); }, function (count) { mail.selectMessage(function (msg) true, false, false, false, count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["gj"], mappings.add(myModes, ["gj"],
"Select next message, including closed threads", "Select next message, including closed threads",
function (count) { liberator.mail.selectMessage(function (msg) true, false, true, false, count); }, function (count) { mail.selectMessage(function (msg) true, false, true, false, count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["J", "<Tab>"], mappings.add(myModes, ["J", "<Tab>"],
"Select next unread message", "Select next unread message",
function (count) { liberator.mail.selectMessage(function (msg) !msg.isRead, true, true, false, count); }, function (count) { mail.selectMessage(function (msg) !msg.isRead, true, true, false, count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["k", "<Left>"], mappings.add(myModes, ["k", "<Left>"],
"Select previous message", "Select previous message",
function (count) { liberator.mail.selectMessage(function (msg) true, false, false, true, count); }, function (count) { mail.selectMessage(function (msg) true, false, false, true, count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["gk"], mappings.add(myModes, ["gk"],
"Select previous message", "Select previous message",
function (count) { liberator.mail.selectMessage(function (msg) true, false, true, true, count); }, function (count) { mail.selectMessage(function (msg) true, false, true, true, count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["K"], mappings.add(myModes, ["K"],
"Select previous unread message", "Select previous unread message",
function (count) { liberator.mail.selectMessage(function (msg) !msg.isRead, true, true, true, count); }, function (count) { mail.selectMessage(function (msg) !msg.isRead, true, true, true, count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["*"], mappings.add(myModes, ["*"],
"Select next message from the same sender", "Select next message from the same sender",
function (count) function (count)
{ {
try try
{ {
var author = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor.toLowerCase(); var author = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor.toLowerCase();
liberator.mail.selectMessage(function (msg) msg.mime2DecodedAuthor.toLowerCase().indexOf(author) == 0, true, true, false, count); mail.selectMessage(function (msg) msg.mime2DecodedAuthor.toLowerCase().indexOf(author) == 0, true, true, false, count);
} }
catch (e) { liberator.beep(); } catch (e) { beep(); }
}, },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["#"], mappings.add(myModes, ["#"],
"Select previous message from the same sender", "Select previous message from the same sender",
function (count) function (count)
{ {
try try
{ {
var author = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor.toLowerCase(); var author = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor.toLowerCase();
liberator.mail.selectMessage(function (msg) msg.mime2DecodedAuthor.toLowerCase().indexOf(author) == 0, true, true, true, count); mail.selectMessage(function (msg) msg.mime2DecodedAuthor.toLowerCase().indexOf(author) == 0, true, true, true, count);
} }
catch (e) { liberator.beep(); } catch (e) { beep(); }
}, },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
// SENDING MESSAGES // SENDING MESSAGES
liberator.mappings.add(modes, ["m"], mappings.add(myModes, ["m"],
"Compose a new message", "Compose a new message",
function () { liberator.commandline.open(":", "message -subject=", liberator.modes.EX); }); function () { commandline.open(":", "message -subject=", modes.EX); });
liberator.mappings.add(modes, ["M"], mappings.add(myModes, ["M"],
"Compose a new message to the sender of selected mail", "Compose a new message to the sender of selected mail",
function () function ()
{ {
try try
{ {
var to = escapeRecipient(gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor); var to = escapeRecipient(gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor);
liberator.commandline.open(":", "message " + to + " -subject=", liberator.modes.EX); commandline.open(":", "message " + to + " -subject=", modes.EX);
} }
catch (e) catch (e)
{ {
liberator.beep(); beep();
} }
}); });
liberator.mappings.add(modes, ["r"], mappings.add(myModes, ["r"],
"Reply to sender", "Reply to sender",
function () { goDoCommand("cmd_reply"); }); function () { goDoCommand("cmd_reply"); });
liberator.mappings.add(modes, ["R"], mappings.add(myModes, ["R"],
"Reply to all", "Reply to all",
function () { goDoCommand("cmd_replyall"); }); function () { goDoCommand("cmd_replyall"); });
liberator.mappings.add(modes, ["f"], mappings.add(myModes, ["f"],
"Forward message", "Forward message",
function () { goDoCommand("cmd_forward"); }); function () { goDoCommand("cmd_forward"); });
liberator.mappings.add(modes, ["F"], mappings.add(myModes, ["F"],
"Forward message inline", "Forward message inline",
function () { goDoCommand("cmd_forwardInline"); }); function () { goDoCommand("cmd_forwardInline"); });
// SCROLLING // SCROLLING
liberator.mappings.add(modes, ["<Down>"], mappings.add(myModes, ["<Down>"],
"Scroll message down", "Scroll message down",
function (count) { liberator.buffer.scrollLines(count > 1 ? count : 1); }, function (count) { buffer.scrollLines(count > 1 ? count : 1); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["<Up>"], mappings.add(myModes, ["<Up>"],
"Scroll message up", "Scroll message up",
function (count) { liberator.buffer.scrollLines(-(count > 1 ? count : 1)); }, function (count) { buffer.scrollLines(-(count > 1 ? count : 1)); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.MESSAGE], ["<Left>"], mappings.add([modes.MESSAGE], ["<Left>"],
"Select previous message", "Select previous message",
function (count) { liberator.mail.selectMessage(function (msg) true, false, false, true, count); }, function (count) { mail.selectMessage(function (msg) true, false, false, true, count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.MESSAGE], ["<Right>"], mappings.add([modes.MESSAGE], ["<Right>"],
"Select next message", "Select next message",
function (count) { liberator.mail.selectMessage(function (msg) true, false, false, false, count); }, function (count) { mail.selectMessage(function (msg) true, false, false, false, count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
// UNDO/REDO // UNDO/REDO
liberator.mappings.add(modes, ["u"], mappings.add(myModes, ["u"],
"Undo", "Undo",
function () function ()
{ {
if (messenger.canUndo()) if (messenger.canUndo())
messenger.undo(msgWindow); messenger.undo(msgWindow);
else else
liberator.beep(); beep();
}); });
liberator.mappings.add(modes, ["<C-r>"], mappings.add(myModes, ["<C-r>"],
"Redo", "Redo",
function () function ()
{ {
if (messenger.canRedo()) if (messenger.canRedo())
messenger.redo(msgWindow); messenger.redo(msgWindow);
else else
liberator.beep(); beep();
}); });
// GETTING MAIL // GETTING MAIL
liberator.mappings.add(modes, ["gm"], mappings.add(myModes, ["gm"],
"Get new messages", "Get new messages",
function () { liberator.mail.getNewMessages(); }); function () { mail.getNewMessages(); });
liberator.mappings.add(modes, ["gM"], mappings.add(myModes, ["gM"],
"Get new messages for current account only", "Get new messages for current account only",
function () { liberator.mail.getNewMessages(true); }); function () { mail.getNewMessages(true); });
// MOVING MAIL // MOVING MAIL
liberator.mappings.add(modes, ["c"], mappings.add(myModes, ["c"],
"Change folders", "Change folders",
function () { liberator.commandline.open(":", "goto ", liberator.modes.EX); }); function () { commandline.open(":", "goto ", modes.EX); });
liberator.mappings.add(modes, ["s"], mappings.add(myModes, ["s"],
"Move selected messages", "Move selected messages",
function () { liberator.commandline.open(":", "moveto ", liberator.modes.EX); }); function () { commandline.open(":", "moveto ", modes.EX); });
liberator.mappings.add(modes, ["S"], mappings.add(myModes, ["S"],
"Copy selected messages", "Copy selected messages",
function () { liberator.commandline.open(":", "copyto ", liberator.modes.EX); }); function () { commandline.open(":", "copyto ", modes.EX); });
liberator.mappings.add(modes, ["<C-s>"], mappings.add(myModes, ["<C-s>"],
"Archive message", "Archive message",
function () { moveOrCopy(false, "Archive"); }); function () { moveOrCopy(false, "Archive"); });
liberator.mappings.add(modes, ["]s"], mappings.add(myModes, ["]s"],
"Select next starred message", "Select next starred message",
function (count) { liberator.mail.selectMessage(function (msg) msg.isFlagged, true, true, false, count); }, function (count) { mail.selectMessage(function (msg) msg.isFlagged, true, true, false, count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["[s"], mappings.add(myModes, ["[s"],
"Select previous starred message", "Select previous starred message",
function (count) { liberator.mail.selectMessage(function (msg) msg.isFlagged, true, true, true, count); }, function (count) { mail.selectMessage(function (msg) msg.isFlagged, true, true, true, count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["]a"], mappings.add(myModes, ["]a"],
"Select next message with an attachment", "Select next message with an attachment",
function (count) { liberator.mail.selectMessage(function (msg) gDBView.db.HasAttachments(msg.messageKey), true, true, false, count); }, function (count) { mail.selectMessage(function (msg) gDBView.db.HasAttachments(msg.messageKey), true, true, false, count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["[a"], mappings.add(myModes, ["[a"],
"Select previous message with an attachment", "Select previous message with an attachment",
function (count) { liberator.mail.selectMessage(function (msg) gDBView.db.HasAttachments(msg.messageKey), true, true, true, count); }, function (count) { mail.selectMessage(function (msg) gDBView.db.HasAttachments(msg.messageKey), true, true, true, count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
// FOLDER SWITCHING // FOLDER SWITCHING
liberator.mappings.add(modes, ["gi"], mappings.add(myModes, ["gi"],
"Go to inbox", "Go to inbox",
function (count) function (count)
{ {
var folder = liberator.mail.getFolders("Inbox", false, true)[(count > 0) ? (count - 1) : 0]; var folder = mail.getFolders("Inbox", false, true)[(count > 0) ? (count - 1) : 0];
if (folder) if (folder)
SelectFolder(folder.URI); SelectFolder(folder.URI);
else else
liberator.beep(); beep();
}, },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["<C-n>"], mappings.add(myModes, ["<C-n>"],
"Select next folder", "Select next folder",
function (count) function (count)
{ {
@@ -475,22 +475,22 @@ liberator.Mail = function () //{{{
var c = tree.currentIndex; var c = tree.currentIndex;
if (c + count >= tree.view.rowCount) if (c + count >= tree.view.rowCount)
{ {
liberator.beep(); beep();
return; return;
} }
tree.view.selection.timedSelect(c + count, tree._selectDelay ); tree.view.selection.timedSelect(c + count, tree._selectDelay );
}, },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["<C-N>"], mappings.add(myModes, ["<C-N>"],
"Go to next mailbox with unread messages", "Go to next mailbox with unread messages",
function (count) function (count)
{ {
selectUnreadFolder(false, count); selectUnreadFolder(false, count);
}, },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["<C-p>"], mappings.add(myModes, ["<C-p>"],
"Select previous folder", "Select previous folder",
function (count) function (count)
{ {
@@ -499,69 +499,69 @@ liberator.Mail = function () //{{{
var c = tree.currentIndex; var c = tree.currentIndex;
if (c - count < 0) if (c - count < 0)
{ {
liberator.beep(); beep();
return; return;
} }
tree.view.selection.timedSelect(c - count, tree._selectDelay ); tree.view.selection.timedSelect(c - count, tree._selectDelay );
}, },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["<C-P>"], mappings.add(myModes, ["<C-P>"],
"Go to previous mailbox with unread messages", "Go to previous mailbox with unread messages",
function (count) function (count)
{ {
selectUnreadFolder(true, count); selectUnreadFolder(true, count);
}, },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
// THREADING // THREADING
liberator.mappings.add(modes, ["za"], mappings.add(myModes, ["za"],
"Toggle thread collapsed/expanded", "Toggle thread collapsed/expanded",
function () { if (!liberator.mail.expandThread()) liberator.mail.collapseThread(); }); function () { if (!mail.expandThread()) mail.collapseThread(); });
liberator.mappings.add(modes, ["zc"], mappings.add(myModes, ["zc"],
"Collapse thread", "Collapse thread",
function () { liberator.mail.collapseThread(); }); function () { mail.collapseThread(); });
liberator.mappings.add(modes, ["zo"], mappings.add(myModes, ["zo"],
"Open thread", "Open thread",
function () { liberator.mail.expandThread(); }); function () { mail.expandThread(); });
liberator.mappings.add(modes, ["zr", "zR"], mappings.add(myModes, ["zr", "zR"],
"Expand all threads", "Expand all threads",
function () { goDoCommand("cmd_expandAllThreads"); }); function () { goDoCommand("cmd_expandAllThreads"); });
liberator.mappings.add(modes, ["zm", "zM"], mappings.add(myModes, ["zm", "zM"],
"Collapse all threads", "Collapse all threads",
function () { goDoCommand("cmd_collapseAllThreads"); }); function () { goDoCommand("cmd_collapseAllThreads"); });
liberator.mappings.add(modes, ["<C-i>"], mappings.add(myModes, ["<C-i>"],
"Go forward", "Go forward",
function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.forward, true); }, function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.forward, true); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["<C-o>"], mappings.add(myModes, ["<C-o>"],
"Go back", "Go back",
function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.back, true); }, function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.back, true); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["gg"], mappings.add(myModes, ["gg"],
"Select first message", "Select first message",
function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.firstMessage, true); }, function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.firstMessage, true); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add(modes, ["G"], mappings.add(myModes, ["G"],
"Select last message", "Select last message",
function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.lastMessage, false); }, function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.lastMessage, false); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
// tagging messages // tagging messages
liberator.mappings.add(modes, ["l"], mappings.add(myModes, ["l"],
"Label message", "Label message",
function (arg) function (arg)
{ {
if (!GetSelectedMessages()) if (!GetSelectedMessages())
return liberator.beep(); return beep();
switch (arg) switch (arg)
{ {
@@ -572,33 +572,33 @@ liberator.Mail = function () //{{{
case "p": ToggleMessageTagKey(3); break; // Personal case "p": ToggleMessageTagKey(3); break; // Personal
case "t": ToggleMessageTagKey(4); break; // TODO case "t": ToggleMessageTagKey(4); break; // TODO
case "l": ToggleMessageTagKey(5); break; // Later case "l": ToggleMessageTagKey(5); break; // Later
default: liberator.beep(); default: beep();
} }
}, },
{ {
flags: liberator.Mappings.flags.ARGUMENT flags: Mappings.flags.ARGUMENT
}); });
// TODO: change binding? // TODO: change binding?
liberator.mappings.add(modes, ["T"], mappings.add(myModes, ["T"],
"Mark current folder as read", "Mark current folder as read",
function () function ()
{ {
if (liberator.mail.currentFolder.isServer) if (mail.currentFolder.isServer)
return liberator.beep(); return beep();
liberator.mail.currentFolder.markAllMessagesRead(); mail.currentFolder.markAllMessagesRead();
}); });
liberator.mappings.add(modes, ["<C-t>"], mappings.add(myModes, ["<C-t>"],
"Mark all messages as read", "Mark all messages as read",
function () function ()
{ {
liberator.mail.getFolders("", false).forEach(function (folder) { folder.markAllMessagesRead(); }); mail.getFolders("", false).forEach(function (folder) { folder.markAllMessagesRead(); });
}); });
// DISPLAY OPTIONS // DISPLAY OPTIONS
liberator.mappings.add(modes, ["h"], mappings.add(myModes, ["h"],
"Toggle displayed headers", "Toggle displayed headers",
function () function ()
{ {
@@ -607,55 +607,55 @@ liberator.Mail = function () //{{{
MsgReload(); MsgReload();
}); });
liberator.mappings.add(modes, ["x"], mappings.add(myModes, ["x"],
"Toggle HTML message display", "Toggle HTML message display",
function () function ()
{ {
var want_html = (gPrefBranch.getIntPref("mailnews.display.html_as", 1) == 1); var want_html = (gPrefBranch.getIntPref("mailnews.display.html_as", 1) == 1);
liberator.mail.setHTML(want_html ? 1 : 0); mail.setHTML(want_html ? 1 : 0);
}); });
// YANKING TEXT // YANKING TEXT
liberator.mappings.add(modes, ["Y"], mappings.add(myModes, ["Y"],
"Yank subject", "Yank subject",
function () function ()
{ {
try try
{ {
var subject = gDBView.hdrForFirstSelectedMessage.mime2DecodedSubject; var subject = gDBView.hdrForFirstSelectedMessage.mime2DecodedSubject;
liberator.util.copyToClipboard(subject, true); util.copyToClipboard(subject, true);
} }
catch (e) { liberator.beep(); } catch (e) { beep(); }
}); });
liberator.mappings.add(modes, ["y"], mappings.add(myModes, ["y"],
"Yank sender or feed URL", "Yank sender or feed URL",
function () function ()
{ {
try try
{ {
if (liberator.mail.currentAccount.server.type == "rss") if (mail.currentAccount.server.type == "rss")
liberator.util.copyToClipboard(getRSSUrl(), true); util.copyToClipboard(getRSSUrl(), true);
else else
liberator.util.copyToClipboard(gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor, true); util.copyToClipboard(gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor, true);
} }
catch (e) { liberator.beep(); } catch (e) { beep(); }
}); });
// RSS specific mappings // RSS specific mappings
liberator.mappings.add(modes, ["p"], mappings.add(myModes, ["p"],
"Open RSS message in browser", "Open RSS message in browser",
function () function ()
{ {
try try
{ {
if (liberator.mail.currentAccount.server.type == "rss") if (mail.currentAccount.server.type == "rss")
messenger.launchExternalURL(getRSSUrl()); messenger.launchExternalURL(getRSSUrl());
// TODO: what to do for non-rss message? // TODO: what to do for non-rss message?
} }
catch (e) catch (e)
{ {
liberator.beep(); beep();
} }
}); });
@@ -663,17 +663,17 @@ liberator.Mail = function () //{{{
////////////////////// COMMANDS //////////////////////////////////////////////// ////////////////////// COMMANDS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.commands.add(["go[to]"], commands.add(["go[to]"],
"Select a folder", "Select a folder",
function (args, special, count) function (args, special, count)
{ {
args = args || "Inbox"; args = args || "Inbox";
count = count > 0 ? (count - 1) : 0; count = count > 0 ? (count - 1) : 0;
var folder = liberator.mail.getFolders(args, true, true)[count]; var folder = mail.getFolders(args, true, true)[count];
if (!folder) if (!folder)
liberator.echoerr("Folder \"" + args + "\" does not exist"); echoerr("Folder \"" + args + "\" does not exist");
else if (liberator.forceNewTab) else if (forceNewTab)
MsgOpenNewTabForFolder(folder.URI); MsgOpenNewTabForFolder(folder.URI);
else else
SelectFolder(folder.URI); SelectFolder(folder.URI);
@@ -683,7 +683,7 @@ liberator.Mail = function () //{{{
count: true count: true
}); });
liberator.commands.add(["m[essage]"], commands.add(["m[essage]"],
"Write a new message", "Write a new message",
function (args) function (args)
{ {
@@ -704,38 +704,38 @@ liberator.Mail = function () //{{{
// TODO: is there a better way to check for validity? // TODO: is there a better way to check for validity?
if (addresses.some(function (recipient) !(/\S@\S+\.\S/.test(recipient)))) if (addresses.some(function (recipient) !(/\S@\S+\.\S/.test(recipient))))
{ {
liberator.echoerr("Exxx: Invalid e-mail address"); echoerr("Exxx: Invalid e-mail address");
return; return;
} }
liberator.mail.composeNewMail(mailargs); mail.composeNewMail(mailargs);
}, },
{ {
options: [[["-subject", "-s"], liberator.commands.OPTION_STRING], options: [[["-subject", "-s"], commands.OPTION_STRING],
[["-attachment", "-a"], liberator.commands.OPTION_LIST], [["-attachment", "-a"], commands.OPTION_LIST],
[["-bcc", "-b"], liberator.commands.OPTION_STRING], [["-bcc", "-b"], commands.OPTION_STRING],
[["-cc", "-c"], liberator.commands.OPTION_STRING], [["-cc", "-c"], commands.OPTION_STRING],
[["-text", "-t"], liberator.commands.OPTION_STRING]] [["-text", "-t"], commands.OPTION_STRING]]
}); });
liberator.commands.add(["copy[to]"], commands.add(["copy[to]"],
"Copy selected messages", "Copy selected messages",
function (args) { moveOrCopy(true, args); }, function (args) { moveOrCopy(true, args); },
{ completer: function (filter) getFolderCompletions(filter) }); { completer: function (filter) getFolderCompletions(filter) });
liberator.commands.add(["move[to]"], commands.add(["move[to]"],
"Move selected messages", "Move selected messages",
function (args) { moveOrCopy(false, args); }, function (args) { moveOrCopy(false, args); },
{ completer: function (filter) getFolderCompletions(filter) }); { completer: function (filter) getFolderCompletions(filter) });
liberator.commands.add(["empty[trash]"], commands.add(["empty[trash]"],
"Empty trash of the current account", "Empty trash of the current account",
function () { goDoCommand("cmd_emptyTrash"); }, function () { goDoCommand("cmd_emptyTrash"); },
{ argCount: "0" }); { argCount: "0" });
liberator.commands.add(["get[messages]"], commands.add(["get[messages]"],
"Check for new messages", "Check for new messages",
function (args, special) liberator.mail.getNewMessages(!special), function (args, special) mail.getNewMessages(!special),
{ {
argCount: "0", argCount: "0",
bang: true, bang: true,
@@ -785,10 +785,10 @@ liberator.Mail = function () //{{{
while (args.attachments.length > 0) while (args.attachments.length > 0)
{ {
var url = args.attachments.pop(); var url = args.attachments.pop();
var file = liberator.io.getFile(url); var file = io.getFile(url);
if (!file.exists()) if (!file.exists())
{ {
liberator.echoerr("Exxx: Could not attach file `" + url + "'", liberator.commandline.FORCE_SINGLELINE); echoerr("Exxx: Could not attach file `" + url + "'", commandline.FORCE_SINGLELINE);
return; return;
} }
@@ -848,7 +848,7 @@ liberator.Mail = function () //{{{
} }
catch (e) catch (e)
{ {
liberator.log("Error getting messages for account " + account.prettyName + ": " + e); log("Error getting messages for account " + account.prettyName + ": " + e);
} }
}); });
}, },
@@ -1006,7 +1006,7 @@ liberator.Mail = function () //{{{
} }
catch (e) catch (e)
{ {
liberator.dump("ERROR: " + folder.prettyName + " failed to getMessages\n"); dump("ERROR: " + folder.prettyName + " failed to getMessages\n");
continue; continue;
} }
@@ -1031,7 +1031,7 @@ liberator.Mail = function () //{{{
// TODO: finally for the "rest" of the current folder // TODO: finally for the "rest" of the current folder
liberator.beep(); beep();
}, },
setHTML: function (value) setHTML: function (value)

View File

@@ -27,8 +27,8 @@ the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/ }}} ***** END LICENSE BLOCK *****/
// Do NOT create instances of this class yourself, use the helper method // Do NOT create instances of this class yourself, use the helper method
// liberator.mappings.add() instead // mappings.add() instead
liberator.Map = function (modes, cmds, description, action, extraInfo) //{{{ with (liberator) liberator.Map = function (modes, cmds, description, action, extraInfo) //{{{
{ {
if (!modes || (!cmds || !cmds.length) || !action) if (!modes || (!cmds || !cmds.length) || !action)
return null; return null;
@@ -47,7 +47,7 @@ liberator.Map = function (modes, cmds, description, action, extraInfo) //{{{
this.noremap = extraInfo.noremap || false; this.noremap = extraInfo.noremap || false;
}; };
liberator.Map.prototype = { with (liberator) liberator.Map.prototype = {
hasName: function (name) hasName: function (name)
{ {
@@ -58,23 +58,23 @@ liberator.Map.prototype = {
{ {
var args = []; var args = [];
if (this.flags & liberator.Mappings.flags.MOTION) if (this.flags & Mappings.flags.MOTION)
args.push(motion); args.push(motion);
if (this.flags & liberator.Mappings.flags.COUNT) if (this.flags & Mappings.flags.COUNT)
args.push(count); args.push(count);
if (this.flags & liberator.Mappings.flags.ARGUMENT) if (this.flags & Mappings.flags.ARGUMENT)
args.push(argument); args.push(argument);
let self = this; let self = this;
// FIXME: Kludge. // FIXME: Kludge.
if (this.names[0] != ".") if (this.names[0] != ".")
liberator.mappings.repeat = function () self.action.apply(self, args); mappings.repeat = function () self.action.apply(self, args);
return this.action.apply(this, args); return this.action.apply(this, args);
} }
}; //}}} }; //}}}
liberator.Mappings = function () //{{{ with (liberator) liberator.Mappings = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -83,7 +83,7 @@ liberator.Mappings = function () //{{{
var main = []; // default mappings var main = []; // default mappings
var user = []; // user created mappings var user = []; // user created mappings
for (let mode in liberator.modes) for (let mode in modes)
{ {
main[mode] = []; main[mode] = [];
user[mode] = []; user[mode] = [];
@@ -99,10 +99,10 @@ liberator.Mappings = function () //{{{
{ {
var maps = stack[mode]; var maps = stack[mode];
for (let i = 0; i < maps.length; i++) for (let [,map] in Iterator(maps))
{ {
if (maps[i].hasName(cmd)) if (map.hasName(cmd))
return maps[i]; return map;
} }
return null; return null;
@@ -113,18 +113,15 @@ liberator.Mappings = function () //{{{
var maps = user[mode]; var maps = user[mode];
var names; var names;
for (let i = 0; i < maps.length; i++) for (let [i, map] in Iterator(maps))
{ {
names = maps[i].names; for (let [j, name] in Iterator(map.names))
for (let j = 0; j < names.length; j++)
{ {
if (names[j] == cmd) if (name == cmd)
{ {
names.splice(j, 1); map.names.splice(j, 1);
if (map.names.length == 0)
if (names.length == 0)
maps.splice(i, 1); maps.splice(i, 1);
return; return;
} }
} }
@@ -134,7 +131,7 @@ liberator.Mappings = function () //{{{
function expandLeader(keyString) function expandLeader(keyString)
{ {
var leaderRegexp = /<Leader>/i; var leaderRegexp = /<Leader>/i;
var currentLeader = liberator.mappings.getMapLeader(); var currentLeader = mappings.getMapLeader();
return keyString.replace(leaderRegexp, currentLeader); return keyString.replace(leaderRegexp, currentLeader);
} }
@@ -175,7 +172,7 @@ liberator.Mappings = function () //{{{
{ {
if (!args) if (!args)
{ {
liberator.mappings.list(mode); mappings.list(mode);
return; return;
} }
@@ -184,17 +181,17 @@ liberator.Mappings = function () //{{{
if (!rhs) // list the mapping if (!rhs) // list the mapping
{ {
liberator.mappings.list(mode, expandLeader(lhs)); mappings.list(mode, expandLeader(lhs));
} }
else else
{ {
for (let index = 0; index < mode.length; index++) for (let [,m] in Iterator(mode))
{ {
liberator.mappings.addUserMap([mode[index]], [lhs], mappings.addUserMap([m], [lhs],
"User defined mapping", "User defined mapping",
function (count) { liberator.events.feedkeys((count > 1 ? count : "") + rhs, noremap); }, function (count) { events.feedkeys((count > 1 ? count : "") + rhs, noremap); },
{ {
flags: liberator.Mappings.flags.COUNT, flags: Mappings.flags.COUNT,
rhs: rhs, rhs: rhs,
noremap: noremap noremap: noremap
}); });
@@ -204,65 +201,65 @@ liberator.Mappings = function () //{{{
modeDescription = modeDescription ? " in " + modeDescription + " mode" : ""; modeDescription = modeDescription ? " in " + modeDescription + " mode" : "";
liberator.commands.add([ch ? ch + "m[ap]" : "map"], commands.add([ch ? ch + "m[ap]" : "map"],
"Map a key sequence" + modeDescription, "Map a key sequence" + modeDescription,
function (args) { map(args, modes, false); }, function (args) { map(args, modes, false); },
{ completer: function (filter) liberator.completion.userMapping(filter, modes) }); { completer: function (filter) completion.userMapping(filter, modes) });
liberator.commands.add([ch + "no[remap]"], commands.add([ch + "no[remap]"],
"Map a key sequence without remapping keys" + modeDescription, "Map a key sequence without remapping keys" + modeDescription,
function (args) { map(args, modes, true); }); function (args) { map(args, modes, true); });
liberator.commands.add([ch + "mapc[lear]"], commands.add([ch + "mapc[lear]"],
"Remove all mappings" + modeDescription, "Remove all mappings" + modeDescription,
function () function ()
{ {
for (let i = 0; i < modes.length; i++) for (let i = 0; i < modes.length; i++)
liberator.mappings.removeAll(modes[i]); mappings.removeAll(modes[i]);
}, },
{ argCount: "0" }); { argCount: "0" });
liberator.commands.add([ch + "unm[ap]"], commands.add([ch + "unm[ap]"],
"Remove a mapping" + modeDescription, "Remove a mapping" + modeDescription,
function (args) function (args)
{ {
if (!args) if (!args)
{ {
liberator.echoerr("E474: Invalid argument"); echoerr("E474: Invalid argument");
return; return;
} }
var found = false; let found = false;
for (let i = 0; i < modes.length; i++) for (let [,mode] in Iterator(modes))
{ {
if (liberator.mappings.hasMap(modes[i], args)) if (mappings.hasMap(mode, args))
{ {
liberator.mappings.remove(modes[i], args); mappings.remove(mode, args);
found = true; found = true;
} }
} }
if (!found) if (!found)
liberator.echoerr("E31: No such mapping"); echoerr("E31: No such mapping");
}, },
{ completer: function (filter) liberator.completion.userMapping(filter, modes) }); { completer: function (filter) completion.userMapping(filter, modes) });
} }
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// COMMANDS //////////////////////////////////////////////// ////////////////////// COMMANDS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
addMapCommands("", [liberator.modes.NORMAL], ""); addMapCommands("", [modes.NORMAL], "");
addMapCommands("c", [liberator.modes.COMMAND_LINE], "command line"); addMapCommands("c", [modes.COMMAND_LINE], "command line");
addMapCommands("i", [liberator.modes.INSERT, liberator.modes.TEXTAREA], "insert"); addMapCommands("i", [modes.INSERT, modes.TEXTAREA], "insert");
if (liberator.has("mail")) if (liberator.has("mail"))
addMapCommands("m", [liberator.modes.MESSAGE], "message"); addMapCommands("m", [modes.MESSAGE], "message");
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// PUBLIC SECTION ////////////////////////////////////////// ////////////////////// PUBLIC SECTION //////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
// FIXME: // FIXME:
liberator.Mappings.flags = { Mappings.flags = {
ALLOW_EVENT_ROUTING: 1 << 0, // if set, return true inside the map command to pass the event further to firefox ALLOW_EVENT_ROUTING: 1 << 0, // if set, return true inside the map command to pass the event further to firefox
MOTION: 1 << 1, MOTION: 1 << 1,
COUNT: 1 << 2, COUNT: 1 << 2,
@@ -274,7 +271,7 @@ liberator.Mappings = function () //{{{
// NOTE: just normal mode for now // NOTE: just normal mode for now
__iterator__: function () __iterator__: function ()
{ {
return mappingsIterator([liberator.modes.NORMAL], main); return mappingsIterator([modes.NORMAL], main);
}, },
// used by :mkvimperatorrc to save mappings // used by :mkvimperatorrc to save mappings
@@ -285,13 +282,13 @@ liberator.Mappings = function () //{{{
add: function (modes, keys, description, action, extra) add: function (modes, keys, description, action, extra)
{ {
addMap(new liberator.Map(modes, keys, description, action, extra), false); addMap(new Map(modes, keys, description, action, extra), false);
}, },
addUserMap: function (modes, keys, description, action, extra) addUserMap: function (modes, keys, description, action, extra)
{ {
keys = keys.map(function (key) expandLeader(key)); keys = keys.map(function (key) expandLeader(key));
var map = new liberator.Map(modes, keys, description || "User defined mapping", action, extra); var map = new Map(modes, keys, description || "User defined mapping", action, extra);
// remove all old mappings to this key sequence // remove all old mappings to this key sequence
for (let i = 0; i < map.names.length; i++) for (let i = 0; i < map.names.length; i++)
@@ -305,31 +302,30 @@ liberator.Mappings = function () //{{{
get: function (mode, cmd) get: function (mode, cmd)
{ {
mode = mode || liberator.modes.NORMAL; mode = mode || modes.NORMAL;
return getMap(mode, cmd, user) || getMap(mode, cmd, main); return getMap(mode, cmd, user) || getMap(mode, cmd, main);
}, },
getDefault: function (mode, cmd) getDefault: function (mode, cmd)
{ {
mode = mode || liberator.modes.NORMAL; mode = mode || modes.NORMAL;
return getMap(mode, cmd, main); return getMap(mode, cmd, main);
}, },
// returns an array of mappings with names which START with "cmd" (but are NOT "cmd") // returns an array of mappings with names which START with "cmd" (but are NOT "cmd")
getCandidates: function (mode, cmd) getCandidates: function (mode, cmd)
{ {
var mappings = user[mode].concat(main[mode]); let mappings = user[mode].concat(main[mode]);
var matches = []; let matches = [];
for (let i = 0; i < mappings.length; i++) for (let [,map] in Iterator(mappings))
{ {
var map = mappings[i]; for (let [,name] in Iterator(map.names))
for (let j = 0; j < map.names.length; j++)
{ {
if (map.names[j].indexOf(cmd) == 0 && map.names[j].length > cmd.length) if (name.indexOf(cmd) == 0 && name.length > cmd.length)
{ {
// for < only return a candidate if it doesn't look like a <c-x> mapping // for < only return a candidate if it doesn't look like a <c-x> mapping
if (cmd != "<" || !/^<.+>/.test(map.names[j])) if (cmd != "<" || !/^<.+>/.test(name))
matches.push(map); matches.push(map);
} }
} }
@@ -340,7 +336,7 @@ liberator.Mappings = function () //{{{
getMapLeader: function () getMapLeader: function ()
{ {
var leaderRef = liberator.variableReference("mapleader"); var leaderRef = variableReference("mapleader");
return leaderRef[0] ? leaderRef[0][leaderRef[1]] : "\\"; return leaderRef[0] ? leaderRef[0][leaderRef[1]] : "\\";
}, },
@@ -368,7 +364,7 @@ liberator.Mappings = function () //{{{
if (!maps || maps.length == 0) if (!maps || maps.length == 0)
{ {
liberator.echo("No mappings found"); echo("No mappings found");
return; return;
} }
@@ -398,20 +394,20 @@ liberator.Mappings = function () //{{{
var flag = output.some(function (x) x); var flag = output.some(function (x) x);
if (!flag) if (!flag)
{ {
liberator.echo("No mappings found"); echo("No mappings found");
return; return;
} }
var modeSign = ""; var modeSign = "";
modes.forEach(function (mode) modes.forEach(function (mode)
{ {
if (mode == liberator.modes.NORMAL) if (mode == modes.NORMAL)
modeSign += "n"; modeSign += "n";
if ((mode == liberator.modes.INSERT || mode == liberator.modes.TEXTAREA) && modeSign.indexOf("i") == -1) if ((mode == modes.INSERT || mode == modes.TEXTAREA) && modeSign.indexOf("i") == -1)
modeSign += "i"; modeSign += "i";
if (mode == liberator.modes.COMMAND_LINE) if (mode == modes.COMMAND_LINE)
modeSign += "c"; modeSign += "c";
if (mode == liberator.modes.MESSAGRE) if (mode == modes.MESSAGRE)
modeSign += "m"; modeSign += "m";
}); });
@@ -419,8 +415,8 @@ liberator.Mappings = function () //{{{
if (output[i])); if (output[i]));
let list = <table> let list = <table>
{ {
liberator.template.map(_maps, function (map) template.map(_maps, function (map)
liberator.template.map(map.names, function (name) template.map(map.names, function (name)
<tr> <tr>
<td>{modeSign} {name}</td> <td>{modeSign} {name}</td>
<td>{map.noremap ? "*" : " "}</td> <td>{map.noremap ? "*" : " "}</td>
@@ -428,7 +424,7 @@ liberator.Mappings = function () //{{{
</tr>)) </tr>))
} }
</table>; </table>;
liberator.commandline.echo(list, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
} }
}; };

View File

@@ -26,7 +26,7 @@ the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL. the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/ }}} ***** END LICENSE BLOCK *****/
liberator.modes = (function () //{{{ with (liberator) liberator.modes = (function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -50,44 +50,44 @@ liberator.modes = (function () //{{{
return "-- PASS THROUGH --"; return "-- PASS THROUGH --";
var ext = ""; var ext = "";
if (extended & liberator.modes.QUICK_HINT) if (extended & modes.QUICK_HINT)
ext += " (quick)"; ext += " (quick)";
if (extended & liberator.modes.EXTENDED_HINT) if (extended & modes.EXTENDED_HINT)
ext += " (extended)"; ext += " (extended)";
if (extended & liberator.modes.ALWAYS_HINT) if (extended & modes.ALWAYS_HINT)
ext += " (always)"; ext += " (always)";
if (extended & liberator.modes.INACTIVE_HINT) if (extended & modes.INACTIVE_HINT)
ext += " (inactive)"; ext += " (inactive)";
if (extended & liberator.modes.MENU) // TODO: desirable? if (extended & modes.MENU) // TODO: desirable?
ext += " (menu)"; ext += " (menu)";
// when recording a macro // when recording a macro
var macromode = ""; var macromode = "";
if (liberator.modes.isRecording) if (modes.isRecording)
macromode = "recording"; macromode = "recording";
else if (liberator.modes.isReplaying) else if (modes.isReplaying)
macromode = "replaying"; macromode = "replaying";
ext += " --" + macromode; ext += " --" + macromode;
switch (main) switch (main)
{ {
case liberator.modes.INSERT: case modes.INSERT:
return "-- INSERT" + ext; return "-- INSERT" + ext;
case liberator.modes.VISUAL: case modes.VISUAL:
return (extended & liberator.modes.LINE) ? "-- VISUAL LINE" + ext : "-- VISUAL" + ext; return (extended & modes.LINE) ? "-- VISUAL LINE" + ext : "-- VISUAL" + ext;
case liberator.modes.HINTS: case modes.HINTS:
return "-- HINTS" + ext; return "-- HINTS" + ext;
case liberator.modes.CARET: case modes.CARET:
return "-- CARET" + ext; return "-- CARET" + ext;
case liberator.modes.TEXTAREA: case modes.TEXTAREA:
return "-- TEXTAREA" + ext; return "-- TEXTAREA" + ext;
case liberator.modes.MESSAGE: case modes.MESSAGE:
return "-- MESSAGE" + ext; return "-- MESSAGE" + ext;
case liberator.modes.COMPOSE: case modes.COMPOSE:
return "-- COMPOSE" + ext; return "-- COMPOSE" + ext;
case liberator.modes.CUSTOM: case modes.CUSTOM:
return "-- " + liberator.plugins.mode + ext; return "-- " + plugins.mode + ext;
default: // NORMAL mode default: // NORMAL mode
return macromode; return macromode;
} }
@@ -95,23 +95,23 @@ liberator.modes = (function () //{{{
// NOTE: Pay attention that you don't run into endless loops // NOTE: Pay attention that you don't run into endless loops
// Usually you should only indicate to leave a special mode like HINTS // Usually you should only indicate to leave a special mode like HINTS
// by calling liberator.modes.reset() and adding the stuff which is needed // by calling modes.reset() and adding the stuff which is needed
// for its cleanup here // for its cleanup here
function handleModeChange(oldMode, newMode) function handleModeChange(oldMode, newMode)
{ {
// TODO: fix v.log() to work with verbosity level // TODO: fix v.log() to work with verbosity level
//liberator.log("switching from mode " + oldMode + " to mode " + newMode, 7); //log("switching from mode " + oldMode + " to mode " + newMode, 7);
//liberator.dump("switching from mode " + oldMode + " to mode " + newMode + "\n"); //dump("switching from mode " + oldMode + " to mode " + newMode + "\n");
switch (oldMode) switch (oldMode)
{ {
case liberator.modes.TEXTAREA: case modes.TEXTAREA:
case liberator.modes.INSERT: case modes.INSERT:
liberator.editor.unselectText(); editor.unselectText();
break; break;
case liberator.modes.VISUAL: case modes.VISUAL:
if (newMode == liberator.modes.CARET) if (newMode == modes.CARET)
{ {
// clear any selection made // clear any selection made
var selection = window.content.getSelection(); var selection = window.content.getSelection();
@@ -122,31 +122,31 @@ liberator.modes = (function () //{{{
catch (e) {} catch (e) {}
} }
else else
liberator.editor.unselectText(); editor.unselectText();
break; break;
case liberator.modes.CUSTOM: case modes.CUSTOM:
liberator.plugins.stop(); plugins.stop();
break; break;
case liberator.modes.HINTS: case modes.HINTS:
liberator.hints.hide(); hints.hide();
break; break;
case liberator.modes.COMMAND_LINE: case modes.COMMAND_LINE:
liberator.commandline.close(); commandline.close();
break; break;
} }
if (newMode == liberator.modes.NORMAL) if (newMode == modes.NORMAL)
{ {
// disable caret mode when we want to switch to normal mode // disable caret mode when we want to switch to normal mode
var value = liberator.options.getPref("accessibility.browsewithcaret", false); var value = options.getPref("accessibility.browsewithcaret", false);
if (value) if (value)
liberator.options.setPref("accessibility.browsewithcaret", false); options.setPref("accessibility.browsewithcaret", false);
liberator.statusline.updateUrl(); statusline.updateUrl();
liberator.focusContent(false); focusContent(false);
} }
} }
@@ -183,13 +183,7 @@ liberator.modes = (function () //{{{
RECORDING: 1 << 21, RECORDING: 1 << 21,
PROMPT: 1 << 22, PROMPT: 1 << 22,
__iterator__: function () __iterator__: function () util.arrayIter(this.all),
{
var modes = this.all;
for (let i = 0; i < modes.length; i++)
yield modes[i];
},
get all() [this.NONE, this.NORMAL, this.INSERT, this.VISUAL, get all() [this.NONE, this.NORMAL, this.INSERT, this.VISUAL,
this.HINTS, this.COMMAND_LINE, this.CARET, this.HINTS, this.COMMAND_LINE, this.CARET,
@@ -198,15 +192,15 @@ liberator.modes = (function () //{{{
// show the current mode string in the command line // show the current mode string in the command line
show: function () show: function ()
{ {
if (!liberator.options["showmode"]) if (!options["showmode"])
return; return;
// never show mode messages if we are in command line mode // never show mode messages if we are in command line mode
if (main == liberator.modes.COMMAND_LINE) if (main == modes.COMMAND_LINE)
return; return;
liberator.commandline.echo(getModeMessage(), liberator.commandline.HL_MODEMSG, commandline.echo(getModeMessage(), commandline.HL_MODEMSG,
liberator.commandline.DISALLOW_MULTILINE); commandline.DISALLOW_MULTILINE);
}, },
// add/remove always work on the extended mode only // add/remove always work on the extended mode only
@@ -228,7 +222,7 @@ liberator.modes = (function () //{{{
main = mainMode; main = mainMode;
if (!extendedMode) if (!extendedMode)
extended = liberator.modes.NONE; extended = modes.NONE;
} }
if (typeof extendedMode === "number") if (typeof extendedMode === "number")
extended = extendedMode; extended = extendedMode;
@@ -255,24 +249,24 @@ liberator.modes = (function () //{{{
setCustomMode: function (modestr, oneventfunc, stopfunc) setCustomMode: function (modestr, oneventfunc, stopfunc)
{ {
// TODO this.plugin[id]... ('id' maybe submode or what..) // TODO this.plugin[id]... ('id' maybe submode or what..)
liberator.plugins.mode = modestr; plugins.mode = modestr;
liberator.plugins.onEvent = oneventfunc; plugins.onEvent = oneventfunc;
liberator.plugins.stop = stopfunc; plugins.stop = stopfunc;
}, },
// keeps recording state // keeps recording state
reset: function (silent) reset: function (silent)
{ {
modeStack = []; modeStack = [];
if (liberator.config.isComposeWindow) if (config.isComposeWindow)
this.set(liberator.modes.COMPOSE, liberator.modes.NONE, silent); this.set(modes.COMPOSE, modes.NONE, silent);
else else
this.set(liberator.modes.NORMAL, liberator.modes.NONE, silent); this.set(modes.NORMAL, modes.NONE, silent);
}, },
remove: function (mode) remove: function (mode)
{ {
extended = (extended | mode) ^ mode; extended &= ~mode;
this.show(); this.show();
}, },
@@ -295,7 +289,7 @@ liberator.modes = (function () //{{{
main = value; main = value;
// setting the main mode always resets any extended mode // setting the main mode always resets any extended mode
extended = liberator.modes.NONE; extended = modes.NONE;
this.show(); this.show();
}, },

View File

@@ -26,7 +26,7 @@ the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL. the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/ }}} ***** END LICENSE BLOCK *****/
liberator.config = { //{{{ with (liberator) liberator.config = { //{{{
/*** required options, no checks done if they really exist, so be careful ***/ /*** required options, no checks done if they really exist, so be careful ***/
name: "Muttator", name: "Muttator",
hostApplication: "Thunderbird", // TODO: can this be found out otherwise? gBrandBundle.getString("brandShortName"); hostApplication: "Thunderbird", // TODO: can this be found out otherwise? gBrandBundle.getString("brandShortName");
@@ -37,7 +37,7 @@ liberator.config = { //{{{
guioptions: { m: ["mail-toolbar-menubar2"], T: ["mail-bar2"], f: ["folderPaneBox", "folderpane_splitter"], F: ["folderPaneHeader"] }, guioptions: { m: ["mail-toolbar-menubar2"], T: ["mail-bar2"], f: ["folderPaneBox", "folderpane_splitter"], F: ["folderPaneHeader"] },
get isComposeWindow() window.wintype == "msgcompose", get isComposeWindow() window.wintype == "msgcompose",
get browserModes() [liberator.modes.MESSAGE], get browserModes() [modes.MESSAGE],
// focusContent() focuses this widget // focusContent() focuses this widget
get mainWidget() this.isComposeWindow ? document.getElementById("content-frame") : GetThreadTree(), get mainWidget() this.isComposeWindow ? document.getElementById("content-frame") : GetThreadTree(),
get mainWindowID() this.isComposeWindow ? "msgcomposeWindow" : "messengerWindow", get mainWindowID() this.isComposeWindow ? "msgcomposeWindow" : "messengerWindow",
@@ -92,7 +92,7 @@ liberator.config = { //{{{
/*["searchengines", "Manage installed search engines", /*["searchengines", "Manage installed search engines",
function () { openDialog("chrome://browser/content/search/engineManager.xul", "_blank", "chrome,dialog,modal,centerscreen"); }], function () { openDialog("chrome://browser/content/search/engineManager.xul", "_blank", "chrome,dialog,modal,centerscreen"); }],
["selectionsource", "View selection source", ["selectionsource", "View selection source",
function () { liberator.buffer.viewSelectionSource(); }]*/ function () { buffer.viewSelectionSource(); }]*/
], ],
// they are sorted by relevance, not alphabetically // they are sorted by relevance, not alphabetically
@@ -111,7 +111,7 @@ liberator.config = { //{{{
// 0: never automatically edit externally // 0: never automatically edit externally
// 1: automatically edit externally when message window is shown the first time // 1: automatically edit externally when message window is shown the first time
// 2: automatically edit externally, once the message text gets focus (not working currently) // 2: automatically edit externally, once the message text gets focus (not working currently)
liberator.options.add(["autoexternal", "ae"], options.add(["autoexternal", "ae"],
"Edit message with external editor by default", "Edit message with external editor by default",
"boolean", false); "boolean", false);
@@ -119,39 +119,39 @@ liberator.config = { //{{{
if (this.isComposeWindow) if (this.isComposeWindow)
{ {
this.features = ["addressbook"]; // the composer has no special features this.features = ["addressbook"]; // the composer has no special features
//liberator.loadModule("addressbook", liberator.Addressbook); //loadModule("addressbook", Addressbook);
// TODO: move mappings elsewhere, probably compose.js // TODO: move mappings elsewhere, probably compose.js
liberator.mappings.add([liberator.modes.COMPOSE], mappings.add([modes.COMPOSE],
["e"], "Edit message", ["e"], "Edit message",
function () { liberator.editor.editWithExternalEditor(); }); function () { editor.editWithExternalEditor(); });
liberator.mappings.add([liberator.modes.COMPOSE], mappings.add([modes.COMPOSE],
["y"], "Send message now", ["y"], "Send message now",
function () { goDoCommand("cmd_sendNow"); }); function () { goDoCommand("cmd_sendNow"); });
liberator.mappings.add([liberator.modes.COMPOSE], mappings.add([modes.COMPOSE],
["Y"], "Send message later", ["Y"], "Send message later",
function () { goDoCommand("cmd_sendLater"); }); function () { goDoCommand("cmd_sendLater"); });
// FIXME: does not really work reliably // FIXME: does not really work reliably
liberator.mappings.add([liberator.modes.COMPOSE], mappings.add([modes.COMPOSE],
["t"], "Select To: field", ["t"], "Select To: field",
function () { awSetFocus(0, awGetInputElement(1)); }); function () { awSetFocus(0, awGetInputElement(1)); });
liberator.mappings.add([liberator.modes.COMPOSE], mappings.add([modes.COMPOSE],
["s"], "Select Subject: field", ["s"], "Select Subject: field",
function () { GetMsgSubjectElement().focus(); }); function () { GetMsgSubjectElement().focus(); });
liberator.mappings.add([liberator.modes.COMPOSE], mappings.add([modes.COMPOSE],
["i"], "Select message body", ["i"], "Select message body",
function () { SetMsgBodyFrameFocus(); }); function () { SetMsgBodyFrameFocus(); });
liberator.mappings.add([liberator.modes.COMPOSE], mappings.add([modes.COMPOSE],
["q"], "Close composer, ask when for unsaved changes", ["q"], "Close composer, ask when for unsaved changes",
function () { DoCommandClose(); }); function () { DoCommandClose(); });
liberator.mappings.add([liberator.modes.COMPOSE], mappings.add([modes.COMPOSE],
["Q", "ZQ"], "Force closing composer", ["Q", "ZQ"], "Force closing composer",
function () { MsgComposeCloseWindow(true); /* cache window for better performance*/ }); function () { MsgComposeCloseWindow(true); /* cache window for better performance*/ });
@@ -168,10 +168,10 @@ liberator.config = { //{{{
NotifyDocumentStateChanged: function (nowDirty) NotifyDocumentStateChanged: function (nowDirty)
{ {
// only edit with external editor if this window was not cached! // only edit with external editor if this window was not cached!
if (liberator.options["autoexternal"] && !window.messageWasEditedExternally/* && !gMsgCompose.recycledWindow*/) if (options["autoexternal"] && !window.messageWasEditedExternally/* && !gMsgCompose.recycledWindow*/)
{ {
window.messageWasEditedExternally = true; window.messageWasEditedExternally = true;
liberator.editor.editWithExternalEditor(); editor.editWithExternalEditor();
} }
}, },
@@ -195,16 +195,16 @@ liberator.config = { //{{{
}, true); }, true);
/*window.document.addEventListener("unload", function () { /*window.document.addEventListener("unload", function () {
GetCurrentEditor().removeDocumentStateListener(liberator.config.stateListener); GetCurrentEditor().removeDocumentStateListener(config.stateListener);
}, true);*/ }, true);*/
} }
else else
{ {
liberator.loadModule("mail", liberator.Mail); loadModule("mail", Mail);
liberator.loadModule("addressbook", liberator.Addressbook); loadModule("addressbook", Addressbook);
liberator.loadModule("tabs", liberator.Tabs); loadModule("tabs", Tabs);
liberator.loadModule("marks", liberator.Marks); loadModule("marks", Marks);
liberator.loadModule("hints", liberator.Hints); loadModule("hints", Hints);
} }
} }
}; //}}} }; //}}}

View File

@@ -27,8 +27,8 @@ the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/ }}} ***** END LICENSE BLOCK *****/
// do NOT create instances of this class yourself, use the helper method // do NOT create instances of this class yourself, use the helper method
// liberator.options.add() instead // options.add() instead
liberator.Option = function (names, description, type, defaultValue, extraInfo) //{{{ with (liberator) liberator.Option = function (names, description, type, defaultValue, extraInfo) //{{{
{ {
if (!names || !type) if (!names || !type)
return null; return null;
@@ -40,8 +40,8 @@ liberator.Option = function (names, description, type, defaultValue, extraInfo)
this.name = cannonName; this.name = cannonName;
this.names = names; this.names = names;
this.type = type; this.type = type;
this.scope = (extraInfo.scope & liberator.options.OPTION_SCOPE_BOTH) || this.scope = (extraInfo.scope & options.OPTION_SCOPE_BOTH) ||
liberator.options.OPTION_SCOPE_GLOBAL; options.OPTION_SCOPE_GLOBAL;
// XXX set to BOTH by default someday? - kstep // XXX set to BOTH by default someday? - kstep
this.description = description || ""; this.description = description || "";
@@ -68,8 +68,8 @@ liberator.Option = function (names, description, type, defaultValue, extraInfo)
} }
} }
this.__defineGetter__("globalvalue", function () liberator.options.store.get(cannonName)); this.__defineGetter__("globalvalue", function () options.store.get(cannonName));
this.__defineSetter__("globalvalue", function (val) { liberator.options.store.set(cannonName, val); }); this.__defineSetter__("globalvalue", function (val) { options.store.set(cannonName, val); });
if (this.globalvalue == undefined) if (this.globalvalue == undefined)
this.globalvalue = this.defaultValue; this.globalvalue = this.defaultValue;
@@ -87,9 +87,9 @@ liberator.Option = function (names, description, type, defaultValue, extraInfo)
var aValue; var aValue;
if (liberator.has("tabs") && (scope & liberator.options.OPTION_SCOPE_LOCAL)) if (liberator.has("tabs") && (scope & options.OPTION_SCOPE_LOCAL))
aValue = liberator.tabs.options[this.name]; aValue = tabs.options[this.name];
if ((scope & liberator.options.OPTION_SCOPE_GLOBAL) && (aValue == undefined)) if ((scope & options.OPTION_SCOPE_GLOBAL) && (aValue == undefined))
aValue = this.globalvalue; aValue = this.globalvalue;
if (this.getter) if (this.getter)
@@ -112,13 +112,13 @@ liberator.Option = function (names, description, type, defaultValue, extraInfo)
if (newValue === undefined) if (newValue === undefined)
{ {
newValue = tmpValue; newValue = tmpValue;
liberator.log("DEPRECATED: '" + this.name + "' setter should return a value"); log("DEPRECATED: '" + this.name + "' setter should return a value");
} }
} }
if (liberator.has("tabs") && (scope & liberator.options.OPTION_SCOPE_LOCAL)) if (liberator.has("tabs") && (scope & options.OPTION_SCOPE_LOCAL))
liberator.tabs.options[this.name] = newValue; tabs.options[this.name] = newValue;
if ((scope & liberator.options.OPTION_SCOPE_GLOBAL) && newValue != this.globalValue) if ((scope & options.OPTION_SCOPE_GLOBAL) && newValue != this.globalValue)
this.globalvalue = newValue; this.globalvalue = newValue;
this.hasChanged = true; this.hasChanged = true;
@@ -156,7 +156,7 @@ liberator.Option = function (names, description, type, defaultValue, extraInfo)
}; //}}} }; //}}}
liberator.Options = function () //{{{ with (liberator) liberator.Options = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -164,20 +164,20 @@ liberator.Options = function () //{{{
var prefService = Components.classes["@mozilla.org/preferences-service;1"] var prefService = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch); .getService(Components.interfaces.nsIPrefBranch);
var options = {}; var optionHash = {};
function optionObserver(key, event, option) function optionObserver(key, event, option)
{ {
// Trigger any setters. // Trigger any setters.
let opt = liberator.options.get(option); let opt = options.get(option);
if (event == "change" && opt) if (event == "change" && opt)
opt.set(opt.value, liberator.options.OPTION_SCOPE_GLOBAL) opt.set(opt.value, options.OPTION_SCOPE_GLOBAL)
} }
liberator.storage.newMap("options", false); storage.newMap("options", false);
liberator.storage.addObserver("options", optionObserver); storage.addObserver("options", optionObserver);
liberator.registerObserver("shutdown", function () { registerObserver("shutdown", function () {
liberator.storage.removeObserver("options", optionObserver) storage.removeObserver("options", optionObserver)
}); });
function storePreference(name, value) function storePreference(name, value)
@@ -189,26 +189,26 @@ liberator.Options = function () //{{{
if (type == prefService.PREF_INVALID || type == prefService.PREF_STRING) if (type == prefService.PREF_INVALID || type == prefService.PREF_STRING)
prefService.setCharPref(name, value); prefService.setCharPref(name, value);
else if (type == prefService.PREF_INT) else if (type == prefService.PREF_INT)
liberator.echoerr("E521: Number required after =: " + name + "=" + value); echoerr("E521: Number required after =: " + name + "=" + value);
else else
liberator.echoerr("E474: Invalid argument: " + name + "=" + value); echoerr("E474: Invalid argument: " + name + "=" + value);
break; break;
case "number": case "number":
if (type == prefService.PREF_INVALID || type == prefService.PREF_INT) if (type == prefService.PREF_INVALID || type == prefService.PREF_INT)
prefService.setIntPref(name, value); prefService.setIntPref(name, value);
else else
liberator.echoerr("E474: Invalid argument: " + name + "=" + value); echoerr("E474: Invalid argument: " + name + "=" + value);
break; break;
case "boolean": case "boolean":
if (type == prefService.PREF_INVALID || type == prefService.PREF_BOOL) if (type == prefService.PREF_INVALID || type == prefService.PREF_BOOL)
prefService.setBoolPref(name, value); prefService.setBoolPref(name, value);
else if (type == prefService.PREF_INT) else if (type == prefService.PREF_INT)
liberator.echoerr("E521: Number required after =: " + name + "=" + value); echoerr("E521: Number required after =: " + name + "=" + value);
else else
liberator.echoerr("E474: Invalid argument: " + name + "=" + value); echoerr("E474: Invalid argument: " + name + "=" + value);
break; break;
default: default:
liberator.echoerr("Unknown preference type: " + typeof value + " (" + name + "=" + value + ")"); echoerr("Unknown preference type: " + typeof value + " (" + name + "=" + value + ")");
} }
} }
@@ -254,7 +254,7 @@ liberator.Options = function () //{{{
if (!/keypress/.test(popupAllowedEvents)) if (!/keypress/.test(popupAllowedEvents))
{ {
storePreference("dom.popup_allowed_events", popupAllowedEvents + " keypress"); storePreference("dom.popup_allowed_events", popupAllowedEvents + " keypress");
liberator.registerObserver("shutdown", function () registerObserver("shutdown", function ()
{ {
if (loadPreference("dom.popup_allowed_events", "") if (loadPreference("dom.popup_allowed_events", "")
== popupAllowedEvents + " keypress") == popupAllowedEvents + " keypress")
@@ -275,7 +275,7 @@ liberator.Options = function () //{{{
////////////////////// COMMANDS //////////////////////////////////////////////// ////////////////////// COMMANDS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.commands.add(["let"], commands.add(["let"],
"Set or list a variable", "Set or list a variable",
function (args) function (args)
{ {
@@ -284,7 +284,7 @@ liberator.Options = function () //{{{
var str = var str =
<table> <table>
{ {
liberator.template.map(liberator.globalVariables, function ([i, value]) { template.map(globalVariables, function ([i, value]) {
let prefix = typeof value == "number" ? "#" : let prefix = typeof value == "number" ? "#" :
typeof value == "function" ? "*" : typeof value == "function" ? "*" :
" "; " ";
@@ -296,9 +296,9 @@ liberator.Options = function () //{{{
} }
</table>; </table>;
if (str.*.length()) if (str.*.length())
liberator.echo(str, liberator.commandline.FORCE_MULTILINE); echo(str, commandline.FORCE_MULTILINE);
else else
liberator.echo("No variables found"); echo("No variables found");
return; return;
} }
@@ -308,17 +308,17 @@ liberator.Options = function () //{{{
{ {
if (!matches[1]) if (!matches[1])
{ {
var reference = liberator.variableReference(matches[2]); var reference = variableReference(matches[2]);
if (!reference[0] && matches[3]) if (!reference[0] && matches[3])
{ {
liberator.echoerr("E121: Undefined variable: " + matches[2]); echoerr("E121: Undefined variable: " + matches[2]);
return; return;
} }
var expr = liberator.evalExpression(matches[4]); var expr = evalExpression(matches[4]);
if (expr === undefined) if (expr === undefined)
{ {
liberator.echoerr("E15: Invalid expression: " + matches[4]); echoerr("E15: Invalid expression: " + matches[4]);
return; return;
} }
else else
@@ -326,7 +326,7 @@ liberator.Options = function () //{{{
if (!reference[0]) if (!reference[0])
{ {
if (reference[2] == "g") if (reference[2] == "g")
reference[0] = liberator.globalVariables; reference[0] = globalVariables;
else else
return; // for now return; // for now
} }
@@ -348,10 +348,10 @@ liberator.Options = function () //{{{
// 1 - name // 1 - name
else if (matches = args.match(/^\s*([\w:]+)\s*$/)) else if (matches = args.match(/^\s*([\w:]+)\s*$/))
{ {
var reference = liberator.variableReference(matches[1]); var reference = variableReference(matches[1]);
if (!reference[0]) if (!reference[0])
{ {
liberator.echoerr("E121: Undefined variable: " + matches[1]); echoerr("E121: Undefined variable: " + matches[1]);
return; return;
} }
@@ -359,19 +359,19 @@ liberator.Options = function () //{{{
let prefix = typeof value == "number" ? "#" : let prefix = typeof value == "number" ? "#" :
typeof value == "function" ? "*" : typeof value == "function" ? "*" :
" "; " ";
liberator.echo(reference[1] + "\t\t" + prefix + value); echo(reference[1] + "\t\t" + prefix + value);
} }
}); });
liberator.commands.add(["pref[erences]", "prefs"], commands.add(["pref[erences]", "prefs"],
"Show " + liberator.config.hostApplication + " preferences", "Show " + config.hostApplication + " preferences",
function (args, special) function (args, special)
{ {
if (special) // open Firefox settings GUI dialog if (special) // open Firefox settings GUI dialog
{ {
liberator.open("about:config", open("about:config",
(liberator.options["newtab"] && liberator.options.get("newtab").has("all", "prefs")) (options["newtab"] && options.get("newtab").has("all", "prefs"))
? liberator.NEW_TAB : liberator.CURRENT_TAB); ? NEW_TAB : CURRENT_TAB);
} }
else else
{ {
@@ -383,34 +383,34 @@ liberator.Options = function () //{{{
bang: true, bang: true,
}); });
liberator.commands.add(["setl[ocal]"], commands.add(["setl[ocal]"],
"Set local option", "Set local option",
function (args, special, count) function (args, special, count)
{ {
liberator.commands.get("set").execute(args, special, count, { scope: liberator.options.OPTION_SCOPE_LOCAL }); commands.get("set").execute(args, special, count, { scope: options.OPTION_SCOPE_LOCAL });
}, },
{ {
bang: true, bang: true,
count: true, count: true,
completer: function (filter, special, count) completer: function (filter, special, count)
{ {
return liberator.commands.get("set").completer(filter, special, count, { scope: liberator.options.OPTION_SCOPE_LOCAL }); return commands.get("set").completer(filter, special, count, { scope: options.OPTION_SCOPE_LOCAL });
} }
} }
); );
liberator.commands.add(["setg[lobal]"], commands.add(["setg[lobal]"],
"Set global option", "Set global option",
function (args, special, count) function (args, special, count)
{ {
liberator.commands.get("set").execute(args, special, count, { scope: liberator.options.OPTION_SCOPE_GLOBAL }); commands.get("set").execute(args, special, count, { scope: options.OPTION_SCOPE_GLOBAL });
}, },
{ {
bang: true, bang: true,
count: true, count: true,
completer: function (filter, special, count) completer: function (filter, special, count)
{ {
return liberator.commands.get("set").completer(filter, special, count, { scope: liberator.options.OPTION_SCOPE_GLOBAL }); return commands.get("set").completer(filter, special, count, { scope: options.OPTION_SCOPE_GLOBAL });
} }
} }
); );
@@ -432,7 +432,7 @@ liberator.Options = function () //{{{
} }
if (matches) if (matches)
ret.option = liberator.options.get(ret.name, ret.scope); ret.option = options.get(ret.name, ret.scope);
ret.prefix = prefix; ret.prefix = prefix;
ret.postfix = postfix; ret.postfix = postfix;
@@ -469,7 +469,7 @@ liberator.Options = function () //{{{
} }
// TODO: support setting multiple options at once // TODO: support setting multiple options at once
liberator.commands.add(["se[t]"], commands.add(["se[t]"],
"Set an option", "Set an option",
function (args, special, count, modifiers) function (args, special, count, modifiers)
{ {
@@ -488,13 +488,13 @@ liberator.Options = function () //{{{
let invertBoolean = (postfix == "!"); let invertBoolean = (postfix == "!");
if (name == "all" && reset) if (name == "all" && reset)
liberator.echoerr("You can't reset all options, it could make " + liberator.config.hostApplication + " unusable."); echoerr("You can't reset all options, it could make " + config.hostApplication + " unusable.");
else if (name == "all") else if (name == "all")
liberator.options.listPrefs(onlyNonDefault, ""); options.listPrefs(onlyNonDefault, "");
else if (reset) else if (reset)
liberator.options.resetPref(name); options.resetPref(name);
else if (invertBoolean) else if (invertBoolean)
liberator.options.invertPref(name); options.invertPref(name);
else if (valueGiven) else if (valueGiven)
{ {
switch (value) switch (value)
@@ -512,11 +512,11 @@ liberator.Options = function () //{{{
if (/^\d+$/.test(value)) if (/^\d+$/.test(value))
value = parseInt(value, 10); value = parseInt(value, 10);
} }
liberator.options.setPref(name, value); options.setPref(name, value);
} }
else else
{ {
liberator.options.listPrefs(onlyNonDefault, name); options.listPrefs(onlyNonDefault, name);
} }
return; return;
} }
@@ -524,14 +524,14 @@ liberator.Options = function () //{{{
let opt = parseOpt(args, modifiers); let opt = parseOpt(args, modifiers);
if (!opt) if (!opt)
{ {
liberator.echoerr("Error parsing :set command: " + args); echoerr("Error parsing :set command: " + args);
return; return;
} }
let option = opt.option; let option = opt.option;
if (option == null && !opt.all) if (option == null && !opt.all)
{ {
liberator.echoerr("No such option: " + opt.name); echoerr("No such option: " + opt.name);
return; return;
} }
@@ -540,7 +540,7 @@ liberator.Options = function () //{{{
{ {
if (opt.all) if (opt.all)
{ {
for (let option in liberator.options) for (let option in options)
option.reset(); option.reset();
} }
else else
@@ -553,14 +553,14 @@ liberator.Options = function () //{{{
{ {
if (opt.all) if (opt.all)
{ {
liberator.options.list(opt.onlyNonDefault, opt.scope); options.list(opt.onlyNonDefault, opt.scope);
} }
else else
{ {
if (option.type == "boolean") if (option.type == "boolean")
liberator.echo((opt.optionValue ? " " : "no") + option.name); echo((opt.optionValue ? " " : "no") + option.name);
else else
liberator.echo(" " + option.name + "=" + opt.optionValue); echo(" " + option.name + "=" + opt.optionValue);
} }
} }
// write access // write access
@@ -576,7 +576,7 @@ liberator.Options = function () //{{{
case "boolean": case "boolean":
if (opt.valueGiven) if (opt.valueGiven)
{ {
liberator.echoerr("E474: Invalid argument: " + args); echoerr("E474: Invalid argument: " + args);
return; return;
} }
@@ -592,7 +592,7 @@ liberator.Options = function () //{{{
if (isNaN(value)) if (isNaN(value))
{ {
liberator.echoerr("E521: Number required after =: " + args); echoerr("E521: Number required after =: " + args);
return; return;
} }
@@ -619,11 +619,11 @@ liberator.Options = function () //{{{
switch (opt.operator) switch (opt.operator)
{ {
case "+": case "+":
newValue = liberator.util.uniq(Array.concat(opt.optionHas, opt.valueHas), true); newValue = util.uniq(Array.concat(opt.optionHas, opt.valueHas), true);
break; break;
case "^": case "^":
// NOTE: Vim doesn't prepend if there's a match in the current value // NOTE: Vim doesn't prepend if there's a match in the current value
newValue = liberator.util.uniq(Array.concat(opt.valueHas, opt.optionHas), true); newValue = util.uniq(Array.concat(opt.valueHas, opt.optionHas), true);
break; break;
case "-": case "-":
newValue = opt.optionHas.filter(function (item) opt.valueHas.indexOf(item) == -1); newValue = opt.optionHas.filter(function (item) opt.valueHas.indexOf(item) == -1);
@@ -662,7 +662,7 @@ liberator.Options = function () //{{{
break; break;
default: default:
liberator.echoerr("E685: Internal error: option type `" + option.type + "' not supported"); echoerr("E685: Internal error: option type `" + option.type + "' not supported");
} }
if (option.isValidValue(newValue)) if (option.isValidValue(newValue))
@@ -671,7 +671,7 @@ liberator.Options = function () //{{{
} }
else else
// FIXME: need to be able to specify more specific errors // FIXME: need to be able to specify more specific errors
liberator.echoerr("E474: Invalid argument: " + args); echoerr("E474: Invalid argument: " + args);
} }
}, },
{ {
@@ -696,7 +696,7 @@ liberator.Options = function () //{{{
{ {
if (name.match("^" + filter.substr(0, filter.length - 1) + "$" )) if (name.match("^" + filter.substr(0, filter.length - 1) + "$" ))
{ {
let value = liberator.options.getPref(name) + ""; let value = options.getPref(name) + "";
return [filter.length + 1, [[value, ""]]]; return [filter.length + 1, [[value, ""]]];
} }
} }
@@ -704,36 +704,36 @@ liberator.Options = function () //{{{
} }
optionCompletions = prefArray.map(function (pref) optionCompletions = prefArray.map(function (pref)
[pref, liberator.options.getPref(pref)]); [pref, options.getPref(pref)]);
return [0, liberator.completion.filter(optionCompletions, filter)]; return [0, completion.filter(optionCompletions, filter)];
} }
let prefix = (filter.match(/^(no|inv)/) || [""])[0]; let prefix = (filter.match(/^(no|inv)/) || [""])[0];
if (prefix) if (prefix)
filter = filter.substr(prefix.length); filter = filter.substr(prefix.length);
let scope = modifiers && modifiers.scope || liberator.options.OPTION_SCOPE_BOTH; let scope = modifiers && modifiers.scope || options.OPTION_SCOPE_BOTH;
let options = (opt for (opt in liberator.options) let opts = (opt for (opt in options)
if ((opt.scope & scope) && (!prefix || opt.type == "boolean" || prefix == "inv" && /list$/.test(opt.type)))); if ((opt.scope & scope) && (!prefix || opt.type == "boolean" || prefix == "inv" && /list$/.test(opt.type))));
if (!filter) if (!filter)
{ {
let opts = [[prefix + option.name, option.description] let opts = [[prefix + option.name, option.description]
for (option in options)]; for (option in opts)];
return [0, opts]; return [0, opts];
} }
else if (filter.indexOf("=") == -1) else if (filter.indexOf("=") == -1)
{ {
for (let option in options) for (let option in opts)
optionCompletions.push([[prefix + name, option.description] optionCompletions.push([[prefix + name, option.description]
for each (name in option.names) for each (name in option.names)
if (name.indexOf(filter) == 0)]); if (name.indexOf(filter) == 0)]);
// Flatten array. // Flatten array.
optionCompletions = Array.concat.apply(Array, optionCompletions); optionCompletions = Array.concat.apply(Array, optionCompletions);
return [0, liberator.completion.filter(optionCompletions, prefix + filter, true)]; return [0, completion.filter(optionCompletions, prefix + filter, true)];
} }
else if (prefix == "no") else if (prefix == "no")
return; return;
@@ -790,11 +790,11 @@ liberator.Options = function () //{{{
} }
} }
} }
return [len, liberator.completion.filter(completions, filter, true)]; return [len, completion.filter(completions, filter, true)];
} }
}); });
liberator.commands.add(["unl[et]"], commands.add(["unl[et]"],
"Delete a variable", "Delete a variable",
function (args, special) function (args, special)
{ {
@@ -806,11 +806,11 @@ liberator.Options = function () //{{{
for (let i = 0; i < args.arguments.length; i++) for (let i = 0; i < args.arguments.length; i++)
{ {
var name = args.arguments[i]; var name = args.arguments[i];
var reference = liberator.variableReference(name); var reference = variableReference(name);
if (!reference[0]) if (!reference[0])
{ {
if (!special) if (!special)
liberator.echoerr("E108: No such variable: " + name); echoerr("E108: No such variable: " + name);
return; return;
} }
@@ -834,8 +834,7 @@ liberator.Options = function () //{{{
__iterator__: function () __iterator__: function ()
{ {
let sorted = [o for ([,o] in Iterator(options))] let sorted = [o for ([i, o] in Iterator(optionHash))].sort(function (a, b) String.localeCompare(a.name, b.name));
.sort(function (a, b) String.localeCompare(a.name, b.name));
return (v for ([k, v] in Iterator(sorted))); return (v for ([k, v] in Iterator(sorted)));
}, },
@@ -844,38 +843,38 @@ liberator.Options = function () //{{{
if (!extraInfo) if (!extraInfo)
extraInfo = {}; extraInfo = {};
var option = new liberator.Option(names, description, type, defaultValue, extraInfo); let option = new Option(names, description, type, defaultValue, extraInfo);
if (!option) if (!option)
return false; return false;
if (option.name in options) if (option.name in optionHash)
{ {
// never replace for now // never replace for now
liberator.log("Warning: '" + names[0] + "' already exists, NOT replacing existing option.", 1); log("Warning: '" + names[0] + "' already exists, NOT replacing existing option.", 1);
return false; return false;
} }
// quickly access options with liberator.options["wildmode"]: // quickly access options with options["wildmode"]:
this.__defineGetter__(option.name, function () option.value); this.__defineGetter__(option.name, function () option.value);
this.__defineSetter__(option.name, function (value) { option.value = value; }); this.__defineSetter__(option.name, function (value) { option.value = value; });
options[option.name] = option; optionHash[option.name] = option;
return true; return true;
}, },
get: function (name, scope) get: function (name, scope)
{ {
if (!scope) if (!scope)
scope = liberator.options.OPTION_SCOPE_BOTH; scope = options.OPTION_SCOPE_BOTH;
if (name in options && (options[name].scope & scope)) if (name in optionHash)
return options[name]; return (optionHash[name].scope & scope) && optionHash[name];
for (let [,opt] in Iterator(options)) for (let opt in Iterator(options))
{ {
if (opt.hasName(name) && (opt.scope & scope)) if (opt.hasName(name))
return opt; return (opt.scope & scope) && opt;
} }
return null; return null;
@@ -884,10 +883,10 @@ liberator.Options = function () //{{{
list: function (onlyNonDefault, scope) list: function (onlyNonDefault, scope)
{ {
if (!scope) if (!scope)
scope = liberator.options.OPTION_SCOPE_BOTH; scope = options.OPTION_SCOPE_BOTH;
let opts = function (opt) { let opts = function (opt) {
for (let opt in Iterator(liberator.options)) for (let opt in Iterator(options))
{ {
let option = { let option = {
isDefault: opt.value == opt.defaultValue, isDefault: opt.value == opt.defaultValue,
@@ -910,14 +909,14 @@ liberator.Options = function () //{{{
} }
else else
{ {
option.value = <>={liberator.template.highlight(opt.value)}</>; option.value = <>={template.highlight(opt.value)}</>;
} }
yield option; yield option;
} }
} }
let list = liberator.template.options("Options", opts()); let list = template.options("Options", opts());
liberator.commandline.echo(list, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
}, },
listPrefs: function (onlyNonDefault, filter) listPrefs: function (onlyNonDefault, filter)
@@ -934,14 +933,14 @@ liberator.Options = function () //{{{
if (onlyNonDefault && !userValue || pref.indexOf(filter) == -1) if (onlyNonDefault && !userValue || pref.indexOf(filter) == -1)
continue; continue;
value = liberator.options.getPref(pref); value = options.getPref(pref);
if (typeof value == "string") if (typeof value == "string")
value = value.substr(0, 100).replace(/\n/g, " "); value = value.substr(0, 100).replace(/\n/g, " ");
let option = { let option = {
isDefault: !userValue, isDefault: !userValue,
default: loadPreference(pref, null, true), default: loadPreference(pref, null, true),
value: <>={liberator.template.highlight(value)}</>, value: <>={template.highlight(value)}</>,
name: pref, name: pref,
pre: "  ", /* Unicode nonbreaking space. */ pre: "  ", /* Unicode nonbreaking space. */
}; };
@@ -950,11 +949,11 @@ liberator.Options = function () //{{{
} }
} }
let list = liberator.template.options(liberator.config.hostApplication + " Options", prefs()); let list = template.options(config.hostApplication + " Options", prefs());
liberator.commandline.echo(list, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
}, },
get store() liberator.storage.options, get store() storage.options,
getPref: function (name, forcedDefault) getPref: function (name, forcedDefault)
{ {
@@ -977,7 +976,7 @@ liberator.Options = function () //{{{
if (prefService.getPrefType(name) == prefService.PREF_BOOL) if (prefService.getPrefType(name) == prefService.PREF_BOOL)
this.setPref(name, !this.getPref(name)); this.setPref(name, !this.getPref(name));
else else
liberator.echoerr("E488: Trailing characters: " + name + "!"); echoerr("E488: Trailing characters: " + name + "!");
} }
}; };
//}}} //}}}

View File

@@ -28,7 +28,7 @@ the terms of any one of the MPL, the GPL or the LGPL.
// TODO: many methods do not work with Thunderbird correctly yet // TODO: many methods do not work with Thunderbird correctly yet
liberator.Tabs = function () //{{{ with (liberator) liberator.Tabs = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -36,7 +36,7 @@ liberator.Tabs = function () //{{{
var tabmail; var tabmail;
var getBrowser = (function () { var getBrowser = (function () {
if (liberator.config.hostApplication == "Thunderbird") if (config.hostApplication == "Thunderbird")
{ {
return function () return function ()
{ {
@@ -107,37 +107,37 @@ liberator.Tabs = function () //{{{
} }
// hide tabs initially // hide tabs initially
if (liberator.config.name == "Vimperator") if (config.name == "Vimperator")
getBrowser().mStrip.getElementsByClassName("tabbrowser-tabs")[0].collapsed = true; getBrowser().mStrip.getElementsByClassName("tabbrowser-tabs")[0].collapsed = true;
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// OPTIONS ///////////////////////////////////////////////// ////////////////////// OPTIONS /////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.options.add(["showtabline", "stal"], options.add(["showtabline", "stal"],
"Control when to show the tab bar of opened web pages", "Control when to show the tab bar of opened web pages",
"number", liberator.config.name == "Vimperator" ? 2 : 0, "number", config.name == "Vimperator" ? 2 : 0,
{ {
setter: function (value) setter: function (value)
{ {
var tabs = liberator.tabs.tabStrip; let tabStrip = tabs.tabStrip;
if (!tabs) if (!tabStrip)
return; return;
if (value == 0) if (value == 0)
{ {
tabs.collapsed = true; tabStrip.collapsed = true;
} }
else if (value == 1) else if (value == 1)
{ {
liberator.options.setPref("browser.tabs.autoHide", true); options.setPref("browser.tabStrip.autoHide", true);
tabs.collapsed = false; tabStrip.collapsed = false;
} }
else else
{ {
liberator.options.setPref("browser.tabs.autoHide", false); options.setPref("browser.tabStrip.autoHide", false);
tabs.collapsed = false; tabStrip.collapsed = false;
} }
return value; return value;
@@ -153,9 +153,9 @@ liberator.Tabs = function () //{{{
validator: function (value) value >= 0 && value <= 2 validator: function (value) value >= 0 && value <= 2
}); });
if (liberator.config.name == "Vimperator") if (config.name == "Vimperator")
{ {
liberator.options.add(["activate", "act"], options.add(["activate", "act"],
"Define when tabs are automatically activated", "Define when tabs are automatically activated",
"stringlist", "homepage,quickmark,tabopen,paste", "stringlist", "homepage,quickmark,tabopen,paste",
{ {
@@ -176,7 +176,7 @@ liberator.Tabs = function () //{{{
} }
}); });
liberator.options.add(["newtab"], options.add(["newtab"],
"Define which commands should output in a new tab by default", "Define which commands should output in a new tab by default",
"stringlist", "", "stringlist", "",
{ {
@@ -199,7 +199,7 @@ liberator.Tabs = function () //{{{
} }
}); });
liberator.options.add(["popups", "pps"], options.add(["popups", "pps"],
"Where to show requested popup windows", "Where to show requested popup windows",
"number", 1, "number", 1,
{ {
@@ -211,8 +211,8 @@ liberator.Tabs = function () //{{{
[1, 2], // always in new window [1, 2], // always in new window
[2, 1]];// current tab unless it has specified sizes [2, 1]];// current tab unless it has specified sizes
liberator.options.setPref("browser.link.open_newwindow.restriction", values[value][0]); options.setPref("browser.link.open_newwindow.restriction", values[value][0]);
liberator.options.setPref("browser.link.open_newwindow", values[value][1]); options.setPref("browser.link.open_newwindow", values[value][1]);
return value; return value;
}, },
@@ -234,76 +234,76 @@ liberator.Tabs = function () //{{{
////////////////////// MAPPINGS //////////////////////////////////////////////// ////////////////////// MAPPINGS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.mappings.add([liberator.modes.NORMAL], ["g0", "g^"], mappings.add([modes.NORMAL], ["g0", "g^"],
"Go to the first tab", "Go to the first tab",
function (count) { liberator.tabs.select(0); }); function (count) { tabs.select(0); });
liberator.mappings.add([liberator.modes.NORMAL], ["g$"], mappings.add([modes.NORMAL], ["g$"],
"Go to the last tab", "Go to the last tab",
function (count) { liberator.tabs.select("$"); }); function (count) { tabs.select("$"); });
liberator.mappings.add([liberator.modes.NORMAL], ["gt", "<C-n>", "<C-Tab>", "<C-PageDown>"], mappings.add([modes.NORMAL], ["gt", "<C-n>", "<C-Tab>", "<C-PageDown>"],
"Go to the next tab", "Go to the next tab",
function (count) { liberator.tabs.select(count > 0 ? count - 1: "+1", count > 0 ? false : true); }, function (count) { tabs.select(count > 0 ? count - 1: "+1", count > 0 ? false : true); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.NORMAL], ["gT", "<C-p>", "<C-S-Tab>", "<C-PageUp>"], mappings.add([modes.NORMAL], ["gT", "<C-p>", "<C-S-Tab>", "<C-PageUp>"],
"Go to previous tab", "Go to previous tab",
function (count) { liberator.tabs.select("-" + (count < 1 ? 1 : count), true); }, function (count) { tabs.select("-" + (count < 1 ? 1 : count), true); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
if (liberator.config.name == "Vimperator") if (config.name == "Vimperator")
{ {
liberator.mappings.add([liberator.modes.NORMAL], ["b"], mappings.add([modes.NORMAL], ["b"],
"Open a prompt to switch buffers", "Open a prompt to switch buffers",
function () { liberator.commandline.open(":", "buffer! ", liberator.modes.EX); }); function () { commandline.open(":", "buffer! ", modes.EX); });
liberator.mappings.add([liberator.modes.NORMAL], ["B"], mappings.add([modes.NORMAL], ["B"],
"Show buffer list", "Show buffer list",
function () { liberator.tabs.list(false); }); function () { tabs.list(false); });
liberator.mappings.add([liberator.modes.NORMAL], ["d"], mappings.add([modes.NORMAL], ["d"],
"Delete current buffer", "Delete current buffer",
function (count) { liberator.tabs.remove(getBrowser().mCurrentTab, count, false, 0); }, function (count) { tabs.remove(getBrowser().mCurrentTab, count, false, 0); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.NORMAL], ["D"], mappings.add([modes.NORMAL], ["D"],
"Delete current buffer, focus tab to the left", "Delete current buffer, focus tab to the left",
function (count) { liberator.tabs.remove(getBrowser().mCurrentTab, count, true, 0); }, function (count) { tabs.remove(getBrowser().mCurrentTab, count, true, 0); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.NORMAL], ["gb"], mappings.add([modes.NORMAL], ["gb"],
"Repeat last :buffer[!] command", "Repeat last :buffer[!] command",
function (count) { liberator.tabs.switchTo(null, null, count, false); }, function (count) { tabs.switchTo(null, null, count, false); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.NORMAL], ["gB"], mappings.add([modes.NORMAL], ["gB"],
"Repeat last :buffer[!] command in reverse direction", "Repeat last :buffer[!] command in reverse direction",
function (count) { liberator.tabs.switchTo(null, null, count, true); }, function (count) { tabs.switchTo(null, null, count, true); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.NORMAL], ["u"], mappings.add([modes.NORMAL], ["u"],
"Undo closing of a tab", "Undo closing of a tab",
function (count) { liberator.commands.get("undo").execute("", false, count); }, function (count) { commands.get("undo").execute("", false, count); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.NORMAL], ["<C-^>", "<C-6>"], mappings.add([modes.NORMAL], ["<C-^>", "<C-6>"],
"Select the alternate tab or the [count]th tab", "Select the alternate tab or the [count]th tab",
function (count) function (count)
{ {
if (count < 1) if (count < 1)
liberator.tabs.selectAlternateTab(); tabs.selectAlternateTab();
else else
liberator.tabs.switchTo(count.toString(), false); tabs.switchTo(count.toString(), false);
}, },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
} }
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// COMMANDS //////////////////////////////////////////////// ////////////////////// COMMANDS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.commands.add(["bd[elete]", "bw[ipeout]", "bun[load]", "tabc[lose]"], commands.add(["bd[elete]", "bw[ipeout]", "bun[load]", "tabc[lose]"],
"Delete current buffer", "Delete current buffer",
function (args, special, count) function (args, special, count)
{ {
@@ -314,7 +314,7 @@ liberator.Tabs = function () //{{{
var match; var match;
if (match = args.match(/^(\d+):?/)) if (match = args.match(/^(\d+):?/))
{ {
liberator.tabs.remove(liberator.tabs.getTab(parseInt(match[1], 10) - 1)); tabs.remove(tabs.getTab(parseInt(match[1], 10) - 1));
removed = 1; removed = 1;
} }
else else
@@ -329,47 +329,47 @@ liberator.Tabs = function () //{{{
if (host.indexOf(args) >= 0 || uri == args || if (host.indexOf(args) >= 0 || uri == args ||
(special && (title.indexOf(args) >= 0 || uri.indexOf(args) >= 0))) (special && (title.indexOf(args) >= 0 || uri.indexOf(args) >= 0)))
{ {
liberator.tabs.remove(liberator.tabs.getTab(i)); tabs.remove(tabs.getTab(i));
removed++; removed++;
} }
} }
} }
if (removed > 0) if (removed > 0)
liberator.echo(removed + " fewer tab(s)"); echo(removed + " fewer tab(s)");
else else
liberator.echoerr("E94: No matching tab for " + args); echoerr("E94: No matching tab for " + args);
} }
else // just remove the current tab else // just remove the current tab
liberator.tabs.remove(getBrowser().mCurrentTab, count > 0 ? count : 1, special, 0); tabs.remove(getBrowser().mCurrentTab, count > 0 ? count : 1, special, 0);
}, },
{ {
bang: true, bang: true,
count: true, count: true,
completer: function (filter) liberator.completion.buffer(filter) completer: function (filter) completion.buffer(filter)
}); });
// TODO: this should open in a new tab positioned directly after the current one, not at the end // TODO: this should open in a new tab positioned directly after the current one, not at the end
liberator.commands.add(["tab"], commands.add(["tab"],
"Execute a command and tell it to output in a new tab", "Execute a command and tell it to output in a new tab",
function (args) function (args)
{ {
liberator.forceNewTab = true; liberator.forceNewTab = true;
liberator.execute(args.string); execute(args.string);
liberator.forceNewTab = false; liberator.forceNewTab = false;
}, },
{ {
argCount: "+", argCount: "+",
completer: function (filter) liberator.completion.ex(filter) completer: function (filter) completion.ex(filter)
}); });
liberator.commands.add(["tabl[ast]", "bl[ast]"], commands.add(["tabl[ast]", "bl[ast]"],
"Switch to the last tab", "Switch to the last tab",
function () liberator.tabs.select("$", false), function () tabs.select("$", false),
{ argCount: "0" }); { argCount: "0" });
// TODO: "Zero count" if 0 specified as arg // TODO: "Zero count" if 0 specified as arg
liberator.commands.add(["tabp[revious]", "tp[revious]", "tabN[ext]", "tN[ext]", "bp[revious]", "bN[ext]"], commands.add(["tabp[revious]", "tp[revious]", "tabN[ext]", "tN[ext]", "bp[revious]", "bN[ext]"],
"Switch to the previous tab or go [count] tabs back", "Switch to the previous tab or go [count] tabs back",
function (args, special, count) function (args, special, count)
{ {
@@ -377,23 +377,23 @@ liberator.Tabs = function () //{{{
if (args) if (args)
{ {
if (/^\d+$/.test(args)) if (/^\d+$/.test(args))
liberator.tabs.select("-" + args, true); // FIXME: urgh! tabs.select("-" + args, true); // FIXME: urgh!
else else
liberator.echoerr("E488: Trailing characters"); echoerr("E488: Trailing characters");
} }
else if (count > 0) else if (count > 0)
{ {
liberator.tabs.select("-" + count, true); tabs.select("-" + count, true);
} }
else else
{ {
liberator.tabs.select("-1", true); tabs.select("-1", true);
} }
}, },
{ count: true }); { count: true });
// TODO: "Zero count" if 0 specified as arg // TODO: "Zero count" if 0 specified as arg
liberator.commands.add(["tabn[ext]", "tn[ext]", "bn[ext]"], commands.add(["tabn[ext]", "tn[ext]", "bn[ext]"],
"Switch to the next or [count]th tab", "Switch to the next or [count]th tab",
function (args, special, count) function (args, special, count)
{ {
@@ -410,7 +410,7 @@ liberator.Tabs = function () //{{{
} }
else else
{ {
liberator.echoerr("E488: Trailing characters"); echoerr("E488: Trailing characters");
return; return;
} }
} }
@@ -419,27 +419,27 @@ liberator.Tabs = function () //{{{
index = count - 1; index = count - 1;
} }
if (index < liberator.tabs.count) if (index < tabs.count)
liberator.tabs.select(index, true); tabs.select(index, true);
else else
liberator.beep(); beep();
} }
else else
{ {
liberator.tabs.select("+1", true); tabs.select("+1", true);
} }
}, },
{ count: true }); { count: true });
liberator.commands.add(["tabr[ewind]", "tabfir[st]", "br[ewind]", "bf[irst]"], commands.add(["tabr[ewind]", "tabfir[st]", "br[ewind]", "bf[irst]"],
"Switch to the first tab", "Switch to the first tab",
function () { liberator.tabs.select(0, false); }, function () { tabs.select(0, false); },
{ argCount: "0" }); { argCount: "0" });
if (liberator.config.name == "Vimperator") if (config.name == "Vimperator")
{ {
// TODO: "Zero count" if 0 specified as arg, multiple args and count ranges? // TODO: "Zero count" if 0 specified as arg, multiple args and count ranges?
liberator.commands.add(["b[uffer]"], commands.add(["b[uffer]"],
"Switch to a buffer", "Switch to a buffer",
function (args, special, count) function (args, special, count)
{ {
@@ -448,108 +448,108 @@ liberator.Tabs = function () //{{{
if (args && count > 0) if (args && count > 0)
{ {
if (/^\d+$/.test(args)) if (/^\d+$/.test(args))
liberator.tabs.switchTo(args, special); tabs.switchTo(args, special);
else else
liberator.echoerr("E488: Trailing characters"); echoerr("E488: Trailing characters");
} }
else if (count > 0) else if (count > 0)
{ {
liberator.tabs.switchTo(count.toString(), special); tabs.switchTo(count.toString(), special);
} }
else else
{ {
liberator.tabs.switchTo(args, special); tabs.switchTo(args, special);
} }
}, },
{ {
bang: true, bang: true,
count: true, count: true,
completer: function (filter) liberator.completion.buffer(filter) completer: function (filter) completion.buffer(filter)
}); });
liberator.commands.add(["buffers", "files", "ls", "tabs"], commands.add(["buffers", "files", "ls", "tabs"],
"Show a list of all buffers", "Show a list of all buffers",
function (args) { liberator.tabs.list(); }, function (args) { tabs.list(); },
{ argCount: "0" }); { argCount: "0" });
liberator.commands.add(["quita[ll]", "qa[ll]"], commands.add(["quita[ll]", "qa[ll]"],
"Quit " + liberator.config.name, "Quit " + config.name,
function (args, special) { liberator.quit(false, special); }, function (args, special) { quit(false, special); },
{ {
argCount: "0", argCount: "0",
bang: true bang: true
}); });
liberator.commands.add(["reloada[ll]"], commands.add(["reloada[ll]"],
"Reload all tab pages", "Reload all tab pages",
function (args, special) { liberator.tabs.reloadAll(special); }, function (args, special) { tabs.reloadAll(special); },
{ {
argCount: "0", argCount: "0",
bang: true bang: true
}); });
// TODO: add count support // TODO: add count support
liberator.commands.add(["tabm[ove]"], commands.add(["tabm[ove]"],
"Move the current tab after tab N", "Move the current tab after tab N",
function (args, special) function (args, special)
{ {
// FIXME: tabmove! N should probably produce an error // FIXME: tabmove! N should probably produce an error
if (!/^([+-]?\d+|)$/.test(args)) if (!/^([+-]?\d+|)$/.test(args))
{ {
liberator.echoerr("E488: Trailing characters"); echoerr("E488: Trailing characters");
return; return;
} }
if (!args) if (!args)
args = "$"; // if not specified, move to the last tab args = "$"; // if not specified, move to the last tab
liberator.tabs.move(getBrowser().mCurrentTab, args, special); tabs.move(getBrowser().mCurrentTab, args, special);
}, },
{ bang: true }); { bang: true });
liberator.commands.add(["tabo[nly]"], commands.add(["tabo[nly]"],
"Close all other tabs", "Close all other tabs",
function () { liberator.tabs.keepOnly(getBrowser().mCurrentTab); }, function () { tabs.keepOnly(getBrowser().mCurrentTab); },
{ argCount: "0" }); { argCount: "0" });
liberator.commands.add(["tabopen", "t[open]", "tabnew", "tabe[dit]"], commands.add(["tabopen", "t[open]", "tabnew", "tabe[dit]"],
"Open one or more URLs in a new tab", "Open one or more URLs in a new tab",
function (args, special) function (args, special)
{ {
var where = special ? liberator.NEW_TAB : liberator.NEW_BACKGROUND_TAB; var where = special ? NEW_TAB : NEW_BACKGROUND_TAB;
if (/\btabopen\b/.test(liberator.options["activate"])) if (/\btabopen\b/.test(options["activate"]))
where = special ? liberator.NEW_BACKGROUND_TAB : liberator.NEW_TAB; where = special ? NEW_BACKGROUND_TAB : NEW_TAB;
if (args) if (args)
liberator.open(args, where); open(args, where);
else else
liberator.open("about:blank", where); open("about:blank", where);
}, },
{ {
bang: true, bang: true,
completer: function (filter) liberator.completion.url(filter) completer: function (filter) completion.url(filter)
}); });
liberator.commands.add(["tabde[tach]"], commands.add(["tabde[tach]"],
"Detach current tab to its own window", "Detach current tab to its own window",
function () { liberator.tabs.detachTab(null); }, function () { tabs.detachTab(null); },
{ argCount: "0" }); { argCount: "0" });
liberator.commands.add(["tabd[uplicate]"], commands.add(["tabd[uplicate]"],
"Duplicate current tab", "Duplicate current tab",
function (args, special, count) function (args, special, count)
{ {
var tab = liberator.tabs.getTab(); var tab = tabs.getTab();
var activate = special ? true : false; var activate = special ? true : false;
if (/\btabopen\b/.test(liberator.options["activate"])) if (/\btabopen\b/.test(options["activate"]))
activate = !activate; activate = !activate;
if (count < 1) if (count < 1)
count = 1; count = 1;
for (let i = 0; i < count; i++) for (let i = 0; i < count; i++)
liberator.tabs.cloneTab(tab, activate); tabs.cloneTab(tab, activate);
}, },
{ {
argCount: "0", argCount: "0",
@@ -561,7 +561,7 @@ liberator.Tabs = function () //{{{
if (liberator.has("session")) if (liberator.has("session"))
{ {
// TODO: extract common functionality of "undoall" // TODO: extract common functionality of "undoall"
liberator.commands.add(["u[ndo]"], commands.add(["u[ndo]"],
"Undo closing of a tab", "Undo closing of a tab",
function (args, special, count) function (args, special, count)
{ {
@@ -596,7 +596,7 @@ liberator.Tabs = function () //{{{
{ {
var url = undoItems[i].state.entries[0].url; var url = undoItems[i].state.entries[0].url;
var title = undoItems[i].title; var title = undoItems[i].title;
if (liberator.completion.match([url, title], filter, false)) if (completion.match([url, title], filter, false))
completions.push([url, title]); completions.push([url, title]);
} }
return [0, completions]; return [0, completions];
@@ -604,7 +604,7 @@ liberator.Tabs = function () //{{{
count: true count: true
}); });
liberator.commands.add(["undoa[ll]"], commands.add(["undoa[ll]"],
"Undo closing of all closed tabs", "Undo closing of all closed tabs",
function (args, special, count) function (args, special, count)
{ {
@@ -620,9 +620,9 @@ liberator.Tabs = function () //{{{
count: true count: true
}); });
liberator.commands.add(["wqa[ll]", "wq", "xa[ll]"], commands.add(["wqa[ll]", "wq", "xa[ll]"],
"Save the session and quit", "Save the session and quit",
function () { liberator.quit(true); }, function () { quit(true); },
{ argCount: "0" }); { argCount: "0" });
} }
@@ -655,9 +655,9 @@ liberator.Tabs = function () //{{{
get tabStrip() get tabStrip()
{ {
if (liberator.config.hostApplication == "Firefox") if (config.hostApplication == "Firefox")
return getBrowser().mStrip.getElementsByClassName("tabbrowser-tabs")[0]; return getBrowser().mStrip.getElementsByClassName("tabbrowser-tabs")[0];
else if (liberator.config.hostApplication == "Thunderbird") else if (config.hostApplication == "Thunderbird")
return getBrowser().mStrip; return getBrowser().mStrip;
}, },
@@ -715,14 +715,14 @@ liberator.Tabs = function () //{{{
// TODO: shouldn't that have a filter argument? // TODO: shouldn't that have a filter argument?
list: function () list: function ()
{ {
// TODO: move this to liberator.tabs.get() // TODO: move this to tabs.get()
let items = <table/> let items = <table/>
for (let [i, item] in Iterator(liberator.completion.buffer("")[1])) for (let [i, item] in Iterator(completion.buffer("")[1]))
{ {
if (i == liberator.tabs.index()) if (i == tabs.index())
indicator = "%" indicator = "%"
else if (i == liberator.tabs.index(liberator.tabs.alternate)) else if (i == tabs.index(tabs.alternate))
indicator = "#"; indicator = "#";
else else
indicator = " "; indicator = " ";
@@ -737,8 +737,8 @@ liberator.Tabs = function () //{{{
</tr>; </tr>;
} }
let list = liberator.template.generic(items); let list = template.generic(items);
liberator.commandline.echo(list, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
}, },
// wrap causes the movement to wrap around the start and end of the tab list // wrap causes the movement to wrap around the start and end of the tab list
@@ -760,14 +760,14 @@ liberator.Tabs = function () //{{{
getBrowser().removeTab(tab); getBrowser().removeTab(tab);
else else
{ {
if (liberator.buffer.URL != "about:blank" || if (buffer.URL != "about:blank" ||
getWebNavigation().sessionHistory.count > 0) getWebNavigation().sessionHistory.count > 0)
{ {
liberator.open("about:blank", liberator.NEW_BACKGROUND_TAB); open("about:blank", NEW_BACKGROUND_TAB);
getBrowser().removeTab(tab); getBrowser().removeTab(tab);
} }
else else
liberator.beep(); beep();
} }
}, },
Thunderbird: function (tab) Thunderbird: function (tab)
@@ -775,19 +775,19 @@ liberator.Tabs = function () //{{{
if (getBrowser().mTabs.length > 1) if (getBrowser().mTabs.length > 1)
getBrowser().removeTab(tab); getBrowser().removeTab(tab);
else else
liberator.beep(); beep();
} }
}[liberator.config.hostApplication] || function () {}; }[config.hostApplication] || function () {};
if (typeof count != "number" || count < 1) if (typeof count != "number" || count < 1)
count = 1; count = 1;
if (quitOnLastTab >= 1 && getBrowser().mTabs.length <= count) if (quitOnLastTab >= 1 && getBrowser().mTabs.length <= count)
{ {
if (liberator.windows.length > 1) if (windows.length > 1)
window.close(); window.close();
else else
liberator.quit(quitOnLastTab == 2); quit(quitOnLastTab == 2);
return; return;
} }
@@ -825,7 +825,7 @@ liberator.Tabs = function () //{{{
// FIXME: // FIXME:
if (index === -1) if (index === -1)
{ {
liberator.beep(); // XXX: move to ex-handling? beep(); // XXX: move to ex-handling?
return; return;
} }
getBrowser().mTabContainer.selectedIndex = index; getBrowser().mTabContainer.selectedIndex = index;
@@ -890,7 +890,7 @@ liberator.Tabs = function () //{{{
if (buffer == "#") if (buffer == "#")
{ {
liberator.tabs.selectAlternateTab(); tabs.selectAlternateTab();
return; return;
} }
@@ -902,13 +902,13 @@ liberator.Tabs = function () //{{{
var match; var match;
if (match = buffer.match(/^(\d+):?/)) if (match = buffer.match(/^(\d+):?/))
{ {
liberator.tabs.select(parseInt(match[1], 10) - 1, false); // make it zero-based tabs.select(parseInt(match[1], 10) - 1, false); // make it zero-based
return; return;
} }
var matches = []; var matches = [];
var lowerBuffer = buffer.toLowerCase(); var lowerBuffer = buffer.toLowerCase();
var first = liberator.tabs.index() + (reverse ? 0 : 1); var first = tabs.index() + (reverse ? 0 : 1);
for (let i = 0; i < getBrowser().browsers.length; i++) for (let i = 0; i < getBrowser().browsers.length; i++)
{ {
var index = (i + first) % getBrowser().browsers.length; var index = (i + first) % getBrowser().browsers.length;
@@ -916,7 +916,7 @@ liberator.Tabs = function () //{{{
var title = getBrowser().getBrowserAtIndex(index).contentDocument.title.toLowerCase(); var title = getBrowser().getBrowserAtIndex(index).contentDocument.title.toLowerCase();
if (url == buffer) if (url == buffer)
{ {
liberator.tabs.select(index, false); tabs.select(index, false);
return; return;
} }
@@ -924,9 +924,9 @@ liberator.Tabs = function () //{{{
matches.push(index); matches.push(index);
} }
if (matches.length == 0) if (matches.length == 0)
liberator.echoerr("E94: No matching buffer for " + buffer); echoerr("E94: No matching buffer for " + buffer);
else if (matches.length > 1 && !allowNonUnique) else if (matches.length > 1 && !allowNonUnique)
liberator.echoerr("E93: More than one match for " + buffer); echoerr("E93: More than one match for " + buffer);
else else
{ {
if (reverse) if (reverse)
@@ -938,7 +938,7 @@ liberator.Tabs = function () //{{{
else else
index = (count - 1) % matches.length; index = (count - 1) % matches.length;
liberator.tabs.select(matches[index], false); tabs.select(matches[index], false);
} }
}, },
@@ -969,23 +969,23 @@ liberator.Tabs = function () //{{{
selectAlternateTab: function () selectAlternateTab: function ()
{ {
if (liberator.tabs.alternate == null || liberator.tabs.getTab() == liberator.tabs.alternate) if (tabs.alternate == null || tabs.getTab() == tabs.alternate)
{ {
liberator.echoerr("E23: No alternate page"); echoerr("E23: No alternate page");
return; return;
} }
// NOTE: this currently relies on v.tabs.index() returning the // NOTE: this currently relies on v.tabs.index() returning the
// currently selected tab index when passed null // currently selected tab index when passed null
var index = liberator.tabs.index(liberator.tabs.alternate); var index = tabs.index(tabs.alternate);
// TODO: since a tab close is more like a bdelete for us we // TODO: since a tab close is more like a bdelete for us we
// should probably reopen the closed tab when a 'deleted' // should probably reopen the closed tab when a 'deleted'
// alternate is selected // alternate is selected
if (index == -1) if (index == -1)
liberator.echoerr("E86: Buffer does not exist"); // TODO: This should read "Buffer N does not exist" echoerr("E86: Buffer does not exist"); // TODO: This should read "Buffer N does not exist"
else else
liberator.tabs.select(index); tabs.select(index);
}, },
// NOTE: when restarting a session FF selects the first tab and then the // NOTE: when restarting a session FF selects the first tab and then the

View File

@@ -1,12 +1,12 @@
liberator.template = { with (liberator) liberator.template = {
add: function (a, b) a + b, add: function (a, b) a + b,
join: function (c) function (a, b) a + c + b, join: function (c) function (a, b) a + c + b,
map: function (iter, fn, sep) map: function (iter, fn, sep)
{ {
if (iter.length) /* Kludge? */ if (iter.length) /* Kludge? */
iter = liberator.util.arrayIter(iter); iter = util.arrayIter(iter);
let ret = <></>; let ret = <></>;
let n = 0; let n = 0;
for each (let i in Iterator(iter)) for each (let i in Iterator(iter))
@@ -46,7 +46,7 @@ liberator.template = {
return <span class="hl-Number">{arg}</span>; return <span class="hl-Number">{arg}</span>;
case "string": case "string":
if (processStrings) if (processStrings)
arg = <>{liberator.util.escapeString(arg)}</>; arg = <>{util.escapeString(arg)}</>;
return <span class="hl-String">{arg}</span>; return <span class="hl-String">{arg}</span>;
case "boolean": case "boolean":
return <span class="hl-Boolean">{arg}</span>; return <span class="hl-Boolean">{arg}</span>;
@@ -107,7 +107,7 @@ liberator.template = {
generic: function (xml) generic: function (xml)
{ {
return <>:{liberator.commandline.getCommand()}<br/></> + xml; return <>:{commandline.getCommand()}<br/></> + xml;
}, },
bookmarks: function (header, items) bookmarks: function (header, items)
@@ -120,14 +120,14 @@ liberator.template = {
{ {
this.map(items, function (item) this.map(items, function (item)
<tr> <tr>
<td>{liberator.util.clip(item.title, 50)}</td> <td>{util.clip(item.title, 50)}</td>
<td style="width: 100%"> <td style="width: 100%">
<a href="#" class="hl-URL">{item.url}</a>&#160; <a href="#" class="hl-URL">{item.url}</a>&#160;
{ {
!(item.extra && item.extra.length) ? "" : !(item.extra && item.extra.length) ? "" :
<span class="extra-info"> <span class="extra-info">
({ ({
liberator.template.map(item.extra, function (e) template.map(item.extra, function (e)
<>{e[0]}: <span class={e[2]}>{e[1]}</span></>, <>{e[0]}: <span class={e[2]}>{e[1]}</span></>,
<![CDATA[ ]]>/* Non-breaking space */) <![CDATA[ ]]>/* Non-breaking space */)
}) })
@@ -188,7 +188,7 @@ liberator.template = {
this.map(data, function (datum) this.map(data, function (datum)
<tr> <tr>
<td style={"font-weight: bold; min-width: 150px; padding-left: " + (indent || "2ex")}>{datum[0]}</td> <td style={"font-weight: bold; min-width: 150px; padding-left: " + (indent || "2ex")}>{datum[0]}</td>
<td>{liberator.template.maybeXML(datum[1])}</td> <td>{template.maybeXML(datum[1])}</td>
</tr>) </tr>)
} }
</table>; </table>;
@@ -211,7 +211,7 @@ liberator.template = {
this.map(iter, function (row) this.map(iter, function (row)
<tr> <tr>
{ {
liberator.template.map(Iterator(row), function ([i, d]) template.map(Iterator(row), function ([i, d])
<td style={style[i] || ""}>{d}</td>) <td style={style[i] || ""}>{d}</td>)
} }
</tr>) </tr>)

View File

@@ -32,7 +32,7 @@ the terms of any one of the MPL, the GPL or the LGPL.
* it consists of a prompt and command field * it consists of a prompt and command field
* be sure to only create objects of this class when the chrome is ready * be sure to only create objects of this class when the chrome is ready
*/ */
liberator.CommandLine = function () //{{{ with (liberator) liberator.CommandLine = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -40,13 +40,13 @@ liberator.CommandLine = function () //{{{
const UNINITIALIZED = -2; // notifies us, if we need to start history/tab-completion from the beginning const UNINITIALIZED = -2; // notifies us, if we need to start history/tab-completion from the beginning
liberator.storage.newArray("history-search", true); storage.newArray("history-search", true);
liberator.storage.newArray("history-command", true); storage.newArray("history-command", true);
var history = { var inputHistory = {
get mode() (liberator.modes.extended == liberator.modes.EX) ? "command" : "search", get mode() (modes.extended == modes.EX) ? "command" : "search",
get store() liberator.storage["history-" + this.mode], get store() storage["history-" + this.mode],
get length() this.store.length, get length() this.store.length,
@@ -59,7 +59,7 @@ liberator.CommandLine = function () //{{{
this.store.mutate('filter', function (line) line != str); this.store.mutate('filter', function (line) line != str);
this.store.push(str); this.store.push(str);
this.store.truncate(liberator.options["history"], true); this.store.truncate(options["history"], true);
} }
}; };
@@ -70,7 +70,7 @@ liberator.CommandLine = function () //{{{
_messages: [], _messages: [],
get messages() get messages()
{ {
let max = liberator.options["messages"]; let max = options["messages"];
// resize if 'messages' has changed // resize if 'messages' has changed
if (this._messages.length > max) if (this._messages.length > max)
@@ -86,7 +86,7 @@ liberator.CommandLine = function () //{{{
if (!message) if (!message)
return; return;
if (this._messages.length >= liberator.options["messages"]) if (this._messages.length >= options["messages"])
this._messages.shift(); this._messages.shift();
this._messages.push(message); this._messages.push(message);
@@ -94,7 +94,7 @@ liberator.CommandLine = function () //{{{
}; };
var lastMowOutput = null; var lastMowOutput = null;
var completionList = new liberator.ItemList("liberator-completions"); var completionList = new ItemList("liberator-completions");
var completions = []; var completions = [];
// for the example command "open sometext| othertext" (| is the cursor pos): // for the example command "open sometext| othertext" (| is the cursor pos):
var completionStartIndex = 0; // will be 5 because we want to complete arguments for the :open command var completionStartIndex = 0; // will be 5 because we want to complete arguments for the :open command
@@ -105,13 +105,13 @@ liberator.CommandLine = function () //{{{
var wildIndex = 0; // keep track how often we press <Tab> in a row var wildIndex = 0; // keep track how often we press <Tab> in a row
var startHints = false; // whether we're waiting to start hints mode var startHints = false; // whether we're waiting to start hints mode
var statusTimer = new liberator.util.Timer(5, 100, function () var statusTimer = new util.Timer(5, 100, function ()
liberator.statusline.updateProgress("match " + (completionIndex + 1) + " of " + completions.length)); statusline.updateProgress("match " + (completionIndex + 1) + " of " + completions.length));
var autocompleteTimer = new liberator.util.Timer(201, 300, function (command) { var autocompleteTimer = new util.Timer(201, 300, function (command) {
if (liberator.modes.isReplaying) if (modes.isReplaying)
return; return;
let [start, compl] = liberator.completion.ex(command); let [start, compl] = completion.ex(command);
liberator.commandline.setCompletions(compl, start); commandline.setCompletions(compl, start);
}); });
// the containing box for the promptWidget and commandWidget // the containing box for the promptWidget and commandWidget
@@ -145,8 +145,8 @@ liberator.CommandLine = function () //{{{
var promptCallback = null; var promptCallback = null;
var promptCompleter = null; var promptCompleter = null;
liberator.registerCallback("change", liberator.modes.EX, function (command) { registerCallback("change", modes.EX, function (command) {
if (liberator.options.get("wildoptions").has("auto")) if (options.get("wildoptions").has("auto"))
autocompleteTimer.tell(command); autocompleteTimer.tell(command);
else else
completionIndex = UNINITIALIZED; completionIndex = UNINITIALIZED;
@@ -157,13 +157,13 @@ liberator.CommandLine = function () //{{{
let callback = promptCallback; let callback = promptCallback;
promptCallback = null; promptCallback = null;
currentExtendedMode = null; currentExtendedMode = null;
liberator.commandline.clear(); commandline.clear();
if (callback) if (callback)
callback(value); callback(value);
} }
liberator.registerCallback("cancel", liberator.modes.PROMPT, closePrompt); registerCallback("cancel", modes.PROMPT, closePrompt);
liberator.registerCallback("submit", liberator.modes.PROMPT, closePrompt); registerCallback("submit", modes.PROMPT, closePrompt);
liberator.registerCallback("complete", liberator.modes.PROMPT, registerCallback("complete", modes.PROMPT,
function (str) { if (promptCompleter) return promptCompleter(str); }); function (str) { if (promptCompleter) return promptCompleter(str); });
function setHighlightGroup(group) function setHighlightGroup(group)
@@ -185,7 +185,7 @@ liberator.CommandLine = function () //{{{
{ {
promptWidget.collapsed = true; promptWidget.collapsed = true;
} }
promptWidget.setAttribute("class", highlightGroup || liberator.commandline.HL_NORMAL); promptWidget.setAttribute("class", highlightGroup || commandline.HL_NORMAL);
} }
// sets the command - e.g. 'tabopen', 'open http://example.com/' // sets the command - e.g. 'tabopen', 'open http://example.com/'
@@ -216,7 +216,7 @@ liberator.CommandLine = function () //{{{
* after interpolated data. * after interpolated data.
*/ */
XML.ignoreWhitespace = typeof str == "xml"; XML.ignoreWhitespace = typeof str == "xml";
var output = <div class={"ex-command-output " + highlightGroup}>{liberator.template.maybeXML(str)}</div>; var output = <div class={"ex-command-output " + highlightGroup}>{template.maybeXML(str)}</div>;
XML.ignoreWhiteSpace = true; XML.ignoreWhiteSpace = true;
lastMowOutput = output; lastMowOutput = output;
@@ -226,7 +226,7 @@ liberator.CommandLine = function () //{{{
if (outputContainer.collapsed) if (outputContainer.collapsed)
doc.body.innerHTML = ""; doc.body.innerHTML = "";
doc.body.appendChild(liberator.util.xmlToDom(output, doc)); doc.body.appendChild(util.xmlToDom(output, doc));
var availableHeight = 250; var availableHeight = 250;
try try
@@ -241,27 +241,27 @@ liberator.CommandLine = function () //{{{
outputContainer.height = height + "px"; outputContainer.height = height + "px";
outputContainer.collapsed = false; outputContainer.collapsed = false;
if (liberator.options["more"] && win.scrollMaxY > 0) if (options["more"] && win.scrollMaxY > 0)
{ {
// start the last executed command's output at the top of the screen // start the last executed command's output at the top of the screen
var elements = doc.getElementsByClassName("ex-command-output"); var elements = doc.getElementsByClassName("ex-command-output");
elements[elements.length - 1].scrollIntoView(true); elements[elements.length - 1].scrollIntoView(true);
if (win.scrollY >= win.scrollMaxY) if (win.scrollY >= win.scrollMaxY)
setLine("Press ENTER or type command to continue", liberator.commandline.HL_QUESTION); setLine("Press ENTER or type command to continue", commandline.HL_QUESTION);
else else
setLine("-- More --", liberator.commandline.HL_QUESTION); setLine("-- More --", commandline.HL_QUESTION);
} }
else else
{ {
win.scrollTo(0, contentHeight); win.scrollTo(0, contentHeight);
setLine("Press ENTER or type command to continue", liberator.commandline.HL_QUESTION); setLine("Press ENTER or type command to continue", commandline.HL_QUESTION);
} }
win.focus(); win.focus();
startHints = false; startHints = false;
liberator.modes.push(liberator.modes.COMMAND_LINE, liberator.modes.OUTPUT_MULTILINE); modes.push(modes.COMMAND_LINE, modes.OUTPUT_MULTILINE);
} }
function autosizeMultilineInputWidget() function autosizeMultilineInputWidget()
@@ -282,18 +282,18 @@ liberator.CommandLine = function () //{{{
try try
{ {
arg = liberator.eval(arg); arg = eval(arg);
} }
catch (e) catch (e)
{ {
liberator.echoerr(e); echoerr(e);
return null; return null;
} }
if (typeof arg === "object") if (typeof arg === "object")
arg = liberator.util.objectToString(arg, useColor); arg = util.objectToString(arg, useColor);
else if (typeof arg === "function") else if (typeof arg === "function")
arg = liberator.util.escapeHTML(arg.toString()); arg = util.escapeHTML(arg.toString());
else if (typeof arg === "number" || typeof arg === "boolean") else if (typeof arg === "number" || typeof arg === "boolean")
arg = "" + arg; arg = "" + arg;
else if (typeof arg === "undefined") else if (typeof arg === "undefined")
@@ -307,7 +307,7 @@ liberator.CommandLine = function () //{{{
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
// TODO: doesn't belong in ui.js // TODO: doesn't belong in ui.js
liberator.options.add(["complete", "cpt"], options.add(["complete", "cpt"],
"Items which are completed at the :[tab]open prompt", "Items which are completed at the :[tab]open prompt",
"charlist", "sfbh", "charlist", "sfbh",
{ {
@@ -325,25 +325,25 @@ liberator.CommandLine = function () //{{{
validator: function (value) !/[^sfbhSl]/.test(value) validator: function (value) !/[^sfbhSl]/.test(value)
}); });
liberator.options.add(["history", "hi"], options.add(["history", "hi"],
"Number of Ex commands and search patterns to store in the command-line history", "Number of Ex commands and search patterns to store in the command-line history",
"number", 500, "number", 500,
{ validator: function (value) value >= 0 }); { validator: function (value) value >= 0 });
liberator.options.add(["messages", "msgs"], options.add(["messages", "msgs"],
"Number of messages to store in the message history", "Number of messages to store in the message history",
"number", 100, "number", 100,
{ validator: function (value) value >= 0 }); { validator: function (value) value >= 0 });
liberator.options.add(["more"], options.add(["more"],
"Pause the message list window when more than one screen of listings is displayed", "Pause the message list window when more than one screen of listings is displayed",
"boolean", true); "boolean", true);
liberator.options.add(["showmode", "smd"], options.add(["showmode", "smd"],
"Show the current mode in the command line", "Show the current mode in the command line",
"boolean", true); "boolean", true);
liberator.options.add(["suggestengines"], options.add(["suggestengines"],
"Engine Alias which has a feature of suggest", "Engine Alias which has a feature of suggest",
"stringlist", "google", "stringlist", "google",
{ {
@@ -368,7 +368,7 @@ liberator.CommandLine = function () //{{{
} }
}); });
liberator.options.add(["wildignore", "wig"], options.add(["wildignore", "wig"],
"List of file patterns to ignore when completing files", "List of file patterns to ignore when completing files",
"stringlist", "", "stringlist", "",
{ {
@@ -387,7 +387,7 @@ liberator.CommandLine = function () //{{{
} }
}); });
liberator.options.add(["wildmode", "wim"], options.add(["wildmode", "wim"],
"Define how command line completion works", "Define how command line completion works",
"stringlist", "list:full", "stringlist", "list:full",
{ {
@@ -410,7 +410,7 @@ liberator.CommandLine = function () //{{{
} }
}); });
liberator.options.add(["wildoptions", "wop"], options.add(["wildoptions", "wop"],
"Change how command line completion is done", "Change how command line completion is done",
"stringlist", "", "stringlist", "",
{ {
@@ -431,37 +431,37 @@ liberator.CommandLine = function () //{{{
////////////////////// MAPPINGS //////////////////////////////////////////////// ////////////////////// MAPPINGS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
var modes = [liberator.modes.COMMAND_LINE]; var myModes = [modes.COMMAND_LINE];
// TODO: move "<Esc>", "<C-[" here from mappings // TODO: move "<Esc>", "<C-[" here from mappings
liberator.mappings.add(modes, mappings.add(myModes,
["<C-c>"], "Focus content", ["<C-c>"], "Focus content",
function () { liberator.events.onEscape(); }); function () { events.onEscape(); });
liberator.mappings.add(modes, mappings.add(myModes,
["<Space>"], "Expand command line abbreviation", ["<Space>"], "Expand command line abbreviation",
function () function ()
{ {
liberator.commandline.resetCompletions(); commandline.resetCompletions();
return liberator.editor.expandAbbreviation("c"); return editor.expandAbbreviation("c");
}, },
{ flags: liberator.Mappings.flags.ALLOW_EVENT_ROUTING }); { flags: Mappings.flags.ALLOW_EVENT_ROUTING });
liberator.mappings.add(modes, mappings.add(myModes,
["<C-]>", "<C-5>"], "Expand command line abbreviation", ["<C-]>", "<C-5>"], "Expand command line abbreviation",
function () { liberator.editor.expandAbbreviation("c"); }); function () { editor.expandAbbreviation("c"); });
// FIXME: Should be "g<" but that doesn't work unless it has a non-null // FIXME: Should be "g<" but that doesn't work unless it has a non-null
// rhs, getCandidates broken? // rhs, getCandidates broken?
liberator.mappings.add([liberator.modes.NORMAL], mappings.add([modes.NORMAL],
["gm"], "Redisplay the last command output", ["gm"], "Redisplay the last command output",
function () function ()
{ {
if (lastMowOutput) if (lastMowOutput)
liberator.commandline.echo(lastMowOutput, commandline.echo(lastMowOutput,
liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE); commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
else else
liberator.beep(); beep();
}); });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
@@ -472,22 +472,22 @@ liberator.CommandLine = function () //{{{
{ {
name: "ec[ho]", name: "ec[ho]",
description: "Display a string at the bottom of the window", description: "Display a string at the bottom of the window",
action: liberator.echo action: echo
}, },
{ {
name: "echoe[rr]", name: "echoe[rr]",
description: "Display an error string at the bottom of the window", description: "Display an error string at the bottom of the window",
action: liberator.echoerr action: echoerr
}, },
{ {
name: "echom[sg]", name: "echom[sg]",
description: "Display a message at the bottom of the window saving it in the message history", description: "Display a message at the bottom of the window saving it in the message history",
action: liberator.echomsg action: echomsg
} }
]; ];
echoCommands.forEach(function (command) { echoCommands.forEach(function (command) {
liberator.commands.add([command.name], commands.add([command.name],
command.description, command.description,
function (args) function (args)
{ {
@@ -495,10 +495,10 @@ liberator.CommandLine = function () //{{{
if (str != null) if (str != null)
command.action(str); command.action(str);
}, },
{ completer: function (filter) liberator.completion.javascript(filter) }); { completer: function (filter) completion.javascript(filter) });
}); });
liberator.commands.add(["mes[sages]"], commands.add(["mes[sages]"],
"Display previously given messages", "Display previously given messages",
function () function ()
{ {
@@ -508,7 +508,7 @@ liberator.CommandLine = function () //{{{
if (messageHistory.length == 1) if (messageHistory.length == 1)
{ {
let message = messageHistory.messages[0]; let message = messageHistory.messages[0];
liberator.commandline.echo(message.str, message.highlight, liberator.commandline.FORCE_SINGLELINE); commandline.echo(message.str, message.highlight, commandline.FORCE_SINGLELINE);
} }
else if (messageHistory.length > 1) else if (messageHistory.length > 1)
{ {
@@ -517,7 +517,7 @@ liberator.CommandLine = function () //{{{
for (let [,message] in Iterator(messageHistory.messages)) for (let [,message] in Iterator(messageHistory.messages))
list += <div class={message.highlight}>{message.str}</div>; list += <div class={message.highlight}>{message.str}</div>;
liberator.echo(list, liberator.commandline.FORCE_MULTILINE); echo(list, commandline.FORCE_MULTILINE);
} }
}, },
{ argCount: "0" }); { argCount: "0" });
@@ -547,7 +547,7 @@ liberator.CommandLine = function () //{{{
get autocompleteTimer() autocompleteTimer, get autocompleteTimer() autocompleteTimer,
get mode() (liberator.modes.extended == liberator.modes.EX) ? "cmd" : "search", get mode() (modes.extended == modes.EX) ? "cmd" : "search",
getCommand: function () getCommand: function ()
{ {
@@ -565,7 +565,7 @@ liberator.CommandLine = function () //{{{
historyIndex = UNINITIALIZED; historyIndex = UNINITIALIZED;
completionIndex = UNINITIALIZED; completionIndex = UNINITIALIZED;
liberator.modes.push(liberator.modes.COMMAND_LINE, currentExtendedMode); modes.push(modes.COMMAND_LINE, currentExtendedMode);
setHighlightGroup(this.HL_NORMAL); setHighlightGroup(this.HL_NORMAL);
setPrompt(currentPrompt); setPrompt(currentPrompt);
setCommand(currentCommand); setCommand(currentCommand);
@@ -574,17 +574,17 @@ liberator.CommandLine = function () //{{{
// open the completion list automatically if wanted // open the completion list automatically if wanted
if (/\s/.test(cmd) && if (/\s/.test(cmd) &&
liberator.options.get("wildoptions").has("auto") >= 0 && options.get("wildoptions").has("auto") >= 0 &&
extendedMode == liberator.modes.EX) extendedMode == modes.EX)
autocompleteTimer.tell(cmd); autocompleteTimer.tell(cmd);
}, },
// normally used when pressing esc, does not execute a command // normally used when pressing esc, does not execute a command
close: function () close: function ()
{ {
var res = liberator.triggerCallback("cancel", currentExtendedMode); var res = triggerCallback("cancel", currentExtendedMode);
history.add(this.getCommand()); inputHistory.add(this.getCommand());
liberator.statusline.updateProgress(""); // we may have a "match x of y" visible statusline.updateProgress(""); // we may have a "match x of y" visible
this.clear(); this.clear();
}, },
@@ -600,7 +600,7 @@ liberator.CommandLine = function () //{{{
setLine("", this.HL_NORMAL); setLine("", this.HL_NORMAL);
}, },
// liberator.echo uses different order of flags as it omits the hightlight group, change v.commandline.echo argument order? --mst // echo uses different order of flags as it omits the hightlight group, change v.commandline.echo argument order? --mst
echo: function (str, highlightGroup, flags) echo: function (str, highlightGroup, flags)
{ {
var focused = document.commandDispatcher.focusedElement; var focused = document.commandDispatcher.focusedElement;
@@ -643,15 +643,15 @@ liberator.CommandLine = function () //{{{
}, },
// this will prompt the user for a string // this will prompt the user for a string
// liberator.commandline.input("(s)ave or (o)pen the file?") // commandline.input("(s)ave or (o)pen the file?")
input: function (prompt, callback, extra) input: function (prompt, callback, extra)
{ {
extra = extra || {}; extra = extra || {};
promptCallback = callback; promptCallback = callback;
promptCompleter = extra.completer; promptCompleter = extra.completer;
liberator.modes.push(liberator.modes.COMMAND_LINE, liberator.modes.PROMPT); modes.push(modes.COMMAND_LINE, modes.PROMPT);
currentExtendedMode = liberator.modes.PROMPT; currentExtendedMode = modes.PROMPT;
setPrompt(prompt + " ", this.HL_QUESTION); setPrompt(prompt + " ", this.HL_QUESTION);
setCommand(extra.default || ""); setCommand(extra.default || "");
commandWidget.focus(); commandWidget.focus();
@@ -662,7 +662,7 @@ liberator.CommandLine = function () //{{{
inputMultiline: function (untilRegexp, callbackFunc) inputMultiline: function (untilRegexp, callbackFunc)
{ {
// save the mode, because we need to restore it // save the mode, because we need to restore it
liberator.modes.push(liberator.modes.COMMAND_LINE, liberator.modes.INPUT_MULTILINE); modes.push(modes.COMMAND_LINE, modes.INPUT_MULTILINE);
// save the arguments, they are needed in the event handler onEvent // save the arguments, they are needed in the event handler onEvent
multilineRegexp = untilRegexp; multilineRegexp = untilRegexp;
@@ -683,9 +683,9 @@ liberator.CommandLine = function () //{{{
{ {
// prevent losing focus, there should be a better way, but it just didn't work otherwise // prevent losing focus, there should be a better way, but it just didn't work otherwise
setTimeout(function () { setTimeout(function () {
if (liberator.mode == liberator.modes.COMMAND_LINE && if (mode == modes.COMMAND_LINE &&
!(liberator.modes.extended & liberator.modes.INPUT_MULTILINE) && !(modes.extended & modes.INPUT_MULTILINE) &&
!(liberator.modes.extended & liberator.modes.OUTPUT_MULTILINE)) !(modes.extended & modes.OUTPUT_MULTILINE))
commandWidget.inputField.focus(); commandWidget.inputField.focus();
}, 0); }, 0);
} }
@@ -696,38 +696,38 @@ liberator.CommandLine = function () //{{{
} }
else if (event.type == "input") else if (event.type == "input")
{ {
liberator.triggerCallback("change", currentExtendedMode, command); triggerCallback("change", currentExtendedMode, command);
} }
else if (event.type == "keypress") else if (event.type == "keypress")
{ {
if (!currentExtendedMode) if (!currentExtendedMode)
return true; return true;
var key = liberator.events.toString(event); var key = events.toString(event);
//liberator.log("command line handling key: " + key + "\n"); //log("command line handling key: " + key + "\n");
// user pressed ENTER to carry out a command // user pressed ENTER to carry out a command
// user pressing ESCAPE is handled in the global onEscape // user pressing ESCAPE is handled in the global onEscape
// FIXME: <Esc> should trigger "cancel" event // FIXME: <Esc> should trigger "cancel" event
if (liberator.events.isAcceptKey(key)) if (events.isAcceptKey(key))
{ {
var mode = currentExtendedMode; // save it here, as setMode() resets it let mode = currentExtendedMode; // save it here, as setMode() resets it
currentExtendedMode = null; /* Don't let modes.pop trigger "cancel" */ currentExtendedMode = null; /* Don't let modes.pop trigger "cancel" */
history.add(command); inputHistory.add(command);
liberator.modes.pop(true); modes.pop(true);
autocompleteTimer.reset(); autocompleteTimer.reset();
completionList.hide(); completionList.hide();
liberator.focusContent(false); focusContent(false);
liberator.statusline.updateProgress(""); // we may have a "match x of y" visible statusline.updateProgress(""); // we may have a "match x of y" visible
return liberator.triggerCallback("submit", mode, command); return triggerCallback("submit", mode, command);
} }
// user pressed UP or DOWN arrow to cycle history completion // user pressed UP or DOWN arrow to cycle history completion
else if (/^(<Up>|<Down>|<S-Up>|<S-Down>|<PageUp>|<PageDown>)$/.test(key)) else if (/^(<Up>|<Down>|<S-Up>|<S-Down>|<PageUp>|<PageDown>)$/.test(key))
{ {
function gotoHistoryItem(index) function gotoHistoryItem(index)
{ {
setCommand(history.get(historyIndex)); setCommand(inputHistory.get(historyIndex));
liberator.triggerCallback("change", currentExtendedMode, liberator.commandline.getCommand()); triggerCallback("change", currentExtendedMode, commandline.getCommand());
} }
let previousItem = /Up/.test(key); let previousItem = /Up/.test(key);
@@ -742,21 +742,21 @@ liberator.CommandLine = function () //{{{
// save 'start' position for iterating through the history // save 'start' position for iterating through the history
if (historyIndex == UNINITIALIZED) if (historyIndex == UNINITIALIZED)
{ {
historyIndex = history.length; historyIndex = inputHistory.length;
historyStart = command; historyStart = command;
} }
// search the history for the first item matching the current // search the history for the first item matching the current
// commandline string // commandline string
while (historyIndex >= -1 && historyIndex <= history.length) while (historyIndex >= -1 && historyIndex <= inputHistory.length)
{ {
previousItem ? historyIndex-- : historyIndex++; previousItem ? historyIndex-- : historyIndex++;
// user pressed DOWN when there is no newer history item // user pressed DOWN when there is no newer history item
if (historyIndex == history.length) if (historyIndex == inputHistory.length)
{ {
setCommand(historyStart); setCommand(historyStart);
liberator.triggerCallback("change", currentExtendedMode, this.getCommand()); triggerCallback("change", currentExtendedMode, this.getCommand());
break; break;
} }
@@ -764,19 +764,19 @@ liberator.CommandLine = function () //{{{
if (historyIndex <= -1) if (historyIndex <= -1)
{ {
historyIndex = 0; historyIndex = 0;
liberator.beep(); beep();
break; break;
} }
else if (historyIndex >= history.length + 1) else if (historyIndex >= inputHistory.length + 1)
{ {
historyIndex = history.length; historyIndex = inputHistory.length;
liberator.beep(); beep();
break; break;
} }
if (matchCurrent) if (matchCurrent)
{ {
if (history.get(historyIndex).indexOf(historyStart) == 0) if (inputHistory.get(historyIndex).indexOf(historyStart) == 0)
{ {
gotoHistoryItem(historyIndex); gotoHistoryItem(historyIndex);
break; break;
@@ -796,7 +796,7 @@ liberator.CommandLine = function () //{{{
historyIndex = UNINITIALIZED; historyIndex = UNINITIALIZED;
// TODO: call just once, and not on each <Tab> // TODO: call just once, and not on each <Tab>
var wim = liberator.options["wildmode"].split(","); var wim = options["wildmode"].split(",");
var hasList = false; var hasList = false;
var longest = false; var longest = false;
var full = false; var full = false;
@@ -815,12 +815,12 @@ liberator.CommandLine = function () //{{{
completionIndex = -1; completionIndex = -1;
completionPrefix = command.substring(0, commandWidget.selectionStart); completionPrefix = command.substring(0, commandWidget.selectionStart);
completionPostfix = command.substring(commandWidget.selectionStart); completionPostfix = command.substring(commandWidget.selectionStart);
var res = liberator.triggerCallback("complete", currentExtendedMode, completionPrefix); var res = triggerCallback("complete", currentExtendedMode, completionPrefix);
if (res) if (res)
[completionStartIndex, completions] = res; [completionStartIndex, completions] = res;
// sort the completion list // sort the completion list
if (liberator.options.get("wildoptions").has("sort")) if (options.get("wildoptions").has("sort"))
completions.sort(function (a, b) String.localeCompare(a[0], b[0])); completions.sort(function (a, b) String.localeCompare(a[0], b[0]));
completionList.setItems(completions); completionList.setItems(completions);
@@ -828,7 +828,7 @@ liberator.CommandLine = function () //{{{
if (completions.length == 0) if (completions.length == 0)
{ {
liberator.beep(); beep();
// prevent tab from moving to the next field: // prevent tab from moving to the next field:
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
@@ -867,7 +867,7 @@ liberator.CommandLine = function () //{{{
{ {
var compl = null; var compl = null;
if (longest && completions.length > 1) if (longest && completions.length > 1)
compl = liberator.completion.getLongestSubstring(); compl = completion.getLongestSubstring();
else if (full) else if (full)
compl = completions[completionIndex][0]; compl = completions[completionIndex][0];
else if (completions.length == 1) else if (completions.length == 1)
@@ -878,7 +878,7 @@ liberator.CommandLine = function () //{{{
setCommand(command.substring(0, completionStartIndex) + compl + completionPostfix); setCommand(command.substring(0, completionStartIndex) + compl + completionPostfix);
commandWidget.selectionStart = commandWidget.selectionEnd = completionStartIndex + compl.length; commandWidget.selectionStart = commandWidget.selectionEnd = completionStartIndex + compl.length;
if (longest) if (longest)
liberator.triggerCallback("change", currentExtendedMode, this.getCommand()); triggerCallback("change", currentExtendedMode, this.getCommand());
// Start a new completion in the next iteration. Useful for commands like :source // Start a new completion in the next iteration. Useful for commands like :source
// RFC: perhaps the command can indicate whether the completion should be restarted // RFC: perhaps the command can indicate whether the completion should be restarted
@@ -900,8 +900,8 @@ liberator.CommandLine = function () //{{{
// and blur the command line if there is no text left // and blur the command line if there is no text left
if (command.length == 0) if (command.length == 0)
{ {
liberator.triggerCallback("cancel", currentExtendedMode); triggerCallback("cancel", currentExtendedMode);
liberator.modes.pop(); // FIXME: use mode stack modes.pop(); // FIXME: use mode stack
} }
} }
else // any other key else // any other key
@@ -916,27 +916,27 @@ liberator.CommandLine = function () //{{{
{ {
if (event.type == "keypress") if (event.type == "keypress")
{ {
var key = liberator.events.toString(event); var key = events.toString(event);
if (liberator.events.isAcceptKey(key)) if (events.isAcceptKey(key))
{ {
var text = multilineInputWidget.value.substr(0, multilineInputWidget.selectionStart); var text = multilineInputWidget.value.substr(0, multilineInputWidget.selectionStart);
if (text.match(multilineRegexp)) if (text.match(multilineRegexp))
{ {
text = text.replace(multilineRegexp, ""); text = text.replace(multilineRegexp, "");
liberator.modes.pop(); modes.pop();
multilineInputWidget.collapsed = true; multilineInputWidget.collapsed = true;
multilineCallback.call(this, text); multilineCallback.call(this, text);
} }
} }
else if (liberator.events.isCancelKey(key)) else if (events.isCancelKey(key))
{ {
liberator.modes.pop(); modes.pop();
multilineInputWidget.collapsed = true; multilineInputWidget.collapsed = true;
} }
} }
else if (event.type == "blur") else if (event.type == "blur")
{ {
if (liberator.modes.extended & liberator.modes.INPUT_MULTILINE) if (modes.extended & modes.INPUT_MULTILINE)
setTimeout(function () { multilineInputWidget.inputField.focus(); }, 0); setTimeout(function () { multilineInputWidget.inputField.focus(); }, 0);
} }
else if (event.type == "input") else if (event.type == "input")
@@ -960,13 +960,13 @@ liberator.CommandLine = function () //{{{
function isScrollable() !win.scrollMaxY == 0; function isScrollable() !win.scrollMaxY == 0;
function atEnd() win.scrollY / win.scrollMaxY >= 1; function atEnd() win.scrollY / win.scrollMaxY >= 1;
var key = liberator.events.toString(event); var key = events.toString(event);
if (startHints) if (startHints)
{ {
liberator.statusline.updateInputBuffer(""); statusline.updateInputBuffer("");
startHints = false; startHints = false;
liberator.hints.show(liberator.modes.EXTENDED_HINT, key, undefined, win); hints.show(modes.EXTENDED_HINT, key, undefined, win);
return; return;
} }
@@ -977,13 +977,13 @@ liberator.CommandLine = function () //{{{
break; // handled globally in events.js:onEscape() break; // handled globally in events.js:onEscape()
case ":": case ":":
liberator.commandline.open(":", "", liberator.modes.EX); commandline.open(":", "", modes.EX);
return; return;
// down a line // down a line
case "j": case "j":
case "<Down>": case "<Down>":
if (liberator.options["more"] && isScrollable()) if (options["more"] && isScrollable())
win.scrollByLines(1); win.scrollByLines(1);
else else
passEvent = true; passEvent = true;
@@ -992,7 +992,7 @@ liberator.CommandLine = function () //{{{
case "<C-j>": case "<C-j>":
case "<C-m>": case "<C-m>":
case "<Return>": case "<Return>":
if (liberator.options["more"] && isScrollable() && !atEnd()) if (options["more"] && isScrollable() && !atEnd())
win.scrollByLines(1); win.scrollByLines(1);
else else
closeWindow = true; // don't propagate the event for accept keys closeWindow = true; // don't propagate the event for accept keys
@@ -1002,9 +1002,9 @@ liberator.CommandLine = function () //{{{
case "k": case "k":
case "<Up>": case "<Up>":
case "<BS>": case "<BS>":
if (liberator.options["more"] && isScrollable()) if (options["more"] && isScrollable())
win.scrollByLines(-1); win.scrollByLines(-1);
else if (liberator.options["more"] && !isScrollable()) else if (options["more"] && !isScrollable())
showMorePrompt = true; showMorePrompt = true;
else else
passEvent = true; passEvent = true;
@@ -1012,7 +1012,7 @@ liberator.CommandLine = function () //{{{
// half page down // half page down
case "d": case "d":
if (liberator.options["more"] && isScrollable()) if (options["more"] && isScrollable())
win.scrollBy(0, win.innerHeight / 2); win.scrollBy(0, win.innerHeight / 2);
else else
passEvent = true; passEvent = true;
@@ -1022,22 +1022,22 @@ liberator.CommandLine = function () //{{{
case "<LeftMouse>": case "<LeftMouse>":
if (event.originalTarget.className == "hl-URL buffer-list") if (event.originalTarget.className == "hl-URL buffer-list")
{ {
liberator.tabs.select(parseInt(event.originalTarget.parentNode.parentNode.firstChild.textContent, 10) - 1); tabs.select(parseInt(event.originalTarget.parentNode.parentNode.firstChild.textContent, 10) - 1);
closeWindow = true; closeWindow = true;
break; break;
} }
else if (event.originalTarget.localName.toLowerCase() == "a") else if (event.originalTarget.localName.toLowerCase() == "a")
{ {
liberator.open(event.originalTarget.textContent); open(event.originalTarget.textContent);
break; break;
} }
case "<A-LeftMouse>": // for those not owning a 3-button mouse case "<A-LeftMouse>": // for those not owning a 3-button mouse
case "<MiddleMouse>": case "<MiddleMouse>":
if (event.originalTarget.localName.toLowerCase() == "a") if (event.originalTarget.localName.toLowerCase() == "a")
{ {
var where = /\btabopen\b/.test(liberator.options["activate"]) ? var where = /\btabopen\b/.test(options["activate"]) ?
liberator.NEW_TAB : liberator.NEW_BACKGROUND_TAB; NEW_TAB : NEW_BACKGROUND_TAB;
liberator.open(event.originalTarget.textContent, where); open(event.originalTarget.textContent, where);
} }
break; break;
@@ -1049,7 +1049,7 @@ liberator.CommandLine = function () //{{{
// page down // page down
case "f": case "f":
if (liberator.options["more"] && isScrollable()) if (options["more"] && isScrollable())
win.scrollByPages(1); win.scrollByPages(1);
else else
passEvent = true; passEvent = true;
@@ -1057,7 +1057,7 @@ liberator.CommandLine = function () //{{{
case "<Space>": case "<Space>":
case "<PageDown>": case "<PageDown>":
if (liberator.options["more"] && isScrollable() && !atEnd()) if (options["more"] && isScrollable() && !atEnd())
win.scrollByPages(1); win.scrollByPages(1);
else else
passEvent = true; passEvent = true;
@@ -1066,7 +1066,7 @@ liberator.CommandLine = function () //{{{
// half page up // half page up
case "u": case "u":
// if (more and scrollable) // if (more and scrollable)
if (liberator.options["more"] && isScrollable()) if (options["more"] && isScrollable())
win.scrollBy(0, -(win.innerHeight / 2)); win.scrollBy(0, -(win.innerHeight / 2));
else else
passEvent = true; passEvent = true;
@@ -1074,16 +1074,16 @@ liberator.CommandLine = function () //{{{
// page up // page up
case "b": case "b":
if (liberator.options["more"] && isScrollable()) if (options["more"] && isScrollable())
win.scrollByPages(-1); win.scrollByPages(-1);
else if (liberator.options["more"] && !isScrollable()) else if (options["more"] && !isScrollable())
showMorePrompt = true; showMorePrompt = true;
else else
passEvent = true; passEvent = true;
break; break;
case "<PageUp>": case "<PageUp>":
if (liberator.options["more"] && isScrollable()) if (options["more"] && isScrollable())
win.scrollByPages(-1); win.scrollByPages(-1);
else else
passEvent = true; passEvent = true;
@@ -1091,9 +1091,9 @@ liberator.CommandLine = function () //{{{
// top of page // top of page
case "g": case "g":
if (liberator.options["more"] && isScrollable()) if (options["more"] && isScrollable())
win.scrollTo(0, 0); win.scrollTo(0, 0);
else if (liberator.options["more"] && !isScrollable()) else if (options["more"] && !isScrollable())
showMorePrompt = true; showMorePrompt = true;
else else
passEvent = true; passEvent = true;
@@ -1101,7 +1101,7 @@ liberator.CommandLine = function () //{{{
// bottom of page // bottom of page
case "G": case "G":
if (liberator.options["more"] && isScrollable() && !atEnd()) if (options["more"] && isScrollable() && !atEnd())
win.scrollTo(0, win.scrollMaxY); win.scrollTo(0, win.scrollMaxY);
else else
passEvent = true; passEvent = true;
@@ -1109,7 +1109,7 @@ liberator.CommandLine = function () //{{{
// copy text to clipboard // copy text to clipboard
case "<C-y>": case "<C-y>":
liberator.util.copyToClipboard(win.getSelection()); util.copyToClipboard(win.getSelection());
break; break;
// close the window // close the window
@@ -1118,13 +1118,13 @@ liberator.CommandLine = function () //{{{
break; break;
case ";": case ";":
liberator.statusline.updateInputBuffer(";"); statusline.updateInputBuffer(";");
startHints = true; startHints = true;
break; break;
// unmapped key // unmapped key
default: default:
if (!liberator.options["more"] || !isScrollable() || atEnd() || liberator.events.isCancelKey(key)) if (!options["more"] || !isScrollable() || atEnd() || events.isCancelKey(key))
passEvent = true; passEvent = true;
else else
showMoreHelpPrompt = true; showMoreHelpPrompt = true;
@@ -1133,17 +1133,17 @@ liberator.CommandLine = function () //{{{
if (passEvent || closeWindow) if (passEvent || closeWindow)
{ {
// FIXME: use mode stack // FIXME: use mode stack
liberator.modes.pop(); modes.pop();
this.clear(); this.clear();
if (passEvent) if (passEvent)
liberator.events.onKeyPress(event); events.onKeyPress(event);
} }
else // set update the prompt string else // set update the prompt string
{ {
if (showMoreHelpPrompt) if (showMoreHelpPrompt)
setLine("-- More -- SPACE/d/j: screen/page/line down, b/u/k: up, q: quit", this.HL_MOREMSG); setLine("-- More -- SPACE/d/j: screen/page/line down, b/u/k: up, q: quit", this.HL_MOREMSG);
else if (showMorePrompt || (liberator.options["more"] && isScrollable() && !atEnd())) else if (showMorePrompt || (options["more"] && isScrollable() && !atEnd()))
setLine("-- More --", this.HL_MOREMSG); setLine("-- More --", this.HL_MOREMSG);
else else
setLine("Press ENTER or type command to continue", this.HL_QUESTION); setLine("Press ENTER or type command to continue", this.HL_QUESTION);
@@ -1153,7 +1153,7 @@ liberator.CommandLine = function () //{{{
// to allow asynchronous adding of completions // to allow asynchronous adding of completions
setCompletions: function (compl, start) setCompletions: function (compl, start)
{ {
if (liberator.mode != liberator.modes.COMMAND_LINE) if (mode != modes.COMMAND_LINE)
return; return;
// FIXME: Kludge. // FIXME: Kludge.
@@ -1164,10 +1164,10 @@ liberator.CommandLine = function () //{{{
.inputField.QueryInterface(Components.interfaces.nsIDOMNSEditableElement).editor; .inputField.QueryInterface(Components.interfaces.nsIDOMNSEditableElement).editor;
let sel = editor.selectionController.getSelection(SEL_TYPE); let sel = editor.selectionController.getSelection(SEL_TYPE);
sel.removeAllRanges(); sel.removeAllRanges();
if (liberator.completion.parenMatch != null) if (completion.parenMatch != null)
{ {
let range = editor.selection.getRangeAt(0).cloneRange(); let range = editor.selection.getRangeAt(0).cloneRange();
let paren = liberator.completion.parenMatch + this.getCommand().indexOf(" ") + 1; let paren = completion.parenMatch + this.getCommand().indexOf(" ") + 1;
let node = range.startContainer; let node = range.startContainer;
range.setStart(node, paren); range.setStart(node, paren);
range.setEnd(node, paren + 1); range.setEnd(node, paren + 1);
@@ -1194,7 +1194,7 @@ liberator.CommandLine = function () //{{{
completions = compl; completions = compl;
completionList.selectItem(completionIndex); completionList.selectItem(completionIndex);
if (liberator.options.get("wildoptions").has("auto")) if (options.get("wildoptions").has("auto"))
completionList.show(); completionList.show();
var command = this.getCommand(); var command = this.getCommand();
@@ -1223,7 +1223,7 @@ liberator.CommandLine = function () //{{{
* *
* TODO: get rid off "completion" variables, we are dealing with variables after all * TODO: get rid off "completion" variables, we are dealing with variables after all
*/ */
liberator.ItemList = function (id) //{{{ with (liberator) liberator.ItemList = function (id) //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -1238,7 +1238,7 @@ liberator.ItemList = function (id) //{{{
var iframe = document.getElementById(id); var iframe = document.getElementById(id);
if (!iframe) if (!iframe)
{ {
liberator.log("No iframe with id: " + id + " found, strange things may happen!"); // "The truth is out there..." -- djk log("No iframe with id: " + id + " found, strange things may happen!"); // "The truth is out there..." -- djk
return; return;
} }
@@ -1267,11 +1267,11 @@ liberator.ItemList = function (id) //{{{
function createRow([b, c, a], dom) function createRow([b, c, a], dom)
{ {
/* Obviously, ItemList shouldn't know or care about this. */ /* Obviously, ItemList shouldn't know or care about this. */
let filter = liberator.completion.filterString; let filter = completion.filterString;
if (filter) if (filter)
{ {
b = liberator.template.highlightFilter(b, filter); b = template.highlightFilter(b, filter);
c = liberator.template.highlightFilter(c, filter); c = template.highlightFilter(c, filter);
} }
if (typeof a == "function") if (typeof a == "function")
@@ -1285,7 +1285,7 @@ liberator.ItemList = function (id) //{{{
</ul>; </ul>;
if (dom) if (dom)
return liberator.util.xmlToDom(row, doc); return util.xmlToDom(row, doc);
return row; return row;
} }
@@ -1335,18 +1335,18 @@ liberator.ItemList = function (id) //{{{
</div>; </div>;
let tbody = div.div; let tbody = div.div;
for (let i in liberator.util.range(offset, endIndex)) for (let i in util.range(offset, endIndex))
tbody.* += createRow(completions[i]); tbody.* += createRow(completions[i]);
div.* += div.* +=
<div class="completion-items"> <div class="completion-items">
{ {
liberator.template.map(liberator.util.range(0, maxItems), function (i) template.map(util.range(0, maxItems), function (i)
<ul class="compitem hl-NonText"><li>~</li></ul>) <ul class="compitem hl-NonText"><li>~</li></ul>)
} }
</div>; </div>;
let dom = liberator.util.xmlToDom(div, doc); let dom = util.xmlToDom(div, doc);
completionBody = dom.getElementsByClassName("completion-items")[0]; completionBody = dom.getElementsByClassName("completion-items")[0];
completionElements = completionBody.childNodes; completionElements = completionBody.childNodes;
doc.body.replaceChild(dom, doc.body.firstChild); doc.body.replaceChild(dom, doc.body.firstChild);
@@ -1432,7 +1432,7 @@ liberator.ItemList = function (id) //{{{
//}}} //}}}
}; //}}} }; //}}}
liberator.StatusLine = function () //{{{ with (liberator) liberator.StatusLine = function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -1453,7 +1453,7 @@ liberator.StatusLine = function () //{{{
////////////////////// OPTIONS ///////////////////////////////////////////////// ////////////////////// OPTIONS /////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.options.add(["laststatus", "ls"], options.add(["laststatus", "ls"],
"Show the status line", "Show the status line",
"number", 2, "number", 2,
{ {
@@ -1462,7 +1462,7 @@ liberator.StatusLine = function () //{{{
if (value == 0) if (value == 0)
document.getElementById("status-bar").collapsed = true; document.getElementById("status-bar").collapsed = true;
else if (value == 1) else if (value == 1)
liberator.echo("show status line only with > 1 window not implemented yet"); echo("show status line only with > 1 window not implemented yet");
else else
document.getElementById("status-bar").collapsed = false; document.getElementById("status-bar").collapsed = false;
@@ -1515,12 +1515,12 @@ liberator.StatusLine = function () //{{{
return; return;
} }
url = liberator.buffer.URL; url = buffer.URL;
// make it even more vim-like // make it even more vim-like
if (url == "about:blank") if (url == "about:blank")
{ {
var title = liberator.buffer.title; var title = buffer.title;
if (!title) if (!title)
url = "[No Name]"; url = "[No Name]";
} }
@@ -1530,7 +1530,7 @@ liberator.StatusLine = function () //{{{
} }
// when session information is available, add [+] when we can go backwards // when session information is available, add [+] when we can go backwards
if (liberator.config.name == "Vimperator") if (config.name == "Vimperator")
{ {
var sh = getWebNavigation().sessionHistory; var sh = getWebNavigation().sessionHistory;
var modified = ""; var modified = "";
@@ -1538,7 +1538,7 @@ liberator.StatusLine = function () //{{{
modified += "+"; modified += "+";
if (sh.index < sh.count -1) if (sh.index < sh.count -1)
modified += "-"; modified += "-";
if (liberator.bookmarks.isBookmarked(liberator.buffer.URL)) if (bookmarks.isBookmarked(buffer.URL))
modified += "\u2764"; // a heart symbol: ❤ modified += "\u2764"; // a heart symbol: ❤
//modified += "\u2665"; // a heart symbol: ♥ //modified += "\u2665"; // a heart symbol: ♥
@@ -1593,14 +1593,13 @@ liberator.StatusLine = function () //{{{
return; return;
} }
let tabs = getBrowser().mTabs; for (let [i, tab] in Iterator(getBrowser().mTabs))
for (let i = 0; i < tabs.length; i++) tab.setAttribute("ordinal", i + 1);
tabs[i].setAttribute("ordinal", i + 1);
if (!currentIndex || typeof currentIndex != "number") if (!currentIndex || typeof currentIndex != "number")
currentIndex = liberator.tabs.index() + 1; currentIndex = tabs.index() + 1;
if (!totalTabs || typeof currentIndex != "number") if (!totalTabs || typeof currentIndex != "number")
totalTabs = liberator.tabs.count; totalTabs = tabs.count;
tabCountWidget.value = "[" + currentIndex + "/" + totalTabs + "]"; tabCountWidget.value = "[" + currentIndex + "/" + totalTabs + "]";
}, },

View File

@@ -26,7 +26,7 @@ the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL. the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/ }}} ***** END LICENSE BLOCK *****/
liberator.util = { //{{{ with (liberator) liberator.util = { //{{{
Timer: function Timer(minInterval, maxInterval, callback) Timer: function Timer(minInterval, maxInterval, callback)
{ {
@@ -104,7 +104,7 @@ liberator.util = { //{{{
clipboardHelper.copyString(str); clipboardHelper.copyString(str);
if (verbose) if (verbose)
liberator.echo("Yanked " + str, liberator.commandline.FORCE_SINGLELINE); echo("Yanked " + str, commandline.FORCE_SINGLELINE);
}, },
createURI: function (str) createURI: function (str)
@@ -184,9 +184,9 @@ liberator.util = { //{{{
generateHelp: function (command, extraHelp) generateHelp: function (command, extraHelp)
{ {
var start = "", end = ""; var start = "", end = "";
if (command instanceof liberator.Command) if (command instanceof Command)
start = ":"; start = ":";
else if (command instanceof liberator.Option) else if (command instanceof Option)
start = end = "'"; start = end = "'";
var ret = ""; var ret = "";
@@ -275,7 +275,7 @@ liberator.util = { //{{{
} }
catch (e) {} catch (e) {}
value = liberator.template.highlight(value, true); value = template.highlight(value, true);
if (color) if (color)
{ {
value = value.toXMLString(); value = value.toXMLString();
@@ -303,8 +303,8 @@ liberator.util = { //{{{
if (Date.now() > endTime) if (Date.now() > endTime)
{ {
liberator.interrupted = false; liberator.interrupted = false;
liberator.threadYield(); threadYield();
if (liberator.interrupted) if (interrupted)
throw new Error("Interrupted"); throw new Error("Interrupted");
endTime = Date.now() + time; endTime = Date.now() + time;
} }
@@ -346,13 +346,13 @@ liberator.util = { //{{{
// and returns an array ['www.google.com/search?q=bla', 'www.osnews.com'] // and returns an array ['www.google.com/search?q=bla', 'www.osnews.com']
stringToURLArray: function (str) stringToURLArray: function (str)
{ {
var urls = str.split(new RegExp("\s*" + liberator.options["urlseparator"] + "\s*")); var urls = str.split(new RegExp("\s*" + options["urlseparator"] + "\s*"));
for (let url = 0; url < urls.length; url++) for (let url = 0; url < urls.length; url++)
{ {
try try
{ {
var file = liberator.io.getFile(urls[url]); var file = io.getFile(urls[url]);
if (file.exists() && file.isReadable()) if (file.exists() && file.isReadable())
{ {
urls[url] = file.path; urls[url] = file.path;
@@ -376,7 +376,7 @@ liberator.util = { //{{{
// like the comments below ;-) // like the comments below ;-)
// check for a search engine match in the string // check for a search engine match in the string
var searchURL = liberator.bookmarks.getSearchURL(urls[url], false); var searchURL = bookmarks.getSearchURL(urls[url], false);
if (searchURL) if (searchURL)
{ {
urls[url] = searchURL; urls[url] = searchURL;
@@ -384,7 +384,7 @@ liberator.util = { //{{{
} }
else // no search engine match, search for the whole string in the default engine else // no search engine match, search for the whole string in the default engine
{ {
searchURL = liberator.bookmarks.getSearchURL(urls[url], true); searchURL = bookmarks.getSearchURL(urls[url], true);
if (searchURL) if (searchURL)
{ {
urls[url] = searchURL; urls[url] = searchURL;
@@ -464,6 +464,7 @@ liberator.util.Struct = function Struct()
ConStructor.prototype = self; ConStructor.prototype = self;
return self.constructor = ConStructor; return self.constructor = ConStructor;
} }
liberator.util.Struct.prototype = { liberator.util.Struct.prototype = {
clone: function () clone: function ()
{ {
@@ -472,6 +473,7 @@ liberator.util.Struct.prototype = {
// Iterator over our named members // Iterator over our named members
__iterator__: function () ([v, this[v]] for ([k, v] in this.members)) __iterator__: function () ([v, this[v]] for ([k, v] in this.members))
} }
// Add no-sideeffect array methods. Can't set new Array() as the prototype or // Add no-sideeffect array methods. Can't set new Array() as the prototype or
// get length() won't work. // get length() won't work.
for (let [,k] in Iterator(["concat", "every", "filter", "forEach", "indexOf", "join", "lastIndexOf", for (let [,k] in Iterator(["concat", "every", "filter", "forEach", "indexOf", "join", "lastIndexOf",

View File

@@ -26,7 +26,7 @@ the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL. the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/ }}} ***** END LICENSE BLOCK *****/
liberator.config = { //{{{ with (liberator) liberator.config = { //{{{
/*** required options, no checks done if they really exist, so be careful ***/ /*** required options, no checks done if they really exist, so be careful ***/
name: "Vimperator", name: "Vimperator",
hostApplication: "Firefox", hostApplication: "Firefox",
@@ -68,7 +68,7 @@ liberator.config = { //{{{
["customizetoolbar", "Customize the Toolbar", ["customizetoolbar", "Customize the Toolbar",
function () { BrowserCustomizeToolbar(); }], function () { BrowserCustomizeToolbar(); }],
["dominspector", "DOM Inspector", ["dominspector", "DOM Inspector",
function () { try { inspectDOMDocument(content.document); } catch (e) { liberator.echoerr("DOM Inspector extension not installed"); } }], function () { try { inspectDOMDocument(content.document); } catch (e) { echoerr("DOM Inspector extension not installed"); } }],
["downloads", "Manage Downloads", ["downloads", "Manage Downloads",
function () { toOpenWindowByType("Download:Manager", "chrome://mozapps/content/downloads/downloads.xul", "chrome,dialog=no,resizable"); }], function () { toOpenWindowByType("Download:Manager", "chrome://mozapps/content/downloads/downloads.xul", "chrome,dialog=no,resizable"); }],
["history", "List your history", ["history", "List your history",
@@ -98,7 +98,7 @@ liberator.config = { //{{{
["searchengines", "Manage installed search engines", ["searchengines", "Manage installed search engines",
function () { openDialog("chrome://browser/content/search/engineManager.xul", "_blank", "chrome,dialog,modal,centerscreen"); }], function () { openDialog("chrome://browser/content/search/engineManager.xul", "_blank", "chrome,dialog,modal,centerscreen"); }],
["selectionsource", "View selection source", ["selectionsource", "View selection source",
function () { liberator.buffer.viewSelectionSource(); }] function () { buffer.viewSelectionSource(); }]
], ],
// they are sorted by relevance, not alphabetically // they are sorted by relevance, not alphabetically
@@ -114,12 +114,12 @@ liberator.config = { //{{{
{ {
function incrementURL(count) function incrementURL(count)
{ {
var url = liberator.buffer.URL; var url = buffer.URL;
var regex = /(.*?)(\d+)(\D*)$/; var regex = /(.*?)(\d+)(\D*)$/;
var matches = url.match(regex); var matches = url.match(regex);
if (!matches || !matches[2]) // no number to increment if (!matches || !matches[2]) // no number to increment
return liberator.beep(); return beep();
var newNum = parseInt(matches[2], 10) + count + ""; // "" to make sure its a string var newNum = parseInt(matches[2], 10) + count + ""; // "" to make sure its a string
var nums = newNum.match(/^(-?)(\d+)$/); var nums = newNum.match(/^(-?)(\d+)$/);
@@ -129,71 +129,71 @@ liberator.config = { //{{{
newNum += "0"; // keep leading zeros newNum += "0"; // keep leading zeros
newNum += nums[2]; newNum += nums[2];
liberator.open(matches[1] + newNum + matches[3]); open(matches[1] + newNum + matches[3]);
} }
// load Vimperator specific modules // load Vimperator specific modules
liberator.loadModule("search", liberator.Search); loadModule("search", Search);
liberator.loadModule("bookmarks", liberator.Bookmarks); loadModule("bookmarks", Bookmarks);
liberator.loadModule("history", liberator.History); loadModule("history", History);
liberator.loadModule("tabs", liberator.Tabs); loadModule("tabs", Tabs);
liberator.loadModule("marks", liberator.Marks); loadModule("marks", Marks);
liberator.loadModule("quickmarks", liberator.QuickMarks); loadModule("quickmarks", QuickMarks);
liberator.loadModule("hints", liberator.Hints); loadModule("hints", Hints);
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// MAPPINGS //////////////////////////////////////////////// ////////////////////// MAPPINGS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.mappings.add([liberator.modes.NORMAL], mappings.add([modes.NORMAL],
["y"], "Yank current location to the clipboard", ["y"], "Yank current location to the clipboard",
function () { liberator.util.copyToClipboard(liberator.buffer.URL, true); }); function () { util.copyToClipboard(buffer.URL, true); });
// opening websites // opening websites
liberator.mappings.add([liberator.modes.NORMAL], mappings.add([modes.NORMAL],
["o"], "Open one or more URLs", ["o"], "Open one or more URLs",
function () { liberator.commandline.open(":", "open ", liberator.modes.EX); }); function () { commandline.open(":", "open ", modes.EX); });
liberator.mappings.add([liberator.modes.NORMAL], ["O"], mappings.add([modes.NORMAL], ["O"],
"Open one or more URLs, based on current location", "Open one or more URLs, based on current location",
function () { liberator.commandline.open(":", "open " + liberator.buffer.URL, liberator.modes.EX); }); function () { commandline.open(":", "open " + buffer.URL, modes.EX); });
liberator.mappings.add([liberator.modes.NORMAL], ["t"], mappings.add([modes.NORMAL], ["t"],
"Open one or more URLs in a new tab", "Open one or more URLs in a new tab",
function () { liberator.commandline.open(":", "tabopen ", liberator.modes.EX); }); function () { commandline.open(":", "tabopen ", modes.EX); });
liberator.mappings.add([liberator.modes.NORMAL], ["T"], mappings.add([modes.NORMAL], ["T"],
"Open one or more URLs in a new tab, based on current location", "Open one or more URLs in a new tab, based on current location",
function () { liberator.commandline.open(":", "tabopen " + liberator.buffer.URL, liberator.modes.EX); }); function () { commandline.open(":", "tabopen " + buffer.URL, modes.EX); });
liberator.mappings.add([liberator.modes.NORMAL], mappings.add([modes.NORMAL],
["<C-a>"], "Increment last number in URL", ["<C-a>"], "Increment last number in URL",
function (count) { incrementURL(count > 1 ? count : 1); }, function (count) { incrementURL(count > 1 ? count : 1); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.NORMAL], mappings.add([modes.NORMAL],
["<C-x>"], "Decrement last number in URL", ["<C-x>"], "Decrement last number in URL",
function (count) { incrementURL(-(count > 1 ? count : 1)); }, function (count) { incrementURL(-(count > 1 ? count : 1)); },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.NORMAL], ["~"], mappings.add([modes.NORMAL], ["~"],
"Open home directory", "Open home directory",
function () { liberator.open("~"); }); function () { open("~"); });
liberator.mappings.add([liberator.modes.NORMAL], ["gh"], mappings.add([modes.NORMAL], ["gh"],
"Open homepage", "Open homepage",
function () { BrowserHome(); }); function () { BrowserHome(); });
liberator.mappings.add([liberator.modes.NORMAL], ["gH"], mappings.add([modes.NORMAL], ["gH"],
"Open homepage in a new tab", "Open homepage in a new tab",
function () function ()
{ {
var homepages = gHomeButton.getHomePage(); var homepages = gHomeButton.getHomePage();
liberator.open(homepages, /\bhomepage\b/.test(liberator.options["activate"]) ? open(homepages, /\bhomepage\b/.test(options["activate"]) ?
liberator.NEW_TAB : liberator.NEW_BACKGROUND_TAB); NEW_TAB : NEW_BACKGROUND_TAB);
}); });
liberator.mappings.add([liberator.modes.NORMAL], ["gu"], mappings.add([modes.NORMAL], ["gu"],
"Go to parent directory", "Go to parent directory",
function (count) function (count)
{ {
@@ -202,7 +202,7 @@ liberator.config = { //{{{
if (/^file:\/|^\//.test(url)) if (/^file:\/|^\//.test(url))
{ {
//var strippedFilename = url.replace(/^(file:\/\/)?(.*)/, "$2"); //var strippedFilename = url.replace(/^(file:\/\/)?(.*)/, "$2");
var file = liberator.io.getFile(url); var file = io.getFile(url);
if (!file.exists() || !file.isDirectory()) if (!file.exists() || !file.isDirectory())
return false; return false;
else else
@@ -216,7 +216,7 @@ liberator.config = { //{{{
if (count < 1) if (count < 1)
count = 1; count = 1;
var url = liberator.buffer.URL; var url = buffer.URL;
for (let i = 0; i < count; i++) for (let i = 0; i < count; i++)
{ {
if (isDirectory(url)) if (isDirectory(url))
@@ -226,53 +226,53 @@ liberator.config = { //{{{
} }
url = url.replace(/^(.*:\/+.*?)\/+$/, "$1/"); // get rid of more than 1 / at the end url = url.replace(/^(.*:\/+.*?)\/+$/, "$1/"); // get rid of more than 1 / at the end
if (url == liberator.buffer.URL) if (url == buffer.URL)
{ {
liberator.beep(); beep();
return; return;
} }
liberator.open(url); open(url);
}, },
{ flags: liberator.Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
liberator.mappings.add([liberator.modes.NORMAL], ["gU"], mappings.add([modes.NORMAL], ["gU"],
"Go to the root of the website", "Go to the root of the website",
function () function ()
{ {
var uri = content.document.location; var uri = content.document.location;
if (/(about|mailto):/.test(uri.protocol)) // exclude these special protocols for now if (/(about|mailto):/.test(uri.protocol)) // exclude these special protocols for now
{ {
liberator.beep(); beep();
return; return;
} }
liberator.open(uri.protocol + "//" + (uri.host || "") + "/"); open(uri.protocol + "//" + (uri.host || "") + "/");
}); });
liberator.mappings.add([liberator.modes.NORMAL], ["<C-l>"], mappings.add([modes.NORMAL], ["<C-l>"],
"Redraw the screen", "Redraw the screen",
function () { liberator.commands.get("redraw").execute(); }); function () { commands.get("redraw").execute(); });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// COMMANDS //////////////////////////////////////////////// ////////////////////// COMMANDS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.commands.add(["downl[oads]", "dl"], commands.add(["downl[oads]", "dl"],
"Show progress of current downloads", "Show progress of current downloads",
function () function ()
{ {
liberator.open("chrome://mozapps/content/downloads/downloads.xul", open("chrome://mozapps/content/downloads/downloads.xul",
liberator.options.get("newtab").has("all", "downloads") options.get("newtab").has("all", "downloads")
? liberator.NEW_TAB : liberator.CURRENT_TAB); ? NEW_TAB : CURRENT_TAB);
}, },
{ argCount: "0" }); { argCount: "0" });
liberator.commands.add(["o[pen]", "e[dit]"], commands.add(["o[pen]", "e[dit]"],
"Open one or more URLs in the current tab", "Open one or more URLs in the current tab",
function (args, special) function (args, special)
{ {
if (args) if (args)
{ {
liberator.open(args); open(args);
} }
else else
{ {
@@ -284,10 +284,10 @@ liberator.config = { //{{{
}, },
{ {
bang: true, bang: true,
completer: function (filter) liberator.completion.url(filter) completer: function (filter) completion.url(filter)
}); });
liberator.commands.add(["redr[aw]"], commands.add(["redr[aw]"],
"Redraw the screen", "Redraw the screen",
function () function ()
{ {
@@ -298,7 +298,7 @@ liberator.config = { //{{{
{ argCount: "0" }); { argCount: "0" });
// TODO: move sidebar commands to ui.js? // TODO: move sidebar commands to ui.js?
liberator.commands.add(["sbcl[ose]"], commands.add(["sbcl[ose]"],
"Close the sidebar window", "Close the sidebar window",
function () function ()
{ {
@@ -307,7 +307,7 @@ liberator.config = { //{{{
}, },
{ argCount: "0" }); { argCount: "0" });
liberator.commands.add(["sideb[ar]", "sb[ar]", "sbope[n]"], commands.add(["sideb[ar]", "sb[ar]", "sbope[n]"],
"Open the sidebar window", "Open the sidebar window",
function (args) function (args)
{ {
@@ -327,34 +327,34 @@ liberator.config = { //{{{
return; return;
} }
} }
liberator.echoerr("No sidebar " + args.string + " found"); echoerr("No sidebar " + args.string + " found");
}, },
{ {
argCount: "+", argCount: "+",
completer: function (filter) liberator.completion.sidebar(filter) completer: function (filter) completion.sidebar(filter)
}); });
liberator.commands.add(["winc[lose]", "wc[lose]"], commands.add(["winc[lose]", "wc[lose]"],
"Close window", "Close window",
function () { window.close(); }, function () { window.close(); },
{ argCount: "0" }); { argCount: "0" });
liberator.commands.add(["wino[pen]", "wo[pen]", "wine[dit]"], commands.add(["wino[pen]", "wo[pen]", "wine[dit]"],
"Open one or more URLs in a new window", "Open one or more URLs in a new window",
function (args) function (args)
{ {
if (args) if (args)
liberator.open(args, liberator.NEW_WINDOW); open(args, NEW_WINDOW);
else else
liberator.open("about:blank", liberator.NEW_WINDOW); open("about:blank", NEW_WINDOW);
}, },
{ completer: function (filter) liberator.completion.url(filter) }); { completer: function (filter) completion.url(filter) });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// OPTIONS ///////////////////////////////////////////////// ////////////////////// OPTIONS /////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
liberator.options.add(["online"], options.add(["online"],
"Set the 'work offline' option", "Set the 'work offline' option",
"boolean", true, "boolean", true,
{ {
@@ -375,7 +375,7 @@ liberator.config = { //{{{
} }
}); });
liberator.options.add(["titlestring"], options.add(["titlestring"],
"Change the title of the window", "Change the title of the window",
"string", "Vimperator", "string", "Vimperator",
{ {
@@ -383,7 +383,7 @@ liberator.config = { //{{{
{ {
try try
{ {
var id = liberator.config.mainWindowID || "main-window"; var id = config.mainWindowID || "main-window";
document.getElementById(id).setAttribute("titlemodifier", value); document.getElementById(id).setAttribute("titlemodifier", value);
if (window.content.document.title.length > 0) if (window.content.document.title.length > 0)
document.title = window.content.document.title + " - " + value; document.title = window.content.document.title + " - " + value;
@@ -392,14 +392,14 @@ liberator.config = { //{{{
} }
catch (e) catch (e)
{ {
liberator.log("Couldn't set titlestring", 3); log("Couldn't set titlestring", 3);
} }
return value; return value;
} }
}); });
liberator.options.add(["urlseparator"], options.add(["urlseparator"],
"Set the separator regexp used to separate multiple URL args", "Set the separator regexp used to separate multiple URL args",
"string", ",\\s"); "string", ",\\s");
} }