]> git.donarmstrong.com Git - dactyl.git/blob - common/modules/buffer.jsm
Import r6923 from upstream hg supporting Firefox up to 22.0a1
[dactyl.git] / common / modules / buffer.jsm
1 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
3 // Copyright (c) 2008-2013 Kris Maglione <maglione.k at Gmail>
4 //
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
7 "use strict";
8
9 defineModule("buffer", {
10     exports: ["Buffer", "buffer"],
11     require: ["prefs", "services", "util"]
12 });
13
14 lazyRequire("bookmarkcache", ["bookmarkcache"]);
15 lazyRequire("contexts", ["Group"]);
16 lazyRequire("io", ["io"]);
17 lazyRequire("finder", ["RangeFind"]);
18 lazyRequire("overlay", ["overlay"]);
19 lazyRequire("sanitizer", ["sanitizer"]);
20 lazyRequire("storage", ["File", "storage"]);
21 lazyRequire("template", ["template"]);
22
23 /**
24  * A class to manage the primary web content buffer. The name comes
25  * from Vim's term, 'buffer', which signifies instances of open
26  * files.
27  * @instance buffer
28  */
29 var Buffer = Module("Buffer", {
30     Local: function Local(dactyl, modules, window) ({
31         get win() {
32             return window.content;
33
34             let win = services.focus.focusedWindow;
35             if (!win || win == window || util.topWindow(win) != window)
36                 return window.content
37             if (win.top == window)
38                 return win;
39             return win.top;
40         }
41     }),
42
43     init: function init(win) {
44         if (win)
45             this.win = win;
46     },
47
48     get addPageInfoSection() Buffer.closure.addPageInfoSection,
49
50     get pageInfo() Buffer.pageInfo,
51
52     // called when the active document is scrolled
53     _updateBufferPosition: function _updateBufferPosition() {
54         this.modules.statusline.updateBufferPosition();
55         this.modules.commandline.clear(true);
56     },
57
58     /**
59      * @property {Array} The alternative style sheets for the current
60      *     buffer. Only returns style sheets for the 'screen' media type.
61      */
62     get alternateStyleSheets() {
63         let stylesheets = array.flatten(
64             this.allFrames().map(function (w) Array.slice(w.document.styleSheets)));
65
66         return stylesheets.filter(
67             function (stylesheet) /^(screen|all|)$/i.test(stylesheet.media.mediaText) && !/^\s*$/.test(stylesheet.title)
68         );
69     },
70
71     /**
72      * Gets a content preference for the given buffer.
73      *
74      * @param {string} pref The preference to get.
75      * @param {function(string|number|boolean)} callback The callback to
76      *      call with the preference value. @optional
77      * @returns {string|number|boolean} The value of the preference, if
78      *      callback is not provided.
79      */
80     getPref: function getPref(pref, callback) {
81         // God damn it.
82         if (config.haveGecko("19.0a1"))
83             services.contentPrefs.getPref(this.uri, pref,
84                                           sanitizer.getContext(this.win), callback);
85         else
86             services.contentPrefs.getPref(uri, pref, callback);
87     },
88
89     /**
90      * Sets a content preference for the given buffer.
91      *
92      * @param {string} pref The preference to set.
93      * @param {string} value The value to store.
94      */
95     setPref: function setPref(pref, value) {
96         services.contentPrefs.setPref(
97             this.uri, pref, value, sanitizer.getContext(this.win));
98     },
99
100     /**
101      * Clear a content preference for the given buffer.
102      *
103      * @param {string} pref The preference to clear.
104      */
105     clearPref: function clearPref(pref) {
106         services.contentPrefs.removePref(
107             this.uri, pref, sanitizer.getContext(this.win));
108     },
109
110     climbUrlPath: function climbUrlPath(count) {
111         let { dactyl } = this.modules;
112
113         let url = this.documentURI.clone();
114         dactyl.assert(url instanceof Ci.nsIURL);
115
116         while (count-- && url.path != "/")
117             url.path = url.path.replace(/[^\/]*\/*$/, "");
118
119         dactyl.assert(!url.equals(this.documentURI));
120         dactyl.open(url.spec);
121     },
122
123     incrementURL: function incrementURL(count) {
124         let { dactyl } = this.modules;
125
126         let matches = this.uri.spec.match(/(.*?)(\d+)(\D*)$/);
127         dactyl.assert(matches);
128         let oldNum = matches[2];
129
130         // disallow negative numbers as trailing numbers are often proceeded by hyphens
131         let newNum = String(Math.max(parseInt(oldNum, 10) + count, 0));
132         if (/^0/.test(oldNum))
133             while (newNum.length < oldNum.length)
134                 newNum = "0" + newNum;
135
136         matches[2] = newNum;
137         dactyl.open(matches.slice(1).join(""));
138     },
139
140     /**
141      * @property {number} True when the buffer is fully loaded.
142      */
143     get loaded() Math.min.apply(null,
144         this.allFrames()
145             .map(function (frame) ["loading", "interactive", "complete"]
146                                       .indexOf(frame.document.readyState))),
147
148     /**
149      * @property {Object} The local state store for the currently selected
150      *     tab.
151      */
152     get localStore() {
153         let { doc } = this;
154
155         let store = overlay.getData(doc, "buffer", null);
156         if (!store || !this.localStorePrototype.isPrototypeOf(store))
157             store = overlay.setData(doc, "buffer", Object.create(this.localStorePrototype));
158         return store.instance = store;
159     },
160
161     localStorePrototype: memoize({
162         instance: {},
163         get jumps() [],
164         jumpsIndex: -1
165     }),
166
167     /**
168      * @property {Node} The last focused input field in the buffer. Used
169      *     by the "gi" key binding.
170      */
171     get lastInputField() {
172         let field = this.localStore.lastInputField && this.localStore.lastInputField.get();
173
174         let doc = field && field.ownerDocument;
175         let win = doc && doc.defaultView;
176         return win && doc === win.document ? field : null;
177     },
178     set lastInputField(value) { this.localStore.lastInputField = util.weakReference(value); },
179
180     /**
181      * @property {nsIURI} The current top-level document.
182      */
183     get doc() this.win.document,
184
185     get docShell() util.docShell(this.win),
186
187     get modules() this.topWindow.dactyl.modules,
188     set modules(val) {},
189
190     topWindow: Class.Memoize(function () util.topWindow(this.win)),
191
192     /**
193      * @property {nsIURI} The current top-level document's URI.
194      */
195     get uri() util.newURI(this.win.location.href),
196
197     /**
198      * @property {nsIURI} The current top-level document's URI, sans any
199      *     fragment identifier.
200      */
201     get documentURI() this.doc.documentURIObject || util.newURI(this.doc.documentURI),
202
203     /**
204      * @property {string} The current top-level document's URL.
205      */
206     get URL() update(new String(this.win.location.href), util.newURI(this.win.location.href)),
207
208     /**
209      * @property {number} The buffer's height in pixels.
210      */
211     get pageHeight() this.win.innerHeight,
212
213     get contentViewer() this.docShell.contentViewer
214                                      .QueryInterface(Components.interfaces.nsIMarkupDocumentViewer),
215
216     /**
217      * @property {number} The current browser's zoom level, as a
218      *     percentage with 100 as 'normal'.
219      */
220     get zoomLevel() {
221         let v = this.contentViewer;
222         return v[v.textZoom == 1 ? "fullZoom" : "textZoom"] * 100
223     },
224     set zoomLevel(value) { this.setZoom(value, this.fullZoom); },
225
226     /**
227      * @property {boolean} Whether the current browser is using full
228      *     zoom, as opposed to text zoom.
229      */
230     get fullZoom() this.ZoomManager.useFullZoom,
231     set fullZoom(value) { this.setZoom(this.zoomLevel, value); },
232
233     get ZoomManager() this.topWindow.ZoomManager,
234
235     /**
236      * @property {string} The current document's title.
237      */
238     get title() this.doc.title,
239
240     /**
241      * @property {number} The buffer's horizontal scroll percentile.
242      */
243     get scrollXPercent() {
244         let elem = Buffer.Scrollable(this.findScrollable(0, true));
245         if (elem.scrollWidth - elem.clientWidth === 0)
246             return 0;
247         return elem.scrollLeft * 100 / (elem.scrollWidth - elem.clientWidth);
248     },
249
250     /**
251      * @property {number} The buffer's vertical scroll percentile.
252      */
253     get scrollYPercent() {
254         let elem = Buffer.Scrollable(this.findScrollable(0, false));
255         if (elem.scrollHeight - elem.clientHeight === 0)
256             return 0;
257         return elem.scrollTop * 100 / (elem.scrollHeight - elem.clientHeight);
258     },
259
260     /**
261      * @property {{ x: number, y: number }} The buffer's current scroll position
262      * as reported by {@link Buffer.getScrollPosition}.
263      */
264     get scrollPosition() Buffer.getScrollPosition(this.findScrollable(0, false)),
265
266     /**
267      * Returns a list of all frames in the given window or current buffer.
268      */
269     allFrames: function allFrames(win, focusedFirst) {
270         let frames = [];
271         (function rec(frame) {
272             if (true || frame.document.body instanceof Ci.nsIDOMHTMLBodyElement)
273                 frames.push(frame);
274             Array.forEach(frame.frames, rec);
275         })(win || this.win);
276
277         if (focusedFirst)
278             return frames.filter(function (f) f === this.focusedFrame, this).concat(
279                    frames.filter(function (f) f !== this.focusedFrame, this));
280         return frames;
281     },
282
283     /**
284      * @property {Window} Returns the currently focused frame.
285      */
286     get focusedFrame() {
287         let frame = this.localStore.focusedFrame;
288         return frame && frame.get() || this.win;
289     },
290     set focusedFrame(frame) {
291         this.localStore.focusedFrame = util.weakReference(frame);
292     },
293
294     /**
295      * Returns the currently selected word. If the selection is
296      * null, it tries to guess the word that the caret is
297      * positioned in.
298      *
299      * @returns {string}
300      */
301     get currentWord() Buffer.currentWord(this.focusedFrame),
302     getCurrentWord: deprecated("buffer.currentWord", function getCurrentWord() Buffer.currentWord(this.focusedFrame, true)),
303
304     /**
305      * Returns true if a scripts are allowed to focus the given input
306      * element or input elements in the given window.
307      *
308      * @param {Node|Window}
309      * @returns {boolean}
310      */
311     focusAllowed: function focusAllowed(elem) {
312         if (elem instanceof Ci.nsIDOMWindow && !DOM(elem).isEditable)
313             return true;
314
315         let { options } = this.modules;
316
317         let doc = elem.ownerDocument || elem.document || elem;
318         switch (options.get("strictfocus").getKey(doc.documentURIObject || util.newURI(doc.documentURI), "moderate")) {
319         case "despotic":
320             return overlay.getData(elem)["focus-allowed"]
321                     || elem.frameElement && overlay.getData(elem.frameElement)["focus-allowed"];
322         case "moderate":
323             return overlay.getData(doc, "focus-allowed")
324                     || elem.frameElement && overlay.getData(elem.frameElement.ownerDocument)["focus-allowed"];
325         default:
326             return true;
327         }
328     },
329
330     /**
331      * Focuses the given element. In contrast to a simple
332      * elem.focus() call, this function works for iframes and
333      * image maps.
334      *
335      * @param {Node} elem The element to focus.
336      */
337     focusElement: function focusElement(elem) {
338         let win = elem.ownerDocument && elem.ownerDocument.defaultView || elem;
339         overlay.setData(elem, "focus-allowed", true);
340         overlay.setData(win.document, "focus-allowed", true);
341
342         if (isinstance(elem, [Ci.nsIDOMHTMLFrameElement,
343                               Ci.nsIDOMHTMLIFrameElement]))
344             elem = elem.contentWindow;
345
346         if (elem.document)
347             overlay.setData(elem.document, "focus-allowed", true);
348
349         if (elem instanceof Ci.nsIDOMHTMLInputElement && elem.type == "file") {
350             Buffer.openUploadPrompt(elem);
351             this.lastInputField = elem;
352         }
353         else {
354             if (isinstance(elem, [Ci.nsIDOMHTMLInputElement,
355                                   Ci.nsIDOMXULTextBoxElement]))
356                 var flags = services.focus.FLAG_BYMOUSE;
357             else
358                 flags = services.focus.FLAG_SHOWRING;
359
360             // Hack to deal with current versions of Firefox misplacing
361             // the caret
362             if (!overlay.getData(elem, "had-focus", false) && elem.value &&
363                     elem instanceof Ci.nsIDOMHTMLInputElement &&
364                     DOM(elem).isEditable &&
365                     elem.selectionStart != null &&
366                     elem.selectionStart == elem.selectionEnd)
367                 elem.selectionStart = elem.selectionEnd = elem.value.length;
368
369             DOM(elem).focus(flags);
370
371             if (elem instanceof Ci.nsIDOMWindow) {
372                 let sel = elem.getSelection();
373                 if (sel && !sel.rangeCount)
374                     sel.addRange(RangeFind.endpoint(
375                         RangeFind.nodeRange(elem.document.body || elem.document.documentElement),
376                         true));
377             }
378             else {
379                 let range = RangeFind.nodeRange(elem);
380                 let sel = (elem.ownerDocument || elem).defaultView.getSelection();
381                 if (!sel.rangeCount || !RangeFind.intersects(range, sel.getRangeAt(0))) {
382                     range.collapse(true);
383                     sel.removeAllRanges();
384                     sel.addRange(range);
385                 }
386             }
387
388             // for imagemap
389             if (elem instanceof Ci.nsIDOMHTMLAreaElement) {
390                 try {
391                     let [x, y] = elem.getAttribute("coords").split(",").map(parseFloat);
392
393                     DOM(elem).mouseover({ screenX: x, screenY: y });
394                 }
395                 catch (e) {}
396             }
397         }
398     },
399
400     /**
401      * Find the *count*th last link on a page matching one of the given
402      * regular expressions, or with a @rel or @rev attribute matching
403      * the given relation. Each frame is searched beginning with the
404      * last link and progressing to the first, once checking for
405      * matching @rel or @rev properties, and then once for each given
406      * regular expression. The first match is returned. All frames of
407      * the page are searched, beginning with the currently focused.
408      *
409      * If follow is true, the link is followed.
410      *
411      * @param {string} rel The relationship to look for.
412      * @param {[RegExp]} regexps The regular expressions to search for.
413      * @param {number} count The nth matching link to follow.
414      * @param {bool} follow Whether to follow the matching link.
415      * @param {string} path The CSS to use for the search. @optional
416      */
417     findLink: function findLink(rel, regexps, count, follow, path) {
418         let { Hints, dactyl, options } = this.modules;
419
420         let selector = path || options.get("hinttags").stringDefaultValue;
421
422         function followFrame(frame) {
423             function iter(elems) {
424                 for (let i = 0; i < elems.length; i++)
425                     if (elems[i].rel.toLowerCase() === rel || elems[i].rev.toLowerCase() === rel)
426                         yield elems[i];
427             }
428
429             let elems = frame.document.getElementsByTagName("link");
430             for (let elem in iter(elems))
431                 yield elem;
432
433             elems = frame.document.getElementsByTagName("a");
434             for (let elem in iter(elems))
435                 yield elem;
436
437             function a(regexp, elem) regexp.test(elem.textContent) === regexp.result ||
438                             Array.some(elem.childNodes, function (child) regexp.test(child.alt) === regexp.result);
439             function b(regexp, elem) regexp.test(elem.title) === regexp.result;
440
441             let res = Array.filter(frame.document.querySelectorAll(selector), Hints.isVisible);
442             for (let test in values([a, b]))
443                 for (let regexp in values(regexps))
444                     for (let i in util.range(res.length, 0, -1))
445                         if (test(regexp, res[i]))
446                             yield res[i];
447         }
448
449         for (let frame in values(this.allFrames(null, true)))
450             for (let elem in followFrame(frame))
451                 if (count-- === 0) {
452                     if (follow)
453                         this.followLink(elem, dactyl.CURRENT_TAB);
454                     return elem;
455                 }
456
457         if (follow)
458             dactyl.beep();
459     },
460     followDocumentRelationship: deprecated("buffer.findLink",
461         function followDocumentRelationship(rel) {
462             let { options } = this.modules;
463
464             this.findLink(rel, options[rel + "pattern"], 0, true);
465         }),
466
467     /**
468      * Fakes a click on a link.
469      *
470      * @param {Node} elem The element to click.
471      * @param {number} where Where to open the link. See
472      *     {@link dactyl.open}.
473      */
474     followLink: function followLink(elem, where) {
475         let { dactyl } = this.modules;
476
477         let doc = elem.ownerDocument;
478         let win = doc.defaultView;
479         let { left: offsetX, top: offsetY } = elem.getBoundingClientRect();
480
481         if (isinstance(elem, [Ci.nsIDOMHTMLFrameElement,
482                               Ci.nsIDOMHTMLIFrameElement]))
483             return this.focusElement(elem);
484
485         if (isinstance(elem, Ci.nsIDOMHTMLLinkElement))
486             return dactyl.open(elem.href, where);
487
488         if (elem instanceof Ci.nsIDOMHTMLAreaElement) { // for imagemap
489             let coords = elem.getAttribute("coords").split(",");
490             offsetX = Number(coords[0]) + 1;
491             offsetY = Number(coords[1]) + 1;
492         }
493         else if (elem instanceof Ci.nsIDOMHTMLInputElement && elem.type == "file") {
494             Buffer.openUploadPrompt(elem);
495             return;
496         }
497
498         let { dactyl } = this.modules;
499
500         let ctrlKey = false, shiftKey = false;
501         let button = 0;
502         switch (dactyl.forceTarget || where) {
503         case dactyl.NEW_TAB:
504         case dactyl.NEW_BACKGROUND_TAB:
505             button = 1;
506             shiftKey = dactyl.forceBackground != null ? dactyl.forceBackground
507                                                       : where != dactyl.NEW_BACKGROUND_TAB;
508             break;
509         case dactyl.NEW_WINDOW:
510             shiftKey = true;
511             break;
512         case dactyl.CURRENT_TAB:
513             break;
514         }
515
516         this.focusElement(elem);
517
518         prefs.withContext(function () {
519             prefs.set("browser.tabs.loadInBackground", true);
520             let params = {
521                 button: button, screenX: offsetX, screenY: offsetY,
522                 ctrlKey: ctrlKey, shiftKey: shiftKey, metaKey: ctrlKey
523             };
524
525             DOM(elem).mousedown(params).mouseup(params);
526             if (!config.haveGecko("2b"))
527                 DOM(elem).click(params);
528
529             let sel = util.selectionController(win);
530             sel.getSelection(sel.SELECTION_FOCUS_REGION).collapseToStart();
531         });
532     },
533
534     /**
535      * Resets the caret position so that it resides within the current
536      * viewport.
537      */
538     resetCaret: function resetCaret() {
539         function visible(range) util.intersection(DOM(range).rect, viewport);
540
541         function getRanges(rect) {
542             let nodes = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils)
543                            .nodesFromRect(rect.x, rect.y, 0, rect.width, rect.height, 0, false, false);
544             return Array.filter(nodes, function (n) n instanceof Ci.nsIDOMText)
545                         .map(RangeFind.nodeContents);
546         }
547
548         let win = this.focusedFrame;
549         let doc = win.document;
550         let sel = win.getSelection();
551         let { viewport } = DOM(win);
552
553         if (sel.rangeCount) {
554             var range = sel.getRangeAt(0);
555             if (visible(range).height > 0)
556                 return;
557
558             var { rect } = DOM(range);
559             var reverse = rect.bottom > viewport.bottom;
560
561             rect = { x: rect.left, y: 0, width: rect.width, height: win.innerHeight };
562         }
563         else {
564             let w = win.innerWidth;
565             rect = { x: w / 3, y: 0, width: w / 3, height: win.innerHeight };
566         }
567
568         var reduce = function (a, b) DOM(a).rect.top < DOM(b).rect.top ? a : b;
569         var dir = "forward";
570         var y = 0;
571         if (reverse) {
572             reduce = function (a, b) DOM(b).rect.bottom > DOM(a).rect.bottom ? b : a;
573             dir = "backward";
574             y = win.innerHeight - 1;
575         }
576
577         let ranges = getRanges(rect);
578         if (!ranges.length)
579             ranges = getRanges({ x: 0, y: y, width: win.innerWidth, height: 0 });
580
581         if (ranges.length) {
582             range = ranges.reduce(reduce);
583
584             if (range) {
585                 range.collapse(!reverse);
586                 sel.removeAllRanges();
587                 sel.addRange(range);
588                 do {
589                     if (visible(range).height > 0)
590                         break;
591
592                     var { startContainer, startOffset } = range;
593                     sel.modify("move", dir, "line");
594                     range = sel.getRangeAt(0);
595                 }
596                 while (startContainer != range.startContainer || startOffset != range.startOffset);
597
598                 sel.modify("move", reverse ? "forward" : "backward", "lineboundary");
599             }
600         }
601
602         if (!sel.rangeCount)
603             sel.collapse(doc.body || doc.querySelector("body") || doc.documentElement,
604                          0);
605     },
606
607     /**
608      * @property {nsISelection} The current document's normal selection.
609      */
610     get selection() this.win.getSelection(),
611
612     /**
613      * @property {nsISelectionController} The current document's selection
614      *     controller.
615      */
616     get selectionController() util.selectionController(this.focusedFrame),
617
618     /**
619      * @property {string|null} The canonical short URL for the current
620      *      document.
621      */
622     get shortURL() {
623         let { uri, doc } = this;
624
625         for each (let shortener in Buffer.uriShorteners)
626             try {
627                 let shortened = shortener(uri, doc);
628                 if (shortened)
629                     return shortened.spec;
630             }
631             catch (e) {
632                 util.reportError(e);
633             }
634
635         let link = DOM("link[href][rev=canonical], \
636                         link[href][rel=shortlink]", doc);
637         if (link)
638             return link.attr("href");
639
640         return null;
641     },
642
643     /**
644      * Opens the appropriate context menu for *elem*.
645      *
646      * @param {Node} elem The context element.
647      */
648     openContextMenu: deprecated("DOM#contextmenu", function openContextMenu(elem) DOM(elem).contextmenu()),
649
650     /**
651      * Saves a page link to disk.
652      *
653      * @param {HTMLAnchorElement} elem The page link to save.
654      * @param {boolean} overwrite If true, overwrite any existing file.
655      */
656     saveLink: function saveLink(elem, overwrite) {
657         let { completion, dactyl, io } = this.modules;
658
659         let self = this;
660         let doc      = elem.ownerDocument;
661         let uri      = util.newURI(elem.href || elem.src, null, util.newURI(elem.baseURI));
662         let referrer = util.newURI(doc.documentURI, doc.characterSet);
663
664         try {
665             services.security.checkLoadURIWithPrincipal(doc.nodePrincipal, uri,
666                         services.security.STANDARD);
667
668             io.CommandFileMode(_("buffer.prompt.saveLink") + " ", {
669                 onSubmit: function (path) {
670                     let file = io.File(path);
671                     if (file.exists() && file.isDirectory())
672                         file.append(Buffer.getDefaultNames(elem)[0][0]);
673
674                     util.assert(!file.exists() || overwrite, _("io.existsNoOverride", file.path));
675
676                     try {
677                         if (!file.exists())
678                             file.create(File.NORMAL_FILE_TYPE, octal(644));
679                     }
680                     catch (e) {
681                         util.assert(false, _("save.invalidDestination", e.name));
682                     }
683
684                     self.saveURI({ uri: uri, file: file, context: elem });
685                 },
686
687                 completer: function (context) completion.savePage(context, elem)
688             }).open();
689         }
690         catch (e) {
691             dactyl.echoerr(e);
692         }
693     },
694
695     /**
696      * Saves the contents of a URI to disk.
697      *
698      * @param {nsIURI} uri The URI to save
699      * @param {nsIFile} file The file into which to write the result.
700      */
701     saveURI: function saveURI(params) {
702         if (params instanceof Ci.nsIURI)
703             // Deprecated?
704             params = { uri: arguments[0], file: arguments[1],
705                        callback: arguments[2], self: arguments[3] };
706
707         var persist = services.Persist();
708         persist.persistFlags = persist.PERSIST_FLAGS_FROM_CACHE
709                              | persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
710
711         let window = this.topWindow;
712         let privacy = sanitizer.getContext(params.context || this.win);
713         let file = File(params.file);
714         if (!file.exists())
715             file.create(Ci.nsIFile.NORMAL_FILE_TYPE, octal(666));
716
717         let downloadListener = new window.DownloadListener(window,
718                 services.Transfer(params.uri, file.URI, "", null, null, null,
719                                   persist, privacy && privacy.usePrivateBrowsing));
720
721         var { callback, self } = params;
722         if (callback)
723             persist.progressListener = update(Object.create(downloadListener), {
724                 onStateChange: util.wrapCallback(function onStateChange(progress, request, flags, status) {
725                     if (callback && (flags & Ci.nsIWebProgressListener.STATE_STOP) && status == 0)
726                         util.trapErrors(callback, self, params.uri, file.file,
727                                         progress, request, flags, status);
728
729                     return onStateChange.superapply(this, arguments);
730                 })
731             });
732         else
733             persist.progressListener = downloadListener;
734
735         persist.saveURI(params.uri, null, null, null, null,
736                         file.file, privacy);
737     },
738
739     /**
740      * Scrolls the currently active element horizontally. See
741      * {@link Buffer.scrollHorizontal} for parameters.
742      */
743     scrollHorizontal: function scrollHorizontal(increment, number)
744         Buffer.scrollHorizontal(this.findScrollable(number, true), increment, number),
745
746     /**
747      * Scrolls the currently active element vertically. See
748      * {@link Buffer.scrollVertical} for parameters.
749      */
750     scrollVertical: function scrollVertical(increment, number)
751         Buffer.scrollVertical(this.findScrollable(number, false), increment, number),
752
753     /**
754      * Scrolls the currently active element to the given horizontal and
755      * vertical percentages. See {@link Buffer.scrollToPercent} for
756      * parameters.
757      */
758     scrollToPercent: function scrollToPercent(horizontal, vertical)
759         Buffer.scrollToPercent(this.findScrollable(0, vertical == null), horizontal, vertical),
760
761     /**
762      * Scrolls the currently active element to the given horizontal and
763      * vertical positions. See {@link Buffer.scrollToPosition} for
764      * parameters.
765      */
766     scrollToPosition: function scrollToPosition(horizontal, vertical)
767         Buffer.scrollToPosition(this.findScrollable(0, vertical == null), horizontal, vertical),
768
769     _scrollByScrollSize: function _scrollByScrollSize(count, direction) {
770         let { options } = this.modules;
771
772         if (count > 0)
773             options["scroll"] = count;
774         this.scrollByScrollSize(direction);
775     },
776
777     /**
778      * Scrolls the buffer vertically 'scroll' lines.
779      *
780      * @param {boolean} direction The direction to scroll. If true then
781      *     scroll up and if false scroll down.
782      * @param {number} count The multiple of 'scroll' lines to scroll.
783      * @optional
784      */
785     scrollByScrollSize: function scrollByScrollSize(direction, count) {
786         let { options } = this.modules;
787
788         direction = direction ? 1 : -1;
789         count = count || 1;
790
791         if (options["scroll"] > 0)
792             this.scrollVertical("lines", options["scroll"] * direction);
793         else
794             this.scrollVertical("pages", direction / 2);
795     },
796
797     /**
798      * Find the best candidate scrollable element for the given
799      * direction and orientation.
800      *
801      * @param {number} dir The direction in which the element must be
802      *   able to scroll. Negative numbers represent up or left, while
803      *   positive numbers represent down or right.
804      * @param {boolean} horizontal If true, look for horizontally
805      *   scrollable elements, otherwise look for vertically scrollable
806      *   elements.
807      */
808     findScrollable: function findScrollable(dir, horizontal) {
809         function find(elem) {
810             while (elem && !(elem instanceof Ci.nsIDOMElement) && elem.parentNode)
811                 elem = elem.parentNode;
812             for (; elem instanceof Ci.nsIDOMElement; elem = elem.parentNode)
813                 if (Buffer.isScrollable(elem, dir, horizontal))
814                     break;
815
816             return elem;
817         }
818
819         try {
820             var elem = this.focusedFrame.document.activeElement;
821             if (elem == elem.ownerDocument.body)
822                 elem = null;
823         }
824         catch (e) {}
825
826         try {
827             var sel = this.focusedFrame.getSelection();
828         }
829         catch (e) {}
830
831         if (!elem && sel && sel.rangeCount)
832             elem = sel.getRangeAt(0).startContainer;
833
834         if (!elem) {
835             let area = -1;
836             for (let e in DOM(Buffer.SCROLLABLE_SEARCH_SELECTOR,
837                               this.focusedFrame.document)) {
838                 if (Buffer.isScrollable(e, dir, horizontal)) {
839                     let r = DOM(e).rect;
840                     let a = r.width * r.height;
841                     if (a > area) {
842                         area = a;
843                         elem = e;
844                     }
845                 }
846             }
847             if (elem)
848                 util.trapErrors("focus", elem);
849         }
850         if (elem)
851             elem = find(elem);
852
853         if (!(elem instanceof Ci.nsIDOMElement)) {
854             let doc = this.findScrollableWindow().document;
855             elem = find(doc.body || doc.getElementsByTagName("body")[0] ||
856                         doc.documentElement);
857         }
858         let doc = this.focusedFrame.document;
859         return util.assert(elem || doc.body || doc.documentElement);
860     },
861
862     /**
863      * Find the best candidate scrollable frame in the current buffer.
864      */
865     findScrollableWindow: function findScrollableWindow() {
866         let { document } = this.topWindow;
867
868         let win = document.commandDispatcher.focusedWindow;
869         if (win && (win.scrollMaxX > 0 || win.scrollMaxY > 0))
870             return win;
871
872         let win = this.focusedFrame;
873         if (win && (win.scrollMaxX > 0 || win.scrollMaxY > 0))
874             return win;
875
876         win = this.win;
877         if (win.scrollMaxX > 0 || win.scrollMaxY > 0)
878             return win;
879
880         for (let frame in array.iterValues(win.frames))
881             if (frame.scrollMaxX > 0 || frame.scrollMaxY > 0)
882                 return frame;
883
884         return win;
885     },
886
887     /**
888      * Finds the next visible element for the node path in 'jumptags'
889      * for *arg*.
890      *
891      * @param {string} arg The element in 'jumptags' to use for the search.
892      * @param {number} count The number of elements to jump.
893      *      @optional
894      * @param {boolean} reverse If true, search backwards. @optional
895      * @param {boolean} offScreen If true, include only off-screen elements. @optional
896      */
897     findJump: function findJump(arg, count, reverse, offScreen) {
898         let { marks, options } = this.modules;
899
900         const FUDGE = 10;
901
902         marks.push();
903
904         let path = options["jumptags"][arg];
905         util.assert(path, _("error.invalidArgument", arg));
906
907         let distance = reverse ? function (rect) -rect.top : function (rect) rect.top;
908         let elems = [[e, distance(e.getBoundingClientRect())] for (e in path.matcher(this.focusedFrame.document))]
909                         .filter(function (e) e[1] > FUDGE)
910                         .sort(function (a, b) a[1] - b[1])
911
912         if (offScreen && !reverse)
913             elems = elems.filter(function (e) e[1] > this, this.topWindow.innerHeight);
914
915         let idx = Math.min((count || 1) - 1, elems.length);
916         util.assert(idx in elems);
917
918         let elem = elems[idx][0];
919         elem.scrollIntoView(true);
920
921         let sel = elem.ownerDocument.defaultView.getSelection();
922         sel.removeAllRanges();
923         sel.addRange(RangeFind.endpoint(RangeFind.nodeRange(elem), true));
924     },
925
926     // TODO: allow callback for filtering out unwanted frames? User defined?
927     /**
928      * Shifts the focus to another frame within the buffer. Each buffer
929      * contains at least one frame.
930      *
931      * @param {number} count The number of frames to skip through. A negative
932      *     count skips backwards.
933      */
934     shiftFrameFocus: function shiftFrameFocus(count) {
935         if (!(this.doc instanceof Ci.nsIDOMHTMLDocument))
936             return;
937
938         let frames = this.allFrames();
939
940         if (frames.length == 0) // currently top is always included
941             return;
942
943         // remove all hidden frames
944         frames = frames.filter(function (frame) !(frame.document.body instanceof Ci.nsIDOMHTMLFrameSetElement))
945                        .filter(function (frame) !frame.frameElement ||
946             let (rect = frame.frameElement.getBoundingClientRect())
947                 rect.width && rect.height);
948
949         // find the currently focused frame index
950         let current = Math.max(0, frames.indexOf(this.focusedFrame));
951
952         // calculate the next frame to focus
953         let next = current + count;
954         if (next < 0 || next >= frames.length)
955             util.dactyl.beep();
956         next = Math.constrain(next, 0, frames.length - 1);
957
958         // focus next frame and scroll into view
959         DOM(frames[next]).focus();
960         if (frames[next] != this.win)
961             DOM(frames[next].frameElement).scrollIntoView();
962
963         // add the frame indicator
964         let doc = frames[next].document;
965         let indicator = DOM(["div", { highlight: "FrameIndicator" }], doc)
966                             .appendTo(doc.body || doc.documentElement || doc);
967
968         util.timeout(function () { indicator.remove(); }, 500);
969
970         // Doesn't unattach
971         //doc.body.setAttributeNS(NS, "activeframe", "true");
972         //util.timeout(function () { doc.body.removeAttributeNS(NS, "activeframe"); }, 500);
973     },
974
975     // similar to pageInfo
976     // TODO: print more useful information, just like the DOM inspector
977     /**
978      * Displays information about the specified element.
979      *
980      * @param {Node} elem The element to query.
981      */
982     showElementInfo: function showElementInfo(elem) {
983         let { dactyl } = this.modules;
984
985         dactyl.echo(["", /*L*/"Element:", ["br"], util.objectToString(elem, true)]);
986     },
987
988     /**
989      * Displays information about the current buffer.
990      *
991      * @param {boolean} verbose Display more verbose information.
992      * @param {string} sections A string limiting the displayed sections.
993      * @default The value of 'pageinfo'.
994      */
995     showPageInfo: function showPageInfo(verbose, sections) {
996         let { commandline, dactyl, options } = this.modules;
997
998         let self = this;
999
1000         // Ctrl-g single line output
1001         if (!verbose) {
1002             let file = this.win.location.pathname.split("/").pop() || _("buffer.noName");
1003             let title = this.win.document.title || _("buffer.noTitle");
1004
1005             let info = template.map(
1006                 (sections || options["pageinfo"])
1007                     .map(function (opt) Buffer.pageInfo[opt].action.call(self)),
1008                 function (res) res && iter(res).join(", ") || undefined,
1009                 ", ").join("");
1010
1011             if (bookmarkcache.isBookmarked(this.URL))
1012                 info += ", " + _("buffer.bookmarked");
1013
1014             let pageInfoText = [file.quote(), " [", info, "] ", title].join("");
1015             dactyl.echo(pageInfoText, commandline.FORCE_SINGLELINE);
1016             return;
1017         }
1018
1019         let list = template.map(sections || options["pageinfo"], function (option) {
1020             let { action, title } = Buffer.pageInfo[option];
1021             return template.table(title, action.call(self, true));
1022         }, ["br"]);
1023
1024         commandline.commandOutput(list);
1025     },
1026
1027     /**
1028      * Stops loading and animations in the current content.
1029      */
1030     stop: function stop() {
1031         let { config } = this.modules;
1032
1033         if (config.stop)
1034             config.stop();
1035         else
1036             this.docShell.stop(this.docShell.STOP_ALL);
1037     },
1038
1039     /**
1040      * Opens a viewer to inspect the source of the currently selected
1041      * range.
1042      */
1043     viewSelectionSource: function viewSelectionSource() {
1044         // copied (and tuned somewhat) from browser.jar -> nsContextMenu.js
1045         let { document, window } = this.topWindow;
1046
1047         let win = document.commandDispatcher.focusedWindow;
1048         if (win == this.topWindow)
1049             win = this.focusedFrame;
1050
1051         let charset = win ? "charset=" + win.document.characterSet : null;
1052
1053         window.openDialog("chrome://global/content/viewPartialSource.xul",
1054                           "_blank", "scrollbars,resizable,chrome,dialog=no",
1055                           null, charset, win.getSelection(), "selection");
1056     },
1057
1058     /**
1059      * Opens a viewer to inspect the source of the current buffer or the
1060      * specified *url*. Either the default viewer or the configured external
1061      * editor is used.
1062      *
1063      * @param {string|object|null} loc If a string, the URL of the source,
1064      *      otherwise an object with some or all of the following properties:
1065      *
1066      *          url: The URL to view.
1067      *          doc: The document to view.
1068      *          line: The line to select.
1069      *          column: The column to select.
1070      *
1071      *      If no URL is provided, the current document is used.
1072      *  @default The current buffer.
1073      * @param {boolean} useExternalEditor View the source in the external editor.
1074      */
1075     viewSource: function viewSource(loc, useExternalEditor) {
1076         let { dactyl, editor, history, options } = this.modules;
1077
1078         let window = this.topWindow;
1079
1080         let doc = this.focusedFrame.document;
1081
1082         if (isObject(loc)) {
1083             if (options.get("editor").has("line") || !loc.url)
1084                 this.viewSourceExternally(loc.doc || loc.url || doc, loc);
1085             else
1086                 window.openDialog("chrome://global/content/viewSource.xul",
1087                                   "_blank", "all,dialog=no",
1088                                   loc.url, null, null, loc.line);
1089         }
1090         else {
1091             if (useExternalEditor)
1092                 this.viewSourceExternally(loc || doc);
1093             else {
1094                 let url = loc || doc.location.href;
1095                 const PREFIX = "view-source:";
1096                 if (url.indexOf(PREFIX) == 0)
1097                     url = url.substr(PREFIX.length);
1098                 else
1099                     url = PREFIX + url;
1100
1101                 let sh = history.session;
1102                 if (sh[sh.index].URI.spec == url)
1103                     this.docShell.gotoIndex(sh.index);
1104                 else
1105                     dactyl.open(url, { hide: true });
1106             }
1107         }
1108     },
1109
1110     /**
1111      * Launches an editor to view the source of the given document. The
1112      * contents of the document are saved to a temporary local file and
1113      * removed when the editor returns. This function returns
1114      * immediately.
1115      *
1116      * @param {Document} doc The document to view.
1117      * @param {function|object} callback If a function, the callback to be
1118      *      called with two arguments: the nsIFile of the file, and temp, a
1119      *      boolean which is true if the file is temporary. Otherwise, an object
1120      *      with line and column properties used to determine where to open the
1121      *      source.
1122      *      @optional
1123      */
1124     viewSourceExternally: Class("viewSourceExternally",
1125         XPCOM([Ci.nsIWebProgressListener, Ci.nsISupportsWeakReference]), {
1126         init: function init(doc, callback) {
1127             this.callback = callable(callback) ? callback :
1128                 function (file, temp) {
1129                     let { editor } = overlay.activeModules;
1130
1131                     editor.editFileExternally(update({ file: file.path }, callback || {}),
1132                                               function () { temp && file.remove(false); });
1133                     return true;
1134                 };
1135
1136             if (isString(doc)) {
1137                 var privacyContext = null;
1138                 var uri = util.newURI(doc);
1139             }
1140             else {
1141                 privacyContext = sanitizer.getContext(doc);
1142                 uri = util.newURI(doc.location.href);
1143             }
1144
1145             let ext = uri.fileExtension || "txt";
1146             if (doc.contentType)
1147                 ext = services.mime.getPrimaryExtension(doc.contentType, ext);
1148
1149             if (!isString(doc))
1150                 return io.withTempFiles(function (temp) {
1151                     let encoder = services.HtmlEncoder();
1152                     encoder.init(doc, "text/unicode", encoder.OutputRaw|encoder.OutputPreformatted);
1153                     temp.write(encoder.encodeToString(), ">");
1154                     return this.callback(temp, true);
1155                 }, this, true, ext);
1156
1157             let file = util.getFile(uri);
1158             if (file)
1159                 this.callback(file, false);
1160             else {
1161                 this.file = io.createTempFile();
1162                 var persist = services.Persist();
1163                 persist.persistFlags = persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
1164                 persist.progressListener = this;
1165                 persist.saveURI(uri, null, null, null, null, this.file,
1166                                 privacyContext);
1167             }
1168             return null;
1169         },
1170
1171         onStateChange: function onStateChange(progress, request, flags, status) {
1172             if ((flags & this.STATE_STOP) && status == 0) {
1173                 try {
1174                     var ok = this.callback(this.file, true);
1175                 }
1176                 finally {
1177                     if (ok !== true)
1178                         this.file.remove(false);
1179                 }
1180             }
1181             return 0;
1182         }
1183     }),
1184
1185     /**
1186      * Increases the zoom level of the current buffer.
1187      *
1188      * @param {number} steps The number of zoom levels to jump.
1189      * @param {boolean} fullZoom Whether to use full zoom or text zoom.
1190      */
1191     zoomIn: function zoomIn(steps, fullZoom) {
1192         this.bumpZoomLevel(steps, fullZoom);
1193     },
1194
1195     /**
1196      * Decreases the zoom level of the current buffer.
1197      *
1198      * @param {number} steps The number of zoom levels to jump.
1199      * @param {boolean} fullZoom Whether to use full zoom or text zoom.
1200      */
1201     zoomOut: function zoomOut(steps, fullZoom) {
1202         this.bumpZoomLevel(-steps, fullZoom);
1203     },
1204
1205     /**
1206      * Adjusts the page zoom of the current buffer to the given absolute
1207      * value.
1208      *
1209      * @param {number} value The new zoom value as a possibly fractional
1210      *   percentage of the page's natural size.
1211      * @param {boolean} fullZoom If true, zoom all content of the page,
1212      *   including raster images. If false, zoom only text. If omitted,
1213      *   use the current zoom function. @optional
1214      * @throws {FailedAssertion} if the given *value* is not within the
1215      *   closed range [Buffer.ZOOM_MIN, Buffer.ZOOM_MAX].
1216      */
1217     setZoom: function setZoom(value, fullZoom) {
1218         let { dactyl, statusline, storage } = this.modules;
1219         let { ZoomManager } = this;
1220
1221         if (fullZoom === undefined)
1222             fullZoom = ZoomManager.useFullZoom;
1223         else
1224             ZoomManager.useFullZoom = fullZoom;
1225
1226         value /= 100;
1227         try {
1228             this.contentViewer.textZoom =  fullZoom ? 1 : value;
1229             this.contentViewer.fullZoom = !fullZoom ? 1 : value;
1230         }
1231         catch (e if e == Cr.NS_ERROR_ILLEGAL_VALUE) {
1232             return dactyl.echoerr(_("zoom.illegal"));
1233         }
1234
1235         if (prefs.get("browser.zoom.siteSpecific")) {
1236             var privacy = sanitizer.getContext(this.win);
1237             if (value == 1) {
1238                 this.clearPref("browser.content.full-zoom");
1239                 this.clearPref("dactyl.content.full-zoom");
1240             }
1241             else {
1242                 this.setPref("browser.content.full-zoom", value);
1243                 this.setPref("dactyl.content.full-zoom", fullZoom);
1244             }
1245         }
1246
1247         statusline.updateZoomLevel();
1248     },
1249
1250     /**
1251      * Updates the zoom level of this buffer from a content preference.
1252      */
1253     updateZoom: util.wrapCallback(function updateZoom() {
1254         let self = this;
1255         let uri = this.uri;
1256
1257         if (prefs.get("browser.zoom.siteSpecific")) {
1258             this.getPref("dactyl.content.full-zoom", function (val) {
1259                 if (val != null && uri.equals(self.uri) && val != prefs.get("browser.zoom.full"))
1260                     [self.contentViewer.textZoom, self.contentViewer.fullZoom] =
1261                         [self.contentViewer.fullZoom, self.contentViewer.textZoom];
1262             });
1263         }
1264     }),
1265
1266     /**
1267      * Adjusts the page zoom of the current buffer relative to the
1268      * current zoom level.
1269      *
1270      * @param {number} steps The integral number of natural fractions by which
1271      *     to adjust the current page zoom. If positive, the zoom level is
1272      *     increased, if negative it is decreased.
1273      * @param {boolean} fullZoom If true, zoom all content of the page,
1274      *     including raster images. If false, zoom only text. If omitted, use
1275      *     the current zoom function. @optional
1276      * @throws {FailedAssertion} if the buffer's zoom level is already at its
1277      *     extreme in the given direction.
1278      */
1279     bumpZoomLevel: function bumpZoomLevel(steps, fullZoom) {
1280         let { ZoomManager } = this;
1281
1282         if (fullZoom === undefined)
1283             fullZoom = ZoomManager.useFullZoom;
1284
1285         let values = ZoomManager.zoomValues;
1286         let cur = values.indexOf(ZoomManager.snap(this.zoomLevel / 100));
1287         let i = Math.constrain(cur + steps, 0, values.length - 1);
1288
1289         util.assert(i != cur || fullZoom != ZoomManager.useFullZoom);
1290
1291         this.setZoom(Math.round(values[i] * 100), fullZoom);
1292     },
1293
1294     getAllFrames: deprecated("buffer.allFrames", "allFrames"),
1295     scrollTop: deprecated("buffer.scrollToPercent", function scrollTop() this.scrollToPercent(null, 0)),
1296     scrollBottom: deprecated("buffer.scrollToPercent", function scrollBottom() this.scrollToPercent(null, 100)),
1297     scrollStart: deprecated("buffer.scrollToPercent", function scrollStart() this.scrollToPercent(0, null)),
1298     scrollEnd: deprecated("buffer.scrollToPercent", function scrollEnd() this.scrollToPercent(100, null)),
1299     scrollColumns: deprecated("buffer.scrollHorizontal", function scrollColumns(cols) this.scrollHorizontal("columns", cols)),
1300     scrollPages: deprecated("buffer.scrollHorizontal", function scrollPages(pages) this.scrollVertical("pages", pages)),
1301     scrollTo: deprecated("Buffer.scrollTo", function scrollTo(x, y) this.win.scrollTo(x, y)),
1302     textZoom: deprecated("buffer.zoomValue/buffer.fullZoom", function textZoom() this.contentViewer.markupDocumentViewer.textZoom * 100)
1303 }, {
1304     /**
1305      * The pattern used to search for a scrollable element when we have
1306      * no starting point.
1307      */
1308     SCROLLABLE_SEARCH_SELECTOR: "html, body, div",
1309
1310     PageInfo: Struct("PageInfo", "name", "title", "action")
1311                         .localize("title"),
1312
1313     pageInfo: {},
1314
1315     /**
1316      * Adds a new section to the page information output.
1317      *
1318      * @param {string} option The section's value in 'pageinfo'.
1319      * @param {string} title The heading for this section's
1320      *     output.
1321      * @param {function} func The function to generate this
1322      *     section's output.
1323      */
1324     addPageInfoSection: function addPageInfoSection(option, title, func) {
1325         this.pageInfo[option] = Buffer.PageInfo(option, title, func);
1326     },
1327
1328     uriShorteners: [],
1329
1330     /**
1331      * Adds a new URI shortener for documents matching the given filter.
1332      *
1333      * @param {string|function(URI, Document):boolean} filter A site filter
1334      *      string or a function which accepts a URI and a document and
1335      *      returns true if it can shorten the document's URI.
1336      * @param {function(URI, Document):URI} shortener Returns a shortened
1337      *      URL for the given URI and document.
1338      */
1339     addURIShortener: function addURIShortener(filter, shortener) {
1340         if (isString(filter))
1341             filter = Group.compileFilter(filter);
1342
1343         this.uriShorteners.push(function uriShortener(uri, doc) {
1344             if (filter(uri, doc))
1345                 return shortener(uri, doc);
1346         });
1347     },
1348
1349     Scrollable: function Scrollable(elem) {
1350         if (elem instanceof Ci.nsIDOMElement)
1351             return elem;
1352         if (isinstance(elem, [Ci.nsIDOMWindow, Ci.nsIDOMDocument]))
1353             return {
1354                 __proto__: elem.documentElement || elem.ownerDocument.documentElement,
1355
1356                 win: elem.defaultView || elem.ownerDocument.defaultView,
1357
1358                 get clientWidth() this.win.innerWidth,
1359                 get clientHeight() this.win.innerHeight,
1360
1361                 get scrollWidth() this.win.scrollMaxX + this.win.innerWidth,
1362                 get scrollHeight() this.win.scrollMaxY + this.win.innerHeight,
1363
1364                 get scrollLeftMax() this.win.scrollMaxX,
1365                 get scrollRightMax() this.win.scrollMaxY,
1366
1367                 get scrollLeft() this.win.scrollX,
1368                 set scrollLeft(val) { this.win.scrollTo(val, this.win.scrollY) },
1369
1370                 get scrollTop() this.win.scrollY,
1371                 set scrollTop(val) { this.win.scrollTo(this.win.scrollX, val) }
1372             };
1373         return elem;
1374     },
1375
1376     get ZOOM_MIN() prefs.get("zoom.minPercent"),
1377     get ZOOM_MAX() prefs.get("zoom.maxPercent"),
1378
1379     setZoom: deprecated("buffer.setZoom", function setZoom()
1380                         let ({ buffer } = overlay.activeModules) buffer.setZoom.apply(buffer, arguments)),
1381     bumpZoomLevel: deprecated("buffer.bumpZoomLevel", function bumpZoomLevel()
1382                               let ({ buffer } = overlay.activeModules) buffer.bumpZoomLevel.apply(buffer, arguments)),
1383
1384     /**
1385      * Returns the currently selected word in *win*. If the selection is
1386      * null, it tries to guess the word that the caret is positioned in.
1387      *
1388      * @returns {string}
1389      */
1390     currentWord: function currentWord(win, select) {
1391         let { Editor, options } = Buffer(win).modules;
1392
1393         let selection = win.getSelection();
1394         if (selection.rangeCount == 0)
1395             return "";
1396
1397         let range = selection.getRangeAt(0).cloneRange();
1398         if (range.collapsed) {
1399             let re = options.get("iskeyword").regexp;
1400             Editor.extendRange(range, true,  re, true);
1401             Editor.extendRange(range, false, re, true);
1402         }
1403         if (select) {
1404             selection.removeAllRanges();
1405             selection.addRange(range);
1406         }
1407         return DOM.stringify(range);
1408     },
1409
1410     getDefaultNames: function getDefaultNames(node) {
1411         let url = node.href || node.src || node.documentURI;
1412         let currExt = url.replace(/^.*?(?:\.([a-z0-9]+))?$/i, "$1").toLowerCase();
1413
1414         let ext = "";
1415         if (isinstance(node, [Ci.nsIDOMDocument,
1416                               Ci.nsIDOMHTMLImageElement])) {
1417             let type = node.contentType || node.QueryInterface(Ci.nsIImageLoadingContent)
1418                                                .getRequest(0).mimeType;
1419
1420             if (type === "text/plain")
1421                 ext = "." + (currExt || "txt");
1422             else
1423                 ext = "." + services.mime.getPrimaryExtension(type, currExt);
1424         }
1425         else if (currExt)
1426             ext = "." + currExt;
1427
1428         let re = ext ? RegExp("(\\." + currExt + ")?$", "i") : /$/;
1429
1430         var names = [];
1431         if (node.title)
1432             names.push([node.title,
1433                        _("buffer.save.pageName")]);
1434
1435         if (node.alt)
1436             names.push([node.alt,
1437                        _("buffer.save.altText")]);
1438
1439         if (!isinstance(node, Ci.nsIDOMDocument) && node.textContent)
1440             names.push([node.textContent,
1441                        _("buffer.save.linkText")]);
1442
1443         names.push([decodeURIComponent(url.replace(/.*?([^\/]*)\/*$/, "$1")),
1444                     _("buffer.save.filename")]);
1445
1446         return names.filter(function ([leaf, title]) leaf)
1447                     .map(function ([leaf, title]) [leaf.replace(config.OS.illegalCharacters, encodeURIComponent)
1448                                                        .replace(re, ext), title]);
1449     },
1450
1451     findScrollableWindow: deprecated("buffer.findScrollableWindow", function findScrollableWindow()
1452                                      let ({ buffer } = overlay.activeModules) buffer.findScrollableWindow.apply(buffer, arguments)),
1453     findScrollable: deprecated("buffer.findScrollable", function findScrollable()
1454                                let ({ buffer } = overlay.activeModules) buffer.findScrollable.apply(buffer, arguments)),
1455
1456     isScrollable: function isScrollable(elem, dir, horizontal) {
1457         if (!DOM(elem).isScrollable(horizontal ? "horizontal" : "vertical"))
1458             return false;
1459
1460         return this.canScroll(elem, dir, horizontal);
1461     },
1462
1463     canScroll: function canScroll(elem, dir, horizontal) {
1464         let pos = "scrollTop", size = "clientHeight", end = "scrollHeight", layoutSize = "offsetHeight",
1465             overflow = "overflowX", border1 = "borderTopWidth", border2 = "borderBottomWidth";
1466         if (horizontal)
1467             pos = "scrollLeft", size = "clientWidth", end = "scrollWidth", layoutSize = "offsetWidth",
1468             overflow = "overflowX", border1 = "borderLeftWidth", border2 = "borderRightWidth";
1469
1470         if (dir < 0)
1471             return elem[pos] > 0;
1472
1473         let max = pos + "Max";
1474         if (max in elem && pos > 0)
1475             return elem[pos] < elem[max];
1476
1477         let style = DOM(elem).style;
1478         let borderSize = Math.round(parseFloat(style[border1]) + parseFloat(style[border2]));
1479         let realSize = elem[size];
1480
1481         // Stupid Gecko eccentricities. May fail for quirks mode documents.
1482         if (elem[size] + borderSize >= elem[end] || elem[size] == 0) // Stupid, fallible heuristic.
1483             return false;
1484
1485         if (style[overflow] == "hidden")
1486             realSize += borderSize;
1487         return dir > 0 && elem[pos] + realSize < elem[end] || !dir && realSize < elem[end];
1488     },
1489
1490     /**
1491      * Scroll the contents of the given element to the absolute *left*
1492      * and *top* pixel offsets.
1493      *
1494      * @param {Element} elem The element to scroll.
1495      * @param {number|null} left The left absolute pixel offset. If
1496      *      null, to not alter the horizontal scroll offset.
1497      * @param {number|null} top The top absolute pixel offset. If
1498      *      null, to not alter the vertical scroll offset.
1499      * @param {string} reason The reason for the scroll event. See
1500      *      {@link marks.push}. @optional
1501      */
1502     scrollTo: function scrollTo(elem, left, top, reason) {
1503         let doc = elem.ownerDocument || elem.document || elem;
1504
1505         let { buffer, marks, options } = util.topWindow(doc.defaultView).dactyl.modules;
1506
1507         if (~[elem, elem.document, elem.ownerDocument].indexOf(buffer.focusedFrame.document))
1508             marks.push(reason);
1509
1510         if (options["scrollsteps"] > 1)
1511             return this.smoothScrollTo(elem, left, top);
1512
1513         elem = Buffer.Scrollable(elem);
1514         if (left != null)
1515             elem.scrollLeft = left;
1516         if (top != null)
1517             elem.scrollTop = top;
1518     },
1519
1520     /**
1521      * Like scrollTo, but scrolls more smoothly and does not update
1522      * marks.
1523      */
1524     smoothScrollTo: function smoothScrollTo(node, x, y) {
1525         let { options } = overlay.activeModules;
1526
1527         let time = options["scrolltime"];
1528         let steps = options["scrollsteps"];
1529
1530         let elem = Buffer.Scrollable(node);
1531
1532         if (node.dactylScrollTimer)
1533             node.dactylScrollTimer.cancel();
1534
1535         if (x == null)
1536             x = elem.scrollLeft;
1537         if (y == null)
1538             y = elem.scrollTop;
1539
1540         x = node.dactylScrollDestX = Math.min(x, elem.scrollWidth  - elem.clientWidth);
1541         y = node.dactylScrollDestY = Math.min(y, elem.scrollHeight - elem.clientHeight);
1542         let [startX, startY] = [elem.scrollLeft, elem.scrollTop];
1543         let n = 0;
1544         (function next() {
1545             if (n++ === steps) {
1546                 elem.scrollLeft = x;
1547                 elem.scrollTop  = y;
1548                 delete node.dactylScrollDestX;
1549                 delete node.dactylScrollDestY;
1550             }
1551             else {
1552                 elem.scrollLeft = startX + (x - startX) / steps * n;
1553                 elem.scrollTop  = startY + (y - startY) / steps * n;
1554                 node.dactylScrollTimer = util.timeout(next, time / steps);
1555             }
1556         }).call(this);
1557     },
1558
1559     /**
1560      * Scrolls the currently given element horizontally.
1561      *
1562      * @param {Element} elem The element to scroll.
1563      * @param {string} unit The increment by which to scroll.
1564      *   Possible values are: "columns", "pages"
1565      * @param {number} number The possibly fractional number of
1566      *   increments to scroll. Positive values scroll to the right while
1567      *   negative values scroll to the left.
1568      * @throws {FailedAssertion} if scrolling is not possible in the
1569      *   given direction.
1570      */
1571     scrollHorizontal: function scrollHorizontal(node, unit, number) {
1572         let fontSize = parseInt(DOM(node).style.fontSize);
1573
1574         let elem = Buffer.Scrollable(node);
1575         let increment;
1576         if (unit == "columns")
1577             increment = fontSize; // Good enough, I suppose.
1578         else if (unit == "pages")
1579             increment = elem.clientWidth - fontSize;
1580         else
1581             throw Error();
1582
1583         util.assert(number < 0 ? elem.scrollLeft > 0 : elem.scrollLeft < elem.scrollWidth - elem.clientWidth);
1584
1585         let left = node.dactylScrollDestX !== undefined ? node.dactylScrollDestX : elem.scrollLeft;
1586         node.dactylScrollDestX = undefined;
1587
1588         Buffer.scrollTo(node, left + number * increment, null, "h-" + unit);
1589     },
1590
1591     /**
1592      * Scrolls the given element vertically.
1593      *
1594      * @param {Node} node The node to scroll.
1595      * @param {string} unit The increment by which to scroll.
1596      *   Possible values are: "lines", "pages"
1597      * @param {number} number The possibly fractional number of
1598      *   increments to scroll. Positive values scroll upward while
1599      *   negative values scroll downward.
1600      * @throws {FailedAssertion} if scrolling is not possible in the
1601      *   given direction.
1602      */
1603     scrollVertical: function scrollVertical(node, unit, number) {
1604         let fontSize = parseInt(DOM(node).style.lineHeight);
1605
1606         let elem = Buffer.Scrollable(node);
1607         let increment;
1608         if (unit == "lines")
1609             increment = fontSize;
1610         else if (unit == "pages")
1611             increment = elem.clientHeight - fontSize;
1612         else
1613             throw Error();
1614
1615         util.assert(number < 0 ? elem.scrollTop > 0 : elem.scrollTop < elem.scrollHeight - elem.clientHeight);
1616
1617         let top = node.dactylScrollDestY !== undefined ? node.dactylScrollDestY : elem.scrollTop;
1618         node.dactylScrollDestY = undefined;
1619
1620         Buffer.scrollTo(node, null, top + number * increment, "v-" + unit);
1621     },
1622
1623     /**
1624      * Scrolls the currently active element to the given horizontal and
1625      * vertical percentages.
1626      *
1627      * @param {Element} elem The element to scroll.
1628      * @param {number|null} horizontal The possibly fractional
1629      *   percentage of the current viewport width to scroll to. If null,
1630      *   do not scroll horizontally.
1631      * @param {number|null} vertical The possibly fractional percentage
1632      *   of the current viewport height to scroll to. If null, do not
1633      *   scroll vertically.
1634      */
1635     scrollToPercent: function scrollToPercent(node, horizontal, vertical) {
1636         let elem = Buffer.Scrollable(node);
1637         Buffer.scrollTo(node,
1638                         horizontal == null ? null
1639                                            : (elem.scrollWidth - elem.clientWidth) * (horizontal / 100),
1640                         vertical   == null ? null
1641                                            : (elem.scrollHeight - elem.clientHeight) * (vertical / 100));
1642     },
1643
1644     /**
1645      * Scrolls the currently active element to the given horizontal and
1646      * vertical position.
1647      *
1648      * @param {Element} elem The element to scroll.
1649      * @param {number|null} horizontal The possibly fractional
1650      *      line ordinal to scroll to.
1651      * @param {number|null} vertical The possibly fractional
1652      *      column ordinal to scroll to.
1653      */
1654     scrollToPosition: function scrollToPosition(elem, horizontal, vertical) {
1655         let style = DOM(elem.body || elem).style;
1656         Buffer.scrollTo(elem,
1657                         horizontal == null ? null :
1658                         horizontal == 0    ? 0    : this._exWidth(elem) * horizontal,
1659                         vertical   == null ? null : parseFloat(style.lineHeight) * vertical);
1660     },
1661
1662     /**
1663      * Returns the current scroll position as understood by
1664      * {@link #scrollToPosition}.
1665      *
1666      * @param {Element} elem The element to scroll.
1667      */
1668     getScrollPosition: function getPosition(node) {
1669         let style = DOM(node.body || node).style;
1670
1671         let elem = Buffer.Scrollable(node);
1672         return {
1673             x: elem.scrollLeft && elem.scrollLeft / this._exWidth(node),
1674             y: elem.scrollTop / parseFloat(style.lineHeight)
1675         }
1676     },
1677
1678     _exWidth: function _exWidth(elem) {
1679         try {
1680             let div = DOM(["elem", { style: "width: 1ex !important; position: absolute !important; padding: 0 !important; display: block;" }],
1681                           elem.ownerDocument).appendTo(elem.body || elem);
1682             try {
1683                 return parseFloat(div.style.width);
1684             }
1685             finally {
1686                 div.remove();
1687             }
1688         }
1689         catch (e) {
1690             return parseFloat(DOM(elem).fontSize) / 1.618;
1691         }
1692     },
1693
1694     openUploadPrompt: function openUploadPrompt(elem) {
1695         let { io } = overlay.activeModules;
1696
1697         io.CommandFileMode(_("buffer.prompt.uploadFile") + " ", {
1698             onSubmit: function onSubmit(path) {
1699                 let file = io.File(path);
1700                 util.assert(file.exists());
1701
1702                 DOM(elem).val(file.path).change();
1703             }
1704         }).open(elem.value);
1705     }
1706 }, {
1707     init: function init(dactyl, modules, window) {
1708         init.superapply(this, arguments);
1709
1710         dactyl.commands["buffer.viewSource"] = function (event) {
1711             let elem = event.originalTarget;
1712             let obj = { url: elem.getAttribute("href"), line: Number(elem.getAttribute("line")) };
1713             if (elem.hasAttribute("column"))
1714                 obj.column = elem.getAttribute("column");
1715
1716             modules.buffer.viewSource(obj);
1717         };
1718     },
1719     commands: function initCommands(dactyl, modules, window) {
1720         let { buffer, commands, config, options } = modules;
1721
1722         commands.add(["frameo[nly]"],
1723             "Show only the current frame's page",
1724             function (args) {
1725                 dactyl.open(buffer.focusedFrame.location.href);
1726             },
1727             { argCount: "0" });
1728
1729         commands.add(["ha[rdcopy]"],
1730             "Print current document",
1731             function (args) {
1732                 let arg = args[0];
1733
1734                 // FIXME: arg handling is a bit of a mess, check for filename
1735                 dactyl.assert(!arg || arg[0] == ">" && !config.OS.isWindows,
1736                               _("error.trailingCharacters"));
1737
1738                 const PRINTER  = "PostScript/default";
1739                 const BRANCH   = "printer_" + PRINTER + ".";
1740                 const BRANCHES = ["print.", BRANCH, "print." + BRANCH];
1741                 function set(pref, value) {
1742                     BRANCHES.forEach(function (branch) { prefs.set(branch + pref, value) });
1743                 }
1744
1745                 prefs.withContext(function () {
1746                     if (arg) {
1747                         prefs.set("print.print_printer", PRINTER);
1748
1749                         set("print_to_file", true);
1750                         set("print_to_filename", io.File(arg.substr(1)).path);
1751
1752                         dactyl.echomsg(_("print.toFile", arg.substr(1)));
1753                     }
1754                     else
1755                         dactyl.echomsg(_("print.sending"));
1756
1757                     prefs.set("print.always_print_silent", args.bang);
1758                     if (false)
1759                         prefs.set("print.show_print_progress", !args.bang);
1760
1761                     config.browser.contentWindow.print();
1762                 });
1763
1764                 dactyl.echomsg(_("print.sent"));
1765             },
1766             {
1767                 argCount: "?",
1768                 bang: true,
1769                 completer: function (context, args) {
1770                     if (args.bang && /^>/.test(context.filter))
1771                         context.fork("file", 1, modules.completion, "file");
1772                 },
1773                 literal: 0
1774             });
1775
1776         commands.add(["pa[geinfo]"],
1777             "Show various page information",
1778             function (args) {
1779                 let arg = args[0];
1780                 let opt = options.get("pageinfo");
1781
1782                 dactyl.assert(!arg || opt.validator(opt.parse(arg)),
1783                               _("error.invalidArgument", arg));
1784                 buffer.showPageInfo(true, arg);
1785             },
1786             {
1787                 argCount: "?",
1788                 completer: function (context) {
1789                     modules.completion.optionValue(context, "pageinfo", "+", "");
1790                     context.title = ["Page Info"];
1791                 }
1792             });
1793
1794         commands.add(["pagest[yle]", "pas"],
1795             "Select the author style sheet to apply",
1796             function (args) {
1797                 let arg = args[0] || "";
1798
1799                 let titles = buffer.alternateStyleSheets.map(function (stylesheet) stylesheet.title);
1800
1801                 dactyl.assert(!arg || titles.indexOf(arg) >= 0,
1802                               _("error.invalidArgument", arg));
1803
1804                 if (options["usermode"])
1805                     options["usermode"] = false;
1806
1807                 window.stylesheetSwitchAll(buffer.focusedFrame, arg);
1808             },
1809             {
1810                 argCount: "?",
1811                 completer: function (context) modules.completion.alternateStyleSheet(context),
1812                 literal: 0
1813             });
1814
1815         commands.add(["re[load]"],
1816             "Reload the current web page",
1817             function (args) { modules.tabs.reload(config.browser.mCurrentTab, args.bang); },
1818             {
1819                 argCount: "0",
1820                 bang: true
1821             });
1822
1823         // TODO: we're prompted if download.useDownloadDir isn't set and no arg specified - intentional?
1824         commands.add(["sav[eas]", "w[rite]"],
1825             "Save current document to disk",
1826             function (args) {
1827                 let { commandline, io } = modules;
1828                 let { doc, win } = buffer;
1829
1830                 let chosenData = null;
1831                 let filename = args[0];
1832
1833                 let command = commandline.command;
1834                 if (filename) {
1835                     if (filename[0] == "!")
1836                         return buffer.viewSourceExternally(buffer.focusedFrame.document,
1837                             function (file) {
1838                                 let output = io.system(filename.substr(1), file);
1839                                 commandline.command = command;
1840                                 commandline.commandOutput(["span", { highlight: "CmdOutput" }, output]);
1841                             });
1842
1843                     if (/^>>/.test(filename)) {
1844                         let file = io.File(filename.replace(/^>>\s*/, ""));
1845                         dactyl.assert(args.bang || file.exists() && file.isWritable(),
1846                                       _("io.notWriteable", file.path.quote()));
1847
1848                         return buffer.viewSourceExternally(buffer.focusedFrame.document,
1849                             function (tmpFile) {
1850                                 try {
1851                                     file.write(tmpFile, ">>");
1852                                 }
1853                                 catch (e) {
1854                                     dactyl.echoerr(_("io.notWriteable", file.path.quote()));
1855                                 }
1856                             });
1857                     }
1858
1859                     let file = io.File(filename);
1860
1861                     if (filename.substr(-1) === File.PATH_SEP || file.exists() && file.isDirectory())
1862                         file.append(Buffer.getDefaultNames(doc)[0][0]);
1863
1864                     dactyl.assert(args.bang || !file.exists(), _("io.exists"));
1865
1866                     chosenData = { file: file.file, uri: util.newURI(doc.location.href) };
1867                 }
1868
1869                 // if browser.download.useDownloadDir = false then the "Save As"
1870                 // dialog is used with this as the default directory
1871                 // TODO: if we're going to do this shouldn't it be done in setCWD or the value restored?
1872                 prefs.set("browser.download.lastDir", io.cwd.path);
1873
1874                 try {
1875                     var contentDisposition = win.QueryInterface(Ci.nsIInterfaceRequestor)
1876                                                 .getInterface(Ci.nsIDOMWindowUtils)
1877                                                 .getDocumentMetadata("content-disposition");
1878                 }
1879                 catch (e) {}
1880
1881                 window.internalSave(doc.location.href, doc, null, contentDisposition,
1882                                     doc.contentType, false, null, chosenData,
1883                                     doc.referrer ? window.makeURI(doc.referrer) : null,
1884                                     doc, true);
1885             },
1886             {
1887                 argCount: "?",
1888                 bang: true,
1889                 completer: function (context) {
1890                     let { buffer, completion } = modules;
1891
1892                     if (context.filter[0] == "!")
1893                         return;
1894                     if (/^>>/.test(context.filter))
1895                         context.advance(/^>>\s*/.exec(context.filter)[0].length);
1896
1897                     completion.savePage(context, buffer.doc);
1898                     context.fork("file", 0, completion, "file");
1899                 },
1900                 literal: 0
1901             });
1902
1903         commands.add(["st[op]"],
1904             "Stop loading the current web page",
1905             function () { buffer.stop(); },
1906             { argCount: "0" });
1907
1908         commands.add(["vie[wsource]"],
1909             "View source code of current document",
1910             function (args) { buffer.viewSource(args[0], args.bang); },
1911             {
1912                 argCount: "?",
1913                 bang: true,
1914                 completer: function (context) modules.completion.url(context, "bhf")
1915             });
1916
1917         commands.add(["zo[om]"],
1918             "Set zoom value of current web page",
1919             function (args) {
1920                 let arg = args[0];
1921                 let level;
1922
1923                 if (!arg)
1924                     level = 100;
1925                 else if (/^\d+$/.test(arg))
1926                     level = parseInt(arg, 10);
1927                 else if (/^[+-]\d+$/.test(arg))
1928                     level = Math.round(buffer.zoomLevel + parseInt(arg, 10));
1929                 else
1930                     dactyl.assert(false, _("error.trailingCharacters"));
1931
1932                 buffer.setZoom(level, args.bang);
1933             },
1934             {
1935                 argCount: "?",
1936                 bang: true
1937             });
1938     },
1939     completion: function initCompletion(dactyl, modules, window) {
1940         let { CompletionContext, buffer, completion } = modules;
1941
1942         completion.alternateStyleSheet = function alternateStylesheet(context) {
1943             context.title = ["Stylesheet", "Location"];
1944
1945             // unify split style sheets
1946             let styles = iter([s.title, []] for (s in values(buffer.alternateStyleSheets))).toObject();
1947
1948             buffer.alternateStyleSheets.forEach(function (style) {
1949                 styles[style.title].push(style.href || _("style.inline"));
1950             });
1951
1952             context.completions = [[title, href.join(", ")] for ([title, href] in Iterator(styles))];
1953         };
1954
1955         completion.savePage = function savePage(context, node) {
1956             context.fork("generated", context.filter.replace(/[^/]*$/, "").length,
1957                          this, function (context) {
1958                 context.generate = function () {
1959                     this.incomplete = true;
1960                     this.completions = Buffer.getDefaultNames(node);
1961                     util.httpGet(node.href || node.src || node.documentURI, {
1962                         method: "HEAD",
1963                         callback: function callback(xhr) {
1964                             context.incomplete = false;
1965                             try {
1966                                 if (/filename="(.*?)"/.test(xhr.getResponseHeader("Content-Disposition")))
1967                                     context.completions.push([decodeURIComponent(RegExp.$1),
1968                                                              _("buffer.save.suggested")]);
1969                             }
1970                             finally {
1971                                 context.completions = context.completions.slice();
1972                             }
1973                         },
1974                         notificationCallbacks: Class(XPCOM([Ci.nsIChannelEventSink, Ci.nsIInterfaceRequestor]), {
1975                             getInterface: function getInterface(iid) this.QueryInterface(iid),
1976
1977                             asyncOnChannelRedirect: function (oldChannel, newChannel, flags, callback) {
1978                                 if (newChannel instanceof Ci.nsIHttpChannel)
1979                                     newChannel.requestMethod = "HEAD";
1980                                 callback.onRedirectVerifyCallback(Cr.NS_OK);
1981                             }
1982                         })()
1983                     });
1984                 };
1985             });
1986         };
1987     },
1988     events: function initEvents(dactyl, modules, window) {
1989         let { buffer, config, events } = modules;
1990
1991         events.listen(config.browser, "scroll", buffer.closure._updateBufferPosition, false);
1992     },
1993     mappings: function initMappings(dactyl, modules, window) {
1994         let { Editor, Events, buffer, editor, events, ex, mappings, modes, options, tabs } = modules;
1995
1996         mappings.add([modes.NORMAL],
1997             ["y", "<yank-location>"], "Yank current location to the clipboard",
1998             function () {
1999                 let { doc, uri } = buffer;
2000                 if (uri instanceof Ci.nsIURL)
2001                     uri.query = uri.query.replace(/(?:^|&)utm_[^&]+/g, "")
2002                                          .replace(/^&/, "");
2003
2004                 let url = options.get("yankshort").getKey(uri) && buffer.shortURL || uri.spec;
2005                 dactyl.clipboardWrite(url, true);
2006             });
2007
2008         mappings.add([modes.NORMAL],
2009             ["<C-a>", "<increment-url-path>"], "Increment last number in URL",
2010             function (args) { buffer.incrementURL(Math.max(args.count, 1)); },
2011             { count: true });
2012
2013         mappings.add([modes.NORMAL],
2014             ["<C-x>", "<decrement-url-path>"], "Decrement last number in URL",
2015             function (args) { buffer.incrementURL(-Math.max(args.count, 1)); },
2016             { count: true });
2017
2018         mappings.add([modes.NORMAL], ["gu", "<open-parent-path>"],
2019             "Go to parent directory",
2020             function (args) { buffer.climbUrlPath(Math.max(args.count, 1)); },
2021             { count: true });
2022
2023         mappings.add([modes.NORMAL], ["gU", "<open-root-path>"],
2024             "Go to the root of the website",
2025             function () { buffer.climbUrlPath(-1); });
2026
2027         mappings.add([modes.COMMAND], [".", "<repeat-key>"],
2028             "Repeat the last key event",
2029             function (args) {
2030                 if (mappings.repeat) {
2031                     for (let i in util.interruptibleRange(0, Math.max(args.count, 1), 100))
2032                         mappings.repeat();
2033                 }
2034             },
2035             { count: true });
2036
2037         mappings.add([modes.NORMAL], ["i", "<Insert>"],
2038             "Start Caret mode",
2039             function () { modes.push(modes.CARET); });
2040
2041         mappings.add([modes.NORMAL], ["<C-c>", "<stop-load>"],
2042             "Stop loading the current web page",
2043             function () { ex.stop(); });
2044
2045         // scrolling
2046         mappings.add([modes.NORMAL], ["j", "<Down>", "<C-e>", "<scroll-down-line>"],
2047             "Scroll document down",
2048             function (args) { buffer.scrollVertical("lines", Math.max(args.count, 1)); },
2049             { count: true });
2050
2051         mappings.add([modes.NORMAL], ["k", "<Up>", "<C-y>", "<scroll-up-line>"],
2052             "Scroll document up",
2053             function (args) { buffer.scrollVertical("lines", -Math.max(args.count, 1)); },
2054             { count: true });
2055
2056         mappings.add([modes.NORMAL], dactyl.has("mail") ? ["h", "<scroll-left-column>"] : ["h", "<Left>", "<scroll-left-column>"],
2057             "Scroll document to the left",
2058             function (args) { buffer.scrollHorizontal("columns", -Math.max(args.count, 1)); },
2059             { count: true });
2060
2061         mappings.add([modes.NORMAL], dactyl.has("mail") ? ["l", "<scroll-right-column>"] : ["l", "<Right>", "<scroll-right-column>"],
2062             "Scroll document to the right",
2063             function (args) { buffer.scrollHorizontal("columns", Math.max(args.count, 1)); },
2064             { count: true });
2065
2066         mappings.add([modes.NORMAL], ["0", "^", "<scroll-begin>"],
2067             "Scroll to the absolute left of the document",
2068             function () { buffer.scrollToPercent(0, null); });
2069
2070         mappings.add([modes.NORMAL], ["$", "<scroll-end>"],
2071             "Scroll to the absolute right of the document",
2072             function () { buffer.scrollToPercent(100, null); });
2073
2074         mappings.add([modes.NORMAL], ["gg", "<Home>", "<scroll-top>"],
2075             "Go to the top of the document",
2076             function (args) { buffer.scrollToPercent(null, args.count != null ? args.count : 0); },
2077             { count: true });
2078
2079         mappings.add([modes.NORMAL], ["G", "<End>", "<scroll-bottom>"],
2080             "Go to the end of the document",
2081             function (args) {
2082                 if (args.count)
2083                     var elem = options.get("linenumbers")
2084                                       .getLine(buffer.focusedFrame.document,
2085                                                args.count);
2086                 if (elem)
2087                     elem.scrollIntoView(true);
2088                 else if (args.count)
2089                     buffer.scrollToPosition(null, args.count);
2090                 else
2091                     buffer.scrollToPercent(null, 100);
2092             },
2093             { count: true });
2094
2095         mappings.add([modes.NORMAL], ["%", "<scroll-percent>"],
2096             "Scroll to {count} percent of the document",
2097             function (args) {
2098                 dactyl.assert(args.count > 0 && args.count <= 100);
2099                 buffer.scrollToPercent(null, args.count);
2100             },
2101             { count: true });
2102
2103         mappings.add([modes.NORMAL], ["<C-d>", "<scroll-down>"],
2104             "Scroll window downwards in the buffer",
2105             function (args) { buffer._scrollByScrollSize(args.count, true); },
2106             { count: true });
2107
2108         mappings.add([modes.NORMAL], ["<C-u>", "<scroll-up>"],
2109             "Scroll window upwards in the buffer",
2110             function (args) { buffer._scrollByScrollSize(args.count, false); },
2111             { count: true });
2112
2113         mappings.add([modes.NORMAL], ["<C-b>", "<PageUp>", "<S-Space>", "<scroll-up-page>"],
2114             "Scroll up a full page",
2115             function (args) { buffer.scrollVertical("pages", -Math.max(args.count, 1)); },
2116             { count: true });
2117
2118         mappings.add([modes.NORMAL], ["<Space>"],
2119             "Scroll down a full page",
2120             function (args) {
2121                 if (isinstance((services.focus.focusedWindow || buffer.win).document.activeElement,
2122                                [Ci.nsIDOMHTMLInputElement,
2123                                 Ci.nsIDOMHTMLButtonElement,
2124                                 Ci.nsIDOMXULButtonElement]))
2125                     return Events.PASS;
2126
2127                 buffer.scrollVertical("pages", Math.max(args.count, 1));
2128             },
2129             { count: true });
2130
2131         mappings.add([modes.NORMAL], ["<C-f>", "<PageDown>", "<scroll-down-page>"],
2132             "Scroll down a full page",
2133             function (args) { buffer.scrollVertical("pages", Math.max(args.count, 1)); },
2134             { count: true });
2135
2136         mappings.add([modes.NORMAL], ["]f", "<previous-frame>"],
2137             "Focus next frame",
2138             function (args) { buffer.shiftFrameFocus(Math.max(args.count, 1)); },
2139             { count: true });
2140
2141         mappings.add([modes.NORMAL], ["[f", "<next-frame>"],
2142             "Focus previous frame",
2143             function (args) { buffer.shiftFrameFocus(-Math.max(args.count, 1)); },
2144             { count: true });
2145
2146         mappings.add([modes.NORMAL], ["["],
2147             "Jump to the previous element as defined by 'jumptags'",
2148             function (args) { buffer.findJump(args.arg, args.count, true); },
2149             { arg: true, count: true });
2150
2151         mappings.add([modes.NORMAL], ["g]"],
2152             "Jump to the next off-screen element as defined by 'jumptags'",
2153             function (args) { buffer.findJump(args.arg, args.count, false, true); },
2154             { arg: true, count: true });
2155
2156         mappings.add([modes.NORMAL], ["]"],
2157             "Jump to the next element as defined by 'jumptags'",
2158             function (args) { buffer.findJump(args.arg, args.count, false); },
2159             { arg: true, count: true });
2160
2161         mappings.add([modes.NORMAL], ["{"],
2162             "Jump to the previous paragraph",
2163             function (args) { buffer.findJump("p", args.count, true); },
2164             { count: true });
2165
2166         mappings.add([modes.NORMAL], ["}"],
2167             "Jump to the next paragraph",
2168             function (args) { buffer.findJump("p", args.count, false); },
2169             { count: true });
2170
2171         mappings.add([modes.NORMAL], ["]]", "<next-page>"],
2172             "Follow the link labeled 'next' or '>' if it exists",
2173             function (args) {
2174                 buffer.findLink("next", options["nextpattern"], (args.count || 1) - 1, true);
2175             },
2176             { count: true });
2177
2178         mappings.add([modes.NORMAL], ["[[", "<previous-page>"],
2179             "Follow the link labeled 'prev', 'previous' or '<' if it exists",
2180             function (args) {
2181                 buffer.findLink("prev", options["previouspattern"], (args.count || 1) - 1, true);
2182             },
2183             { count: true });
2184
2185         mappings.add([modes.NORMAL], ["gf", "<view-source>"],
2186             "Toggle between rendered and source view",
2187             function () { buffer.viewSource(null, false); });
2188
2189         mappings.add([modes.NORMAL], ["gF", "<view-source-externally>"],
2190             "View source with an external editor",
2191             function () { buffer.viewSource(null, true); });
2192
2193         mappings.add([modes.NORMAL], ["gi", "<focus-input>"],
2194             "Focus last used input field",
2195             function (args) {
2196                 let elem = buffer.lastInputField;
2197
2198                 if (args.count >= 1 || !elem || !events.isContentNode(elem)) {
2199                     let xpath = ["frame", "iframe", "input", "xul:textbox", "textarea[not(@disabled) and not(@readonly)]"];
2200
2201                     let frames = buffer.allFrames(null, true);
2202
2203                     let elements = array.flatten(frames.map(function (win) [m for (m in DOM.XPath(xpath, win.document))]))
2204                                         .filter(function (elem) {
2205                         if (isinstance(elem, [Ci.nsIDOMHTMLFrameElement,
2206                                               Ci.nsIDOMHTMLIFrameElement]))
2207                             return Editor.getEditor(elem.contentWindow);
2208
2209                         elem = DOM(elem);
2210
2211                         if (elem[0].readOnly || !DOM(elem).isEditable)
2212                             return false;
2213
2214                         let style = elem.style;
2215                         let rect = elem.rect;
2216                         return elem.isVisible &&
2217                             (elem[0] instanceof Ci.nsIDOMXULTextBoxElement || style.MozUserFocus != "ignore") &&
2218                             rect.width && rect.height;
2219                     });
2220
2221                     dactyl.assert(elements.length > 0);
2222                     elem = elements[Math.constrain(args.count, 1, elements.length) - 1];
2223                 }
2224                 buffer.focusElement(elem);
2225                 DOM(elem).scrollIntoView();
2226             },
2227             { count: true });
2228
2229         function url() {
2230             let url = dactyl.clipboardRead();
2231             dactyl.assert(url, _("error.clipboardEmpty"));
2232
2233             let proto = /^([-\w]+):/.exec(url);
2234             if (proto && services.PROTOCOL + proto[1] in Cc && !RegExp(options["urlseparator"]).test(url))
2235                 return url.replace(/\s+/g, "");
2236             return url;
2237         }
2238
2239         mappings.add([modes.NORMAL], ["gP"],
2240             "Open (put) a URL based on the current clipboard contents in a new background buffer",
2241             function () {
2242                 dactyl.open(url(), { from: "paste", where: dactyl.NEW_TAB, background: true });
2243             });
2244
2245         mappings.add([modes.NORMAL], ["p", "<MiddleMouse>", "<open-clipboard-url>"],
2246             "Open (put) a URL based on the current clipboard contents in the current buffer",
2247             function () {
2248                 dactyl.open(url());
2249             });
2250
2251         mappings.add([modes.NORMAL], ["P", "<tab-open-clipboard-url>"],
2252             "Open (put) a URL based on the current clipboard contents in a new buffer",
2253             function () {
2254                 dactyl.open(url(), { from: "paste", where: dactyl.NEW_TAB });
2255             });
2256
2257         // reloading
2258         mappings.add([modes.NORMAL], ["r", "<reload>"],
2259             "Reload the current web page",
2260             function () { tabs.reload(tabs.getTab(), false); });
2261
2262         mappings.add([modes.NORMAL], ["R", "<full-reload>"],
2263             "Reload while skipping the cache",
2264             function () { tabs.reload(tabs.getTab(), true); });
2265
2266         // yanking
2267         mappings.add([modes.NORMAL], ["Y", "<yank-selection>"],
2268             "Copy selected text or current word",
2269             function () {
2270                 let sel = buffer.currentWord;
2271                 dactyl.assert(sel);
2272                 editor.setRegister(null, sel, true);
2273             });
2274
2275         // zooming
2276         mappings.add([modes.NORMAL], ["zi", "+", "<text-zoom-in>"],
2277             "Enlarge text zoom of current web page",
2278             function (args) { buffer.zoomIn(Math.max(args.count, 1), false); },
2279             { count: true });
2280
2281         mappings.add([modes.NORMAL], ["zm", "<text-zoom-more>"],
2282             "Enlarge text zoom of current web page by a larger amount",
2283             function (args) { buffer.zoomIn(Math.max(args.count, 1) * 3, false); },
2284             { count: true });
2285
2286         mappings.add([modes.NORMAL], ["zo", "-", "<text-zoom-out>"],
2287             "Reduce text zoom of current web page",
2288             function (args) { buffer.zoomOut(Math.max(args.count, 1), false); },
2289             { count: true });
2290
2291         mappings.add([modes.NORMAL], ["zr", "<text-zoom-reduce>"],
2292             "Reduce text zoom of current web page by a larger amount",
2293             function (args) { buffer.zoomOut(Math.max(args.count, 1) * 3, false); },
2294             { count: true });
2295
2296         mappings.add([modes.NORMAL], ["zz", "<text-zoom>"],
2297             "Set text zoom value of current web page",
2298             function (args) { buffer.setZoom(args.count > 1 ? args.count : 100, false); },
2299             { count: true });
2300
2301         mappings.add([modes.NORMAL], ["ZI", "zI", "<full-zoom-in>"],
2302             "Enlarge full zoom of current web page",
2303             function (args) { buffer.zoomIn(Math.max(args.count, 1), true); },
2304             { count: true });
2305
2306         mappings.add([modes.NORMAL], ["ZM", "zM", "<full-zoom-more>"],
2307             "Enlarge full zoom of current web page by a larger amount",
2308             function (args) { buffer.zoomIn(Math.max(args.count, 1) * 3, true); },
2309             { count: true });
2310
2311         mappings.add([modes.NORMAL], ["ZO", "zO", "<full-zoom-out>"],
2312             "Reduce full zoom of current web page",
2313             function (args) { buffer.zoomOut(Math.max(args.count, 1), true); },
2314             { count: true });
2315
2316         mappings.add([modes.NORMAL], ["ZR", "zR", "<full-zoom-reduce>"],
2317             "Reduce full zoom of current web page by a larger amount",
2318             function (args) { buffer.zoomOut(Math.max(args.count, 1) * 3, true); },
2319             { count: true });
2320
2321         mappings.add([modes.NORMAL], ["zZ", "<full-zoom>"],
2322             "Set full zoom value of current web page",
2323             function (args) { buffer.setZoom(args.count > 1 ? args.count : 100, true); },
2324             { count: true });
2325
2326         // page info
2327         mappings.add([modes.NORMAL], ["<C-g>", "<page-info>"],
2328             "Print the current file name",
2329             function () { buffer.showPageInfo(false); });
2330
2331         mappings.add([modes.NORMAL], ["g<C-g>", "<more-page-info>"],
2332             "Print file information",
2333             function () { buffer.showPageInfo(true); });
2334     },
2335     options: function initOptions(dactyl, modules, window) {
2336         let { Option, buffer, completion, config, options } = modules;
2337
2338         options.add(["encoding", "enc"],
2339             "The current buffer's character encoding",
2340             "string", "UTF-8",
2341             {
2342                 scope: Option.SCOPE_LOCAL,
2343                 getter: function () buffer.docShell.QueryInterface(Ci.nsIDocCharset).charset,
2344                 setter: function (val) {
2345                     if (options["encoding"] == val)
2346                         return val;
2347
2348                     // Stolen from browser.jar/content/browser/browser.js, more or less.
2349                     try {
2350                         buffer.docShell.QueryInterface(Ci.nsIDocCharset).charset = val;
2351                         window.PlacesUtils.history.setCharsetForURI(buffer.uri, val);
2352                         buffer.docShell.reload(Ci.nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE);
2353                     }
2354                     catch (e) { dactyl.reportError(e); }
2355                     return null;
2356                 },
2357                 completer: function (context) completion.charset(context)
2358             });
2359
2360         options.add(["iskeyword", "isk"],
2361             "Regular expression defining which characters constitute words",
2362             "string", '[^\\s.,!?:;/"\'^$%&?()[\\]{}<>#*+|=~_-]',
2363             {
2364                 setter: function (value) {
2365                     this.regexp = util.regexp(value);
2366                     return value;
2367                 },
2368                 validator: function (value) RegExp(value)
2369             });
2370
2371         options.add(["jumptags", "jt"],
2372             "XPath or CSS selector strings of jumpable elements for extended hint modes",
2373             "stringmap", {
2374                 "p": "p,table,ul,ol,blockquote",
2375                 "h": "h1,h2,h3,h4,h5,h6"
2376             },
2377             {
2378                 keepQuotes: true,
2379                 setter: function (vals) {
2380                     for (let [k, v] in Iterator(vals))
2381                         vals[k] = update(new String(v), { matcher: DOM.compileMatcher(Option.splitList(v)) });
2382                     return vals;
2383                 },
2384                 validator: function (value) DOM.validateMatcher.call(this, value)
2385                     && Object.keys(value).every(function (v) v.length == 1)
2386             });
2387
2388         options.add(["linenumbers", "ln"],
2389             "Patterns used to determine line numbers used by G",
2390             "sitemap", {
2391                 // Make sure to update the docs when you change this.
2392                 "view-source:*": 'body,[id^=line]',
2393                 "code.google.com": '#nums [id^="nums_table"] a[href^="#"]',
2394                 "github.com": '.line_numbers>*',
2395                 "mxr.mozilla.org": 'a.l',
2396                 "pastebin.com": '#code_frame>div>ol>li',
2397                 "addons.mozilla.org": '.gutter>.line>a',
2398                 "bugzilla.mozilla.org": ".bz_comment:not(.bz_first_comment):not(.ih_history)",
2399                 "*": '/* Hgweb/Gitweb */ .completecodeline a.codeline, a.linenr'
2400             },
2401             {
2402                 getLine: function getLine(doc, line) {
2403                     let uri = util.newURI(doc.documentURI);
2404                     for (let filter in values(this.value))
2405                         if (filter(uri, doc)) {
2406                             if (/^func:/.test(filter.result))
2407                                 var res = dactyl.userEval("(" + Option.dequote(filter.result.substr(5)) + ")")(doc, line);
2408                             else
2409                                 res = iter.nth(filter.matcher(doc),
2410                                                function (elem) (elem.nodeValue || elem.textContent).trim() == line && DOM(elem).display != "none",
2411                                                0)
2412                                    || iter.nth(filter.matcher(doc), util.identity, line - 1);
2413                             if (res)
2414                                 break;
2415                         }
2416
2417                     return res;
2418                 },
2419
2420                 keepQuotes: true,
2421
2422                 setter: function (vals) {
2423                     for (let value in values(vals))
2424                         if (!/^func:/.test(value.result))
2425                             value.matcher = DOM.compileMatcher(Option.splitList(value.result));
2426                     return vals;
2427                 },
2428
2429                 validator: function validate(values) {
2430                     return this.testValues(values, function (value) {
2431                         if (/^func:/.test(value))
2432                             return callable(dactyl.userEval("(" + Option.dequote(value.substr(5)) + ")"));
2433                         else
2434                             return DOM.testMatcher(Option.dequote(value));
2435                     });
2436                 }
2437             });
2438
2439         options.add(["nextpattern"],
2440             "Patterns to use when guessing the next page in a document sequence",
2441             "regexplist", UTF8(/'^Next [>»]','^Next Â»','\bnext\b',^>$,^(>>|»)$,^(>|»),(>|»)$,'\bmore\b'/.source),
2442             { regexpFlags: "i" });
2443
2444         options.add(["previouspattern"],
2445             "Patterns to use when guessing the previous page in a document sequence",
2446             "regexplist", UTF8(/'[<«] Prev$','« Prev$','\bprev(ious)?\b',^<$,^(<<|«)$,^(<|«),(<|«)$/.source),
2447             { regexpFlags: "i" });
2448
2449         options.add(["pageinfo", "pa"],
2450             "Define which sections are shown by the :pageinfo command",
2451             "charlist", "gesfm",
2452             { get values() values(Buffer.pageInfo).toObject() });
2453
2454         options.add(["scroll", "scr"],
2455             "Number of lines to scroll with <C-u> and <C-d> commands",
2456             "number", 0,
2457             { validator: function (value) value >= 0 });
2458
2459         options.add(["showstatuslinks", "ssli"],
2460             "Where to show the destination of the link under the cursor",
2461             "string", "status",
2462             {
2463                 values: {
2464                     "": "Don't show link destinations",
2465                     "status": "Show link destinations in the status line",
2466                     "command": "Show link destinations in the command line"
2467                 }
2468             });
2469
2470         options.add(["scrolltime", "sct"],
2471             "The time, in milliseconds, in which to smooth scroll to a new position",
2472             "number", 100);
2473
2474         options.add(["scrollsteps", "scs"],
2475             "The number of steps in which to smooth scroll to a new position",
2476             "number", 5,
2477             {
2478                 PREF: "general.smoothScroll",
2479
2480                 initValue: function () {},
2481
2482                 getter: function getter(value) !prefs.get(this.PREF) ? 1 : value,
2483
2484                 setter: function setter(value) {
2485                     prefs.set(this.PREF, value > 1);
2486                     if (value > 1)
2487                         return value;
2488                 },
2489
2490                 validator: function (value) value > 0
2491             });
2492
2493         options.add(["usermode", "um"],
2494             "Show current website without styling defined by the author",
2495             "boolean", false,
2496             {
2497                 setter: function (value) buffer.contentViewer.authorStyleDisabled = value,
2498                 getter: function () buffer.contentViewer.authorStyleDisabled
2499             });
2500
2501         options.add(["yankshort", "ys"],
2502             "Yank the canonical short URL of a web page where provided",
2503             "sitelist", ["youtube.com", "bugzilla.mozilla.org"]);
2504     }
2505 });
2506
2507 Buffer.addPageInfoSection("e", "Search Engines", function (verbose) {
2508     let n = 1;
2509     let nEngines = 0;
2510
2511     for (let { document: doc } in values(this.allFrames())) {
2512         let engines = DOM("link[href][rel=search][type='application/opensearchdescription+xml']", doc);
2513         nEngines += engines.length;
2514
2515         if (verbose)
2516             for (let link in engines)
2517                 yield [link.title || /*L*/ "Engine " + n++,
2518                        ["a", { href: link.href, highlight: "URL",
2519                                onclick: "if (event.button == 0) { window.external.AddSearchProvider(this.href); return false; }" },
2520                             link.href]];
2521     }
2522
2523     if (!verbose && nEngines)
2524         yield nEngines + /*L*/" engine" + (nEngines > 1 ? "s" : "");
2525 });
2526
2527 Buffer.addPageInfoSection("f", "Feeds", function (verbose) {
2528     const feedTypes = {
2529         "application/rss+xml": "RSS",
2530         "application/atom+xml": "Atom",
2531         "text/xml": "XML",
2532         "application/xml": "XML",
2533         "application/rdf+xml": "XML"
2534     };
2535
2536     function isValidFeed(data, principal, isFeed) {
2537         if (!data || !principal)
2538             return false;
2539
2540         if (!isFeed) {
2541             var type = data.type && data.type.toLowerCase();
2542             type = type.replace(/^\s+|\s*(?:;.*)?$/g, "");
2543
2544             isFeed = ["application/rss+xml", "application/atom+xml"].indexOf(type) >= 0 ||
2545                      // really slimy: general XML types with magic letters in the title
2546                      type in feedTypes && /\brss\b/i.test(data.title);
2547         }
2548
2549         if (isFeed) {
2550             try {
2551                 services.security.checkLoadURIStrWithPrincipal(principal, data.href,
2552                         services.security.DISALLOW_INHERIT_PRINCIPAL);
2553             }
2554             catch (e) {
2555                 isFeed = false;
2556             }
2557         }
2558
2559         if (type)
2560             data.type = type;
2561
2562         return isFeed;
2563     }
2564
2565     let nFeed = 0;
2566     for (let [i, win] in Iterator(this.allFrames())) {
2567         let doc = win.document;
2568
2569         for (let link in DOM("link[href][rel=feed], link[href][rel=alternate][type]", doc)) {
2570             let rel = link.rel.toLowerCase();
2571             let feed = { title: link.title, href: link.href, type: link.type || "" };
2572             if (isValidFeed(feed, doc.nodePrincipal, rel == "feed")) {
2573                 nFeed++;
2574                 let type = feedTypes[feed.type] || "RSS";
2575                 if (verbose)
2576                     yield [feed.title, [template.highlightURL(feed.href, true),
2577                                         ["span", { class: "extra-info" }, " (" + type + ")"]]];
2578             }
2579         }
2580
2581     }
2582
2583     if (!verbose && nFeed)
2584         yield nFeed + /*L*/" feed" + (nFeed > 1 ? "s" : "");
2585 });
2586
2587 Buffer.addPageInfoSection("g", "General Info", function (verbose) {
2588     let doc = this.focusedFrame.document;
2589
2590     // get file size
2591     const ACCESS_READ = Ci.nsICache.ACCESS_READ;
2592     let cacheKey = doc.documentURI;
2593
2594     for (let proto in array.iterValues(["HTTP", "FTP"])) {
2595         try {
2596             var cacheEntryDescriptor = services.cache.createSession(proto, 0, true)
2597                                                .openCacheEntry(cacheKey, ACCESS_READ, false);
2598             break;
2599         }
2600         catch (e) {}
2601     }
2602
2603     let pageSize = []; // [0] bytes; [1] kbytes
2604     if (cacheEntryDescriptor) {
2605         pageSize[0] = util.formatBytes(cacheEntryDescriptor.dataSize, 0, false);
2606         pageSize[1] = util.formatBytes(cacheEntryDescriptor.dataSize, 2, true);
2607         if (pageSize[1] == pageSize[0])
2608             pageSize.length = 1; // don't output "xx Bytes" twice
2609     }
2610
2611     let lastModVerbose = new Date(doc.lastModified).toLocaleString();
2612     let lastMod = new Date(doc.lastModified).toLocaleFormat("%x %X");
2613
2614     if (lastModVerbose == "Invalid Date" || new Date(doc.lastModified).getFullYear() == 1970)
2615         lastModVerbose = lastMod = null;
2616
2617     if (!verbose) {
2618         if (pageSize[0])
2619             yield (pageSize[1] || pageSize[0]) + /*L*/" bytes";
2620         yield lastMod;
2621         return;
2622     }
2623
2624     yield ["Title", doc.title];
2625     yield ["URL", template.highlightURL(doc.location.href, true)];
2626
2627     let { shortURL } = this;
2628     if (shortURL)
2629         yield ["Short URL", template.highlightURL(shortURL, true)];
2630
2631     let ref = "referrer" in doc && doc.referrer;
2632     if (ref)
2633         yield ["Referrer", template.highlightURL(ref, true)];
2634
2635     if (pageSize[0])
2636         yield ["File Size", pageSize[1] ? pageSize[1] + " (" + pageSize[0] + ")"
2637                                         : pageSize[0]];
2638
2639     yield ["Mime-Type", doc.contentType];
2640     yield ["Encoding", doc.characterSet];
2641     yield ["Compatibility", doc.compatMode == "BackCompat" ? "Quirks Mode" : "Full/Almost Standards Mode"];
2642     if (lastModVerbose)
2643         yield ["Last Modified", lastModVerbose];
2644 });
2645
2646 Buffer.addPageInfoSection("m", "Meta Tags", function (verbose) {
2647     if (!verbose)
2648         return [];
2649
2650     // get meta tag data, sort and put into pageMeta[]
2651     let metaNodes = this.focusedFrame.document.getElementsByTagName("meta");
2652
2653     return Array.map(metaNodes, function (node) [(node.name || node.httpEquiv),
2654                                                  template.highlightURL(node.content)])
2655                 .sort(function (a, b) util.compareIgnoreCase(a[0], b[0]));
2656 });
2657
2658 Buffer.addPageInfoSection("s", "Security", function (verbose) {
2659     let { statusline } = this.modules
2660
2661     let identity = this.topWindow.gIdentityHandler;
2662
2663     if (!verbose || !identity)
2664         return; // For now
2665
2666     // Modified from Firefox
2667     function location(data) array.compact([
2668         data.city, data.state, data.country
2669     ]).join(", ");
2670
2671     switch (statusline.security) {
2672     case "secure":
2673     case "extended":
2674         var data = identity.getIdentityData();
2675
2676         yield ["Host", identity.getEffectiveHost()];
2677
2678         if (statusline.security === "extended")
2679             yield ["Owner", data.subjectOrg];
2680         else
2681             yield ["Owner", _("pageinfo.s.ownerUnverified", data.subjectOrg)];
2682
2683         if (location(data).length)
2684             yield ["Location", location(data)];
2685
2686         yield ["Verified by", data.caOrg];
2687
2688         if (identity._overrideService.hasMatchingOverride(identity._lastLocation.hostname,
2689                                                       (identity._lastLocation.port || 443),
2690                                                       data.cert, {}, {}))
2691             yield ["User exception", /*L*/"true"];
2692         break;
2693     }
2694 });
2695
2696 // catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
2697
2698 endModule();
2699
2700 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: