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

Add liberator.modules namespace, load scripts via subscript loader, report better errors on :so with here docs, beep when clicking an input field in command line mode.

This commit is contained in:
Kris Maglione
2008-10-13 21:05:48 +00:00
parent b7e36f74ed
commit ff7c3c1210
27 changed files with 789 additions and 751 deletions

View File

@@ -4,6 +4,7 @@ resource liberator modules/
locale liberator en-US locale/en-US/ locale liberator en-US locale/en-US/
skin liberator classic/1.0 skin/ skin liberator classic/1.0 skin/
override chrome://liberator/content/liberator.dtd chrome://liberator/content/vimperator.dtd override chrome://liberator/content/liberator.dtd chrome://liberator/content/vimperator.dtd
override chrome://liberator/content/config.js chrome://liberator/content/vimperator.js
overlay chrome://browser/content/browser.xul chrome://liberator/content/liberator.xul overlay chrome://browser/content/browser.xul chrome://liberator/content/liberator.xul
overlay chrome://browser/content/browser.xul chrome://liberator/content/vimperator.xul overlay chrome://browser/content/browser.xul chrome://liberator/content/vimperator.xul

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 *****/
with (liberator) liberator.Addressbook = function () //{{{ function Addressbook() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -84,7 +84,7 @@ with (liberator) liberator.Addressbook = function () //{{{
} }
catch (e) catch (e)
{ {
beep(); liberator.beep();
} }
if (!to) if (!to)
@@ -123,9 +123,9 @@ with (liberator) liberator.Addressbook = function () //{{{
displayName = generateDisplayName(firstName, lastName); displayName = generateDisplayName(firstName, lastName);
if (addressbook.add(mailAddr, firstName, lastName, displayName)) if (addressbook.add(mailAddr, firstName, lastName, displayName))
echo("Added address: " + displayName + " <" + mailAddr + ">", commandline.FORCE_SINGLELINE); liberator.echo("Added address: " + displayName + " <" + mailAddr + ">", commandline.FORCE_SINGLELINE);
else else
echoerr("Exxx: Could not add bookmark `" + mailAddr + "'", commandline.FORCE_SINGLELINE); liberator.echoerr("Exxx: Could not add bookmark `" + mailAddr + "'", commandline.FORCE_SINGLELINE);
}, },
{ {
@@ -189,7 +189,7 @@ with (liberator) liberator.Addressbook = function () //{{{
} }
if (addresses.length < 1) if (addresses.length < 1)
{ {
echoerr("E94: No matching contact for " + filter, commandline.FORCE_SINGLELINE); liberator.echoerr("E94: No matching contact for " + filter, commandline.FORCE_SINGLELINE);
return false; return false;
} }
@@ -201,7 +201,7 @@ with (liberator) liberator.Addressbook = function () //{{{
function (address) "\"" + address[0].replace(/"/g, "") + " <" + address[1] + ">\"" function (address) "\"" + address[0].replace(/"/g, "") + " <" + address[1] + ">\""
).join(", "); ).join(", ");
mail.composeNewMail(args); liberator.mail.composeNewMail(args);
} }
else else
{ {

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
with (liberator) liberator.Bookmarks = function () //{{{ function Bookmarks() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -43,10 +43,10 @@ with (liberator) 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 util.Struct("url", "title", "icon", "keyword", "tags", "id"); const Bookmark = new Struct("url", "title", "icon", "keyword", "tags", "id");
const Keyword = new util.Struct("keyword", "title", "icon", "url"); const Keyword = new Struct("keyword", "title", "icon", "url");
const storage = liberator.storage; const storage = modules.storage;
function Cache(name, store, serial) function Cache(name, store, serial)
{ {
const rootFolders = [bookmarksService.toolbarFolder, bookmarksService.bookmarksMenuFolder, bookmarksService.unfiledBookmarksFolder]; const rootFolders = [bookmarksService.toolbarFolder, bookmarksService.bookmarksMenuFolder, bookmarksService.unfiledBookmarksFolder];
@@ -100,7 +100,7 @@ with (liberator) liberator.Bookmarks = function () //{{{
this.load = function load() this.load = function load()
{ {
// dump("cache.load()\n"); // liberator.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 @@ with (liberator) liberator.Bookmarks = function () //{{{
onItemMoved: function () {}, onItemMoved: function () {},
onItemAdded: function (itemId, folder, index) onItemAdded: function (itemId, folder, index)
{ {
// dump("onItemAdded(" + itemId + ", " + folder + ", " + index + ")\n"); // liberator.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 @@ with (liberator) liberator.Bookmarks = function () //{{{
}, },
onItemRemoved: function (itemId, folder, index) onItemRemoved: function (itemId, folder, index)
{ {
// dump("onItemRemoved(" + itemId + ", " + folder + ", " + index + ")\n"); // liberator.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 @@ with (liberator) liberator.Bookmarks = function () //{{{
{ {
if (isAnnotation) if (isAnnotation)
return; return;
// dump("onItemChanged(" + itemId + ", " + property + ", " + value + ")\n"); // liberator.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)
{ {
@@ -192,11 +192,11 @@ with (liberator) liberator.Bookmarks = function () //{{{
var cache = storage.newObject("bookmark-cache", Cache, false); var cache = storage.newObject("bookmark-cache", Cache, false);
storage.addObserver("bookmark-cache", bookmarkObserver); storage.addObserver("bookmark-cache", bookmarkObserver);
registerObserver("shutdown", function () { liberator.registerObserver("shutdown", function () {
storage.removeObserver("bookmark-cache", bookmarkObserver) storage.removeObserver("bookmark-cache", bookmarkObserver)
}); });
registerObserver("enter", function () { liberator.registerObserver("enter", function () {
if (options["preload"]) if (options["preload"])
cache.bookmarks; // Forces a load, if not already loaded. cache.bookmarks; // Forces a load, if not already loaded.
}); });
@@ -270,10 +270,10 @@ with (liberator) liberator.Bookmarks = function () //{{{
var extra = ""; var extra = "";
if (title != url) if (title != url)
extra = " (" + title + ")"; extra = " (" + title + ")";
echo("Added bookmark: " + url + extra, commandline.FORCE_SINGLELINE); liberator.echo("Added bookmark: " + url + extra, commandline.FORCE_SINGLELINE);
} }
else else
echoerr("Exxx: Could not add bookmark `" + title + "'", commandline.FORCE_SINGLELINE); liberator.echoerr("Exxx: Could not add bookmark `" + title + "'", commandline.FORCE_SINGLELINE);
}, },
{ {
argCount: "?", argCount: "?",
@@ -302,7 +302,7 @@ with (liberator) liberator.Bookmarks = function () //{{{
let url = args || buffer.URL; let url = args || buffer.URL;
let deletedCount = bookmarks.remove(url); let deletedCount = bookmarks.remove(url);
echo(deletedCount + " bookmark(s) with url `" + url + "' deleted", commandline.FORCE_SINGLELINE); liberator.echo(deletedCount + " bookmark(s) with url `" + url + "' deleted", commandline.FORCE_SINGLELINE);
}, },
{ completer: function (filter) completion.bookmark(filter) }); { completer: function (filter) completion.bookmark(filter) });
@@ -356,7 +356,7 @@ with (liberator) liberator.Bookmarks = function () //{{{
} }
catch (e) catch (e)
{ {
log(e, 0); liberator.log(e, 0);
return false; return false;
} }
@@ -415,7 +415,7 @@ with (liberator) liberator.Bookmarks = function () //{{{
} }
catch (e) catch (e)
{ {
log(e, 0); liberator.log(e, 0);
return i; return i;
} }
@@ -497,19 +497,19 @@ with (liberator) 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)
echoerr("E283: No bookmarks matching tags: \"" + tags + "\" and string: \"" + filter + "\""); liberator.echoerr("E283: No bookmarks matching tags: \"" + tags + "\" and string: \"" + filter + "\"");
else if (filter.length > 0) else if (filter.length > 0)
echoerr("E283: No bookmarks matching string: \"" + filter + "\""); liberator.echoerr("E283: No bookmarks matching string: \"" + filter + "\"");
else if (tags.length > 0) else if (tags.length > 0)
echoerr("E283: No bookmarks matching tags: \"" + tags + "\""); liberator.echoerr("E283: No bookmarks matching tags: \"" + tags + "\"");
else else
echoerr("No bookmarks set"); liberator.echoerr("No bookmarks set");
return; return;
} }
if (openItems) if (openItems)
return open([i.url for each (i in items)], NEW_TAB); return liberator.open([i.url for each (i in items)], liberator.NEW_TAB);
let list = template.bookmarks("title", ( let list = template.bookmarks("title", (
{ {
@@ -525,7 +525,7 @@ with (liberator) liberator.Bookmarks = function () //{{{
//}}} //}}}
}; //}}} }; //}}}
with (liberator) liberator.History = function () //{{{ function History() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -542,12 +542,12 @@ with (liberator) liberator.History = function () //{{{
return faviconService.getFaviconImageForPage(ioService.newURI(uri, null, null)).spec; return faviconService.getFaviconImageForPage(ioService.newURI(uri, null, null)).spec;
} }
var history; var placesHistory;
var cachedHistory = []; // add pages here after loading the initial Places history var cachedHistory = []; // add pages here after loading the initial Places history
function load() function load()
{ {
history = []; placesHistory = [];
// no query parameters will get all history // no query parameters will get all history
// XXX default sorting is... ? // XXX default sorting is... ?
@@ -562,16 +562,16 @@ with (liberator) 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);
// dump("History child " + node.itemId + ": " + node.title + " - " + node.type); // liberator.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)]); placesHistory.push([node.uri, node.title || "[No title]", getIcon(node.uri)]);
} }
// close a container after using it! // close a container after using it!
rootNode.containerOpen = false; rootNode.containerOpen = false;
} }
registerObserver("enter", function () { liberator.registerObserver("enter", function () {
if (options["preload"]) if (options["preload"])
load(); load();
}); });
@@ -584,22 +584,22 @@ with (liberator) liberator.History = function () //{{{
mappings.add(myModes, 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: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
mappings.add(myModes, 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: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
mappings.add(myModes, 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: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
mappings.add(myModes, 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: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
@@ -627,11 +627,11 @@ with (liberator) liberator.History = function () //{{{
return; return;
} }
} }
echoerr("Exxx: URL not found in history"); liberator.echoerr("Exxx: URL not found in history");
} }
else else
{ {
liberator.history.stepTo(count > 0 ? -1 * count : -1); history.stepTo(count > 0 ? -1 * count : -1);
} }
} }
}, },
@@ -675,11 +675,11 @@ with (liberator) liberator.History = function () //{{{
return; return;
} }
} }
echoerr("Exxx: URL not found in history"); liberator.echoerr("Exxx: URL not found in history");
} }
else else
{ {
liberator.history.stepTo(count > 0 ? count : 1); history.stepTo(count > 0 ? count : 1);
} }
} }
}, },
@@ -718,12 +718,12 @@ with (liberator) liberator.History = function () //{{{
get: function (filter) get: function (filter)
{ {
if (!history) if (!placesHistory)
load(); load();
if (!filter) if (!filter)
return cachedHistory.concat(history); return cachedHistory.concat(placesHistory);
return completion.cached("history", filter, function () cachedHistory.concat(history), return completion.cached("history", filter, function () cachedHistory.concat(placesHistory),
"filterURLArray"); "filterURLArray");
}, },
@@ -731,20 +731,20 @@ with (liberator) liberator.History = function () //{{{
// so just update our cached history here // so just update our cached history here
add: function (url, title) add: function (url, title)
{ {
if (!history) if (!placesHistory)
load(); load();
let filter = function (h) h[0] != url; let filter = function (h) h[0] != url;
// don't let cachedHistory grow too large // don't let cachedHistory grow too large
if (cachedHistory.length > 1000) if (cachedHistory.length > 1000)
{ {
history = cachedHistory.concat(history); placesHistory = cachedHistory.concat(placesHistory);
cachedHistory = []; cachedHistory = [];
} }
else else
cachedHistory = cachedHistory.filter(filter); cachedHistory = cachedHistory.filter(filter);
if (history.some(function (h) h[0] == url)) if (placesHistory.some(function (h) h[0] == url))
history = history.filter(filter); placesHistory = placesHistory.filter(filter);
cachedHistory.unshift([url, title || "[No title]", getIcon(url)]); cachedHistory.unshift([url, title || "[No title]", getIcon(url)]);
return true; return true;
@@ -762,7 +762,7 @@ with (liberator) liberator.History = function () //{{{
} }
else else
{ {
beep(); liberator.beep();
} }
}, },
@@ -772,7 +772,7 @@ with (liberator) liberator.History = function () //{{{
if (index == 0) if (index == 0)
{ {
beep(); liberator.beep();
return; return;
} }
@@ -786,7 +786,7 @@ with (liberator) liberator.History = function () //{{{
if (index == max) if (index == max)
{ {
beep(); liberator.beep();
return; return;
} }
@@ -800,16 +800,16 @@ with (liberator) liberator.History = function () //{{{
if (items.length == 0) if (items.length == 0)
{ {
if (filter.length > 0) if (filter.length > 0)
echoerr("E283: No history matching \"" + filter + "\""); liberator.echoerr("E283: No history matching \"" + filter + "\"");
else else
echoerr("No history set"); liberator.echoerr("No history set");
return; return;
} }
if (openItems) if (openItems)
{ {
return open([i[0] for each (i in items)], NEW_TAB); return liberator.open([i[0] for each (i in items)], liberator.NEW_TAB);
} }
else else
{ {
@@ -825,7 +825,7 @@ with (liberator) liberator.History = function () //{{{
//}}} //}}}
}; //}}} }; //}}}
with (liberator) liberator.QuickMarks = function () //{{{ function QuickMarks() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -841,7 +841,7 @@ with (liberator) liberator.QuickMarks = function () //{{{
mappings.add(myModes, mappings.add(myModes,
["go"], "Jump to a QuickMark", ["go"], "Jump to a QuickMark",
function (arg) { quickmarks.jumpTo(arg, CURRENT_TAB); }, function (arg) { quickmarks.jumpTo(arg, liberator.CURRENT_TAB); },
{ flags: Mappings.flags.ARGUMENT }); { flags: Mappings.flags.ARGUMENT });
mappings.add(myModes, mappings.add(myModes,
@@ -850,7 +850,7 @@ with (liberator) liberator.QuickMarks = function () //{{{
{ {
quickmarks.jumpTo(arg, quickmarks.jumpTo(arg,
/\bquickmark\b/.test(options["activate"]) ? /\bquickmark\b/.test(options["activate"]) ?
NEW_TAB : NEW_BACKGROUND_TAB); liberator.NEW_TAB : liberator.NEW_BACKGROUND_TAB);
}, },
{ flags: Mappings.flags.ARGUMENT }); { flags: Mappings.flags.ARGUMENT });
@@ -860,7 +860,7 @@ with (liberator) liberator.QuickMarks = function () //{{{
{ {
if (/[^a-zA-Z0-9]/.test(arg)) if (/[^a-zA-Z0-9]/.test(arg))
{ {
beep(); liberator.beep();
return; return;
} }
@@ -879,13 +879,13 @@ with (liberator) liberator.QuickMarks = function () //{{{
// 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)
{ {
echoerr("E471: Argument required"); liberator.echoerr("E471: Argument required");
return; return;
} }
if (special && args) if (special && args)
{ {
echoerr("E474: Invalid argument"); liberator.echoerr("E474: Invalid argument");
return; return;
} }
@@ -902,7 +902,7 @@ with (liberator) liberator.QuickMarks = function () //{{{
{ {
var matches = args.string.match(/^([a-zA-Z0-9])(?:\s+(.+))?$/); var matches = args.string.match(/^([a-zA-Z0-9])(?:\s+(.+))?$/);
if (!matches) if (!matches)
echoerr("E488: Trailing characters"); liberator.echoerr("E488: Trailing characters");
else if (!matches[2]) else if (!matches[2])
quickmarks.add(matches[1], buffer.URL); quickmarks.add(matches[1], buffer.URL);
else else
@@ -917,7 +917,7 @@ with (liberator) liberator.QuickMarks = function () //{{{
// 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))
{ {
echoerr("E283: No QuickMarks matching \"" + args + "\""); liberator.echoerr("E283: No QuickMarks matching \"" + args + "\"");
return; return;
} }
@@ -957,9 +957,9 @@ with (liberator) liberator.QuickMarks = function () //{{{
var url = qmarks.get(qmark); var url = qmarks.get(qmark);
if (url) if (url)
open(url, where); liberator.open(url, where);
else else
echoerr("E20: QuickMark not set"); liberator.echoerr("E20: QuickMark not set");
}, },
list: function (filter) list: function (filter)
@@ -974,7 +974,7 @@ with (liberator) liberator.QuickMarks = function () //{{{
if (marks.length == 0) if (marks.length == 0)
{ {
echoerr("No QuickMarks set"); liberator.echoerr("No QuickMarks set");
return; return;
} }
@@ -983,7 +983,7 @@ with (liberator) 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)
{ {
echoerr("E283: No QuickMarks matching \"" + filter + "\""); liberator.echoerr("E283: No QuickMarks matching \"" + filter + "\"");
return; return;
} }
} }

View File

@@ -28,7 +28,7 @@ the terms of any one of the MPL, the GPL or the LGPL.
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
with (liberator) liberator.Buffer = function () //{{{ function Buffer() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -49,8 +49,8 @@ with (liberator) liberator.Buffer = function () //{{{
var zoomLevels = [ 1, 10, 25, 50, 75, 90, 100, var zoomLevels = [ 1, 10, 25, 50, 75, 90, 100,
120, 150, 200, 300, 500, 1000, 2000 ]; 120, 150, 200, 300, 500, 1000, 2000 ];
const util = liberator.util; const util = modules.util;
const arrayIter = liberator.util.arrayIter; const arrayIter = util.arrayIter;
function Styles(name, store, serial) function Styles(name, store, serial)
{ {
@@ -59,7 +59,7 @@ with (liberator) liberator.Buffer = function () //{{{
* with this window. * with this window.
*/ */
const sleep = liberator.sleep; const sleep = liberator.sleep;
const storage = liberator.storage; const storage = modules.storage;
const consoleService = Components.classes["@mozilla.org/consoleservice;1"] const consoleService = Components.classes["@mozilla.org/consoleservice;1"]
.getService(Components.interfaces.nsIConsoleService); .getService(Components.interfaces.nsIConsoleService);
const ios = Components.classes["@mozilla.org/network/io-service;1"] const ios = Components.classes["@mozilla.org/network/io-service;1"]
@@ -69,7 +69,7 @@ with (liberator) liberator.Buffer = function () //{{{
const XHTML = "http://www.w3.org/1999/xhtml"; const XHTML = "http://www.w3.org/1999/xhtml";
const namespace = "@namespace html url(" + XHTML + ");\n" + const namespace = "@namespace html url(" + XHTML + ");\n" +
"@namespace xul url(http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul);\n"; "@namespace xul url(http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul);\n";
const Sheet = new util.Struct("name", "sites", "css", "ref"); const Sheet = new Struct("name", "sites", "css", "ref");
let cssUri = function (css) "data:text/css," + encodeURI(css); let cssUri = function (css) "data:text/css," + encodeURI(css);
@@ -284,7 +284,7 @@ with (liberator) liberator.Buffer = function () //{{{
{ {
if (value < 1 || value > 2000) if (value < 1 || value > 2000)
{ {
echoerr("Zoom value out of range (1-2000%)"); liberator.echoerr("Zoom value out of range (1-2000%)");
return; return;
} }
@@ -293,7 +293,7 @@ with (liberator) liberator.Buffer = function () //{{{
else else
getBrowser().markupDocumentViewer.textZoom = value / 100.0; getBrowser().markupDocumentViewer.textZoom = value / 100.0;
echo((fullZoom ? "Full zoom: " : "Text zoom: ") + value + "%"); liberator.echo((fullZoom ? "Full zoom: " : "Text zoom: ") + value + "%");
// TODO: shouldn't this just recalculate hint coords, rather than // TODO: shouldn't this just recalculate hint coords, rather than
// unsuccessfully attempt to reshow hints? i.e. isn't it just relying // unsuccessfully attempt to reshow hints? i.e. isn't it just relying
@@ -334,7 +334,7 @@ with (liberator) liberator.Buffer = function () //{{{
} }
if (index < 0 || index >= zoomLevels.length) if (index < 0 || index >= zoomLevels.length)
{ {
beep(); liberator.beep();
return; return;
} }
setZoom(zoomLevels[index], fullZoom); setZoom(zoomLevels[index], fullZoom);
@@ -344,7 +344,7 @@ with (liberator) liberator.Buffer = function () //{{{
{ {
// NOTE: it's possible to have scrollY > scrollMaxY - FF bug? // NOTE: it's possible to have scrollY > scrollMaxY - FF bug?
if (direction > 0 && win.scrollY >= win.scrollMaxY || direction < 0 && win.scrollY == 0) if (direction > 0 && win.scrollY >= win.scrollMaxY || direction < 0 && win.scrollY == 0)
beep(); liberator.beep();
} }
function findScrollableWindow() function findScrollableWindow()
@@ -537,7 +537,7 @@ with (liberator) liberator.Buffer = function () //{{{
if (count > 0 && count <= 100) if (count > 0 && count <= 100)
buffer.scrollToPercentile(count); buffer.scrollToPercentile(count);
else else
beep(); liberator.beep();
}, },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
@@ -625,7 +625,7 @@ with (liberator) liberator.Buffer = function () //{{{
} }
else else
{ {
beep(); liberator.beep();
} }
} }
}, },
@@ -635,22 +635,22 @@ with (liberator) liberator.Buffer = function () //{{{
"Open (put) a URL based on the current clipboard contents in a new buffer", "Open (put) a URL based on the current clipboard contents in a new buffer",
function () function ()
{ {
open(util.readFromClipboard(), liberator.open(util.readFromClipboard(),
/\bpaste\b/.test(options["activate"]) ? /\bpaste\b/.test(options["activate"]) ?
NEW_BACKGROUND_TAB : NEW_TAB); liberator.NEW_BACKGROUND_TAB : liberator.NEW_TAB);
}); });
mappings.add(myModes, ["p", "<MiddleMouse>"], mappings.add(myModes, ["p", "<MiddleMouse>"],
"Open (put) a URL based on the current clipboard contents in the current buffer", "Open (put) a URL based on the current clipboard contents in the current buffer",
function () { open(util.readFromClipboard()); }); function () { liberator.open(util.readFromClipboard()); });
mappings.add(myModes, ["P"], mappings.add(myModes, ["P"],
"Open (put) a URL based on the current clipboard contents in a new buffer", "Open (put) a URL based on the current clipboard contents in a new buffer",
function () function ()
{ {
open(util.readFromClipboard(), liberator.open(util.readFromClipboard(),
/\bpaste\b/.test(options["activate"]) ? /\bpaste\b/.test(options["activate"]) ?
NEW_TAB : NEW_BACKGROUND_TAB); liberator.NEW_TAB : liberator.NEW_BACKGROUND_TAB);
}); });
// reloading // reloading
@@ -671,7 +671,7 @@ with (liberator) liberator.Buffer = function () //{{{
if (sel) if (sel)
util.copyToClipboard(sel, true); util.copyToClipboard(sel, true);
else else
beep(); liberator.beep();
}); });
// zooming // zooming
@@ -746,7 +746,7 @@ with (liberator) liberator.Buffer = function () //{{{
var aps = options.getPref("print.always_print_silent"); var aps = options.getPref("print.always_print_silent");
var spp = options.getPref("print.show_print_progress"); var spp = options.getPref("print.show_print_progress");
echo("Sending to printer..."); liberator.echo("Sending to printer...");
options.setPref("print.always_print_silent", special); options.setPref("print.always_print_silent", special);
options.setPref("print.show_print_progress", !special); options.setPref("print.show_print_progress", !special);
@@ -754,7 +754,7 @@ with (liberator) liberator.Buffer = function () //{{{
options.setPref("print.always_print_silent", aps); options.setPref("print.always_print_silent", aps);
options.setPref("print.show_print_progress", spp); options.setPref("print.show_print_progress", spp);
echo("Print job sent."); liberator.echo("Print job sent.");
}, },
{ {
argCount: "0", argCount: "0",
@@ -774,7 +774,7 @@ with (liberator) liberator.Buffer = function () //{{{
if (args && titles.indexOf(args) == -1) if (args && titles.indexOf(args) == -1)
{ {
echoerr("E475: Invalid argument: " + args); liberator.echoerr("E475: Invalid argument: " + args);
return; return;
} }
@@ -800,7 +800,7 @@ with (liberator) liberator.Buffer = function () //{{{
let doc = window.content.document; let doc = window.content.document;
let file = io.getFile(args || ""); let file = io.getFile(args || "");
if (args && file.exists() && !special) if (args && file.exists() && !special)
return echoerr("E13: File exists (add ! to override)"); return liberator.echoerr("E13: File exists (add ! to override)");
options.setPref("browser.download.lastDir", io.getCurrentDirectory()); options.setPref("browser.download.lastDir", io.getCurrentDirectory());
try try
@@ -850,7 +850,7 @@ with (liberator) liberator.Buffer = function () //{{{
{ {
let err = styles.addSheet(name, filter, css, false, special); let err = styles.addSheet(name, filter, css, false, special);
if (err) if (err)
echoerr(err); liberator.echoerr(err);
} }
}, },
{ {
@@ -955,7 +955,7 @@ with (liberator) liberator.Buffer = function () //{{{
} }
else else
{ {
echoerr("E488: Trailing characters"); liberator.echoerr("E488: Trailing characters");
return; return;
} }
@@ -1039,7 +1039,7 @@ with (liberator) liberator.Buffer = function () //{{{
nFeed++; nFeed++;
var type = feedTypes[feed.type] || feedTypes["application/rss+xml"]; var type = feedTypes[feed.type] || feedTypes["application/rss+xml"];
if (verbose) if (verbose)
yield [feed.title, template.highlightURL(feed.href, true) + <span class="extra-info"> ({type})</span>]; yield [feed.title, template.highlightURL(feed.href, true) + <span class="extra-info">\u00a0({type})</span>];
} }
} }
} }
@@ -1207,7 +1207,7 @@ with (liberator) liberator.Buffer = function () //{{{
class = highlightClasses.filter(function (i) i == class || i[0] == class)[0]; class = highlightClasses.filter(function (i) i == class || i[0] == class)[0];
if (!class) if (!class)
{ {
echoerr("Unknown highlight keyword"); liberator.echoerr("Unknown highlight keyword");
return; return;
} }
if (!(class instanceof Array)) if (!(class instanceof Array))
@@ -1228,7 +1228,7 @@ with (liberator) liberator.Buffer = function () //{{{
let error = styles.addSheet("hl-" + key, scope, css, true, force); let error = styles.addSheet("hl-" + key, scope, css, true, force);
if (error) if (error)
echoerr(error); liberator.echoerr(error);
else else
highlight.set(key, style); highlight.set(key, style);
}, },
@@ -1347,7 +1347,7 @@ with (liberator) liberator.Buffer = function () //{{{
revString = "next"; revString = "next";
break; break;
default: default:
echoerr("Bad document relationship: " + relationship); liberator.echoerr("Bad document relationship: " + relationship);
} }
relText = new RegExp(relationship, "i"); relText = new RegExp(relationship, "i");
@@ -1358,7 +1358,7 @@ with (liberator) liberator.Buffer = function () //{{{
{ {
if (relText.test(elems[i].rel) || revText.test(elems[i].rev)) if (relText.test(elems[i].rel) || revText.test(elems[i].rev))
{ {
open(elems[i].href); liberator.open(elems[i].href);
return true; return true;
} }
} }
@@ -1369,7 +1369,7 @@ with (liberator) liberator.Buffer = function () //{{{
{ {
if (relText.test(elems[i].rel) || revText.test(elems[i].rev)) if (relText.test(elems[i].rel) || revText.test(elems[i].rev))
{ {
buffer.followLink(elems[i], CURRENT_TAB); buffer.followLink(elems[i], liberator.CURRENT_TAB);
return true; return true;
} }
} }
@@ -1381,7 +1381,7 @@ with (liberator) liberator.Buffer = function () //{{{
{ {
if (patternText.test(elems[i].textContent)) if (patternText.test(elems[i].textContent))
{ {
buffer.followLink(elems[i], CURRENT_TAB); buffer.followLink(elems[i], liberator.CURRENT_TAB);
return true; return true;
} }
else else
@@ -1392,7 +1392,7 @@ with (liberator) liberator.Buffer = function () //{{{
{ {
if (patternText.test(children[j].alt)) if (patternText.test(children[j].alt))
{ {
buffer.followLink(elems[i], CURRENT_TAB); buffer.followLink(elems[i], liberator.CURRENT_TAB);
return true; return true;
} }
} }
@@ -1423,7 +1423,7 @@ with (liberator) liberator.Buffer = function () //{{{
} }
if (!retVal) if (!retVal)
beep(); liberator.beep();
}, },
// artificially "clicks" a link in order to open it // artificially "clicks" a link in order to open it
@@ -1450,18 +1450,18 @@ with (liberator) liberator.Buffer = function () //{{{
var ctrlKey = false, shiftKey = false; var ctrlKey = false, shiftKey = false;
switch (where) switch (where)
{ {
case NEW_TAB: case liberator.NEW_TAB:
case NEW_BACKGROUND_TAB: case liberator.NEW_BACKGROUND_TAB:
ctrlKey = true; ctrlKey = true;
shiftKey = (where == NEW_BACKGROUND_TAB); shiftKey = (where == liberator.NEW_BACKGROUND_TAB);
break; break;
case NEW_WINDOW: case liberator.NEW_WINDOW:
shiftKey = true; shiftKey = true;
break; break;
case CURRENT_TAB: case liberator.CURRENT_TAB:
break; break;
default: default:
log("Invalid where argument for followLink()", 0); liberator.log("Invalid where argument for followLink()", 0);
} }
elem.focus(); elem.focus();
@@ -1490,7 +1490,7 @@ with (liberator) liberator.Buffer = function () //{{{
} }
catch (e) catch (e)
{ {
echoerr(e); liberator.echoerr(e);
} }
}, },
@@ -1505,7 +1505,7 @@ with (liberator) liberator.Buffer = function () //{{{
const COL_WIDTH = 20; const COL_WIDTH = 20;
if (cols > 0 && win.scrollX >= win.scrollMaxX || cols < 0 && win.scrollX == 0) if (cols > 0 && win.scrollX >= win.scrollMaxX || cols < 0 && win.scrollX == 0)
beep(); liberator.beep();
win.scrollBy(COL_WIDTH * cols, 0); win.scrollBy(COL_WIDTH * cols, 0);
}, },
@@ -1604,7 +1604,7 @@ with (liberator) liberator.Buffer = function () //{{{
if (next > frames.length - 1) if (next > frames.length - 1)
{ {
if (current == frames.length - 1) if (current == frames.length - 1)
beep(); // still allow the frame indicator to be activated liberator.beep(); // still allow the frame indicator to be activated
next = frames.length - 1; next = frames.length - 1;
} }
@@ -1619,7 +1619,7 @@ with (liberator) liberator.Buffer = function () //{{{
if (next < 0) if (next < 0)
{ {
if (current == 0) if (current == 0)
beep(); // still allow the frame indicator to be activated liberator.beep(); // still allow the frame indicator to be activated
next = 0; next = 0;
} }
@@ -1643,7 +1643,7 @@ with (liberator) liberator.Buffer = function () //{{{
// TODO: print more useful information, just like the DOM inspector // TODO: print more useful information, just like the DOM inspector
showElementInfo: function (elem) showElementInfo: function (elem)
{ {
echo(<>Element:<br/></> + util.objectToString(elem), commandline.FORCE_MULTILINE); liberator.echo(<>Element:<br/></> + util.objectToString(elem), commandline.FORCE_MULTILINE);
}, },
showPageInfo: function (verbose) showPageInfo: function (verbose)
@@ -1663,7 +1663,7 @@ with (liberator) liberator.Buffer = function () //{{{
info += ", bookmarked"; info += ", bookmarked";
var pageInfoText = <>"{file}" [{info}] {title}</>; var pageInfoText = <>"{file}" [{info}] {title}</>;
echo(pageInfoText, commandline.FORCE_SINGLELINE); liberator.echo(pageInfoText, commandline.FORCE_SINGLELINE);
return; return;
} }
@@ -1674,7 +1674,7 @@ with (liberator) liberator.Buffer = function () //{{{
if (opt) if (opt)
return template.table(opt[1], opt[0](true)); return template.table(opt[1], opt[0](true));
}, <br/>); }, <br/>);
echo(list, commandline.FORCE_MULTILINE); liberator.echo(list, commandline.FORCE_MULTILINE);
}, },
viewSelectionSource: function () viewSelectionSource: function ()
@@ -1710,17 +1710,17 @@ with (liberator) liberator.Buffer = function () //{{{
var args = commands.parseArgs(editor, [], "*", true).arguments; var args = commands.parseArgs(editor, [], "*", true).arguments;
if (args.length < 1) if (args.length < 1)
{ {
echoerr("No editor specified"); liberator.echoerr("No editor specified");
return; return;
} }
var prog = args.shift(); var prog = args.shift();
args.push(url); args.push(url);
callFunctionInThread(null, io.run, [prog, args, true]); liberator.callFunctionInThread(null, io.run, [prog, args, true]);
} }
else else
{ {
open("view-source:" + url); liberator.open("view-source:" + url);
} }
}, },
@@ -1737,7 +1737,7 @@ with (liberator) liberator.Buffer = function () //{{{
//}}} //}}}
}; //}}} }; //}}}
with (liberator) liberator.Marks = function () //{{{ function Marks() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -1785,7 +1785,7 @@ with (liberator) liberator.Marks = function () //{{{
{ {
if (localmark[i].location == win.location.href) if (localmark[i].location == win.location.href)
{ {
log("Deleting local mark: " + markToString(mark, localmark[i]), 5); liberator.log("Deleting local mark: " + markToString(mark, localmark[i]), 5);
localmark.splice(i, 1); localmark.splice(i, 1);
if (localmark.length == 0) if (localmark.length == 0)
localMarks.remove(mark); localMarks.remove(mark);
@@ -1800,7 +1800,7 @@ with (liberator) liberator.Marks = function () //{{{
var urlmark = urlMarks.get(mark); var urlmark = urlMarks.get(mark);
if (urlmark) if (urlmark)
{ {
log("Deleting URL mark: " + markToString(mark, urlmark), 5); liberator.log("Deleting URL mark: " + markToString(mark, urlmark), 5);
urlMarks.remove(mark); urlMarks.remove(mark);
} }
} }
@@ -1849,7 +1849,7 @@ with (liberator) liberator.Marks = function () //{{{
{ {
if (/[^a-zA-Z]/.test(arg)) if (/[^a-zA-Z]/.test(arg))
{ {
beep(); liberator.beep();
return; return;
} }
@@ -1872,12 +1872,12 @@ with (liberator) liberator.Marks = function () //{{{
{ {
if (!special && !args) if (!special && !args)
{ {
echoerr("E471: Argument required"); liberator.echoerr("E471: Argument required");
return; return;
} }
if (special && args) if (special && args)
{ {
echoerr("E474: Invalid argument"); liberator.echoerr("E474: Invalid argument");
return; return;
} }
var matches; var matches;
@@ -1886,7 +1886,7 @@ with (liberator) liberator.Marks = function () //{{{
// NOTE: this currently differs from Vim's behavior which // NOTE: this currently differs from Vim's behavior which
// deletes any valid marks in the arg list, up to the first // deletes any valid marks in the arg list, up to the first
// invalid arg, as well as giving the error message. // invalid arg, as well as giving the error message.
echoerr("E475: Invalid argument: " + matches[0]); liberator.echoerr("E475: Invalid argument: " + matches[0]);
return; return;
} }
// check for illegal ranges - only allow a-z A-Z 0-9 // check for illegal ranges - only allow a-z A-Z 0-9
@@ -1901,7 +1901,7 @@ with (liberator) liberator.Marks = function () //{{{
/[0-9]/.test(start) != /[0-9]/.test(end) || /[0-9]/.test(start) != /[0-9]/.test(end) ||
start > end) start > end)
{ {
echoerr("E475: Invalid argument: " + args.match(matches[i] + ".*")[0]); liberator.echoerr("E475: Invalid argument: " + args.match(matches[i] + ".*")[0]);
return; return;
} }
} }
@@ -1918,12 +1918,12 @@ with (liberator) liberator.Marks = function () //{{{
var mark = args.arguments[0]; var mark = args.arguments[0];
if (mark.length > 1) if (mark.length > 1)
{ {
echoerr("E488: Trailing characters"); liberator.echoerr("E488: Trailing characters");
return; return;
} }
if (!/[a-zA-Z]/.test(mark)) if (!/[a-zA-Z]/.test(mark))
{ {
echoerr("E191: Argument must be a letter or forward/backward quote"); liberator.echoerr("E191: Argument must be a letter or forward/backward quote");
return; return;
} }
@@ -1938,7 +1938,7 @@ with (liberator) liberator.Marks = function () //{{{
// ignore invalid mark characters unless there are no valid mark chars // ignore invalid mark characters unless there are no valid mark chars
if (args && !/[a-zA-Z]/.test(args)) if (args && !/[a-zA-Z]/.test(args))
{ {
echoerr("E283: No marks matching \"" + args + "\""); liberator.echoerr("E283: No marks matching \"" + args + "\"");
return; return;
} }
@@ -1959,7 +1959,7 @@ with (liberator) liberator.Marks = function () //{{{
if (win.document.body.localName.toLowerCase() == "frameset") if (win.document.body.localName.toLowerCase() == "frameset")
{ {
echoerr("Marks support for frameset pages not implemented yet"); liberator.echoerr("Marks support for frameset pages not implemented yet");
return; return;
} }
@@ -1970,7 +1970,7 @@ with (liberator) liberator.Marks = function () //{{{
if (isURLMark(mark)) if (isURLMark(mark))
{ {
urlMarks.set(mark, { location: win.location.href, position: position, tab: tabs.getTab() }); urlMarks.set(mark, { location: win.location.href, position: position, tab: tabs.getTab() });
log("Adding URL mark: " + markToString(mark, urlMarks.get(mark)), 5); liberator.log("Adding URL mark: " + markToString(mark, urlMarks.get(mark)), 5);
} }
else if (isLocalMark(mark)) else if (isLocalMark(mark))
{ {
@@ -1980,7 +1980,7 @@ with (liberator) liberator.Marks = function () //{{{
localMarks.set(mark, []); localMarks.set(mark, []);
let vals = { location: win.location.href, position: position }; let vals = { location: win.location.href, position: position };
localMarks.get(mark).push(vals); localMarks.get(mark).push(vals);
log("Adding local mark: " + markToString(mark, vals), 5); liberator.log("Adding local mark: " + markToString(mark, vals), 5);
} }
}, },
@@ -2022,7 +2022,7 @@ with (liberator) liberator.Marks = function () //{{{
pendingJumps.push(slice); pendingJumps.push(slice);
// NOTE: this obviously won't work on generated pages using // NOTE: this obviously won't work on generated pages using
// non-unique URLs :( // non-unique URLs :(
open(slice.location, NEW_TAB); liberator.open(slice.location, liberator.NEW_TAB);
return; return;
} }
var index = tabs.index(slice.tab); var index = tabs.index(slice.tab);
@@ -2036,7 +2036,7 @@ with (liberator) liberator.Marks = function () //{{{
win.location.href = slice.location; win.location.href = slice.location;
return; return;
} }
log("Jumping to URL mark: " + markToString(mark, slice), 5); liberator.log("Jumping to URL mark: " + markToString(mark, slice), 5);
win.scrollTo(slice.position.x * win.scrollMaxX, slice.position.y * win.scrollMaxY); win.scrollTo(slice.position.x * win.scrollMaxX, slice.position.y * win.scrollMaxY);
ok = true; ok = true;
} }
@@ -2051,7 +2051,7 @@ with (liberator) liberator.Marks = function () //{{{
{ {
if (win.location.href == slice[i].location) if (win.location.href == slice[i].location)
{ {
log("Jumping to local mark: " + markToString(mark, slice[i]), 5); liberator.log("Jumping to local mark: " + markToString(mark, slice[i]), 5);
win.scrollTo(slice[i].position.x * win.scrollMaxX, slice[i].position.y * win.scrollMaxY); win.scrollTo(slice[i].position.x * win.scrollMaxX, slice[i].position.y * win.scrollMaxY);
ok = true; ok = true;
} }
@@ -2059,7 +2059,7 @@ with (liberator) liberator.Marks = function () //{{{
} }
if (!ok) if (!ok)
echoerr("E20: Mark not set"); // FIXME: move up? liberator.echoerr("E20: Mark not set"); // FIXME: move up?
}, },
list: function (filter) list: function (filter)
@@ -2068,7 +2068,7 @@ with (liberator) liberator.Marks = function () //{{{
if (marks.length == 0) if (marks.length == 0)
{ {
echoerr("No marks set"); liberator.echoerr("No marks set");
return; return;
} }
@@ -2077,7 +2077,7 @@ with (liberator) liberator.Marks = function () //{{{
marks = marks.filter(function (mark) filter.indexOf(mark[0]) >= 0); marks = marks.filter(function (mark) filter.indexOf(mark[0]) >= 0);
if (marks.length == 0) if (marks.length == 0)
{ {
echoerr("E283: No marks matching \"" + filter + "\""); liberator.echoerr("E283: No marks matching \"" + filter + "\"");
return; return;
} }
} }

View File

@@ -28,7 +28,7 @@ the terms of any one of the MPL, the GPL or the LGPL.
// Do NOT create instances of this class yourself, use the helper method // Do NOT create instances of this class yourself, use the helper method
// commands.add() instead // commands.add() instead
with (liberator) liberator.Command = function (specs, description, action, extraInfo) //{{{ function Command(specs, description, action, extraInfo) //{{{
{ {
if (!specs || !action) if (!specs || !action)
return null; return null;
@@ -86,7 +86,7 @@ with (liberator) liberator.Command = function (specs, description, action, extra
this.replacementText = extraInfo.replacementText || null; this.replacementText = extraInfo.replacementText || null;
}; };
with (liberator) liberator.Command.prototype = { Command.prototype = {
execute: function (args, special, count, modifiers) execute: function (args, special, count, modifiers)
{ {
@@ -151,7 +151,7 @@ with (liberator) liberator.Command.prototype = {
}; //}}} }; //}}}
with (liberator) liberator.Commands = function () //{{{ function Commands() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -195,7 +195,7 @@ with (liberator) liberator.Commands = function () //{{{
return NaN; return NaN;
} }
const ArgType = new util.Struct("description", "parse"); const ArgType = new Struct("description", "parse");
const argTypes = [ const argTypes = [
null, null,
["no arg", function (arg) !arg], ["no arg", function (arg) !arg],
@@ -246,7 +246,7 @@ with (liberator) liberator.Commands = function () //{{{
if (exCommands[i].name == command.name) if (exCommands[i].name == command.name)
{ {
// never replace for now // never replace for now
log("Warning: :" + names[0] + " already exists, NOT replacing existing command.", 1); liberator.log("Warning: :" + names[0] + " already exists, NOT replacing existing command.", 1);
return false; return false;
} }
} }
@@ -479,7 +479,7 @@ with (liberator) liberator.Commands = function () //{{{
} }
var sub = str.substr(i); var sub = str.substr(i);
//dump(i + ": " + sub + " - " + onlyArgumentsRemaining + "\n"); //liberator.dump(i + ": " + sub + " - " + onlyArgumentsRemaining + "\n");
if ((!onlyArgumentsRemaining) && /^--(\s|$)/.test(sub)) if ((!onlyArgumentsRemaining) && /^--(\s|$)/.test(sub))
{ {
onlyArgumentsRemaining = true; onlyArgumentsRemaining = true;
@@ -536,7 +536,7 @@ with (liberator) liberator.Commands = function () //{{{
{ {
if (!complete) if (!complete)
{ {
echoerr("Invalid argument for option " + optname); liberator.echoerr("Invalid argument for option " + optname);
return null; return null;
} }
let compl = opt[3] || []; let compl = opt[3] || [];
@@ -554,7 +554,7 @@ with (liberator) liberator.Commands = function () //{{{
arg = type.parse(arg); arg = type.parse(arg);
if (arg == null || arg == NaN) if (arg == null || arg == NaN)
{ {
echoerr("Invalid argument for " + type.description + "option: " + optname); liberator.echoerr("Invalid argument for " + type.description + "option: " + optname);
return null; return null;
} }
} }
@@ -564,7 +564,7 @@ with (liberator) liberator.Commands = function () //{{{
{ {
if (opt[2].call(this, arg) == false) if (opt[2].call(this, arg) == false)
{ {
echoerr("Invalid argument for option: " + optname); liberator.echoerr("Invalid argument for option: " + optname);
return null; return null;
} }
} }
@@ -589,12 +589,12 @@ with (liberator) liberator.Commands = function () //{{{
var [count, arg] = getNextArg(sub); var [count, arg] = getNextArg(sub);
if (count == -1) if (count == -1)
{ {
echoerr("Error parsing arguments: " + arg); liberator.echoerr("Error parsing arguments: " + arg);
return null; return null;
} }
else if (!onlyArgumentsRemaining && /^-/.test(arg)) else if (!onlyArgumentsRemaining && /^-/.test(arg))
{ {
echoerr("Invalid option: " + arg); liberator.echoerr("Invalid option: " + arg);
return null; return null;
} }
@@ -610,13 +610,13 @@ with (liberator) 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 == "+"))
{ {
echoerr("E471: Argument required"); liberator.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 == "?"))
{ {
echoerr("E488: Trailing characters"); liberator.echoerr("E488: Trailing characters");
return null; return null;
} }
@@ -705,7 +705,7 @@ with (liberator) liberator.Commands = function () //{{{
count: this.count && count count: this.count && count
}; };
execute(commands.replaceTokens(this.replacementText, tokens)); liberator.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 @@ with (liberator) 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))
{ {
echoerr("E182: Invalid command name"); liberator.echoerr("E182: Invalid command name");
return; return;
} }
@@ -740,7 +740,7 @@ with (liberator) liberator.Commands = function () //{{{
special) special)
) )
{ {
echoerr("E174: Command already exists: add ! to replace it"); liberator.echoerr("E174: Command already exists: add ! to replace it");
} }
} }
else else
@@ -765,7 +765,7 @@ with (liberator) liberator.Commands = function () //{{{
} }
else else
{ {
echo("No user-defined commands found"); liberator.echo("No user-defined commands found");
} }
} }
}, },
@@ -805,7 +805,7 @@ with (liberator) liberator.Commands = function () //{{{
} }
} }
echoerr("E184: No such user-defined command: " + name); liberator.echoerr("E184: No such user-defined command: " + name);
}, },
{ {
argCount: "1", argCount: "1",

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 *****/
with (liberator) liberator.Completion = function () //{{{ function Completion() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -190,8 +190,8 @@ with (liberator) liberator.Completion = function () //{{{
{ {
try try
{ {
// dump("eval(" + util.escapeString(arg) + ")\n"); // liberator.dump("eval(" + util.escapeString(arg) + ")\n");
return eval(arg); return liberator.eval(arg);
} }
catch (e) catch (e)
{ {
@@ -339,7 +339,7 @@ with (liberator) liberator.Completion = function () //{{{
} }
catch (e) catch (e)
{ {
dump(util.escapeString(string) + ": " + e + "\n" + e.stack); liberator.dump(util.escapeString(string) + ": " + e + "\n" + e.stack);
lastIdx = 0; lastIdx = 0;
return [0, []]; return [0, []];
} }
@@ -871,7 +871,7 @@ with (liberator) 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){dump(e)} }catch(e){liberator.dump(e)}
}, },
help: function help(filter) help: function help(filter)
@@ -889,7 +889,7 @@ with (liberator) liberator.Completion = function () //{{{
} }
catch (e) catch (e)
{ {
log("Error opening chrome://liberator/locale/" + files[i], 1); liberator.log("Error opening chrome://liberator/locale/" + files[i], 1);
continue; continue;
} }
var doc = xmlhttp.responseXML; var doc = xmlhttp.responseXML;
@@ -913,7 +913,7 @@ with (liberator) liberator.Completion = function () //{{{
} }
catch (e) catch (e)
{ {
dump(e); liberator.dump(e);
return [0, []]; return [0, []];
} }
}, },
@@ -932,14 +932,14 @@ with (liberator) liberator.Completion = function () //{{{
let engines = this.filter(keywords.concat(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 hist = history.get();
let searches = []; let searches = [];
for (let [, k] in Iterator(keywords)) for (let [, k] in Iterator(keywords))
{ {
if (k[0].toLowerCase() != keyword.toLowerCase() || k[3].indexOf("%s") == -1) if (k[0].toLowerCase() != keyword.toLowerCase() || k[3].indexOf("%s") == -1)
continue; continue;
let [begin, end] = k[3].split("%s"); let [begin, end] = k[3].split("%s");
for (let [, h] in Iterator(history)) for (let [, h] in Iterator(hist))
{ {
if (h[0].indexOf(begin) == 0 && (!end.length || h[0].substr(-end.length) == end)) if (h[0].indexOf(begin) == 0 && (!end.length || h[0].substr(-end.length) == end))
{ {

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
with (liberator) liberator.Editor = function () //{{{ function Editor() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -229,7 +229,7 @@ with (liberator) liberator.Editor = function () //{{{
mappings.add(myModes, 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 " + config.hostApplication + " key bindings", "Ignore certain " + config.hostApplication + " key bindings",
function () { /*beep();*/ }); function () { /*liberator.beep();*/ });
mappings.add(myModes, mappings.add(myModes,
["<C-w>"], "Delete previous word", ["<C-w>"], "Delete previous word",
@@ -285,7 +285,7 @@ with (liberator) liberator.Editor = function () //{{{
// FIXME: <esc> does not work correctly // FIXME: <esc> does not work correctly
mappings.add([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 = modes.TEXTAREA; });
mappings.add([modes.INSERT], mappings.add([modes.INSERT],
["<Space>", "<Return>"], "Expand insert mode abbreviation", ["<Space>", "<Return>"], "Expand insert mode abbreviation",
@@ -306,7 +306,7 @@ with (liberator) liberator.Editor = function () //{{{
function (count) function (count)
{ {
editor.executeCommand("cmd_undo", count); editor.executeCommand("cmd_undo", count);
liberator.mode = liberator.modes.TEXTAREA; liberator.mode = modes.TEXTAREA;
}, },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
@@ -315,7 +315,7 @@ with (liberator) liberator.Editor = function () //{{{
function (count) function (count)
{ {
editor.executeCommand("cmd_redo", count); editor.executeCommand("cmd_redo", count);
liberator.mode = liberator.modes.TEXTAREA; liberator.mode = modes.TEXTAREA;
}, },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
@@ -355,7 +355,7 @@ with (liberator) liberator.Editor = function () //{{{
// visual mode // visual mode
mappings.add([modes.CARET, modes.TEXTAREA, modes.VISUAL], mappings.add([modes.CARET, modes.TEXTAREA, modes.VISUAL],
["v"], "Start visual mode", ["v"], "Start visual mode",
function (count) { modes.set(modes.VISUAL, mode); }); function (count) { modes.set(modes.VISUAL, liberator.mode); });
mappings.add([modes.TEXTAREA], mappings.add([modes.TEXTAREA],
["V"], "Start visual line mode", ["V"], "Start visual line mode",
@@ -376,7 +376,7 @@ with (liberator) liberator.Editor = function () //{{{
modes.set(modes.INSERT, modes.TEXTAREA); modes.set(modes.INSERT, modes.TEXTAREA);
} }
else else
beep(); liberator.beep();
}); });
mappings.add([modes.VISUAL], mappings.add([modes.VISUAL],
@@ -389,7 +389,7 @@ with (liberator) liberator.Editor = function () //{{{
modes.set(modes.TEXTAREA); modes.set(modes.TEXTAREA);
} }
else else
beep(); liberator.beep();
}); });
mappings.add([modes.VISUAL], mappings.add([modes.VISUAL],
@@ -407,7 +407,7 @@ with (liberator) liberator.Editor = function () //{{{
if (sel) if (sel)
util.copyToClipboard(sel, true); util.copyToClipboard(sel, true);
else else
beep(); liberator.beep();
} }
}); });
@@ -420,10 +420,10 @@ with (liberator) liberator.Editor = function () //{{{
if (!count) count = 1; if (!count) count = 1;
while (count--) while (count--)
editor.executeCommand("cmd_paste"); editor.executeCommand("cmd_paste");
liberator.mode = liberator.modes.TEXTAREA; liberator.mode = modes.TEXTAREA;
} }
else else
beep(); liberator.beep();
}); });
// finding characters // finding characters
@@ -433,7 +433,7 @@ with (liberator) liberator.Editor = function () //{{{
{ {
var pos = editor.findCharForward(arg, count); var pos = editor.findCharForward(arg, count);
if (pos >= 0) if (pos >= 0)
editor.moveToPosition(pos, true, mode == modes.VISUAL); editor.moveToPosition(pos, true, liberator.mode == modes.VISUAL);
}, },
{ flags: Mappings.flags.ARGUMENT | Mappings.flags.COUNT }); { flags: Mappings.flags.ARGUMENT | Mappings.flags.COUNT });
@@ -443,7 +443,7 @@ with (liberator) liberator.Editor = function () //{{{
{ {
var pos = editor.findCharBackward(arg, count); var pos = editor.findCharBackward(arg, count);
if (pos >= 0) if (pos >= 0)
editor.moveToPosition(pos, false, mode == modes.VISUAL); editor.moveToPosition(pos, false, liberator.mode == modes.VISUAL);
}, },
{ flags: Mappings.flags.ARGUMENT | Mappings.flags.COUNT }); { flags: Mappings.flags.ARGUMENT | Mappings.flags.COUNT });
@@ -453,7 +453,7 @@ with (liberator) liberator.Editor = function () //{{{
{ {
var pos = editor.findCharForward(arg, count); var pos = editor.findCharForward(arg, count);
if (pos >= 0) if (pos >= 0)
editor.moveToPosition(pos - 1, true, mode == modes.VISUAL); editor.moveToPosition(pos - 1, true, liberator.mode == modes.VISUAL);
}, },
{ flags: Mappings.flags.ARGUMENT | Mappings.flags.COUNT }); { flags: Mappings.flags.ARGUMENT | Mappings.flags.COUNT });
@@ -463,7 +463,7 @@ with (liberator) liberator.Editor = function () //{{{
{ {
var pos = editor.findCharBackward(arg, count); var pos = editor.findCharBackward(arg, count);
if (pos >= 0) if (pos >= 0)
editor.moveToPosition(pos + 1, false, mode == modes.VISUAL); editor.moveToPosition(pos + 1, false, liberator.mode == modes.VISUAL);
}, },
{ flags: Mappings.flags.ARGUMENT | Mappings.flags.COUNT }); { flags: Mappings.flags.ARGUMENT | Mappings.flags.COUNT });
@@ -487,7 +487,7 @@ with (liberator) liberator.Editor = function () //{{{
var pos = getEditor().selectionStart; var pos = getEditor().selectionStart;
if (pos >= text.length) if (pos >= text.length)
{ {
beep(); liberator.beep();
return; return;
} }
var chr = text[pos]; var chr = text[pos];
@@ -575,7 +575,7 @@ with (liberator) 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))
{ {
beep(); liberator.beep();
return false; return false;
} }
@@ -596,7 +596,7 @@ with (liberator) liberator.Editor = function () //{{{
catch (e) catch (e)
{ {
if (!didCommand) if (!didCommand)
beep(); liberator.beep();
return false; return false;
} }
} }
@@ -662,7 +662,7 @@ with (liberator) liberator.Editor = function () //{{{
break; break;
default: default:
beep(); liberator.beep();
return false; return false;
} }
@@ -683,7 +683,7 @@ with (liberator) liberator.Editor = function () //{{{
break; break;
default: default:
beep(); liberator.beep();
return false; return false;
} }
return true; return true;
@@ -748,7 +748,7 @@ with (liberator) liberator.Editor = function () //{{{
return i + 1; // always position the cursor after the char return i + 1; // always position the cursor after the char
} }
beep(); liberator.beep();
return -1; return -1;
}, },
@@ -775,7 +775,7 @@ with (liberator) liberator.Editor = function () //{{{
return i; return i;
} }
beep(); liberator.beep();
return -1; return -1;
}, },
@@ -798,7 +798,7 @@ with (liberator) liberator.Editor = function () //{{{
var args = commands.parseArgs(editor, [], "*", true).arguments; var args = commands.parseArgs(editor, [], "*", true).arguments;
if (args.length < 1) if (args.length < 1)
{ {
echoerr("No editor specified"); liberator.echoerr("No editor specified");
return false; return false;
} }
@@ -808,7 +808,7 @@ with (liberator) liberator.Editor = function () //{{{
} }
catch (e) catch (e)
{ {
echoerr("Could not create temporary file: " + e.message); liberator.echoerr("Could not create temporary file: " + e.message);
return false; return false;
} }
try try
@@ -817,7 +817,7 @@ with (liberator) liberator.Editor = function () //{{{
} }
catch (e) catch (e)
{ {
echoerr("Could not write to temporary file " + tmpfile.path + ": " + e.message); liberator.echoerr("Could not write to temporary file " + tmpfile.path + ": " + e.message);
return false; return false;
} }
@@ -833,7 +833,7 @@ with (liberator) liberator.Editor = function () //{{{
} }
// TODO: save return value in v:shell_error // TODO: save return value in v:shell_error
callFunctionInThread(null, io.run, [prog, args, true]); liberator.callFunctionInThread(null, io.run, [prog, args, true]);
if (textBox) if (textBox)
textBox.removeAttribute("readonly"); textBox.removeAttribute("readonly");
@@ -841,7 +841,7 @@ with (liberator) liberator.Editor = function () //{{{
// if (v:shell_error != 0) // if (v:shell_error != 0)
// { // {
// tmpBg = "red"; // tmpBg = "red";
// echoerr("External editor returned with exit code " + retcode); // liberator.echoerr("External editor returned with exit code " + retcode);
// } // }
// else // else
// { // {
@@ -868,7 +868,7 @@ with (liberator) liberator.Editor = function () //{{{
catch (e) catch (e)
{ {
tmpBg = "red"; tmpBg = "red";
echoerr("Could not read from temporary file " + tmpfile.path + ": " + e.message); liberator.echoerr("Could not read from temporary file " + tmpfile.path + ": " + e.message);
} }
// } // }
@@ -915,11 +915,11 @@ with (liberator) 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)
echo(abbrev[lhs][i][0] + " " + lhs + " " + abbrev[lhs][i][1]); liberator.echo(abbrev[lhs][i][0] + " " + lhs + " " + abbrev[lhs][i][1]);
return true; return true;
} }
} }
echoerr("No abbreviations found"); liberator.echoerr("No abbreviations found");
return false; return false;
} }
else // list all (for that filter {i,c,!}) else // list all (for that filter {i,c,!})
@@ -943,7 +943,7 @@ with (liberator) liberator.Editor = function () //{{{
if (list.*.length()) if (list.*.length())
commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE); commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
else else
echoerr("No abbreviations found"); liberator.echoerr("No abbreviations found");
} }
}, },
@@ -1033,7 +1033,7 @@ with (liberator) liberator.Editor = function () //{{{
{ {
if (!lhs) if (!lhs)
{ {
echoerr("E474: Invalid argument"); liberator.echoerr("E474: Invalid argument");
return false; return false;
} }
@@ -1071,7 +1071,7 @@ with (liberator) liberator.Editor = function () //{{{
} }
} }
echoerr("E24: No such abbreviation"); liberator.echoerr("E24: No such abbreviation");
return false; return false;
}, },

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 *****/
with (liberator) liberator.AutoCommands = function () //{{{ function AutoCommands() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -83,7 +83,7 @@ with (liberator) liberator.AutoCommands = function () //{{{
events = event.split(","); events = event.split(",");
if (!events.every(function (event) validEvents.indexOf(event) >= 0)) if (!events.every(function (event) validEvents.indexOf(event) >= 0))
{ {
echoerr("E216: No such group or event: " + event); liberator.echoerr("E216: No such group or event: " + event);
return; return;
} }
} }
@@ -144,18 +144,18 @@ with (liberator) liberator.AutoCommands = function () //{{{
if (event == "*") if (event == "*")
{ {
echoerr("E217: Can't execute autocommands for ALL events"); liberator.echoerr("E217: Can't execute autocommands for ALL events");
} }
else if (validEvents.indexOf(event) == -1) else if (validEvents.indexOf(event) == -1)
{ {
echoerr("E216: No such group or event: " + args); liberator.echoerr("E216: No such group or event: " + args);
} }
else else
{ {
// TODO: perhaps trigger could return the number of autocmds triggered // TODO: perhaps trigger could return the number of autocmds triggered
// TODO: Perhaps this should take -args to pass to the command? // TODO: Perhaps this should take -args to pass to the command?
if (!autocommands.get(event).some(function (c) c.pattern.test(url))) if (!autocommands.get(event).some(function (c) c.pattern.test(url)))
echo("No matching autocommands"); liberator.echo("No matching autocommands");
else else
autocommands.trigger(event, {url: url}); autocommands.trigger(event, {url: url});
} }
@@ -184,7 +184,7 @@ with (liberator) liberator.AutoCommands = function () //{{{
if (typeof events == "string") if (typeof events == "string")
{ {
events = events.split(","); events = events.split(",");
log("DEPRECATED: the events list arg to autocommands.add() should be an array of event names"); liberator.log("DEPRECATED: the events list arg to autocommands.add() should be an array of event names");
} }
events.forEach(function (event) events.forEach(function (event)
store.push({event: event, pattern: RegExp(regex), command: cmd})); store.push({event: event, pattern: RegExp(regex), command: cmd}));
@@ -242,7 +242,7 @@ with (liberator) liberator.AutoCommands = function () //{{{
let autoCmds = store.filter(function (autoCmd) autoCmd.event == event); let autoCmds = store.filter(function (autoCmd) autoCmd.event == event);
echomsg("Executing " + event + " Auto commands for \"*\"", 8); liberator.echomsg("Executing " + event + " Auto commands for \"*\"", 8);
let lastPattern = null; let lastPattern = null;
@@ -252,12 +252,12 @@ with (liberator) liberator.AutoCommands = function () //{{{
if (autoCmd.pattern.test(url)) if (autoCmd.pattern.test(url))
{ {
if (!lastPattern || lastPattern.source != autoCmd.pattern.source) if (!lastPattern || lastPattern.source != autoCmd.pattern.source)
echomsg("Executing " + event + " Auto commands for \"" + autoCmd.pattern.source + "\"", 8); liberator.echomsg("Executing " + event + " Auto commands for \"" + autoCmd.pattern.source + "\"", 8);
lastPattern = autoCmd.pattern; lastPattern = autoCmd.pattern;
echomsg("autocommand " + autoCmd.command, 9); liberator.echomsg("autocommand " + autoCmd.command, 9);
execute(commands.replaceTokens(autoCmd.command, args)); liberator.execute(commands.replaceTokens(autoCmd.command, args));
} }
} }
} }
@@ -265,12 +265,14 @@ with (liberator) liberator.AutoCommands = function () //{{{
//}}} //}}}
}; //}}} }; //}}}
with (liberator) liberator.Events = function () //{{{ function Events() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{ /////////////////////////////////////////////////////////////////////////////{{{
const input = liberator.input;
var inputBufferLength = 0; // count the number of keys in v.input.buffer (can be different from v.input.buffer.length) var inputBufferLength = 0; // count the number of keys in v.input.buffer (can be different from v.input.buffer.length)
var skipMap = false; // while feeding the keys (stored in v.input.buffer | no map found) - ignore mappings var skipMap = false; // while feeding the keys (stored in v.input.buffer | no map found) - ignore mappings
@@ -306,7 +308,7 @@ with (liberator) liberator.Events = function () //{{{
tabs.updateSelectionHistory(); tabs.updateSelectionHistory();
if (options["focuscontent"]) if (options["focuscontent"])
setTimeout(function () { focusContent(true); }, 10); // just make sure, that no widget has focus setTimeout(function () { liberator.focusContent(true); }, 10); // just make sure, that no widget has focus
}, false); }, false);
} }
@@ -365,7 +367,7 @@ with (liberator) liberator.Events = function () //{{{
// window.document.addEventListener("DOMTitleChanged", function (event) // window.document.addEventListener("DOMTitleChanged", function (event)
// { // {
// log("titlechanged"); // liberator.log("titlechanged");
// }, null); // }, null);
// NOTE: the order of ["Esc", "Escape"] or ["Escape", "Esc"] // NOTE: the order of ["Esc", "Escape"] or ["Escape", "Esc"]
@@ -523,7 +525,7 @@ with (liberator) liberator.Events = function () //{{{
} }
else // background tab else // background tab
{ {
echomsg("Background tab loaded: " + title || url, 1); liberator.echomsg("Background tab loaded: " + title || url, 1);
} }
triggerLoadAutocmd("PageLoad", doc); triggerLoadAutocmd("PageLoad", doc);
@@ -541,12 +543,12 @@ with (liberator) liberator.Events = function () //{{{
catch (e) catch (e)
{ {
if (e.message == "Interrupted") if (e.message == "Interrupted")
echoerr("Interrupted"); liberator.echoerr("Interrupted");
else else
echoerr("Processing " + event.type + " event: " + (e.echoerr || e)); liberator.echoerr("Processing " + event.type + " event: " + (e.echoerr || e));
liberator.dump(e);
if (Components.utils.reportError) if (Components.utils.reportError)
Components.utils.reportError(e); Components.utils.reportError(e);
liberator.dump(e);
} }
} }
} }
@@ -554,8 +556,8 @@ with (liberator) liberator.Events = function () //{{{
// return true when load successful, or false otherwise // return true when load successful, or false otherwise
function waitForPageLoaded() function waitForPageLoaded()
{ {
dump("start waiting in loaded state: " + buffer.loaded); liberator.dump("start waiting in loaded state: " + buffer.loaded);
threadYield(true); // clear queue liberator.threadYield(true); // clear queue
if (buffer.loaded == 1) if (buffer.loaded == 1)
return true; return true;
@@ -564,32 +566,32 @@ with (liberator) liberator.Events = function () //{{{
var then = new Date().getTime(); var then = new Date().getTime();
for (let now = then; now - then < ms; now = new Date().getTime()) for (let now = then; now - then < ms; now = new Date().getTime())
{ {
threadYield(); liberator.threadYield();
if ((now - then) % 1000 < 10) if ((now - then) % 1000 < 10)
dump("waited: " + (now - then) + " ms"); liberator.dump("waited: " + (now - then) + " ms");
if (!events.feedingKeys) if (!events.feedingKeys)
return false; return false;
if (buffer.loaded > 0) if (buffer.loaded > 0)
{ {
sleep(250); liberator.sleep(250);
break; break;
} }
else else
echo("Waiting for page to load..."); liberator.echo("Waiting for page to load...");
} }
modes.show(); modes.show();
// TODO: allow macros to be continued when page does not fully load with an option // TODO: allow macros to be continued when page does not fully load with an option
var ret = (buffer.loaded == 1); var ret = (buffer.loaded == 1);
if (!ret) if (!ret)
echoerr("Page did not load completely in " + ms + " milliseconds. Macro stopped."); liberator.echoerr("Page did not load completely in " + ms + " milliseconds. Macro stopped.");
dump("done waiting: " + ret); liberator.dump("done waiting: " + ret);
// sometimes the input widget had focus when replaying a macro // sometimes the input widget had focus when replaying a macro
// maybe this call should be moved somewhere else? // maybe this call should be moved somewhere else?
// focusContent(true); // liberator.focusContent(true);
return ret; return ret;
} }
@@ -606,9 +608,9 @@ with (liberator) liberator.Events = function () //{{{
{ {
for (let [,dir] in Iterator(dirs)) for (let [,dir] in Iterator(dirs))
{ {
echomsg("Searching for \"macros/*\" in \"" + dir.path + "\"", 2); liberator.echomsg("Searching for \"macros/*\" in \"" + dir.path + "\"", 2);
log("Sourcing macros directory: " + dir.path + "...", 3); liberator.log("Sourcing macros directory: " + dir.path + "...", 3);
let files = io.readDirectory(dir.path); let files = io.readDirectory(dir.path);
@@ -620,19 +622,19 @@ with (liberator) liberator.Events = function () //{{{
let name = file.leafName.replace(/\.vimp$/i, ""); let name = file.leafName.replace(/\.vimp$/i, "");
macros.set(name, io.readFile(file).split("\n")[0]); macros.set(name, io.readFile(file).split("\n")[0]);
log("Macro " + name + " added: " + macros.get(name), 5); liberator.log("Macro " + name + " added: " + macros.get(name), 5);
}); });
} }
} }
else else
{ {
log("No user macros directory found", 3); liberator.log("No user macros directory found", 3);
} }
} }
catch (e) catch (e)
{ {
// thrown if directory does not exist // thrown if directory does not exist
log("Error sourcing macros directory: " + e, 9); liberator.log("Error sourcing macros directory: " + e, 9);
} }
}, 100); }, 100);
@@ -710,7 +712,7 @@ with (liberator) liberator.Events = function () //{{{
{ {
XML.prettyPrinting = false; XML.prettyPrinting = false;
var str = template.tabular(["Macro", "Keys"], [], events.getMacros(args)); var str = template.tabular(["Macro", "Keys"], [], events.getMacros(args));
echo(str, commandline.FORCE_MULTILINE); liberator.echo(str, commandline.FORCE_MULTILINE);
}, },
{ completer: function (filter) completion.macro(filter) }); { completer: function (filter) completion.macro(filter) });
@@ -735,7 +737,7 @@ with (liberator) liberator.Events = function () //{{{
destroy: function () destroy: function ()
{ {
// removeEventListeners() to avoid mem leaks // removeEventListeners() to avoid mem leaks
dump("TODO: remove all eventlisteners"); liberator.dump("TODO: remove all eventlisteners");
if (typeof getBrowser != "undefined") if (typeof getBrowser != "undefined")
getBrowser().removeProgressListener(this.progressListener); getBrowser().removeProgressListener(this.progressListener);
@@ -754,7 +756,7 @@ with (liberator) liberator.Events = function () //{{{
if (!/[a-zA-Z0-9]/.test(macro)) if (!/[a-zA-Z0-9]/.test(macro))
{ {
// TODO: ignore this like Vim? // TODO: ignore this like Vim?
echoerr("E354: Invalid register name: '" + macro + "'"); liberator.echoerr("E354: Invalid register name: '" + macro + "'");
return; return;
} }
@@ -778,7 +780,7 @@ with (liberator) liberator.Events = function () //{{{
var res = false; var res = false;
if (!/[a-zA-Z0-9@]/.test(macro) && macro.length == 1) if (!/[a-zA-Z0-9@]/.test(macro) && macro.length == 1)
{ {
echoerr("E354: Invalid register name: '" + macro + "'"); liberator.echoerr("E354: Invalid register name: '" + macro + "'");
return false; return false;
} }
@@ -786,7 +788,7 @@ with (liberator) liberator.Events = function () //{{{
{ {
if (!lastMacro) if (!lastMacro)
{ {
echoerr("E748: No previously used register"); liberator.echoerr("E748: No previously used register");
return false; return false;
} }
} }
@@ -816,9 +818,9 @@ with (liberator) liberator.Events = function () //{{{
{ {
if (lastMacro.length == 1) if (lastMacro.length == 1)
// TODO: ignore this like Vim? // TODO: ignore this like Vim?
echoerr("Exxx: Register " + lastMacro + " not set"); liberator.echoerr("Exxx: Register " + lastMacro + " not set");
else else
echoerr("Exxx: Named macro '" + lastMacro + "' not set"); liberator.echoerr("Exxx: Named macro '" + lastMacro + "' not set");
} }
return res; return res;
}, },
@@ -922,7 +924,7 @@ with (liberator) liberator.Events = function () //{{{
if (modes.isReplaying && !waitForPageLoaded()) if (modes.isReplaying && !waitForPageLoaded())
break; break;
// else // a short break between keys often helps // else // a short break between keys often helps
// sleep(50); // liberator.sleep(50);
} }
this.feedingKeys = wasFeeding; this.feedingKeys = wasFeeding;
return i == keys.length; return i == keys.length;
@@ -1025,7 +1027,7 @@ with (liberator) liberator.Events = function () //{{{
onFocusChange: function (event) onFocusChange: function (event)
{ {
// command line has it's own focus change handler // command line has it's own focus change handler
if (mode == modes.COMMAND_LINE) if (liberator.mode == modes.COMMAND_LINE)
return; return;
var win = window.document.commandDispatcher.focusedWindow; var win = window.document.commandDispatcher.focusedWindow;
@@ -1033,9 +1035,9 @@ with (liberator) liberator.Events = function () //{{{
if (elem && elem.readOnly) if (elem && elem.readOnly)
return; return;
//log("onFocusChange: " + elem); //liberator.log("onFocusChange: " + elem);
//dump("=+++++++++=\n" + util.objectToString(event.target) + "\n") //liberator.dump("=+++++++++=\n" + util.objectToString(event.target) + "\n")
//dump (elem + ": " + win + "\n");//" - target: " + event.target + " - origtarget: " + event.originalTarget + " - expltarget: " + event.explicitOriginalTarget + "\n"); //liberator.dump (elem + ": " + win + "\n");//" - target: " + event.target + " - origtarget: " + event.originalTarget + " - expltarget: " + event.explicitOriginalTarget + "\n");
if (elem && ( if (elem && (
(elem instanceof HTMLInputElement && (elem.type.toLowerCase() == "text" || elem.type.toLowerCase() == "password")) || (elem instanceof HTMLInputElement && (elem.type.toLowerCase() == "text" || elem.type.toLowerCase() == "password")) ||
@@ -1043,7 +1045,7 @@ with (liberator) liberator.Events = function () //{{{
)) ))
{ {
this.wantsModeReset = false; this.wantsModeReset = false;
liberator.mode = liberator.modes.INSERT; liberator.mode = modes.INSERT;
buffer.lastInputField = elem; buffer.lastInputField = elem;
return; return;
} }
@@ -1069,24 +1071,24 @@ with (liberator) liberator.Events = function () //{{{
{ {
if (config.isComposeWindow) if (config.isComposeWindow)
{ {
dump("Compose editor got focus"); liberator.dump("Compose editor got focus");
modes.set(modes.INSERT, modes.TEXTAREA); modes.set(modes.INSERT, modes.TEXTAREA);
} }
else if (mode != modes.MESSAGE) else if (liberator.mode != modes.MESSAGE)
liberator.mode = liberator.modes.MESSAGE; liberator.mode = modes.MESSAGE;
return; return;
} }
} }
if (mode == modes.INSERT || if (liberator.mode == modes.INSERT ||
mode == modes.TEXTAREA || liberator.mode == modes.TEXTAREA ||
mode == modes.MESSAGE || liberator.mode == modes.MESSAGE ||
mode == modes.VISUAL) liberator.mode == modes.VISUAL)
{ {
// FIXME: currently this hack is disabled to make macros work // FIXME: currently this hack is disabled to make macros work
// this.wantsModeReset = true; // this.wantsModeReset = true;
// setTimeout(function () { // setTimeout(function () {
// dump("cur: " + mode + "\n"); // liberator.dump("cur: " + liberator.mode + "\n");
// if (events.wantsModeReset) // if (events.wantsModeReset)
// { // {
// events.wantsModeReset = false; // events.wantsModeReset = false;
@@ -1103,15 +1105,15 @@ with (liberator) liberator.Events = function () //{{{
if (controller && controller.isCommandEnabled("cmd_copy")) if (controller && controller.isCommandEnabled("cmd_copy"))
couldCopy = true; couldCopy = true;
if (mode != modes.VISUAL) if (liberator.mode != modes.VISUAL)
{ {
if (couldCopy) if (couldCopy)
{ {
if ((mode == modes.TEXTAREA || if ((liberator.mode == modes.TEXTAREA ||
(modes.extended & modes.TEXTAREA)) (modes.extended & modes.TEXTAREA))
&& !options["insertmode"]) && !options["insertmode"])
modes.set(modes.VISUAL, modes.TEXTAREA); modes.set(modes.VISUAL, modes.TEXTAREA);
else if (mode == modes.CARET) else if (liberator.mode == modes.CARET)
modes.set(modes.VISUAL, modes.CARET); modes.set(modes.VISUAL, modes.CARET);
} }
} }
@@ -1119,7 +1121,7 @@ with (liberator) liberator.Events = function () //{{{
// else // else
// { // {
// if (!couldCopy && modes.extended & modes.CARET) // if (!couldCopy && modes.extended & modes.CARET)
// liberator.mode = liberator.modes.CARET; // liberator.mode = modes.CARET;
// } // }
}, },
@@ -1134,7 +1136,7 @@ with (liberator) liberator.Events = function () //{{{
return; return;
} }
switch (mode) switch (liberator.mode)
{ {
case modes.NORMAL: case modes.NORMAL:
// clear any selection made // clear any selection made
@@ -1147,14 +1149,14 @@ with (liberator) liberator.Events = function () //{{{
commandline.clear(); commandline.clear();
modes.reset(); modes.reset();
focusContent(true); liberator.focusContent(true);
break; break;
case modes.VISUAL: case modes.VISUAL:
if (modes.extended & modes.TEXTAREA) if (modes.extended & modes.TEXTAREA)
liberator.mode = liberator.modes.TEXTAREA; liberator.mode = modes.TEXTAREA;
else if (modes.extended & modes.CARET) else if (modes.extended & modes.CARET)
liberator.mode = liberator.modes.CARET; liberator.mode = modes.CARET;
break; break;
case modes.CARET: case modes.CARET:
@@ -1166,12 +1168,12 @@ with (liberator) liberator.Events = function () //{{{
case modes.INSERT: case modes.INSERT:
if ((modes.extended & modes.TEXTAREA) && !options["insertmode"]) if ((modes.extended & modes.TEXTAREA) && !options["insertmode"])
{ {
liberator.mode = liberator.modes.TEXTAREA; liberator.mode = modes.TEXTAREA;
} }
else else
{ {
modes.reset(); modes.reset();
focusContent(true); liberator.focusContent(true);
} }
break; break;
@@ -1190,22 +1192,22 @@ with (liberator) liberator.Events = function () //{{{
if (!key) if (!key)
return true; return true;
//log(key + " in mode: " + mode); //liberator.log(key + " in mode: " + liberator.mode);
//dump(key + " in mode: " + mode + "\n"); //liberator.dump(key + " in mode: " + liberator.mode + "\n");
if (modes.isRecording) if (modes.isRecording)
{ {
if (key == "q") // TODO: should not be hardcoded if (key == "q") // TODO: should not be hardcoded
{ {
modes.isRecording = false; modes.isRecording = false;
log("Recorded " + currentMacro + ": " + macros.get(currentMacro), 9); liberator.log("Recorded " + currentMacro + ": " + macros.get(currentMacro), 9);
echo("Recorded macro '" + currentMacro + "'"); liberator.echo("Recorded macro '" + currentMacro + "'");
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
return true; return true;
} }
else if (!(modes.extended & modes.INACTIVE_HINT) && else if (!(modes.extended & modes.INACTIVE_HINT) &&
!mappings.hasMap(mode, input.buffer + key)) !mappings.hasMap(liberator.mode, input.buffer + key))
{ {
macros.set(currentMacro, macros.get(currentMacro) + key); macros.set(currentMacro, macros.get(currentMacro) + key);
} }
@@ -1223,7 +1225,7 @@ with (liberator) liberator.Events = function () //{{{
if (key == "<C-c>" && !event.isMacro) if (key == "<C-c>" && !event.isMacro)
{ {
events.feedingKeys = false; events.feedingKeys = false;
setTimeout(function () { echo("Canceled playback of macro '" + lastMacro + "'") }, 100); setTimeout(function () { liberator.echo("Canceled playback of macro '" + lastMacro + "'") }, 100);
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
return true; return true;
@@ -1258,7 +1260,7 @@ with (liberator) liberator.Events = function () //{{{
} }
// just forward event without checking any mappings when the MOW is open // just forward event without checking any mappings when the MOW is open
if (mode == modes.COMMAND_LINE && if (liberator.mode == modes.COMMAND_LINE &&
(modes.extended & modes.OUTPUT_MULTILINE)) (modes.extended & modes.OUTPUT_MULTILINE))
{ {
commandline.onMultilineOutputEvent(event); commandline.onMultilineOutputEvent(event);
@@ -1270,8 +1272,8 @@ with (liberator) liberator.Events = function () //{{{
// XXX: ugly hack for now pass certain keys to firefox as they are without beeping // XXX: ugly hack for now pass certain keys to firefox as they are without beeping
// also fixes key navigation in combo boxes, submitting forms, etc. // also fixes key navigation in combo boxes, submitting forms, etc.
// FIXME: breaks iabbr for now --mst // FIXME: breaks iabbr for now --mst
if ((config.name == "Vimperator" && mode == modes.NORMAL) if ((config.name == "Vimperator" && liberator.mode == modes.NORMAL)
|| mode == modes.INSERT) || liberator.mode == modes.INSERT)
{ {
if (key == "<Return>") if (key == "<Return>")
return false; return false;
@@ -1302,7 +1304,7 @@ with (liberator) liberator.Events = function () //{{{
if (key != "<Esc>" && key != "<C-[>") if (key != "<Esc>" && key != "<C-[>")
{ {
// custom mode... // custom mode...
if (mode == modes.CUSTOM) if (liberator.mode == modes.CUSTOM)
{ {
plugins.onEvent(event); plugins.onEvent(event);
event.preventDefault(); event.preventDefault();
@@ -1310,7 +1312,7 @@ with (liberator) liberator.Events = function () //{{{
return false; return false;
} }
// if Hint mode is on, special handling of keys is required // if Hint mode is on, special handling of keys is required
if (mode == modes.HINTS) if (liberator.mode == modes.HINTS)
{ {
hints.onEvent(event); hints.onEvent(event);
event.preventDefault(); event.preventDefault();
@@ -1326,22 +1328,22 @@ with (liberator) liberator.Events = function () //{{{
// whatever reason). if that happens to be correct, well.. // whatever reason). if that happens to be correct, well..
// XXX: why not just do that as well for HINTS mode actually? // XXX: why not just do that as well for HINTS mode actually?
if (mode == modes.CUSTOM) if (liberator.mode == modes.CUSTOM)
return true; return true;
var countStr = input.buffer.match(/^[0-9]*/)[0]; var countStr = input.buffer.match(/^[0-9]*/)[0];
var candidateCommand = (input.buffer + key).replace(countStr, ""); var candidateCommand = (input.buffer + key).replace(countStr, "");
var map; var map;
if (event.noremap) if (event.noremap)
map = mappings.getDefault(mode, candidateCommand); map = mappings.getDefault(liberator.mode, candidateCommand);
else else
map = mappings.get(mode, candidateCommand); map = mappings.get(liberator.mode, candidateCommand);
// counts must be at the start of a complete mapping (10j -> go 10 lines down) // counts must be at the start of a complete mapping (10j -> go 10 lines down)
if (/^[1-9][0-9]*$/.test(input.buffer + key)) if (/^[1-9][0-9]*$/.test(input.buffer + key))
{ {
// no count for insert mode mappings // no count for insert mode mappings
if (mode == modes.INSERT || mode == modes.COMMAND_LINE) if (liberator.mode == modes.INSERT || liberator.mode == modes.COMMAND_LINE)
stop = false; stop = false;
else else
{ {
@@ -1367,7 +1369,7 @@ with (liberator) liberator.Events = function () //{{{
// (allows you to do :map z yy, when zz is a longer mapping than z) // (allows you to do :map z yy, when zz is a longer mapping than z)
// TODO: map.rhs is only defined for user defined commands, should add a "isDefault" property // TODO: map.rhs is only defined for user defined commands, should add a "isDefault" property
else if (map && !skipMap && (map.rhs || else if (map && !skipMap && (map.rhs ||
mappings.getCandidates(mode, candidateCommand).length == 0)) mappings.getCandidates(liberator.mode, candidateCommand).length == 0))
{ {
input.count = parseInt(countStr, 10); input.count = parseInt(countStr, 10);
if (isNaN(input.count)) if (isNaN(input.count))
@@ -1408,7 +1410,7 @@ with (liberator) liberator.Events = function () //{{{
stop = false; stop = false;
} }
} }
else if (mappings.getCandidates(mode, candidateCommand).length > 0 && !skipMap) else if (mappings.getCandidates(liberator.mode, candidateCommand).length > 0 && !skipMap)
{ {
input.buffer += key; input.buffer += key;
inputBufferLength++; inputBufferLength++;
@@ -1416,8 +1418,8 @@ with (liberator) liberator.Events = function () //{{{
else // if the key is neither a mapping nor the start of one else // if the key is neither a mapping nor the start of one
{ {
// the mode checking is necessary so that things like g<esc> do not beep // the mode checking is necessary so that things like g<esc> do not beep
if (input.buffer != "" && !skipMap && (mode == modes.INSERT || if (input.buffer != "" && !skipMap && (liberator.mode == modes.INSERT ||
mode == modes.COMMAND_LINE || mode == modes.TEXTAREA)) liberator.mode == modes.COMMAND_LINE || liberator.mode == modes.TEXTAREA))
{ {
// no map found -> refeed stuff in v.input.buffer (only while in INSERT, CO... modes) // no map found -> refeed stuff in v.input.buffer (only while in INSERT, CO... modes)
skipMap = true; // ignore maps while doing so skipMap = true; // ignore maps while doing so
@@ -1438,14 +1440,14 @@ with (liberator) liberator.Events = function () //{{{
// allow key to be passed to firefox if we can't handle it // allow key to be passed to firefox if we can't handle it
stop = false; stop = false;
if (mode == modes.COMMAND_LINE) if (liberator.mode == modes.COMMAND_LINE)
{ {
if (!(modes.extended & modes.INPUT_MULTILINE)) if (!(modes.extended & modes.INPUT_MULTILINE))
commandline.onEvent(event); // reroute event in command line mode commandline.onEvent(event); // reroute event in command line mode
} }
else if (mode != modes.INSERT && mode != modes.TEXTAREA) else if (liberator.mode != modes.INSERT && liberator.mode != modes.TEXTAREA)
{ {
beep(); liberator.beep();
} }
} }
} }
@@ -1505,7 +1507,7 @@ with (liberator) liberator.Events = function () //{{{
if (document.commandDispatcher.focusedWindow == webProgress.DOMWindow) if (document.commandDispatcher.focusedWindow == webProgress.DOMWindow)
{ {
setTimeout(function () { modes.reset(false); }, setTimeout(function () { modes.reset(false); },
mode == modes.HINTS ? 500 : 0); liberator.mode == modes.HINTS ? 500 : 0);
} }
} }
else if (flags & Components.interfaces.nsIWebProgressListener.STATE_STOP) else if (flags & Components.interfaces.nsIWebProgressListener.STATE_STOP)
@@ -1558,7 +1560,7 @@ with (liberator) liberator.Events = function () //{{{
if (ssli == 1) if (ssli == 1)
statusline.updateUrl("Link: " + link); statusline.updateUrl("Link: " + link);
else if (ssli == 2) else if (ssli == 2)
echo("Link: " + link, commandline.DISALLOW_MULTILINE); liberator.echo("Link: " + link, commandline.DISALLOW_MULTILINE);
} }
if (link == "") if (link == "")
@@ -1605,7 +1607,7 @@ with (liberator) liberator.Events = function () //{{{
{ {
case "accessibility.browsewithcaret": case "accessibility.browsewithcaret":
var value = options.getPref("accessibility.browsewithcaret", false); var value = options.getPref("accessibility.browsewithcaret", false);
liberator.mode = value ? liberator.modes.CARET : liberator.modes.NORMAL; liberator.mode = value ? modes.CARET : modes.NORMAL;
break; break;
} }
} }
@@ -1626,7 +1628,7 @@ with (liberator) liberator.Events = function () //{{{
catch (e) {} catch (e) {}
eventManager.prefObserver.register(); eventManager.prefObserver.register();
registerObserver("shutdown", function () { liberator.registerObserver("shutdown", function () {
eventManager.destroy(); eventManager.destroy();
eventManager.prefObserver.unregister(); eventManager.prefObserver.unregister();
}); });

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
with (liberator) liberator.Search = function () //{{{ function Search() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -56,13 +56,13 @@ with (liberator) 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
registerCallback("change", modes.SEARCH_FORWARD, function (command) { search.searchKeyPressed(command); }); liberator.registerCallback("change", modes.SEARCH_FORWARD, function (command) { search.searchKeyPressed(command); });
registerCallback("submit", modes.SEARCH_FORWARD, function (command) { search.searchSubmitted(command); }); liberator.registerCallback("submit", modes.SEARCH_FORWARD, function (command) { search.searchSubmitted(command); });
registerCallback("cancel", modes.SEARCH_FORWARD, function () { search.searchCanceled(); }); liberator.registerCallback("cancel", modes.SEARCH_FORWARD, function () { search.searchCanceled(); });
// TODO: allow advanced myModes in register/triggerCallback // TODO: allow advanced myModes in register/triggerCallback
registerCallback("change", modes.SEARCH_BACKWARD, function (command) { search.searchKeyPressed(command); }); liberator.registerCallback("change", modes.SEARCH_BACKWARD, function (command) { search.searchKeyPressed(command); });
registerCallback("submit", modes.SEARCH_BACKWARD, function (command) { search.searchSubmitted(command); }); liberator.registerCallback("submit", modes.SEARCH_BACKWARD, function (command) { search.searchSubmitted(command); });
registerCallback("cancel", modes.SEARCH_BACKWARD, function () { search.searchCanceled(); }); liberator.registerCallback("cancel", modes.SEARCH_BACKWARD, function () { search.searchCanceled(); });
// set searchString, searchPattern, caseSensitive, linksOnly // set searchString, searchPattern, caseSensitive, linksOnly
function processUserPattern(pattern) function processUserPattern(pattern)
@@ -204,8 +204,8 @@ with (liberator) 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)
threadYield(); liberator.threadYield();
if (interrupted) if (liberator.interrupted)
break; break;
} }
}, },
@@ -343,7 +343,7 @@ with (liberator) 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 () { echoerr("E486: Pattern not found: " + searchPattern); }, 0); setTimeout(function () { liberator.echoerr("E486: Pattern not found: " + searchPattern); }, 0);
return found; return found;
}, },
@@ -362,7 +362,7 @@ with (liberator) liberator.Search = function () //{{{
if (result == Components.interfaces.nsITypeAheadFind.FIND_NOTFOUND) if (result == Components.interfaces.nsITypeAheadFind.FIND_NOTFOUND)
{ {
echoerr("E486: Pattern not found: " + lastSearchPattern); liberator.echoerr("E486: Pattern not found: " + lastSearchPattern);
} }
else if (result == Components.interfaces.nsITypeAheadFind.FIND_WRAPPED) else if (result == Components.interfaces.nsITypeAheadFind.FIND_WRAPPED)
{ {
@@ -379,7 +379,7 @@ with (liberator) liberator.Search = function () //{{{
} }
else else
{ {
echo((up ? "?" : "/") + lastSearchPattern, null, commandline.FORCE_SINGLELINE); liberator.echo((up ? "?" : "/") + lastSearchPattern, null, commandline.FORCE_SINGLELINE);
if (options["hlsearch"]) if (options["hlsearch"])
this.highlight(lastSearchString); this.highlight(lastSearchString);

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 *****/
with (liberator) liberator.Hints = function () //{{{ function Hints() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -303,7 +303,7 @@ with (liberator) liberator.Hints = function () //{{{
{ {
if (validHints.length == 0) if (validHints.length == 0)
{ {
beep(); liberator.beep();
return false; return false;
} }
@@ -329,19 +329,19 @@ with (liberator) liberator.Hints = function () //{{{
case "?": buffer.showElementInfo(elem); break; case "?": buffer.showElementInfo(elem); break;
case "a": buffer.saveLink(elem, false); break; case "a": buffer.saveLink(elem, false); break;
case "s": buffer.saveLink(elem, true); break; case "s": buffer.saveLink(elem, true); break;
case "o": buffer.followLink(elem, CURRENT_TAB); break; case "o": buffer.followLink(elem, liberator.CURRENT_TAB); break;
case "O": commandline.open(":", "open " + loc, modes.EX); break; case "O": commandline.open(":", "open " + loc, modes.EX); break;
case "t": buffer.followLink(elem, NEW_TAB); break; case "t": buffer.followLink(elem, liberator.NEW_TAB); break;
case "b": buffer.followLink(elem, NEW_BACKGROUND_TAB); break; case "b": buffer.followLink(elem, liberator.NEW_BACKGROUND_TAB); break;
case "T": commandline.open(":", "tabopen " + loc, modes.EX); break; case "T": commandline.open(":", "tabopen " + loc, modes.EX); break;
case "v": buffer.viewSource(loc, false); break; case "v": buffer.viewSource(loc, false); break;
case "V": buffer.viewSource(loc, true); break; case "V": buffer.viewSource(loc, true); break;
case "w": buffer.followLink(elem, NEW_WINDOW); break; case "w": buffer.followLink(elem, liberator.NEW_WINDOW); break;
case "W": commandline.open(":", "winopen " + loc, modes.EX); break; case "W": commandline.open(":", "winopen " + loc, modes.EX); break;
case "y": setTimeout(function () { util.copyToClipboard(loc, true); }, timeout + 50); break; case "y": setTimeout(function () { util.copyToClipboard(loc, true); }, timeout + 50); break;
case "Y": setTimeout(function () { util.copyToClipboard(elem.textContent || "", true); }, timeout + 50); break; case "Y": setTimeout(function () { util.copyToClipboard(elem.textContent || "", true); }, timeout + 50); break;
default: default:
echoerr("INTERNAL ERROR: unknown submode: " + submode); liberator.echoerr("INTERNAL ERROR: unknown submode: " + submode);
} }
removeHints(timeout); removeHints(timeout);
@@ -360,14 +360,14 @@ with (liberator) liberator.Hints = function () //{{{
{ {
// 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
events.onFocusChange(); events.onFocusChange();
if (mode == modes.HINTS) if (liberator.mode == modes.HINTS)
modes.reset(false); modes.reset(false);
} }
else else
{ {
modes.add(modes.INACTIVE_HINT); modes.add(modes.INACTIVE_HINT);
setTimeout(function () { setTimeout(function () {
if (mode == modes.HINTS) if (liberator.mode == modes.HINTS)
modes.pop(); modes.pop();
}, timeout); }, timeout);
} }
@@ -536,7 +536,7 @@ with (liberator) liberator.Hints = function () //{{{
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 plugins.customHintMatcher(hintString); case "custom" : return plugins.customHintMatcher(hintString);
default : echoerr("Invalid hintmatching type: " + hintMatching); default : liberator.echoerr("Invalid hintmatching type: " + hintMatching);
} }
return null; return null;
} //}}} } //}}}
@@ -629,7 +629,7 @@ with (liberator) liberator.Hints = function () //{{{
{ {
if (mode == modes.EXTENDED_HINT && !/^[;?asoOtbTvVwWyY]$/.test(minor)) if (mode == modes.EXTENDED_HINT && !/^[;?asoOtbTvVwWyY]$/.test(minor))
{ {
beep(); liberator.beep();
return; return;
} }
@@ -642,14 +642,14 @@ with (liberator) liberator.Hints = function () //{{{
generate(win); generate(win);
// get all keys from the input queue // get all keys from the input queue
threadYield(true); liberator.threadYield(true);
canUpdate = true; canUpdate = true;
showHints(); showHints();
if (validHints.length == 0) if (validHints.length == 0)
{ {
beep(); liberator.beep();
modes.reset(); modes.reset();
return false; return false;
} }
@@ -725,7 +725,7 @@ with (liberator) liberator.Hints = function () //{{{
{ {
usedTabKey = false; usedTabKey = false;
hintNumber = 0; hintNumber = 0;
beep(); liberator.beep();
return; return;
} }
break; break;
@@ -756,7 +756,7 @@ with (liberator) liberator.Hints = function () //{{{
return; return;
} }
beep(); liberator.beep();
return; return;
} }
@@ -785,7 +785,7 @@ with (liberator) liberator.Hints = function () //{{{
if (hintNumber == 0 || hintNumber > validHints.length) if (hintNumber == 0 || hintNumber > validHints.length)
{ {
beep(); liberator.beep();
return; return;
} }

View File

@@ -28,7 +28,7 @@ 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?
with (liberator) liberator.IO = function () //{{{ function IO() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -128,7 +128,7 @@ with (liberator) liberator.IO = function () //{{{
} }
else else
{ {
echoerr("E186: No previous directory"); liberator.echoerr("E186: No previous directory");
return; return;
} }
} }
@@ -141,7 +141,7 @@ with (liberator) liberator.IO = function () //{{{
{ {
// TODO: apparently we don't handle ../ or ./ paths yet // TODO: apparently we don't handle ../ or ./ paths yet
if (io.setCurrentDirectory(args)) if (io.setCurrentDirectory(args))
echo(io.getCurrentDirectory()); liberator.echo(io.getCurrentDirectory());
} }
else else
{ {
@@ -161,7 +161,7 @@ with (liberator) liberator.IO = function () //{{{
{ {
// FIXME: we're just overwriting the error message from // FIXME: we're just overwriting the error message from
// setCurrentDirectory here // setCurrentDirectory here
echo(io.getCurrentDirectory()); liberator.echo(io.getCurrentDirectory());
directoryFound = true; directoryFound = true;
break; break;
} }
@@ -169,7 +169,7 @@ with (liberator) liberator.IO = function () //{{{
if (!directoryFound) if (!directoryFound)
{ {
echoerr("E344: Can't find directory \"" + args + "\" in cdpath" liberator.echoerr("E344: Can't find directory \"" + args + "\" in cdpath"
+ "\n" + "\n"
+ "E472: Command failed"); + "E472: Command failed");
} }
@@ -180,12 +180,12 @@ with (liberator) liberator.IO = function () //{{{
// NOTE: this command is only used in :source // NOTE: this command is only used in :source
commands.add(["fini[sh]"], commands.add(["fini[sh]"],
"Stop sourcing a script file", "Stop sourcing a script file",
function () { echoerr("E168: :finish used outside of a sourced file"); }, function () { liberator.echoerr("E168: :finish used outside of a sourced file"); },
{ argCount: "0" }); { argCount: "0" });
commands.add(["pw[d]"], commands.add(["pw[d]"],
"Print the current directory name", "Print the current directory name",
function () { echo(io.getCurrentDirectory()); }, function () { liberator.echo(io.getCurrentDirectory()); },
{ argCount: "0" }); { argCount: "0" });
// "mkv[imperatorrc]" or "mkm[uttatorrc]" // "mkv[imperatorrc]" or "mkm[uttatorrc]"
@@ -203,11 +203,11 @@ with (liberator) liberator.IO = function () //{{{
var file = io.getFile(filename); var file = io.getFile(filename);
if (file.exists() && !special) if (file.exists() && !special)
{ {
echoerr("E189: \"" + filename + "\" exists (add ! to override)"); liberator.echoerr("E189: \"" + filename + "\" exists (add ! to override)");
return; return;
} }
var line = "\" " + version + "\n"; var line = "\" " + liberator.version + "\n";
line += "\" Mappings\n"; line += "\" Mappings\n";
[[[modes.NORMAL], ""], [[[modes.NORMAL], ""],
@@ -254,8 +254,8 @@ with (liberator) liberator.IO = function () //{{{
} }
catch (e) catch (e)
{ {
echoerr("E190: Cannot open \"" + filename + "\" for writing"); liberator.echoerr("E190: Cannot open \"" + filename + "\" for writing");
log("Could not write to " + file.path + ": " + e.message); // XXX liberator.log("Could not write to " + file.path + ": " + e.message); // XXX
} }
}, },
{ {
@@ -275,7 +275,7 @@ with (liberator) liberator.IO = function () //{{{
let found = false; let found = false;
// FIXME: should use original arg string // FIXME: should use original arg string
echomsg("Searching for \"" + paths.join(" ") + "\" in \"" + options["runtimepath"] + "\"", 2); liberator.echomsg("Searching for \"" + paths.join(" ") + "\" in \"" + options["runtimepath"] + "\"", 2);
outer: outer:
for (let [,runtimeDir] in Iterator(runtimeDirs)) for (let [,runtimeDir] in Iterator(runtimeDirs))
@@ -284,7 +284,7 @@ with (liberator) liberator.IO = function () //{{{
{ {
let file = io.getFile(joinPaths(runtimeDir, path)); let file = io.getFile(joinPaths(runtimeDir, path));
echomsg("Searching for \"" + file.path + "\" in \"", 3); liberator.echomsg("Searching for \"" + file.path + "\" in \"", 3);
if (file.exists() && file.isReadable() && !file.isDirectory()) // XXX if (file.exists() && file.isReadable() && !file.isDirectory()) // XXX
{ {
@@ -298,7 +298,7 @@ with (liberator) liberator.IO = function () //{{{
} }
if (!found) if (!found)
echomsg("not found in 'runtimepath': \"" + paths.join(" ") + "\"", 1); // FIXME: should use original arg string liberator.echomsg("not found in 'runtimepath': \"" + paths.join(" ") + "\"", 1); // FIXME: should use original arg string
}, },
{ {
argCount: "+", argCount: "+",
@@ -324,7 +324,7 @@ with (liberator) liberator.IO = function () //{{{
// 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)
{ {
echoerr("E471: Argument required"); liberator.echoerr("E471: Argument required");
return; return;
} }
@@ -351,7 +351,7 @@ with (liberator) liberator.IO = function () //{{{
var output = io.system(args); var output = io.system(args);
var command = ":" + util.escapeHTML(commandline.getCommand()) + "<br/>"; var command = ":" + util.escapeHTML(commandline.getCommand()) + "<br/>";
echo(command + util.escapeHTML(output)); liberator.echo(command + util.escapeHTML(output));
autocommands.trigger("ShellCmdPost", {}); autocommands.trigger("ShellCmdPost", {});
}, },
@@ -372,6 +372,8 @@ with (liberator) liberator.IO = function () //{{{
MODE_SYNC: 0x40, MODE_SYNC: 0x40,
MODE_EXCL: 0x80, MODE_EXCL: 0x80,
sourcing: null,
expandPath: function (path) expandPath: function (path)
{ {
// TODO: proper pathname separator translation like Vim - this should be done elsewhere // TODO: proper pathname separator translation like Vim - this should be done elsewhere
@@ -439,7 +441,7 @@ with (liberator) liberator.IO = function () //{{{
if (!dir.exists() || !dir.isDirectory()) if (!dir.exists() || !dir.isDirectory())
{ {
echoerr("E344: Can't find directory \"" + dir.path + "\" in path"); liberator.echoerr("E344: Can't find directory \"" + dir.path + "\" in path");
return null; return null;
} }
@@ -670,7 +672,7 @@ lookup:
if (!file.exists()) if (!file.exists())
{ {
echoerr("Command not found: " + program); liberator.echoerr("Command not found: " + program);
return -1; return -1;
} }
@@ -687,7 +689,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)
{ {
echomsg("Calling shell to execute: " + command, 4); liberator.echomsg("Calling shell to execute: " + command, 4);
var stdoutFile = ioManager.createTempFile(); var stdoutFile = ioManager.createTempFile();
var stderrFile = ioManager.createTempFile(); var stderrFile = ioManager.createTempFile();
@@ -740,23 +742,27 @@ lookup:
try try
{ {
var file = ioManager.getFile(filename); var file = ioManager.getFile(filename);
this.sourcing = {
file: file.path,
line: 0
};
if (!file.exists() || !file.isReadable() || file.isDirectory()) if (!file.exists() || !file.isReadable() || file.isDirectory())
{ {
if (!silent) if (!silent)
{ {
if (file.exists() && file.isDirectory()) if (file.exists() && file.isDirectory())
echomsg("Cannot source a directory: \"" + filename + "\"", 0); liberator.echomsg("Cannot source a directory: \"" + filename + "\"", 0);
else else
echomsg("could not source: \"" + filename + "\"", 1); liberator.echomsg("could not source: \"" + filename + "\"", 1);
echoerr("E484: Can't open file " + filename); liberator.echoerr("E484: Can't open file " + filename);
} }
return; return;
} }
echomsg("sourcing \"" + filename + "\"", 2); liberator.echomsg("sourcing \"" + filename + "\"", 2);
let str = ioManager.readFile(file); let str = ioManager.readFile(file);
let uri = util.createURI(file.path); let uri = util.createURI(file.path);
@@ -803,6 +809,7 @@ lookup:
} }
else else
{ {
this.sourcing.line = i + 1;
// skip line comments and blank lines // skip line comments and blank lines
if (/^\s*(".*)?$/.test(line)) if (/^\s*(".*)?$/.test(line))
continue; continue;
@@ -817,11 +824,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
echoerr("Error detected while processing " + file.path, liberator.echoerr("Error detected while processing " + file.path,
commandline.FORCE_MULTILINE); commandline.FORCE_MULTILINE);
commandline.echo("line " + lineNumber + ":", commandline.HL_LINENR, commandline.echo("line " + lineNumber + ":", commandline.HL_LINENR,
commandline.APPEND_TO_MESSAGES); commandline.APPEND_TO_MESSAGES);
echoerr("E492: Not an editor command: " + line); liberator.echoerr("E492: Not an editor command: " + line);
} }
else else
{ {
@@ -849,7 +856,7 @@ lookup:
else else
{ {
// execute a normal liberator command // execute a normal liberator command
execute(line); liberator.execute(line);
} }
} }
} }
@@ -857,15 +864,16 @@ 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 ;-)
eval(heredoc); if (heredocEnd)
command.execute(heredoc, special, count);
} }
if (scriptNames.indexOf(file.path) == -1) if (scriptNames.indexOf(file.path) == -1)
scriptNames.push(file.path); scriptNames.push(file.path);
echomsg("finished sourcing \"" + filename + "\"", 2); liberator.echomsg("finished sourcing \"" + filename + "\"", 2);
log("Sourced: " + file.path, 3); liberator.log("Sourced: " + file.path, 3);
} }
catch (e) catch (e)
{ {
@@ -873,7 +881,11 @@ lookup:
if (Components.utils.reportError) if (Components.utils.reportError)
Components.utils.reportError(e); Components.utils.reportError(e);
if (!silent) if (!silent)
echoerr(message); liberator.echoerr(message);
}
finally
{
this.sourcing = null;
} }
} }
}; //}}} }; //}}}

View File

@@ -0,0 +1,45 @@
(function () {
const modules = {};
const BASE = "chrome://liberator/content/";
modules.modules = modules;
var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Components.interfaces.mozIJSSubScriptLoader);
function load(script) {
try
{
dump("liberator: Loading script: " + script + "\n");
loader.loadSubScript(BASE + script, modules)
}
catch (e)
{
if (Components.utils.reportError)
Components.utils.reportError(e);
dump("liberator: Loading script " + script + ": " + e + "\n");
}
}
Components.utils.import("resource://liberator/storage.jsm", modules);
["liberator.js",
"config.js",
"buffer.js",
"commands.js",
"completion.js",
"editor.js",
"events.js",
"find.js",
"hints.js",
"io.js",
"mappings.js",
"modes.js",
"options.js",
"template.js",
"ui.js",
"util.js"].forEach(load);
modules.config.scripts.forEach(load);
})()

View File

@@ -45,7 +45,7 @@ const liberator = (function () //{{{
{ {
liberator.log(message, 0); liberator.log(message, 0);
liberator.dump(message); liberator.dump(message);
liberator[name] = func(); modules[name] = func();
} }
catch (e) catch (e)
{ {
@@ -63,13 +63,13 @@ const liberator = (function () //{{{
["n", "Tab number", null, ".hl-TabNumber"], ["n", "Tab number", null, ".hl-TabNumber"],
["N", "Tab number over icon", null, ".hl-TabIconNumber"], ["N", "Tab number over icon", null, ".hl-TabIconNumber"],
]; ];
liberator.options.add(["guioptions", "go"], options.add(["guioptions", "go"],
"Show or hide certain GUI elements like the menu or toolbar", "Show or hide certain GUI elements like the menu or toolbar",
"charlist", liberator.config.defaults.guioptions || "", "charlist", config.defaults.guioptions || "",
{ {
setter: function (value) setter: function (value)
{ {
var guioptions = liberator.config.guioptions || {}; var guioptions = config.guioptions || {};
for (let option in guioptions) for (let option in guioptions)
{ {
@@ -87,9 +87,9 @@ const liberator = (function () //{{{
let classes = tabopts.filter(function (o) value.indexOf(o[0]) == -1) let classes = tabopts.filter(function (o) value.indexOf(o[0]) == -1)
.map(function (a) a[3]) .map(function (a) a[3])
if (!classes.length) if (!classes.length)
liberator.storage.styles.removeSheet("taboptions", null, null, null, true); storage.styles.removeSheet("taboptions", null, null, null, true);
else else
liberator.storage.styles.addSheet("taboptions", "chrome://*", classes.join(",") + "{ display: none; }", true, true); storage.styles.addSheet("taboptions", "chrome://*", classes.join(",") + "{ display: none; }", true, true);
return value; return value;
}, },
@@ -101,29 +101,29 @@ const liberator = (function () //{{{
["b", "Bookmark bar"] ["b", "Bookmark bar"]
].concat(!liberator.has("tabs") ? [] : tabopts); ].concat(!liberator.has("tabs") ? [] : tabopts);
}, },
validator: function (value) Array.every(value, function (c) c in liberator.config.guioptions || tabopts.some(function (a) a[0] == c)), validator: function (value) Array.every(value, function (c) c in config.guioptions || tabopts.some(function (a) a[0] == c)),
}); });
liberator.options.add(["helpfile", "hf"], options.add(["helpfile", "hf"],
"Name of the main help file", "Name of the main help file",
"string", "intro.html"); "string", "intro.html");
liberator.options.add(["loadplugins", "lpl"], options.add(["loadplugins", "lpl"],
"Load plugin scripts when starting up", "Load plugin scripts when starting up",
"boolean", true); "boolean", true);
liberator.options.add(["verbose", "vbs"], options.add(["verbose", "vbs"],
"Define which info messages are displayed", "Define which info messages are displayed",
"number", 0, "number", 0,
{ validator: function (value) value >= 0 && value <= 15 }); { validator: function (value) value >= 0 && value <= 15 });
liberator.options.add(["visualbell", "vb"], options.add(["visualbell", "vb"],
"Use visual bell instead of beeping on errors", "Use visual bell instead of beeping on errors",
"boolean", false, "boolean", false,
{ {
setter: function (value) setter: function (value)
{ {
liberator.options.setPref("accessibility.typeaheadfind.enablesound", !value); options.setPref("accessibility.typeaheadfind.enablesound", !value);
return value; return value;
} }
}); });
@@ -131,48 +131,48 @@ const liberator = (function () //{{{
function addMappings() function addMappings()
{ {
liberator.mappings.add(liberator.modes.all, ["<F1>"], mappings.add(modes.all, ["<F1>"],
"Open help window", "Open help window",
function () { liberator.help(); }); function () { liberator.help(); });
if (liberator.has("session")) if (liberator.has("session"))
{ {
liberator.mappings.add([liberator.modes.NORMAL], ["ZQ"], mappings.add([modes.NORMAL], ["ZQ"],
"Quit and don't save the session", "Quit and don't save the session",
function () { liberator.quit(false); }); function () { liberator.quit(false); });
} }
liberator.mappings.add([liberator.modes.NORMAL], ["ZZ"], mappings.add([modes.NORMAL], ["ZZ"],
"Quit and save the session", "Quit and save the session",
function () { liberator.quit(true); }); function () { liberator.quit(true); });
} }
function addCommands() function addCommands()
{ {
liberator.commands.add(["addo[ns]"], commands.add(["addo[ns]"],
"Manage available Extensions and Themes", "Manage available Extensions and Themes",
function () function ()
{ {
liberator.open("chrome://mozapps/content/extensions/extensions.xul", liberator.open("chrome://mozapps/content/extensions/extensions.xul",
(liberator.options["newtab"] && liberator.options.get("newtab").has("all", "addons")) (options["newtab"] && options.get("newtab").has("all", "addons"))
? liberator.NEW_TAB: liberator.CURRENT_TAB); ? liberator.NEW_TAB: liberator.CURRENT_TAB);
}, },
{ argCount: "0" }); { argCount: "0" });
liberator.commands.add(["beep"], commands.add(["beep"],
"Play a system beep", "Play a system beep",
function () { liberator.beep(); }, function () { liberator.beep(); },
{ argCount: "0" }); { argCount: "0" });
liberator.commands.add(["dia[log]"], commands.add(["dia[log]"],
"Open a " + liberator.config.name + " dialog", "Open a " + config.name + " dialog",
function (args) function (args)
{ {
args = args.arguments[0]; args = args.arguments[0];
try try
{ {
var dialogs = liberator.config.dialogs || []; var dialogs = config.dialogs || [];
for (let i = 0; i < dialogs.length; i++) for (let i = 0; i < dialogs.length; i++)
{ {
if (dialogs[i][0] == args) if (dialogs[i][0] == args)
@@ -188,13 +188,13 @@ const liberator = (function () //{{{
{ {
argCount: "1", argCount: "1",
bang: true, bang: true,
completer: function (filter) liberator.completion.dialog(filter) completer: function (filter) completion.dialog(filter)
}); });
// TODO: move this // TODO: move this
function getMenuItems() function getMenuItems()
{ {
var menubar = document.getElementById(liberator.config.guioptions["m"]); var menubar = document.getElementById(config.guioptions["m"]);
var items = []; var items = [];
for (let i = 0; i < menubar.childNodes.length; i++) for (let i = 0; i < menubar.childNodes.length; i++)
@@ -221,7 +221,7 @@ const liberator = (function () //{{{
return items; return items;
} }
liberator.commands.add(["em[enu]"], commands.add(["em[enu]"],
"Execute the specified menu item from the command line", "Execute the specified menu item from the command line",
function (args) function (args)
{ {
@@ -246,11 +246,11 @@ const liberator = (function () //{{{
completer: function (filter) completer: function (filter)
{ {
let completions = getMenuItems().map(function (item) [item.fullMenuPath, item.label]); let completions = getMenuItems().map(function (item) [item.fullMenuPath, item.label]);
return [0, liberator.completion.filter(completions, filter)]; return [0, completion.filter(completions, filter)];
} }
}); });
liberator.commands.add(["exe[cute]"], commands.add(["exe[cute]"],
"Execute the argument as an Ex command", "Execute the argument as an Ex command",
// FIXME: this should evaluate each arg separately then join // FIXME: this should evaluate each arg separately then join
// with " " before executing. // with " " before executing.
@@ -271,7 +271,7 @@ const liberator = (function () //{{{
} }
}); });
liberator.commands.add(["exu[sage]"], commands.add(["exu[sage]"],
"List all Ex commands with a short description", "List all Ex commands with a short description",
function (args, special) function (args, special)
{ {
@@ -282,8 +282,8 @@ const liberator = (function () //{{{
else else
{ {
// TODO: clicking on these should open the help // TODO: clicking on these should open the help
var usage = liberator.template.usage(liberator.commands); var usage = template.usage(commands);
liberator.echo(usage, liberator.commandline.FORCE_MULTILINE); liberator.echo(usage, commandline.FORCE_MULTILINE);
} }
}, },
{ {
@@ -291,7 +291,7 @@ const liberator = (function () //{{{
bang: true bang: true
}); });
liberator.commands.add(["h[elp]"], commands.add(["h[elp]"],
"Display help", "Display help",
function (args, special) function (args, special)
{ {
@@ -305,17 +305,17 @@ const liberator = (function () //{{{
}, },
{ {
bang: true, bang: true,
completer: function (filter) liberator.completion.help(filter) completer: function (filter) completion.help(filter)
}); });
liberator.commands.add(["javas[cript]", "js"], commands.add(["javas[cript]", "js"],
"Run a JavaScript command through eval()", "Run a JavaScript command through eval()",
function (args, special) function (args, special)
{ {
if (special) // open javascript console if (special) // open javascript console
{ {
liberator.open("chrome://global/content/console.xul", liberator.open("chrome://global/content/console.xul",
(liberator.options["newtab"] && liberator.options.get("newtab").has("all", "javascript")) (options["newtab"] && options.get("newtab").has("all", "javascript"))
? liberator.NEW_TAB : liberator.CURRENT_TAB); ? liberator.NEW_TAB : liberator.CURRENT_TAB);
} }
else else
@@ -332,23 +332,23 @@ const liberator = (function () //{{{
}, },
{ {
bang: true, bang: true,
completer: function (filter) liberator.completion.javascript(filter), completer: function (filter) completion.javascript(filter),
hereDoc: true, hereDoc: true,
}); });
liberator.commands.add(["loadplugins", "lpl"], commands.add(["loadplugins", "lpl"],
"Load all plugins immediately", "Load all plugins immediately",
function () { liberator.loadPlugins(); }); function () { liberator.loadPlugins(); });
liberator.commands.add(["norm[al]"], commands.add(["norm[al]"],
"Execute Normal mode commands", "Execute Normal mode commands",
function (args, special) { liberator.events.feedkeys(args.string, special); }, function (args, special) { events.feedkeys(args.string, special); },
{ {
argCount: "+", argCount: "+",
bang: true bang: true
}); });
liberator.commands.add(["optionu[sage]"], commands.add(["optionu[sage]"],
"List all options with a short description", "List all options with a short description",
function (args, special) function (args, special)
{ {
@@ -359,8 +359,8 @@ const liberator = (function () //{{{
else else
{ {
// TODO: clicking on these should open the help // TODO: clicking on these should open the help
var usage = liberator.template.usage(liberator.options); var usage = template.usage(options);
liberator.echo(usage, liberator.commandline.FORCE_MULTILINE); liberator.echo(usage, commandline.FORCE_MULTILINE);
} }
}, },
{ {
@@ -368,12 +368,12 @@ const liberator = (function () //{{{
bang: true bang: true
}); });
liberator.commands.add(["q[uit]"], commands.add(["q[uit]"],
liberator.has("tabs") ? "Quit current tab" : "Quit application", liberator.has("tabs") ? "Quit current tab" : "Quit application",
function (args, special) function (args, special)
{ {
if (liberator.has("tabs")) if (liberator.has("tabs"))
liberator.tabs.remove(getBrowser().mCurrentTab, 1, false, 1); tabs.remove(getBrowser().mCurrentTab, 1, false, 1);
else else
liberator.quit(false, special); liberator.quit(false, special);
}, },
@@ -382,12 +382,12 @@ const liberator = (function () //{{{
bang: true bang: true
}); });
liberator.commands.add(["res[tart]"], commands.add(["res[tart]"],
"Force " + liberator.config.name + " to restart", "Force " + config.name + " to restart",
function () { liberator.restart(); }, function () { liberator.restart(); },
{ argCount: "0" }); { argCount: "0" });
liberator.commands.add(["time"], commands.add(["time"],
"Profile a piece of code or run a command multiple times", "Profile a piece of code or run a command multiple times",
function (args, special, count) function (args, special, count)
{ {
@@ -401,7 +401,7 @@ const liberator = (function () //{{{
let each, eachUnits, totalUnits; let each, eachUnits, totalUnits;
let total = 0; let total = 0;
for (let i in liberator.util.rangeInterruptable(0, count, 500)) for (let i in util.rangeInterruptable(0, count, 500))
{ {
let now = Date.now(); let now = Date.now();
liberator[method](args); liberator[method](args);
@@ -432,16 +432,16 @@ const liberator = (function () //{{{
totalUnits = "msec"; totalUnits = "msec";
} }
var str = liberator.template.generic( var str = template.generic(
<table> <table>
<tr class="hl-Title" align="left"> <tr class="hl-Title" align="left">
<th colspan="3">Code execution summary</th> <th colspan="3">Code execution summary</th>
</tr> </tr>
<tr><td>  Executed:</td><td align="right"><span class="times-executed">{count}</span></td><td>times</td></tr> <tr><td>\u00a0\u00a0Executed:</td><td align="right"><span class="times-executed">{count}</span></td><td>times</td></tr>
<tr><td>  Average time:</td><td align="right"><span class="time-average">{each.toFixed(2)}</span></td><td>{eachUnits}</td></tr> <tr><td>\u00a0\u00a0Average time:</td><td align="right"><span class="time-average">{each.toFixed(2)}</span></td><td>{eachUnits}</td></tr>
<tr><td>  Total time:</td><td align="right"><span class="time-total">{total.toFixed(2)}</span></td><td>{totalUnits}</td></tr> <tr><td>\u00a0\u00a0Total time:</td><td align="right"><span class="time-total">{total.toFixed(2)}</span></td><td>{totalUnits}</td></tr>
</table>); </table>);
liberator.commandline.echo(str, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE); commandline.echo(str, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
} }
else else
{ {
@@ -473,22 +473,22 @@ const liberator = (function () //{{{
completer: function (filter) completer: function (filter)
{ {
if (/^:/.test(filter)) if (/^:/.test(filter))
return liberator.completion.ex(filter); return completion.ex(filter);
else else
return liberator.completion.javascript(filter); return completion.javascript(filter);
}, },
count: true count: true
}); });
liberator.commands.add(["ve[rsion]"], commands.add(["ve[rsion]"],
"Show version information", "Show version information",
function (args, special) function (args, special)
{ {
if (special) if (special)
liberator.open("about:"); liberator.open("about:");
else else
liberator.echo(":" + liberator.util.escapeHTML(liberator.commandline.getCommand()) + "\n" + liberator.echo(":" + util.escapeHTML(commandline.getCommand()) + "\n" +
liberator.config.name + " " + liberator.version + config.name + " " + liberator.version +
" running on:\n" + navigator.userAgent); " running on:\n" + navigator.userAgent);
}, },
{ {
@@ -496,7 +496,7 @@ const liberator = (function () //{{{
bang: true bang: true
}); });
liberator.commands.add(["viu[sage]"], commands.add(["viu[sage]"],
"List all mappings with a short description", "List all mappings with a short description",
function (args, special) function (args, special)
{ {
@@ -507,8 +507,8 @@ const liberator = (function () //{{{
else else
{ {
// TODO: clicking on these should open the help // TODO: clicking on these should open the help
var usage = liberator.template.usage(liberator.mappings); var usage = template.usage(mappings);
liberator.echo(usage, liberator.commandline.FORCE_MULTILINE); liberator.echo(usage, commandline.FORCE_MULTILINE);
} }
}, },
{ {
@@ -521,7 +521,7 @@ const liberator = (function () //{{{
// similar in his config // similar in his config
function hideGUI() function hideGUI()
{ {
var guioptions = liberator.config.guioptions || {}; var guioptions = config.guioptions || {};
for (let option in guioptions) for (let option in guioptions)
{ {
guioptions[option].forEach(function (elem) { guioptions[option].forEach(function (elem) {
@@ -540,8 +540,10 @@ const liberator = (function () //{{{
return { return {
get mode() liberator.modes.main, modules: modules,
set mode(value) liberator.modes.main = value,
get mode() modes.main,
set mode(value) modes.main = value,
// Global constants // Global constants
CURRENT_TAB: 1, CURRENT_TAB: 1,
@@ -603,11 +605,11 @@ const liberator = (function () //{{{
beep: function () beep: function ()
{ {
if (liberator.options["visualbell"]) if (options["visualbell"])
{ {
// flash the visual bell // flash the visual bell
let popup = document.getElementById("liberator-visualbell"); let popup = document.getElementById("liberator-visualbell");
let win = liberator.config.visualbellWindow; let win = config.visualbellWindow;
let box = document.getBoxObjectFor(win); let box = document.getBoxObjectFor(win);
popup.openPopup(win, "overlap", 0, 0, false, false); popup.openPopup(win, "overlap", 0, 0, false, false);
@@ -627,10 +629,10 @@ const liberator = (function () //{{{
dump: function (message) dump: function (message)
{ {
if (typeof message == "object") if (typeof message == "object")
message = liberator.util.objectToString(message); message = util.objectToString(message);
else else
message += "\n"; message += "\n";
dump(liberator.config.name.toLowerCase() + ": " + message); dump(config.name.toLowerCase() + ": " + message);
}, },
dumpStack: function (msg) dumpStack: function (msg)
@@ -654,6 +656,12 @@ const liberator = (function () //{{{
e.source = str; e.source = str;
e.fileName = "<Evaled string>"; e.fileName = "<Evaled string>";
e.lineNumber -= line; e.lineNumber -= line;
if (modules.io && io.sourcing)
{
liberator.dump(io.sourcing);
e.fileName = io.sourcing.file;
e.lineNumber += io.sourcing.line;
}
} }
throw e; throw e;
} }
@@ -669,12 +677,12 @@ const liberator = (function () //{{{
modifiers = modifiers || {}; modifiers = modifiers || {};
let err = null; let err = null;
let [count, cmd, special, args] = liberator.commands.parseCommand(str.replace(/^'(.*)'$/, "$1")); let [count, cmd, special, args] = commands.parseCommand(str.replace(/^'(.*)'$/, "$1"));
let command = liberator.commands.get(cmd); let command = commands.get(cmd);
if (command === null) if (command === null)
{ {
err = "E492: Not a " + liberator.config.name.toLowerCase() + " command: " + str; err = "E492: Not a " + config.name.toLowerCase() + " command: " + str;
liberator.focusContent(); liberator.focusContent();
} }
else if (command.action === null) else if (command.action === null)
@@ -696,7 +704,7 @@ const liberator = (function () //{{{
liberator.echoerr(err); liberator.echoerr(err);
}, },
// TODO: move to liberator.buffer.focus()? // TODO: move to buffer.focus()?
// after pressing Escape, put focus on a non-input field of the browser document // after pressing Escape, put focus on a non-input field of the browser document
// if clearFocusedElement, also blur a focused link // if clearFocusedElement, also blur a focused link
focusContent: function (clearFocusedElement) focusContent: function (clearFocusedElement)
@@ -709,7 +717,7 @@ const liberator = (function () //{{{
// TODO: make more generic // TODO: make more generic
try try
{ {
if (liberator.has("mail") && clearFocusedElement && !liberator.config.isComposeWindow) if (liberator.has("mail") && clearFocusedElement && !config.isComposeWindow)
{ {
var i = gDBView.selection.currentIndex; var i = gDBView.selection.currentIndex;
if (i == -1 && gDBView.rowCount >= 0) if (i == -1 && gDBView.rowCount >= 0)
@@ -720,7 +728,7 @@ const liberator = (function () //{{{
} }
catch (e) {} catch (e) {}
var elem = liberator.config.mainWidget || window.content; var elem = config.mainWidget || window.content;
if (elem && (elem != document.commandDispatcher.focusedElement)) if (elem && (elem != document.commandDispatcher.focusedElement))
elem.focus(); elem.focus();
}, },
@@ -803,51 +811,51 @@ const liberator = (function () //{{{
echo: function (str, flags) echo: function (str, flags)
{ {
liberator.commandline.echo(str, liberator.commandline.HL_NORMAL, flags); commandline.echo(str, commandline.HL_NORMAL, flags);
}, },
// TODO: Vim replaces unprintable characters in echoerr/echomsg // TODO: Vim replaces unprintable characters in echoerr/echomsg
echoerr: function (str, flags) echoerr: function (str, flags)
{ {
flags |= liberator.commandline.APPEND_TO_MESSAGES; flags |= commandline.APPEND_TO_MESSAGES;
if (typeof str == "object" && "echoerr" in str) if (typeof str == "object" && "echoerr" in str)
str = str.echoerr; str = str.echoerr;
else if (str instanceof Error) else if (str instanceof Error)
str = str.fileName + ":" + str.lineNumber + ": " + str; str = str.fileName + ":" + str.lineNumber + ": " + str;
liberator.commandline.echo(str, liberator.commandline.HL_ERRORMSG, flags); commandline.echo(str, commandline.HL_ERRORMSG, flags);
}, },
// TODO: add proper level constants // TODO: add proper level constants
echomsg: function (str, verbosity, flags) echomsg: function (str, verbosity, flags)
{ {
flags |= liberator.commandline.APPEND_TO_MESSAGES; flags |= commandline.APPEND_TO_MESSAGES;
if (verbosity == null) if (verbosity == null)
verbosity = 0; // verbosity level is exclusionary verbosity = 0; // verbosity level is exclusionary
if (liberator.options["verbose"] >= verbosity) if (options["verbose"] >= verbosity)
liberator.commandline.echo(str, liberator.commandline.HL_INFOMSG, flags); commandline.echo(str, commandline.HL_INFOMSG, flags);
}, },
// return true, if this VIM-like extension has a certain feature // return true, if this VIM-like extension has a certain feature
has: function (feature) has: function (feature)
{ {
var features = liberator.config.features || []; var features = config.features || [];
return features.some(function (feat) feat == feature); return features.some(function (feat) feat == feature);
}, },
help: function (topic) help: function (topic)
{ {
var where = (liberator.options["newtab"] && liberator.options.get("newtab").has("all", "help")) var where = (options["newtab"] && options.get("newtab").has("all", "help"))
? liberator.NEW_TAB : liberator.CURRENT_TAB; ? liberator.NEW_TAB : liberator.CURRENT_TAB;
if (!topic) if (!topic)
{ {
var helpFile = liberator.options["helpfile"]; var helpFile = options["helpfile"];
if (liberator.config.helpFiles.indexOf(helpFile) != -1) if (config.helpFiles.indexOf(helpFile) != -1)
liberator.open("chrome://liberator/locale/" + helpFile, where); liberator.open("chrome://liberator/locale/" + helpFile, where);
else else
liberator.echo("Sorry, help file \"" + helpFile + "\" not found"); liberator.echo("Sorry, help file \"" + helpFile + "\" not found");
@@ -860,7 +868,7 @@ const liberator = (function () //{{{
liberator.open("chrome://liberator/locale/" + file, where); liberator.open("chrome://liberator/locale/" + file, where);
// TODO: it would be better wo wait for pageLoad // TODO: it would be better wo wait for pageLoad
setTimeout(function () { setTimeout(function () {
var elem = liberator.buffer.getElement('@class="tag" and text()="' + tag + '"'); var elem = buffer.getElement('@class="tag" and text()="' + tag + '"');
if (elem) if (elem)
window.content.scrollTo(0, elem.getBoundingClientRect().top - 10); // 10px context window.content.scrollTo(0, elem.getBoundingClientRect().top - 10); // 10px context
else else
@@ -868,7 +876,7 @@ const liberator = (function () //{{{
}, 500); }, 500);
} }
var [, items] = liberator.completion.help(topic); var [, items] = completion.help(topic);
var partialMatch = -1; var partialMatch = -1;
for (let i = 0; i < items.length; i++) for (let i = 0; i < items.length; i++)
@@ -899,7 +907,7 @@ const liberator = (function () //{{{
// FIXME: largely duplicated for loading macros // FIXME: largely duplicated for loading macros
try try
{ {
let dirs = liberator.io.getRuntimeDirectories("plugin"); let dirs = io.getRuntimeDirectories("plugin");
if (dirs.length > 0) if (dirs.length > 0)
{ {
@@ -910,15 +918,15 @@ const liberator = (function () //{{{
liberator.log("Sourcing plugin directory: " + dir.path + "...", 3); liberator.log("Sourcing plugin directory: " + dir.path + "...", 3);
let files = liberator.io.readDirectory(dir.path, true); let files = io.readDirectory(dir.path, true);
files.forEach(function (file) { files.forEach(function (file) {
if (!file.isDirectory() && /\.(js|vimp)$/i.test(file.path) && !(file.path in liberator.pluginFiles)) if (!file.isDirectory() && /\.(js|vimp)$/i.test(file.path) && !(file.path in pluginFiles))
{ {
try try
{ {
liberator.io.source(file.path, false); io.source(file.path, false);
liberator.pluginFiles[file.path] = true; pluginFiles[file.path] = true;
} }
catch (e) {}; catch (e) {};
} }
@@ -946,19 +954,19 @@ const liberator = (function () //{{{
if (typeof level != "number") // XXX if (typeof level != "number") // XXX
level = 1; level = 1;
// liberator.options does not exist at the very beginning // options does not exist at the very beginning
if (liberator.options) if (modules.options)
verbose = liberator.options.getPref("extensions.liberator.loglevel", 0); verbose = options.getPref("extensions.liberator.loglevel", 0);
if (level > verbose) if (level > verbose)
return; return;
if (typeof msg == "object") if (typeof msg == "object")
msg = liberator.util.objectToString(msg, false); msg = util.objectToString(msg, false);
var consoleService = Components.classes["@mozilla.org/consoleservice;1"] var consoleService = Components.classes["@mozilla.org/consoleservice;1"]
.getService(Components.interfaces.nsIConsoleService); .getService(Components.interfaces.nsIConsoleService);
consoleService.logStringMessage(liberator.config.name.toLowerCase() + ": " + msg); consoleService.logStringMessage(config.name.toLowerCase() + ": " + msg);
}, },
// open one or more URLs // open one or more URLs
@@ -974,13 +982,13 @@ const liberator = (function () //{{{
open: function (urls, where, force) open: function (urls, where, force)
{ {
// convert the string to an array of converted URLs // convert the string to an array of converted URLs
// -> see liberator.util.stringToURLArray for more details // -> see util.stringToURLArray for more details
if (typeof urls == "string") if (typeof urls == "string")
urls = liberator.util.stringToURLArray(urls); urls = util.stringToURLArray(urls);
if (urls.length > 20 && !force) if (urls.length > 20 && !force)
{ {
liberator.commandline.input("This will open " + urls.length + " new tabs. Would you like to continue? (yes/[no])", commandline.input("This will open " + urls.length + " new tabs. Would you like to continue? (yes/[no])",
function (resp) { if (resp && resp.match(/^y(es)?$/i)) liberator.open(urls, where, true); }); function (resp) { if (resp && resp.match(/^y(es)?$/i)) liberator.open(urls, where, true); });
return true; return true;
} }
@@ -1053,9 +1061,9 @@ const liberator = (function () //{{{
quit: function (saveSession, force) quit: function (saveSession, force)
{ {
if (saveSession) if (saveSession)
liberator.options.setPref("browser.startup.page", 3); // start with saved session options.setPref("browser.startup.page", 3); // start with saved session
else else
liberator.options.setPref("browser.startup.page", 1); // start with default homepage session options.setPref("browser.startup.page", 1); // start with default homepage session
const nsIAppStartup = Components.interfaces.nsIAppStartup; const nsIAppStartup = Components.interfaces.nsIAppStartup;
if (force) if (force)
@@ -1105,43 +1113,40 @@ const liberator = (function () //{{{
{ {
liberator.log("Initializing liberator object...", 0); liberator.log("Initializing liberator object...", 0);
// components which should be shared across all windows
Components.utils.import("resource://liberator/storage.jsm", liberator);
// commands must always be the first module to be initialized // commands must always be the first module to be initialized
loadModule("commands", liberator.Commands); addCommands(); loadModule("commands", Commands); addCommands();
loadModule("options", liberator.Options); addOptions(); loadModule("options", Options); addOptions();
loadModule("mappings", liberator.Mappings); addMappings(); loadModule("mappings", Mappings); addMappings();
loadModule("buffer", liberator.Buffer); loadModule("buffer", Buffer);
loadModule("events", liberator.Events); loadModule("events", Events);
loadModule("commandline", liberator.CommandLine); loadModule("commandline", CommandLine);
loadModule("statusline", liberator.StatusLine); loadModule("statusline", StatusLine);
loadModule("editor", liberator.Editor); loadModule("editor", Editor);
loadModule("autocommands", liberator.AutoCommands); loadModule("autocommands", AutoCommands);
loadModule("io", liberator.IO); loadModule("io", IO);
loadModule("completion", liberator.Completion); loadModule("completion", Completion);
// This adds options/mappings/commands which are only valid in this particular extension // This adds options/mappings/commands which are only valid in this particular extension
if (liberator.config.init) if (config.init)
liberator.config.init(); config.init();
liberator.log("All modules loaded", 3); liberator.log("All modules loaded", 3);
// TODO: move elsewhere // TODO: move elsewhere
liberator.registerCallback("submit", liberator.modes.EX, function (command) { liberator.execute(command); }); liberator.registerCallback("submit", modes.EX, function (command) { liberator.execute(command); });
liberator.registerCallback("complete", liberator.modes.EX, function (str) { return liberator.completion.ex(str); }); liberator.registerCallback("complete", modes.EX, function (str) { return completion.ex(str); });
// first time intro message // first time intro message
if (liberator.options.getPref("extensions." + liberator.config.name.toLowerCase() + ".firsttime", true)) if (options.getPref("extensions." + config.name.toLowerCase() + ".firsttime", true))
{ {
setTimeout(function () { setTimeout(function () {
liberator.help(); liberator.help();
liberator.options.setPref("extensions." + liberator.config.name.toLowerCase() + ".firsttime", false); options.setPref("extensions." + config.name.toLowerCase() + ".firsttime", false);
}, 1000); }, 1000);
} }
// always start in normal mode // always start in normal mode
liberator.modes.reset(); modes.reset();
// TODO: we should have some class where all this guioptions stuff fits well // TODO: we should have some class where all this guioptions stuff fits well
hideGUI(); hideGUI();
@@ -1150,45 +1155,45 @@ const liberator = (function () //{{{
// make sourcing asynchronous, otherwise commands that open new tabs won't work // make sourcing asynchronous, otherwise commands that open new tabs won't work
setTimeout(function () { setTimeout(function () {
var rcFile = liberator.io.getRCFile(); var rcFile = io.getRCFile();
if (rcFile) if (rcFile)
liberator.io.source(rcFile.path, true); io.source(rcFile.path, true);
else else
liberator.log("No user RC file found", 3); liberator.log("No user RC file found", 3);
if (liberator.options["loadplugins"]) if (options["loadplugins"])
liberator.loadPlugins; liberator.loadPlugins;
// after sourcing the initialization files, this function will set // after sourcing the initialization files, this function will set
// all gui options to their default values, if they have not been // all gui options to their default values, if they have not been
// set before by any rc file // set before by any rc file
for (let option in liberator.options) for (let option in options)
{ {
if (option.setter) if (option.setter)
option.value = option.value; option.value = option.value;
} }
liberator.triggerObserver("enter", null); liberator.triggerObserver("enter", null);
liberator.autocommands.trigger(liberator.config.name + "Enter", {}); autocommands.trigger(config.name + "Enter", {});
}, 0); }, 0);
liberator.statusline.update(); statusline.update();
liberator.log(liberator.config.name + " fully initialized", 0); liberator.log(config.name + " fully initialized", 0);
}, },
shutdown: function () shutdown: function ()
{ {
liberator.autocommands.trigger(liberator.config.name + "LeavePre", {}); autocommands.trigger(config.name + "LeavePre", {});
liberator.storage.saveAll(); storage.saveAll();
liberator.triggerObserver("shutdown", null); liberator.triggerObserver("shutdown", null);
liberator.dump("All liberator modules destroyed\n"); liberator.dump("All liberator modules destroyed\n");
liberator.autocommands.trigger(liberator.config.name + "Leave", {}); autocommands.trigger(config.name + "Leave", {});
}, },
sleep: function (ms) sleep: function (ms)
@@ -1255,6 +1260,8 @@ const liberator = (function () //{{{
//}}} //}}}
})(); //}}} })(); //}}}
window.liberator = liberator;
// called when the chrome is fully loaded and before the main window is shown // called when the chrome is fully loaded and before the main window is shown
window.addEventListener("load", liberator.startup, false); window.addEventListener("load", liberator.startup, false);
window.addEventListener("unload", liberator.shutdown, false); window.addEventListener("unload", liberator.shutdown, false);

View File

@@ -1,4 +1,4 @@
<?xml version="1.0"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- ***** BEGIN LICENSE BLOCK ***** {{{ <!-- ***** BEGIN LICENSE BLOCK ***** {{{
Version: MPL 1.1/GPL 2.0/LGPL 2.1 Version: MPL 1.1/GPL 2.0/LGPL 2.1
@@ -39,30 +39,13 @@ the terms of any one of the MPL, the GPL or the LGPL.
xmlns:html="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/x-javascript;version=1.8" src="&liberator.content;liberator.js"/> <script type="application/x-javascript;version=1.8" src="&liberator.content;liberator-overlay.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;&liberator.name;.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;buffer.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;commands.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;completion.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;editor.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;events.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;find.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;help.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;hints.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;io.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;mappings.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;modes.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;options.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;template.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;ui.js"/>
<script type="application/x-javascript;version=1.8" src="&liberator.content;util.js"/>
<window id="&liberator.mainWindow;"> <window id="&liberator.mainWindow;">
<keyset id="mainKeyset"> <keyset id="mainKeyset">
<key id="key_open_vimbar" key=":" oncommand="liberator.commandline.open(':', '', liberator.modes.EX);" modifiers=""/> <key id="key_open_vimbar" key=":" oncommand="liberator.modules.commandline.open(':', '', liberator.modules.modes.EX);" modifiers=""/>
<key id="key_stop" keycode="VK_ESCAPE" oncommand="liberator.events.onEscape();"/> <key id="key_stop" keycode="VK_ESCAPE" oncommand="liberator.modules.events.onEscape();"/>
<!-- other keys are handled inside the event loop in events.js --> <!-- other keys are handled inside the event loop in events.js -->
</keyset> </keyset>
@@ -75,39 +58,39 @@ the terms of any one of the MPL, the GPL or the LGPL.
<commandset id="onVimperatorFocus" <commandset id="onVimperatorFocus"
commandupdater="true" commandupdater="true"
events="focus" events="focus"
oncommandupdate="if (typeof liberator.events != 'undefined') liberator.events.onFocusChange(event);"/> oncommandupdate="if (typeof liberator.modules.events != 'undefined') liberator.modules.events.onFocusChange(event);"/>
<commandset id="onVimperatorSelect" <commandset id="onVimperatorSelect"
commandupdater="true" commandupdater="true"
events="select" events="select"
oncommandupdate="if (typeof liberator.events != 'undefined') liberator.events.onSelectionChange(event);"/> oncommandupdate="if (typeof liberator.modules.events != 'undefined') liberator.modules.events.onSelectionChange(event);"/>
<!-- As of Firefox 3.1pre, <iframe>.height changes do not seem to have immediate effect, <!-- As of Firefox 3.1pre, <iframe>.height changes do not seem to have immediate effect,
therefore we need to put them into a <vbox> for which that works just fine --> therefore we need to put them into a <vbox> for which that works just fine -->
<vbox class="liberator-container" hidden="false" collapsed="true"> <vbox class="liberator-container" hidden="false" collapsed="true">
<iframe id="liberator-multiline-output" src="chrome://liberator/content/buffer.xhtml" <iframe id="liberator-multiline-output" src="chrome://liberator/content/buffer.xhtml"
flex="1" hidden="false" collapsed="false" flex="1" hidden="false" collapsed="false"
onclick="liberator.commandline.onMultilineOutputEvent(event)"/> onclick="liberator.modules.commandline.onMultilineOutputEvent(event)"/>
</vbox> </vbox>
<vbox class="liberator-container" hidden="false" collapsed="true"> <vbox class="liberator-container" hidden="false" collapsed="true">
<iframe id="liberator-completions" src="chrome://liberator/content/buffer.xhtml" <iframe id="liberator-completions" src="chrome://liberator/content/buffer.xhtml"
flex="1" hidden="false" collapsed="false" flex="1" hidden="false" collapsed="false"
onclick="liberator.commandline.onMultilineOutputEvent(event)"/> onclick="liberator.modules.commandline.onMultilineOutputEvent(event)"/>
</vbox> </vbox>
<hbox id="liberator-commandline" hidden="false" class="hl-Normal"> <hbox id="liberator-commandline" hidden="false" class="hl-Normal">
<label class="plain" id="liberator-commandline-prompt" flex="0" crop="end" value="" collapsed="true"/> <label class="plain" id="liberator-commandline-prompt" flex="0" crop="end" value="" collapsed="true"/>
<textbox class="plain" id="liberator-commandline-command" flex="1" type="timed" timeout="100" <textbox class="plain" id="liberator-commandline-command" flex="1" type="timed" timeout="100"
oninput="liberator.commandline.onEvent(event);" oninput="liberator.modules.commandline.onEvent(event);"
onfocus="liberator.commandline.onEvent(event);" onfocus="liberator.modules.commandline.onEvent(event);"
onblur="liberator.commandline.onEvent(event);"/> onblur="liberator.modules.commandline.onEvent(event);"/>
</hbox> </hbox>
<vbox class="liberator-container" hidden="false" collapsed="false"> <vbox class="liberator-container" hidden="false" collapsed="false">
<textbox id="liberator-multiline-input" class="plain" flex="1" rows="1" hidden="false" collapsed="true" multiline="true" <textbox id="liberator-multiline-input" class="plain" flex="1" rows="1" hidden="false" collapsed="true" multiline="true"
onkeypress="liberator.commandline.onMultilineInputEvent(event);" onkeypress="liberator.modules.commandline.onMultilineInputEvent(event);"
oninput="liberator.commandline.onMultilineInputEvent(event);" oninput="liberator.modules.commandline.onMultilineInputEvent(event);"
onblur="liberator.commandline.onMultilineInputEvent(event);"/> onblur="liberator.modules.commandline.onMultilineInputEvent(event);"/>
</vbox> </vbox>
</window> </window>

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 *****/
with (liberator) liberator.Mail = function () //{{{ function Mail() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -92,7 +92,7 @@ with (liberator) liberator.Mail = function () //{{{
function getFolderCompletions(filter) function getFolderCompletions(filter)
{ {
var completions = []; var completions = [];
var folders = mail.getFolders(); var folders = liberator.mail.getFolders();
for (let folder = 0; folder < folders.length; folder++) for (let folder = 0; folder < folders.length; folder++)
{ {
@@ -113,38 +113,38 @@ with (liberator) liberator.Mail = function () //{{{
{ {
if (!destinationFolder) if (!destinationFolder)
{ {
echoerr("E471: Argument required"); liberator.echoerr("E471: Argument required");
return false; return false;
} }
var folders = mail.getFolders(destinationFolder); var folders = liberator.mail.getFolders(destinationFolder);
if (folders.length == 0) if (folders.length == 0)
{ {
echoerr("E94: No matching folder for " + destinationFolder); liberator.echoerr("E94: No matching folder for " + destinationFolder);
return false; return false;
} }
else if (folders.length > 1) else if (folders.length > 1)
{ {
echoerr("E93: More than one match for " + destinationFolder); liberator.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)
{ {
beep(); liberator.beep();
return false; return false;
} }
if (copy) if (copy)
{ {
MsgCopyMessage(folders[0]); MsgCopyMessage(folders[0]);
setTimeout(function () { echo(count + " message(s) copied to " + folders[0].prettyName); }, 100); setTimeout(function () { liberator.echo(count + " message(s) copied to " + folders[0].prettyName); }, 100);
} }
else else
{ {
MsgMoveMessage(folders[0]); MsgMoveMessage(folders[0]);
setTimeout(function () { echo(count + " message(s) moved to " + folders[0].prettyName); }, 100); setTimeout(function () { liberator.echo(count + " message(s) moved to " + folders[0].prettyName); }, 100);
} }
return true; return true;
} }
@@ -184,7 +184,7 @@ with (liberator) liberator.Mail = function () //{{{
i += direction; i += direction;
} }
if (!folder || count > 0) if (!folder || count > 0)
beep(); liberator.beep();
else else
tree.view.selection.timedSelect(c + folder, tree._selectDelay); tree.view.selection.timedSelect(c + folder, tree._selectDelay);
} }
@@ -252,7 +252,7 @@ with (liberator) liberator.Mail = function () //{{{
function () function ()
{ {
if (gDBView && gDBView.selection.count < 1) if (gDBView && gDBView.selection.count < 1)
return beep(); return liberator.beep();
MsgOpenNewTabForMessage(); MsgOpenNewTabForMessage();
}); });
@@ -276,32 +276,32 @@ with (liberator) liberator.Mail = function () //{{{
mappings.add(myModes, ["j", "<Right>"], mappings.add(myModes, ["j", "<Right>"],
"Select next message", "Select next message",
function (count) { mail.selectMessage(function (msg) true, false, false, false, count); }, function (count) { liberator.mail.selectMessage(function (msg) true, false, false, false, count); },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
mappings.add(myModes, ["gj"], mappings.add(myModes, ["gj"],
"Select next message, including closed threads", "Select next message, including closed threads",
function (count) { mail.selectMessage(function (msg) true, false, true, false, count); }, function (count) { liberator.mail.selectMessage(function (msg) true, false, true, false, count); },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
mappings.add(myModes, ["J", "<Tab>"], mappings.add(myModes, ["J", "<Tab>"],
"Select next unread message", "Select next unread message",
function (count) { mail.selectMessage(function (msg) !msg.isRead, true, true, false, count); }, function (count) { liberator.mail.selectMessage(function (msg) !msg.isRead, true, true, false, count); },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
mappings.add(myModes, ["k", "<Left>"], mappings.add(myModes, ["k", "<Left>"],
"Select previous message", "Select previous message",
function (count) { mail.selectMessage(function (msg) true, false, false, true, count); }, function (count) { liberator.mail.selectMessage(function (msg) true, false, false, true, count); },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
mappings.add(myModes, ["gk"], mappings.add(myModes, ["gk"],
"Select previous message", "Select previous message",
function (count) { mail.selectMessage(function (msg) true, false, true, true, count); }, function (count) { liberator.mail.selectMessage(function (msg) true, false, true, true, count); },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
mappings.add(myModes, ["K"], mappings.add(myModes, ["K"],
"Select previous unread message", "Select previous unread message",
function (count) { mail.selectMessage(function (msg) !msg.isRead, true, true, true, count); }, function (count) { liberator.mail.selectMessage(function (msg) !msg.isRead, true, true, true, count); },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
mappings.add(myModes, ["*"], mappings.add(myModes, ["*"],
@@ -311,9 +311,9 @@ with (liberator) liberator.Mail = function () //{{{
try try
{ {
var author = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor.toLowerCase(); var author = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor.toLowerCase();
mail.selectMessage(function (msg) msg.mime2DecodedAuthor.toLowerCase().indexOf(author) == 0, true, true, false, count); liberator.mail.selectMessage(function (msg) msg.mime2DecodedAuthor.toLowerCase().indexOf(author) == 0, true, true, false, count);
} }
catch (e) { beep(); } catch (e) { liberator.beep(); }
}, },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
@@ -324,9 +324,9 @@ with (liberator) liberator.Mail = function () //{{{
try try
{ {
var author = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor.toLowerCase(); var author = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor.toLowerCase();
mail.selectMessage(function (msg) msg.mime2DecodedAuthor.toLowerCase().indexOf(author) == 0, true, true, true, count); liberator.mail.selectMessage(function (msg) msg.mime2DecodedAuthor.toLowerCase().indexOf(author) == 0, true, true, true, count);
} }
catch (e) { beep(); } catch (e) { liberator.beep(); }
}, },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
@@ -346,7 +346,7 @@ with (liberator) liberator.Mail = function () //{{{
} }
catch (e) catch (e)
{ {
beep(); liberator.beep();
} }
}); });
@@ -379,12 +379,12 @@ with (liberator) liberator.Mail = function () //{{{
mappings.add([modes.MESSAGE], ["<Left>"], mappings.add([modes.MESSAGE], ["<Left>"],
"Select previous message", "Select previous message",
function (count) { mail.selectMessage(function (msg) true, false, false, true, count); }, function (count) { liberator.mail.selectMessage(function (msg) true, false, false, true, count); },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
mappings.add([modes.MESSAGE], ["<Right>"], mappings.add([modes.MESSAGE], ["<Right>"],
"Select next message", "Select next message",
function (count) { mail.selectMessage(function (msg) true, false, false, false, count); }, function (count) { liberator.mail.selectMessage(function (msg) true, false, false, false, count); },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
// UNDO/REDO // UNDO/REDO
@@ -395,7 +395,7 @@ with (liberator) liberator.Mail = function () //{{{
if (messenger.canUndo()) if (messenger.canUndo())
messenger.undo(msgWindow); messenger.undo(msgWindow);
else else
beep(); liberator.beep();
}); });
mappings.add(myModes, ["<C-r>"], mappings.add(myModes, ["<C-r>"],
"Redo", "Redo",
@@ -404,17 +404,17 @@ with (liberator) liberator.Mail = function () //{{{
if (messenger.canRedo()) if (messenger.canRedo())
messenger.redo(msgWindow); messenger.redo(msgWindow);
else else
beep(); liberator.beep();
}); });
// GETTING MAIL // GETTING MAIL
mappings.add(myModes, ["gm"], mappings.add(myModes, ["gm"],
"Get new messages", "Get new messages",
function () { mail.getNewMessages(); }); function () { liberator.mail.getNewMessages(); });
mappings.add(myModes, ["gM"], mappings.add(myModes, ["gM"],
"Get new messages for current account only", "Get new messages for current account only",
function () { mail.getNewMessages(true); }); function () { liberator.mail.getNewMessages(true); });
// MOVING MAIL // MOVING MAIL
mappings.add(myModes, ["c"], mappings.add(myModes, ["c"],
@@ -435,22 +435,22 @@ with (liberator) liberator.Mail = function () //{{{
mappings.add(myModes, ["]s"], mappings.add(myModes, ["]s"],
"Select next starred message", "Select next starred message",
function (count) { mail.selectMessage(function (msg) msg.isFlagged, true, true, false, count); }, function (count) { liberator.mail.selectMessage(function (msg) msg.isFlagged, true, true, false, count); },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
mappings.add(myModes, ["[s"], mappings.add(myModes, ["[s"],
"Select previous starred message", "Select previous starred message",
function (count) { mail.selectMessage(function (msg) msg.isFlagged, true, true, true, count); }, function (count) { liberator.mail.selectMessage(function (msg) msg.isFlagged, true, true, true, count); },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
mappings.add(myModes, ["]a"], mappings.add(myModes, ["]a"],
"Select next message with an attachment", "Select next message with an attachment",
function (count) { mail.selectMessage(function (msg) gDBView.db.HasAttachments(msg.messageKey), true, true, false, count); }, function (count) { liberator.mail.selectMessage(function (msg) gDBView.db.HasAttachments(msg.messageKey), true, true, false, count); },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
mappings.add(myModes, ["[a"], mappings.add(myModes, ["[a"],
"Select previous message with an attachment", "Select previous message with an attachment",
function (count) { mail.selectMessage(function (msg) gDBView.db.HasAttachments(msg.messageKey), true, true, true, count); }, function (count) { liberator.mail.selectMessage(function (msg) gDBView.db.HasAttachments(msg.messageKey), true, true, true, count); },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
// FOLDER SWITCHING // FOLDER SWITCHING
@@ -458,11 +458,11 @@ with (liberator) liberator.Mail = function () //{{{
"Go to inbox", "Go to inbox",
function (count) function (count)
{ {
var folder = mail.getFolders("Inbox", false, true)[(count > 0) ? (count - 1) : 0]; var folder = liberator.mail.getFolders("Inbox", false, true)[(count > 0) ? (count - 1) : 0];
if (folder) if (folder)
SelectFolder(folder.URI); SelectFolder(folder.URI);
else else
beep(); liberator.beep();
}, },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
@@ -475,7 +475,7 @@ with (liberator) liberator.Mail = function () //{{{
var c = tree.currentIndex; var c = tree.currentIndex;
if (c + count >= tree.view.rowCount) if (c + count >= tree.view.rowCount)
{ {
beep(); liberator.beep();
return; return;
} }
tree.view.selection.timedSelect(c + count, tree._selectDelay ); tree.view.selection.timedSelect(c + count, tree._selectDelay );
@@ -499,7 +499,7 @@ with (liberator) liberator.Mail = function () //{{{
var c = tree.currentIndex; var c = tree.currentIndex;
if (c - count < 0) if (c - count < 0)
{ {
beep(); liberator.beep();
return; return;
} }
tree.view.selection.timedSelect(c - count, tree._selectDelay ); tree.view.selection.timedSelect(c - count, tree._selectDelay );
@@ -517,15 +517,15 @@ with (liberator) liberator.Mail = function () //{{{
// THREADING // THREADING
mappings.add(myModes, ["za"], mappings.add(myModes, ["za"],
"Toggle thread collapsed/expanded", "Toggle thread collapsed/expanded",
function () { if (!mail.expandThread()) mail.collapseThread(); }); function () { if (!liberator.mail.expandThread()) liberator.mail.collapseThread(); });
mappings.add(myModes, ["zc"], mappings.add(myModes, ["zc"],
"Collapse thread", "Collapse thread",
function () { mail.collapseThread(); }); function () { liberator.mail.collapseThread(); });
mappings.add(myModes, ["zo"], mappings.add(myModes, ["zo"],
"Open thread", "Open thread",
function () { mail.expandThread(); }); function () { liberator.mail.expandThread(); });
mappings.add(myModes, ["zr", "zR"], mappings.add(myModes, ["zr", "zR"],
"Expand all threads", "Expand all threads",
@@ -561,7 +561,7 @@ with (liberator) liberator.Mail = function () //{{{
function (arg) function (arg)
{ {
if (!GetSelectedMessages()) if (!GetSelectedMessages())
return beep(); return liberator.beep();
switch (arg) switch (arg)
{ {
@@ -572,7 +572,7 @@ with (liberator) 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: beep(); default: liberator.beep();
} }
}, },
{ {
@@ -584,17 +584,17 @@ with (liberator) liberator.Mail = function () //{{{
"Mark current folder as read", "Mark current folder as read",
function () function ()
{ {
if (mail.currentFolder.isServer) if (liberator.mail.currentFolder.isServer)
return beep(); return liberator.beep();
mail.currentFolder.markAllMessagesRead(); liberator.mail.currentFolder.markAllMessagesRead();
}); });
mappings.add(myModes, ["<C-t>"], mappings.add(myModes, ["<C-t>"],
"Mark all messages as read", "Mark all messages as read",
function () function ()
{ {
mail.getFolders("", false).forEach(function (folder) { folder.markAllMessagesRead(); }); liberator.mail.getFolders("", false).forEach(function (folder) { folder.markAllMessagesRead(); });
}); });
// DISPLAY OPTIONS // DISPLAY OPTIONS
@@ -612,7 +612,7 @@ with (liberator) liberator.Mail = function () //{{{
function () function ()
{ {
var want_html = (gPrefBranch.getIntPref("mailnews.display.html_as", 1) == 1); var want_html = (gPrefBranch.getIntPref("mailnews.display.html_as", 1) == 1);
mail.setHTML(want_html ? 1 : 0); liberator.mail.setHTML(want_html ? 1 : 0);
}); });
// YANKING TEXT // YANKING TEXT
@@ -625,7 +625,7 @@ with (liberator) liberator.Mail = function () //{{{
var subject = gDBView.hdrForFirstSelectedMessage.mime2DecodedSubject; var subject = gDBView.hdrForFirstSelectedMessage.mime2DecodedSubject;
util.copyToClipboard(subject, true); util.copyToClipboard(subject, true);
} }
catch (e) { beep(); } catch (e) { liberator.beep(); }
}); });
mappings.add(myModes, ["y"], mappings.add(myModes, ["y"],
@@ -634,12 +634,12 @@ with (liberator) liberator.Mail = function () //{{{
{ {
try try
{ {
if (mail.currentAccount.server.type == "rss") if (liberator.mail.currentAccount.server.type == "rss")
util.copyToClipboard(getRSSUrl(), true); util.copyToClipboard(getRSSUrl(), true);
else else
util.copyToClipboard(gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor, true); util.copyToClipboard(gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor, true);
} }
catch (e) { beep(); } catch (e) { liberator.beep(); }
}); });
// RSS specific mappings // RSS specific mappings
@@ -649,13 +649,13 @@ with (liberator) liberator.Mail = function () //{{{
{ {
try try
{ {
if (mail.currentAccount.server.type == "rss") if (liberator.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)
{ {
beep(); liberator.beep();
} }
}); });
@@ -670,10 +670,10 @@ with (liberator) liberator.Mail = function () //{{{
args = args || "Inbox"; args = args || "Inbox";
count = count > 0 ? (count - 1) : 0; count = count > 0 ? (count - 1) : 0;
var folder = mail.getFolders(args, true, true)[count]; var folder = liberator.mail.getFolders(args, true, true)[count];
if (!folder) if (!folder)
echoerr("Folder \"" + args + "\" does not exist"); liberator.echoerr("Folder \"" + args + "\" does not exist");
else if (forceNewTab) else if (liberator.forceNewTab)
MsgOpenNewTabForFolder(folder.URI); MsgOpenNewTabForFolder(folder.URI);
else else
SelectFolder(folder.URI); SelectFolder(folder.URI);
@@ -704,11 +704,11 @@ with (liberator) 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))))
{ {
echoerr("Exxx: Invalid e-mail address"); liberator.echoerr("Exxx: Invalid e-mail address");
return; return;
} }
mail.composeNewMail(mailargs); liberator.mail.composeNewMail(mailargs);
}, },
{ {
options: [[["-subject", "-s"], commands.OPTION_STRING], options: [[["-subject", "-s"], commands.OPTION_STRING],
@@ -735,7 +735,7 @@ with (liberator) liberator.Mail = function () //{{{
commands.add(["get[messages]"], commands.add(["get[messages]"],
"Check for new messages", "Check for new messages",
function (args, special) mail.getNewMessages(!special), function (args, special) liberator.mail.getNewMessages(!special),
{ {
argCount: "0", argCount: "0",
bang: true, bang: true,
@@ -788,7 +788,7 @@ with (liberator) liberator.Mail = function () //{{{
var file = io.getFile(url); var file = io.getFile(url);
if (!file.exists()) if (!file.exists())
{ {
echoerr("Exxx: Could not attach file `" + url + "'", commandline.FORCE_SINGLELINE); liberator.echoerr("Exxx: Could not attach file `" + url + "'", commandline.FORCE_SINGLELINE);
return; return;
} }
@@ -848,7 +848,7 @@ with (liberator) liberator.Mail = function () //{{{
} }
catch (e) catch (e)
{ {
log("Error getting messages for account " + account.prettyName + ": " + e); liberator.log("Error getting messages for account " + account.prettyName + ": " + e);
} }
}); });
}, },
@@ -1006,7 +1006,7 @@ with (liberator) liberator.Mail = function () //{{{
} }
catch (e) catch (e)
{ {
dump("ERROR: " + folder.prettyName + " failed to getMessages\n"); liberator.dump("ERROR: " + folder.prettyName + " failed to getMessages\n");
continue; continue;
} }
@@ -1031,7 +1031,7 @@ with (liberator) liberator.Mail = function () //{{{
// TODO: finally for the "rest" of the current folder // TODO: finally for the "rest" of the current folder
beep(); liberator.beep();
}, },
setHTML: function (value) setHTML: function (value)

View File

@@ -28,7 +28,7 @@ the terms of any one of the MPL, the GPL or the LGPL.
// Do NOT create instances of this class yourself, use the helper method // Do NOT create instances of this class yourself, use the helper method
// mappings.add() instead // mappings.add() instead
with (liberator) liberator.Map = function (modes, cmds, description, action, extraInfo) //{{{ function Map(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 @@ with (liberator) liberator.Map = function (modes, cmds, description, action, ext
this.noremap = extraInfo.noremap || false; this.noremap = extraInfo.noremap || false;
}; };
with (liberator) liberator.Map.prototype = { Map.prototype = {
hasName: function (name) hasName: function (name)
{ {
@@ -74,7 +74,7 @@ with (liberator) liberator.Map.prototype = {
}; //}}} }; //}}}
with (liberator) liberator.Mappings = function () //{{{ function Mappings() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -225,7 +225,7 @@ with (liberator) liberator.Mappings = function () //{{{
{ {
if (!args) if (!args)
{ {
echoerr("E474: Invalid argument"); liberator.echoerr("E474: Invalid argument");
return; return;
} }
@@ -239,7 +239,7 @@ with (liberator) liberator.Mappings = function () //{{{
} }
} }
if (!found) if (!found)
echoerr("E31: No such mapping"); liberator.echoerr("E31: No such mapping");
}, },
{ completer: function (filter) completion.userMapping(filter, modes) }); { completer: function (filter) completion.userMapping(filter, modes) });
} }
@@ -336,7 +336,7 @@ with (liberator) liberator.Mappings = function () //{{{
getMapLeader: function () getMapLeader: function ()
{ {
var leaderRef = variableReference("mapleader"); var leaderRef = liberator.variableReference("mapleader");
return leaderRef[0] ? leaderRef[0][leaderRef[1]] : "\\"; return leaderRef[0] ? leaderRef[0][leaderRef[1]] : "\\";
}, },
@@ -364,7 +364,7 @@ with (liberator) liberator.Mappings = function () //{{{
if (!maps || maps.length == 0) if (!maps || maps.length == 0)
{ {
echo("No mappings found"); liberator.echo("No mappings found");
return; return;
} }
@@ -394,7 +394,7 @@ with (liberator) liberator.Mappings = function () //{{{
var flag = output.some(function (x) x); var flag = output.some(function (x) x);
if (!flag) if (!flag)
{ {
echo("No mappings found"); liberator.echo("No mappings found");
return; return;
} }

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 *****/
with (liberator) liberator.modes = (function () //{{{ const modes = (function () //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -100,8 +100,8 @@ with (liberator) liberator.modes = (function () //{{{
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
//log("switching from mode " + oldMode + " to mode " + newMode, 7); //liberator.log("switching from mode " + oldMode + " to mode " + newMode, 7);
//dump("switching from mode " + oldMode + " to mode " + newMode + "\n"); //liberator.dump("switching from mode " + oldMode + " to mode " + newMode + "\n");
switch (oldMode) switch (oldMode)
{ {
@@ -146,7 +146,7 @@ with (liberator) liberator.modes = (function () //{{{
options.setPref("accessibility.browsewithcaret", false); options.setPref("accessibility.browsewithcaret", false);
statusline.updateUrl(); statusline.updateUrl();
focusContent(false); liberator.focusContent(false);
} }
} }

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 *****/
with (liberator) liberator.config = { //{{{ const 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");
@@ -103,6 +103,12 @@ with (liberator) liberator.config = { //{{{
"various.html" "various.html"
],*/ ],*/
scripts: [
"addressbook.js",
"mail.js",
"tabs.js",
],
init: function () init: function ()
{ {
// don't wait too long when selecting new messages // don't wait too long when selecting new messages
@@ -119,7 +125,7 @@ with (liberator) 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
//loadModule("addressbook", Addressbook); //liberator.loadModule("addressbook", Addressbook);
// TODO: move mappings elsewhere, probably compose.js // TODO: move mappings elsewhere, probably compose.js
mappings.add([modes.COMPOSE], mappings.add([modes.COMPOSE],
@@ -200,11 +206,11 @@ with (liberator) liberator.config = { //{{{
} }
else else
{ {
loadModule("mail", Mail); liberator.loadModule("mail", Mail);
loadModule("addressbook", Addressbook); liberator.loadModule("addressbook", Addressbook);
loadModule("tabs", Tabs); liberator.loadModule("tabs", Tabs);
loadModule("marks", Marks); liberator.loadModule("marks", Marks);
loadModule("hints", Hints); liberator.loadModule("hints", Hints);
} }
} }
}; //}}} }; //}}}

View File

@@ -36,10 +36,6 @@ the terms of any one of the MPL, the GPL or the LGPL.
xmlns:html="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/x-javascript;version=1.8" src="addressbook.js"/>
<script type="application/x-javascript;version=1.8" src="mail.js"/>
<script type="application/x-javascript;version=1.8" src="tabs.js"/>
</overlay> </overlay>
<!-- vim: set fdm=marker sw=4 ts=4 et: --> <!-- vim: set fdm=marker sw=4 ts=4 et: -->

View File

@@ -37,25 +37,7 @@ the terms of any one of the MPL, the GPL or the LGPL.
xmlns:html="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/x-javascript;version=1.8" src="liberator.js"/> <script type="application/x-javascript;version=1.8" src="liberator-overlay.js"/>
<script type="application/x-javascript;version=1.8" src="muttator.js"/>
<!--script type="application/x-javascript;version=1.8" src="mail.js"/-->
<script type="application/x-javascript;version=1.8" src="buffer.js"/>
<script type="application/x-javascript;version=1.8" src="commands.js"/>
<script type="application/x-javascript;version=1.8" src="completion.js"/>
<script type="application/x-javascript;version=1.8" src="editor.js"/>
<script type="application/x-javascript;version=1.8" src="events.js"/>
<script type="application/x-javascript;version=1.8" src="find.js"/>
<script type="application/x-javascript;version=1.8" src="help.js"/>
<script type="application/x-javascript;version=1.8" src="hints.js"/>
<script type="application/x-javascript;version=1.8" src="io.js"/>
<script type="application/x-javascript;version=1.8" src="mappings.js"/>
<script type="application/x-javascript;version=1.8" src="modes.js"/>
<script type="application/x-javascript;version=1.8" src="options.js"/>
<script type="application/x-javascript;version=1.8" src="template.js"/>
<script type="application/x-javascript;version=1.8" src="ui.js"/>
<script type="application/x-javascript;version=1.8" src="util.js"/>
<window id="msgcomposeWindow"> <window id="msgcomposeWindow">

View File

@@ -28,7 +28,7 @@ the terms of any one of the MPL, the GPL or the LGPL.
// do NOT create instances of this class yourself, use the helper method // do NOT create instances of this class yourself, use the helper method
// options.add() instead // options.add() instead
with (liberator) liberator.Option = function (names, description, type, defaultValue, extraInfo) //{{{ function Option(names, description, type, defaultValue, extraInfo) //{{{
{ {
if (!names || !type) if (!names || !type)
return null; return null;
@@ -112,7 +112,7 @@ with (liberator) liberator.Option = function (names, description, type, defaultV
if (newValue === undefined) if (newValue === undefined)
{ {
newValue = tmpValue; newValue = tmpValue;
log("DEPRECATED: '" + this.name + "' setter should return a value"); liberator.log("DEPRECATED: '" + this.name + "' setter should return a value");
} }
} }
@@ -156,7 +156,7 @@ with (liberator) liberator.Option = function (names, description, type, defaultV
}; //}}} }; //}}}
with (liberator) liberator.Options = function () //{{{ function Options() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -176,7 +176,7 @@ with (liberator) liberator.Options = function () //{{{
storage.newMap("options", false); storage.newMap("options", false);
storage.addObserver("options", optionObserver); storage.addObserver("options", optionObserver);
registerObserver("shutdown", function () { liberator.registerObserver("shutdown", function () {
storage.removeObserver("options", optionObserver) storage.removeObserver("options", optionObserver)
}); });
@@ -189,26 +189,26 @@ with (liberator) 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)
echoerr("E521: Number required after =: " + name + "=" + value); liberator.echoerr("E521: Number required after =: " + name + "=" + value);
else else
echoerr("E474: Invalid argument: " + name + "=" + value); liberator.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
echoerr("E474: Invalid argument: " + name + "=" + value); liberator.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)
echoerr("E521: Number required after =: " + name + "=" + value); liberator.echoerr("E521: Number required after =: " + name + "=" + value);
else else
echoerr("E474: Invalid argument: " + name + "=" + value); liberator.echoerr("E474: Invalid argument: " + name + "=" + value);
break; break;
default: default:
echoerr("Unknown preference type: " + typeof value + " (" + name + "=" + value + ")"); liberator.echoerr("Unknown preference type: " + typeof value + " (" + name + "=" + value + ")");
} }
} }
@@ -254,7 +254,7 @@ with (liberator) 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");
registerObserver("shutdown", function () liberator.registerObserver("shutdown", function ()
{ {
if (loadPreference("dom.popup_allowed_events", "") if (loadPreference("dom.popup_allowed_events", "")
== popupAllowedEvents + " keypress") == popupAllowedEvents + " keypress")
@@ -296,9 +296,9 @@ with (liberator) liberator.Options = function () //{{{
} }
</table>; </table>;
if (str.*.length()) if (str.*.length())
echo(str, commandline.FORCE_MULTILINE); liberator.echo(str, commandline.FORCE_MULTILINE);
else else
echo("No variables found"); liberator.echo("No variables found");
return; return;
} }
@@ -308,17 +308,17 @@ with (liberator) liberator.Options = function () //{{{
{ {
if (!matches[1]) if (!matches[1])
{ {
var reference = variableReference(matches[2]); var reference = liberator.variableReference(matches[2]);
if (!reference[0] && matches[3]) if (!reference[0] && matches[3])
{ {
echoerr("E121: Undefined variable: " + matches[2]); liberator.echoerr("E121: Undefined variable: " + matches[2]);
return; return;
} }
var expr = evalExpression(matches[4]); var expr = liberator.evalExpression(matches[4]);
if (expr === undefined) if (expr === undefined)
{ {
echoerr("E15: Invalid expression: " + matches[4]); liberator.echoerr("E15: Invalid expression: " + matches[4]);
return; return;
} }
else else
@@ -348,10 +348,10 @@ with (liberator) 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 = variableReference(matches[1]); var reference = liberator.variableReference(matches[1]);
if (!reference[0]) if (!reference[0])
{ {
echoerr("E121: Undefined variable: " + matches[1]); liberator.echoerr("E121: Undefined variable: " + matches[1]);
return; return;
} }
@@ -359,7 +359,7 @@ with (liberator) liberator.Options = function () //{{{
let prefix = typeof value == "number" ? "#" : let prefix = typeof value == "number" ? "#" :
typeof value == "function" ? "*" : typeof value == "function" ? "*" :
" "; " ";
echo(reference[1] + "\t\t" + prefix + value); liberator.echo(reference[1] + "\t\t" + prefix + value);
} }
}); });
@@ -369,9 +369,9 @@ with (liberator) liberator.Options = function () //{{{
{ {
if (special) // open Firefox settings GUI dialog if (special) // open Firefox settings GUI dialog
{ {
open("about:config", liberator.open("about:config",
(options["newtab"] && options.get("newtab").has("all", "prefs")) (options["newtab"] && options.get("newtab").has("all", "prefs"))
? NEW_TAB : CURRENT_TAB); ? liberator.NEW_TAB : liberator.CURRENT_TAB);
} }
else else
{ {
@@ -488,7 +488,7 @@ with (liberator) liberator.Options = function () //{{{
let invertBoolean = (postfix == "!"); let invertBoolean = (postfix == "!");
if (name == "all" && reset) if (name == "all" && reset)
echoerr("You can't reset all options, it could make " + config.hostApplication + " unusable."); liberator.echoerr("You can't reset all options, it could make " + config.hostApplication + " unusable.");
else if (name == "all") else if (name == "all")
options.listPrefs(onlyNonDefault, ""); options.listPrefs(onlyNonDefault, "");
else if (reset) else if (reset)
@@ -524,14 +524,14 @@ with (liberator) liberator.Options = function () //{{{
let opt = parseOpt(args, modifiers); let opt = parseOpt(args, modifiers);
if (!opt) if (!opt)
{ {
echoerr("Error parsing :set command: " + args); liberator.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)
{ {
echoerr("No such option: " + opt.name); liberator.echoerr("No such option: " + opt.name);
return; return;
} }
@@ -558,9 +558,9 @@ with (liberator) liberator.Options = function () //{{{
else else
{ {
if (option.type == "boolean") if (option.type == "boolean")
echo((opt.optionValue ? " " : "no") + option.name); liberator.echo((opt.optionValue ? " " : "no") + option.name);
else else
echo(" " + option.name + "=" + opt.optionValue); liberator.echo(" " + option.name + "=" + opt.optionValue);
} }
} }
// write access // write access
@@ -576,7 +576,7 @@ with (liberator) liberator.Options = function () //{{{
case "boolean": case "boolean":
if (opt.valueGiven) if (opt.valueGiven)
{ {
echoerr("E474: Invalid argument: " + args); liberator.echoerr("E474: Invalid argument: " + args);
return; return;
} }
@@ -592,7 +592,7 @@ with (liberator) liberator.Options = function () //{{{
if (isNaN(value)) if (isNaN(value))
{ {
echoerr("E521: Number required after =: " + args); liberator.echoerr("E521: Number required after =: " + args);
return; return;
} }
@@ -662,7 +662,7 @@ with (liberator) liberator.Options = function () //{{{
break; break;
default: default:
echoerr("E685: Internal error: option type `" + option.type + "' not supported"); liberator.echoerr("E685: Internal error: option type `" + option.type + "' not supported");
} }
if (option.isValidValue(newValue)) if (option.isValidValue(newValue))
@@ -671,7 +671,7 @@ with (liberator) 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
echoerr("E474: Invalid argument: " + args); liberator.echoerr("E474: Invalid argument: " + args);
} }
}, },
{ {
@@ -806,11 +806,11 @@ with (liberator) 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 = variableReference(name); var reference = liberator.variableReference(name);
if (!reference[0]) if (!reference[0])
{ {
if (!special) if (!special)
echoerr("E108: No such variable: " + name); liberator.echoerr("E108: No such variable: " + name);
return; return;
} }
@@ -851,7 +851,7 @@ with (liberator) liberator.Options = function () //{{{
if (option.name in optionHash) if (option.name in optionHash)
{ {
// never replace for now // never replace for now
log("Warning: '" + names[0] + "' already exists, NOT replacing existing option.", 1); liberator.log("Warning: '" + names[0] + "' already exists, NOT replacing existing option.", 1);
return false; return false;
} }
@@ -892,7 +892,7 @@ with (liberator) liberator.Options = function () //{{{
isDefault: opt.value == opt.defaultValue, isDefault: opt.value == opt.defaultValue,
name: opt.name, name: opt.name,
default: opt.defaultValue, default: opt.defaultValue,
pre: "  ", /* Unicode nonbreaking space. */ pre: "\u00a0\u00a0", /* Unicode nonbreaking space. */
value: <></>, value: <></>,
}; };
@@ -942,7 +942,7 @@ with (liberator) liberator.Options = function () //{{{
default: loadPreference(pref, null, true), default: loadPreference(pref, null, true),
value: <>={template.highlight(value)}</>, value: <>={template.highlight(value)}</>,
name: pref, name: pref,
pre: "  ", /* Unicode nonbreaking space. */ pre: "\u00a0\u00a0", /* Unicode nonbreaking space. */
}; };
yield option; yield option;
@@ -976,7 +976,7 @@ with (liberator) 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
echoerr("E488: Trailing characters: " + name + "!"); liberator.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
with (liberator) liberator.Tabs = function () //{{{ function Tabs() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -336,9 +336,9 @@ with (liberator) liberator.Tabs = function () //{{{
} }
if (removed > 0) if (removed > 0)
echo(removed + " fewer tab(s)"); liberator.echo(removed + " fewer tab(s)");
else else
echoerr("E94: No matching tab for " + args); liberator.echoerr("E94: No matching tab for " + args);
} }
else // just remove the current tab else // just remove the current tab
tabs.remove(getBrowser().mCurrentTab, count > 0 ? count : 1, special, 0); tabs.remove(getBrowser().mCurrentTab, count > 0 ? count : 1, special, 0);
@@ -355,7 +355,7 @@ with (liberator) liberator.Tabs = function () //{{{
function (args) function (args)
{ {
liberator.forceNewTab = true; liberator.forceNewTab = true;
execute(args.string); liberator.execute(args.string);
liberator.forceNewTab = false; liberator.forceNewTab = false;
}, },
{ {
@@ -379,7 +379,7 @@ with (liberator) liberator.Tabs = function () //{{{
if (/^\d+$/.test(args)) if (/^\d+$/.test(args))
tabs.select("-" + args, true); // FIXME: urgh! tabs.select("-" + args, true); // FIXME: urgh!
else else
echoerr("E488: Trailing characters"); liberator.echoerr("E488: Trailing characters");
} }
else if (count > 0) else if (count > 0)
{ {
@@ -410,7 +410,7 @@ with (liberator) liberator.Tabs = function () //{{{
} }
else else
{ {
echoerr("E488: Trailing characters"); liberator.echoerr("E488: Trailing characters");
return; return;
} }
} }
@@ -422,7 +422,7 @@ with (liberator) liberator.Tabs = function () //{{{
if (index < tabs.count) if (index < tabs.count)
tabs.select(index, true); tabs.select(index, true);
else else
beep(); liberator.beep();
} }
else else
{ {
@@ -450,7 +450,7 @@ with (liberator) liberator.Tabs = function () //{{{
if (/^\d+$/.test(args)) if (/^\d+$/.test(args))
tabs.switchTo(args, special); tabs.switchTo(args, special);
else else
echoerr("E488: Trailing characters"); liberator.echoerr("E488: Trailing characters");
} }
else if (count > 0) else if (count > 0)
{ {
@@ -474,7 +474,7 @@ with (liberator) liberator.Tabs = function () //{{{
commands.add(["quita[ll]", "qa[ll]"], commands.add(["quita[ll]", "qa[ll]"],
"Quit " + config.name, "Quit " + config.name,
function (args, special) { quit(false, special); }, function (args, special) { liberator.quit(false, special); },
{ {
argCount: "0", argCount: "0",
bang: true bang: true
@@ -496,7 +496,7 @@ with (liberator) liberator.Tabs = function () //{{{
// FIXME: tabmove! N should probably produce an error // FIXME: tabmove! N should probably produce an error
if (!/^([+-]?\d+|)$/.test(args)) if (!/^([+-]?\d+|)$/.test(args))
{ {
echoerr("E488: Trailing characters"); liberator.echoerr("E488: Trailing characters");
return; return;
} }
@@ -516,14 +516,14 @@ with (liberator) liberator.Tabs = function () //{{{
"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 ? NEW_TAB : NEW_BACKGROUND_TAB; var where = special ? liberator.NEW_TAB : liberator.NEW_BACKGROUND_TAB;
if (/\btabopen\b/.test(options["activate"])) if (/\btabopen\b/.test(options["activate"]))
where = special ? NEW_BACKGROUND_TAB : NEW_TAB; where = special ? liberator.NEW_BACKGROUND_TAB : liberator.NEW_TAB;
if (args) if (args)
open(args, where); liberator.open(args, where);
else else
open("about:blank", where); liberator.open("about:blank", where);
}, },
{ {
bang: true, bang: true,
@@ -622,7 +622,7 @@ with (liberator) liberator.Tabs = function () //{{{
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 () { quit(true); }, function () { liberator.quit(true); },
{ argCount: "0" }); { argCount: "0" });
} }
@@ -763,11 +763,11 @@ with (liberator) liberator.Tabs = function () //{{{
if (buffer.URL != "about:blank" || if (buffer.URL != "about:blank" ||
getWebNavigation().sessionHistory.count > 0) getWebNavigation().sessionHistory.count > 0)
{ {
open("about:blank", NEW_BACKGROUND_TAB); liberator.open("about:blank", liberator.NEW_BACKGROUND_TAB);
getBrowser().removeTab(tab); getBrowser().removeTab(tab);
} }
else else
beep(); liberator.beep();
} }
}, },
Thunderbird: function (tab) Thunderbird: function (tab)
@@ -775,7 +775,7 @@ with (liberator) liberator.Tabs = function () //{{{
if (getBrowser().mTabs.length > 1) if (getBrowser().mTabs.length > 1)
getBrowser().removeTab(tab); getBrowser().removeTab(tab);
else else
beep(); liberator.beep();
} }
}[config.hostApplication] || function () {}; }[config.hostApplication] || function () {};
@@ -784,10 +784,10 @@ with (liberator) liberator.Tabs = function () //{{{
if (quitOnLastTab >= 1 && getBrowser().mTabs.length <= count) if (quitOnLastTab >= 1 && getBrowser().mTabs.length <= count)
{ {
if (windows.length > 1) if (liberator.windows.length > 1)
window.close(); window.close();
else else
quit(quitOnLastTab == 2); liberator.quit(quitOnLastTab == 2);
return; return;
} }
@@ -825,7 +825,7 @@ with (liberator) liberator.Tabs = function () //{{{
// FIXME: // FIXME:
if (index === -1) if (index === -1)
{ {
beep(); // XXX: move to ex-handling? liberator.beep(); // XXX: move to ex-handling?
return; return;
} }
getBrowser().mTabContainer.selectedIndex = index; getBrowser().mTabContainer.selectedIndex = index;
@@ -924,9 +924,9 @@ with (liberator) liberator.Tabs = function () //{{{
matches.push(index); matches.push(index);
} }
if (matches.length == 0) if (matches.length == 0)
echoerr("E94: No matching buffer for " + buffer); liberator.echoerr("E94: No matching buffer for " + buffer);
else if (matches.length > 1 && !allowNonUnique) else if (matches.length > 1 && !allowNonUnique)
echoerr("E93: More than one match for " + buffer); liberator.echoerr("E93: More than one match for " + buffer);
else else
{ {
if (reverse) if (reverse)
@@ -971,7 +971,7 @@ with (liberator) liberator.Tabs = function () //{{{
{ {
if (tabs.alternate == null || tabs.getTab() == tabs.alternate) if (tabs.alternate == null || tabs.getTab() == tabs.alternate)
{ {
echoerr("E23: No alternate page"); liberator.echoerr("E23: No alternate page");
return; return;
} }
@@ -983,7 +983,7 @@ with (liberator) liberator.Tabs = function () //{{{
// 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)
echoerr("E86: Buffer does not exist"); // TODO: This should read "Buffer N does not exist" liberator.echoerr("E86: Buffer does not exist"); // TODO: This should read "Buffer N does not exist"
else else
tabs.select(index); tabs.select(index);
}, },

View File

@@ -1,5 +1,5 @@
with (liberator) liberator.template = { const 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,
@@ -84,7 +84,7 @@ with (liberator) liberator.template = {
return <>{str}</>; return <>{str}</>;
let lcstr = String(str).toLowerCase(); let lcstr = String(str).toLowerCase();
let lcfilter = filter.toLowerCase(); let lcfilter = filter.toLowerCase();
str = String(str).replace(" ", " "); str = String(str).replace(" ", "\u00a0");
let s = <></>; let s = <></>;
let start = 0; let start = 0;
let i; let i;
@@ -129,7 +129,7 @@ with (liberator) liberator.template = {
({ ({
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[\u00a0]]>/* Non-breaking space */)
}) })
</span> </span>
} }

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
*/ */
with (liberator) liberator.CommandLine = function () //{{{ function CommandLine() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -145,7 +145,7 @@ with (liberator) liberator.CommandLine = function () //{{{
var promptCallback = null; var promptCallback = null;
var promptCompleter = null; var promptCompleter = null;
registerCallback("change", modes.EX, function (command) { liberator.registerCallback("change", modes.EX, function (command) {
if (options.get("wildoptions").has("auto")) if (options.get("wildoptions").has("auto"))
autocompleteTimer.tell(command); autocompleteTimer.tell(command);
else else
@@ -161,9 +161,9 @@ with (liberator) liberator.CommandLine = function () //{{{
if (callback) if (callback)
callback(value); callback(value);
} }
registerCallback("cancel", modes.PROMPT, closePrompt); liberator.registerCallback("cancel", modes.PROMPT, closePrompt);
registerCallback("submit", modes.PROMPT, closePrompt); liberator.registerCallback("submit", modes.PROMPT, closePrompt);
registerCallback("complete", modes.PROMPT, liberator.registerCallback("complete", modes.PROMPT,
function (str) { if (promptCompleter) return promptCompleter(str); }); function (str) { if (promptCompleter) return promptCompleter(str); });
function setHighlightGroup(group) function setHighlightGroup(group)
@@ -282,11 +282,11 @@ with (liberator) liberator.CommandLine = function () //{{{
try try
{ {
arg = eval(arg); arg = liberator.eval(arg);
} }
catch (e) catch (e)
{ {
echoerr(e); liberator.echoerr(e);
return null; return null;
} }
@@ -461,7 +461,7 @@ with (liberator) liberator.CommandLine = function () //{{{
commandline.echo(lastMowOutput, commandline.echo(lastMowOutput,
commandline.HL_NORMAL, commandline.FORCE_MULTILINE); commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
else else
beep(); liberator.beep();
}); });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
@@ -472,17 +472,17 @@ with (liberator) 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: echo action: liberator.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: echoerr action: liberator.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: echomsg action: liberator.echomsg
} }
]; ];
@@ -517,7 +517,7 @@ with (liberator) 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>;
echo(list, commandline.FORCE_MULTILINE); liberator.echo(list, commandline.FORCE_MULTILINE);
} }
}, },
{ argCount: "0" }); { argCount: "0" });
@@ -582,7 +582,7 @@ with (liberator) liberator.CommandLine = function () //{{{
// 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 = triggerCallback("cancel", currentExtendedMode); var res = liberator.triggerCallback("cancel", currentExtendedMode);
inputHistory.add(this.getCommand()); inputHistory.add(this.getCommand());
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 @@ with (liberator) liberator.CommandLine = function () //{{{
setLine("", this.HL_NORMAL); setLine("", this.HL_NORMAL);
}, },
// echo uses different order of flags as it omits the hightlight group, change v.commandline.echo argument order? --mst // liberator.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;
@@ -683,7 +683,7 @@ with (liberator) 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 (mode == modes.COMMAND_LINE && if (liberator.mode == modes.COMMAND_LINE &&
!(modes.extended & modes.INPUT_MULTILINE) && !(modes.extended & modes.INPUT_MULTILINE) &&
!(modes.extended & modes.OUTPUT_MULTILINE)) !(modes.extended & modes.OUTPUT_MULTILINE))
commandWidget.inputField.focus(); commandWidget.inputField.focus();
@@ -692,11 +692,14 @@ with (liberator) liberator.CommandLine = function () //{{{
else if (event.type == "focus") else if (event.type == "focus")
{ {
if (!currentExtendedMode && event.target == commandWidget.inputField) if (!currentExtendedMode && event.target == commandWidget.inputField)
{
event.target.blur(); event.target.blur();
liberator.beep();
}
} }
else if (event.type == "input") else if (event.type == "input")
{ {
triggerCallback("change", currentExtendedMode, command); liberator.triggerCallback("change", currentExtendedMode, command);
} }
else if (event.type == "keypress") else if (event.type == "keypress")
{ {
@@ -704,7 +707,7 @@ with (liberator) liberator.CommandLine = function () //{{{
return true; return true;
var key = events.toString(event); var key = events.toString(event);
//log("command line handling key: " + key + "\n"); //liberator.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
@@ -717,9 +720,9 @@ with (liberator) liberator.CommandLine = function () //{{{
modes.pop(true); modes.pop(true);
autocompleteTimer.reset(); autocompleteTimer.reset();
completionList.hide(); completionList.hide();
focusContent(false); liberator.focusContent(false);
statusline.updateProgress(""); // we may have a "match x of y" visible statusline.updateProgress(""); // we may have a "match x of y" visible
return triggerCallback("submit", mode, command); return liberator.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))
@@ -727,7 +730,7 @@ with (liberator) liberator.CommandLine = function () //{{{
function gotoHistoryItem(index) function gotoHistoryItem(index)
{ {
setCommand(inputHistory.get(historyIndex)); setCommand(inputHistory.get(historyIndex));
triggerCallback("change", currentExtendedMode, commandline.getCommand()); liberator.triggerCallback("change", currentExtendedMode, commandline.getCommand());
} }
let previousItem = /Up/.test(key); let previousItem = /Up/.test(key);
@@ -756,7 +759,7 @@ with (liberator) liberator.CommandLine = function () //{{{
if (historyIndex == inputHistory.length) if (historyIndex == inputHistory.length)
{ {
setCommand(historyStart); setCommand(historyStart);
triggerCallback("change", currentExtendedMode, this.getCommand()); liberator.triggerCallback("change", currentExtendedMode, this.getCommand());
break; break;
} }
@@ -764,7 +767,7 @@ with (liberator) liberator.CommandLine = function () //{{{
if (historyIndex <= -1) if (historyIndex <= -1)
{ {
historyIndex = 0; historyIndex = 0;
beep(); liberator.beep();
break; break;
} }
else if (historyIndex >= inputHistory.length + 1) else if (historyIndex >= inputHistory.length + 1)
@@ -815,7 +818,7 @@ with (liberator) 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 = triggerCallback("complete", currentExtendedMode, completionPrefix); var res = liberator.triggerCallback("complete", currentExtendedMode, completionPrefix);
if (res) if (res)
[completionStartIndex, completions] = res; [completionStartIndex, completions] = res;
@@ -828,7 +831,7 @@ with (liberator) liberator.CommandLine = function () //{{{
if (completions.length == 0) if (completions.length == 0)
{ {
beep(); liberator.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();
@@ -878,7 +881,7 @@ with (liberator) 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)
triggerCallback("change", currentExtendedMode, this.getCommand()); liberator.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,7 +903,7 @@ with (liberator) 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)
{ {
triggerCallback("cancel", currentExtendedMode); liberator.triggerCallback("cancel", currentExtendedMode);
modes.pop(); // FIXME: use mode stack modes.pop(); // FIXME: use mode stack
} }
} }
@@ -1028,7 +1031,7 @@ with (liberator) liberator.CommandLine = function () //{{{
} }
else if (event.originalTarget.localName.toLowerCase() == "a") else if (event.originalTarget.localName.toLowerCase() == "a")
{ {
open(event.originalTarget.textContent); liberator.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
@@ -1036,8 +1039,8 @@ with (liberator) liberator.CommandLine = function () //{{{
if (event.originalTarget.localName.toLowerCase() == "a") if (event.originalTarget.localName.toLowerCase() == "a")
{ {
var where = /\btabopen\b/.test(options["activate"]) ? var where = /\btabopen\b/.test(options["activate"]) ?
NEW_TAB : NEW_BACKGROUND_TAB; liberator.NEW_TAB : liberator.NEW_BACKGROUND_TAB;
open(event.originalTarget.textContent, where); liberator.open(event.originalTarget.textContent, where);
} }
break; break;
@@ -1153,7 +1156,7 @@ with (liberator) liberator.CommandLine = function () //{{{
// to allow asynchronous adding of completions // to allow asynchronous adding of completions
setCompletions: function (compl, start) setCompletions: function (compl, start)
{ {
if (mode != modes.COMMAND_LINE) if (liberator.mode != modes.COMMAND_LINE)
return; return;
// FIXME: Kludge. // FIXME: Kludge.
@@ -1223,7 +1226,7 @@ with (liberator) 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
*/ */
with (liberator) liberator.ItemList = function (id) //{{{ function ItemList(id) //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -1238,7 +1241,7 @@ with (liberator) liberator.ItemList = function (id) //{{{
var iframe = document.getElementById(id); var iframe = document.getElementById(id);
if (!iframe) if (!iframe)
{ {
log("No iframe with id: " + id + " found, strange things may happen!"); // "The truth is out there..." -- djk liberator.log("No iframe with id: " + id + " found, strange things may happen!"); // "The truth is out there..." -- djk
return; return;
} }
@@ -1432,7 +1435,7 @@ with (liberator) liberator.ItemList = function (id) //{{{
//}}} //}}}
}; //}}} }; //}}}
with (liberator) liberator.StatusLine = function () //{{{ function StatusLine() //{{{
{ {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION ///////////////////////////////////////// ////////////////////// PRIVATE SECTION /////////////////////////////////////////
@@ -1462,7 +1465,7 @@ with (liberator) 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)
echo("show status line only with > 1 window not implemented yet"); liberator.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;
@@ -1577,7 +1580,7 @@ with (liberator) liberator.StatusLine = function () //{{{
progressStr = "[" progressStr = "["
+ "====================".substr(0, progress) + "====================".substr(0, progress)
+ ">" + ">"
+ "                    ".substr(0, 19 - progress) + "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0".substr(0, 19 - progress)
+ "]"; + "]";
} }
progressWidget.value = progressStr; progressWidget.value = progressStr;
@@ -1593,7 +1596,7 @@ with (liberator) liberator.StatusLine = function () //{{{
return; return;
} }
for (let [i, tab] in Iterator(getBrowser().mTabs)) for (let [i, tab] in Iterator(Array.slice(getBrowser().mTabs)))
tab.setAttribute("ordinal", i + 1); tab.setAttribute("ordinal", i + 1);
if (!currentIndex || typeof currentIndex != "number") if (!currentIndex || typeof currentIndex != "number")

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 *****/
with (liberator) liberator.util = { //{{{ const util = { //{{{
Timer: function Timer(minInterval, maxInterval, callback) Timer: function Timer(minInterval, maxInterval, callback)
{ {
@@ -104,7 +104,7 @@ with (liberator) liberator.util = { //{{{
clipboardHelper.copyString(str); clipboardHelper.copyString(str);
if (verbose) if (verbose)
echo("Yanked " + str, commandline.FORCE_SINGLELINE); liberator.echo("Yanked " + str, commandline.FORCE_SINGLELINE);
}, },
createURI: function (str) createURI: function (str)
@@ -184,9 +184,9 @@ with (liberator) liberator.util = { //{{{
generateHelp: function (command, extraHelp) generateHelp: function (command, extraHelp)
{ {
var start = "", end = ""; var start = "", end = "";
if (command instanceof Command) if (command instanceof liberator.Command)
start = ":"; start = ":";
else if (command instanceof Option) else if (command instanceof liberator.Option)
start = end = "'"; start = end = "'";
var ret = ""; var ret = "";
@@ -303,8 +303,8 @@ with (liberator) liberator.util = { //{{{
if (Date.now() > endTime) if (Date.now() > endTime)
{ {
liberator.interrupted = false; liberator.interrupted = false;
threadYield(); liberator.threadYield();
if (interrupted) if (liberator.interrupted)
throw new Error("Interrupted"); throw new Error("Interrupted");
endTime = Date.now() + time; endTime = Date.now() + time;
} }
@@ -439,7 +439,7 @@ with (liberator) liberator.util = { //{{{
}, },
}; //}}} }; //}}}
liberator.util.Struct = function Struct() function Struct()
{ {
let self = this instanceof Struct ? this : new Struct(); let self = this instanceof Struct ? this : new Struct();
if (!arguments.length) if (!arguments.length)
@@ -465,7 +465,7 @@ liberator.util.Struct = function Struct()
return self.constructor = ConStructor; return self.constructor = ConStructor;
} }
liberator.util.Struct.prototype = { Struct.prototype = {
clone: function () clone: function ()
{ {
return this.constructor.apply(null, this.slice()); return this.constructor.apply(null, this.slice());
@@ -478,6 +478,6 @@ liberator.util.Struct.prototype = {
// 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",
"map", "reduce", "reduceRight", "reverse", "slice", "some", "sort"])) "map", "reduce", "reduceRight", "reverse", "slice", "some", "sort"]))
liberator.util.Struct.prototype[k] = Array.prototype[k]; Struct.prototype[k] = Array.prototype[k];
// vim: set fdm=marker sw=4 ts=4 et: // vim: set fdm=marker sw=4 ts=4 et:

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 *****/
with (liberator) liberator.config = { //{{{ const 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 @@ with (liberator) 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) { echoerr("DOM Inspector extension not installed"); } }], function () { try { inspectDOMDocument(content.document); } catch (e) { liberator.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",
@@ -110,6 +110,11 @@ with (liberator) liberator.config = { //{{{
"message.html", "developer.html", "various.html", "index.html" "message.html", "developer.html", "various.html", "index.html"
], ],
scripts: [
"bookmarks.js",
"tabs.js",
],
init: function () init: function ()
{ {
function incrementURL(count) function incrementURL(count)
@@ -119,7 +124,7 @@ with (liberator) liberator.config = { //{{{
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 beep(); return liberator.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,17 +134,17 @@ with (liberator) liberator.config = { //{{{
newNum += "0"; // keep leading zeros newNum += "0"; // keep leading zeros
newNum += nums[2]; newNum += nums[2];
open(matches[1] + newNum + matches[3]); liberator.open(matches[1] + newNum + matches[3]);
} }
// load Vimperator specific modules // load Vimperator specific modules
loadModule("search", Search); liberator.loadModule("search", Search);
loadModule("bookmarks", Bookmarks); liberator.loadModule("bookmarks", Bookmarks);
loadModule("history", History); liberator.loadModule("history", History);
loadModule("tabs", Tabs); liberator.loadModule("tabs", Tabs);
loadModule("marks", Marks); liberator.loadModule("marks", Marks);
loadModule("quickmarks", QuickMarks); liberator.loadModule("quickmarks", QuickMarks);
loadModule("hints", Hints); liberator.loadModule("hints", Hints);
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
////////////////////// MAPPINGS //////////////////////////////////////////////// ////////////////////// MAPPINGS ////////////////////////////////////////////////
@@ -178,7 +183,7 @@ with (liberator) liberator.config = { //{{{
mappings.add([modes.NORMAL], ["~"], mappings.add([modes.NORMAL], ["~"],
"Open home directory", "Open home directory",
function () { open("~"); }); function () { liberator.open("~"); });
mappings.add([modes.NORMAL], ["gh"], mappings.add([modes.NORMAL], ["gh"],
"Open homepage", "Open homepage",
@@ -189,8 +194,8 @@ with (liberator) liberator.config = { //{{{
function () function ()
{ {
var homepages = gHomeButton.getHomePage(); var homepages = gHomeButton.getHomePage();
open(homepages, /\bhomepage\b/.test(options["activate"]) ? liberator.open(homepages, /\bhomepage\b/.test(options["activate"]) ?
NEW_TAB : NEW_BACKGROUND_TAB); liberator.NEW_TAB : liberator.NEW_BACKGROUND_TAB);
}); });
mappings.add([modes.NORMAL], ["gu"], mappings.add([modes.NORMAL], ["gu"],
@@ -228,10 +233,10 @@ with (liberator) liberator.config = { //{{{
if (url == buffer.URL) if (url == buffer.URL)
{ {
beep(); liberator.beep();
return; return;
} }
open(url); liberator.open(url);
}, },
{ flags: Mappings.flags.COUNT }); { flags: Mappings.flags.COUNT });
@@ -242,15 +247,15 @@ with (liberator) liberator.config = { //{{{
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
{ {
beep(); liberator.beep();
return; return;
} }
open(uri.protocol + "//" + (uri.host || "") + "/"); liberator.open(uri.protocol + "//" + (uri.host || "") + "/");
}); });
mappings.add([modes.NORMAL], ["<C-l>"], mappings.add([modes.NORMAL], ["<C-l>"],
"Redraw the screen", "Redraw the screen",
function () { commands.get("redraw").execute("", false); }); function () { commands.get("redraw").execute(); });
/////////////////////////////////////////////////////////////////////////////}}} /////////////////////////////////////////////////////////////////////////////}}}
////////////////////// COMMANDS //////////////////////////////////////////////// ////////////////////// COMMANDS ////////////////////////////////////////////////
@@ -260,9 +265,9 @@ with (liberator) liberator.config = { //{{{
"Show progress of current downloads", "Show progress of current downloads",
function () function ()
{ {
open("chrome://mozapps/content/downloads/downloads.xul", liberator.open("chrome://mozapps/content/downloads/downloads.xul",
options.get("newtab").has("all", "downloads") options.get("newtab").has("all", "downloads")
? NEW_TAB : CURRENT_TAB); ? liberator.NEW_TAB : liberator.CURRENT_TAB);
}, },
{ argCount: "0" }); { argCount: "0" });
@@ -272,7 +277,7 @@ with (liberator) liberator.config = { //{{{
{ {
if (args) if (args)
{ {
open(args); liberator.open(args);
} }
else else
{ {
@@ -291,10 +296,9 @@ with (liberator) liberator.config = { //{{{
"Redraw the screen", "Redraw the screen",
function () function ()
{ {
var wu = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor) var wu = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor).
.getInterface(Components.interfaces.nsIDOMWindowUtils); getInterface(Components.interfaces.nsIDOMWindowUtils);
wu.redraw(); wu.redraw();
modes.show(); // Clears the shadow of the last command, as in vim.
}, },
{ argCount: "0" }); { argCount: "0" });
@@ -328,7 +332,7 @@ with (liberator) liberator.config = { //{{{
return; return;
} }
} }
echoerr("No sidebar " + args.string + " found"); liberator.echoerr("No sidebar " + args.string + " found");
}, },
{ {
argCount: "+", argCount: "+",
@@ -345,9 +349,9 @@ with (liberator) liberator.config = { //{{{
function (args) function (args)
{ {
if (args) if (args)
open(args, NEW_WINDOW); liberator.open(args, liberator.NEW_WINDOW);
else else
open("about:blank", NEW_WINDOW); liberator.open("about:blank", liberator.NEW_WINDOW);
}, },
{ completer: function (filter) completion.url(filter) }); { completer: function (filter) completion.url(filter) });
@@ -393,7 +397,7 @@ with (liberator) liberator.config = { //{{{
} }
catch (e) catch (e)
{ {
log("Couldn't set titlestring", 3); liberator.log("Couldn't set titlestring", 3);
} }
return value; return value;

View File

@@ -36,9 +36,6 @@ the terms of any one of the MPL, the GPL or the LGPL.
xmlns:html="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/x-javascript;version=1.8" src="bookmarks.js"/>
<script type="application/x-javascript;version=1.8" src="tabs.js"/>
<menupopup id="viewSidebarMenu"> <menupopup id="viewSidebarMenu">
<menuitem observes="vimperator-viewAddonsSidebar" label="Add-ons" accesskey="A"/> <menuitem observes="vimperator-viewAddonsSidebar" label="Add-ons" accesskey="A"/>
<menuitem observes="vimperator-viewConsoleSidebar" label="Console" accesskey="C"/> <menuitem observes="vimperator-viewConsoleSidebar" label="Console" accesskey="C"/>