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-2011 by Kris Maglione <maglione.k at Gmail>
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
9 Components.utils.import("resource://dactyl/bootstrap.jsm");
10 defineModule("buffer", {
11 exports: ["Buffer", "buffer"],
12 require: ["prefs", "services", "util"]
15 this.lazyRequire("finder", ["RangeFind"]);
16 this.lazyRequire("overlay", ["overlay"]);
17 this.lazyRequire("storage", ["storage"]);
18 this.lazyRequire("template", ["template"]);
21 * A class to manage the primary web content buffer. The name comes
22 * from Vim's term, 'buffer', which signifies instances of open
26 var Buffer = Module("Buffer", {
27 Local: function Local(dactyl, modules, window) ({
29 return window.content;
31 let win = services.focus.focusedWindow;
32 if (!win || win == window || util.topWindow(win) != window)
34 if (win.top == window)
40 init: function init(win) {
45 get addPageInfoSection() Buffer.closure.addPageInfoSection,
47 get pageInfo() Buffer.pageInfo,
49 // called when the active document is scrolled
50 _updateBufferPosition: function _updateBufferPosition() {
51 this.modules.statusline.updateBufferPosition();
52 this.modules.commandline.clear(true);
56 * @property {Array} The alternative style sheets for the current
57 * buffer. Only returns style sheets for the 'screen' media type.
59 get alternateStyleSheets() {
60 let stylesheets = array.flatten(
61 this.allFrames().map(function (w) Array.slice(w.document.styleSheets)));
63 return stylesheets.filter(
64 function (stylesheet) /^(screen|all|)$/i.test(stylesheet.media.mediaText) && !/^\s*$/.test(stylesheet.title)
68 climbUrlPath: function climbUrlPath(count) {
69 let { dactyl } = this.modules;
71 let url = this.documentURI.clone();
72 dactyl.assert(url instanceof Ci.nsIURL);
74 while (count-- && url.path != "/")
75 url.path = url.path.replace(/[^\/]+\/*$/, "");
77 dactyl.assert(!url.equals(this.documentURI));
78 dactyl.open(url.spec);
81 incrementURL: function incrementURL(count) {
82 let { dactyl } = this.modules;
84 let matches = this.uri.spec.match(/(.*?)(\d+)(\D*)$/);
85 dactyl.assert(matches);
86 let oldNum = matches[2];
88 // disallow negative numbers as trailing numbers are often proceeded by hyphens
89 let newNum = String(Math.max(parseInt(oldNum, 10) + count, 0));
90 if (/^0/.test(oldNum))
91 while (newNum.length < oldNum.length)
92 newNum = "0" + newNum;
95 dactyl.open(matches.slice(1).join(""));
99 * @property {number} True when the buffer is fully loaded.
101 get loaded() Math.min.apply(null,
103 .map(function (frame) ["loading", "interactive", "complete"]
104 .indexOf(frame.document.readyState))),
107 * @property {Object} The local state store for the currently selected
113 let store = overlay.getData(doc, "buffer", null);
114 if (!store || !this.localStorePrototype.isPrototypeOf(store))
115 store = overlay.setData(doc, "buffer", Object.create(this.localStorePrototype));
116 return store.instance = store;
119 localStorePrototype: memoize({
126 * @property {Node} The last focused input field in the buffer. Used
127 * by the "gi" key binding.
129 get lastInputField() {
130 let field = this.localStore.lastInputField && this.localStore.lastInputField.get();
132 let doc = field && field.ownerDocument;
133 let win = doc && doc.defaultView;
134 return win && doc === win.document ? field : null;
136 set lastInputField(value) { this.localStore.lastInputField = util.weakReference(value); },
139 * @property {nsIURI} The current top-level document.
141 get doc() this.win.document,
143 get docShell() util.docShell(this.win),
145 get modules() this.topWindow.dactyl.modules,
148 topWindow: Class.Memoize(function () util.topWindow(this.win)),
151 * @property {nsIURI} The current top-level document's URI.
153 get uri() util.newURI(this.win.location.href),
156 * @property {nsIURI} The current top-level document's URI, sans any
157 * fragment identifier.
159 get documentURI() this.doc.documentURIObject || util.newURI(this.doc.documentURI),
162 * @property {string} The current top-level document's URL.
164 get URL() update(new String(this.win.location.href), util.newURI(this.win.location.href)),
167 * @property {number} The buffer's height in pixels.
169 get pageHeight() this.win.innerHeight,
171 get contentViewer() this.docShell.contentViewer
172 .QueryInterface(Components.interfaces.nsIMarkupDocumentViewer),
175 * @property {number} The current browser's zoom level, as a
176 * percentage with 100 as 'normal'.
179 let v = this.contentViewer;
180 return v[v.textZoom == 1 ? "fullZoom" : "textZoom"] * 100
182 set zoomLevel(value) { this.setZoom(value, this.fullZoom); },
185 * @property {boolean} Whether the current browser is using full
186 * zoom, as opposed to text zoom.
188 get fullZoom() this.ZoomManager.useFullZoom,
189 set fullZoom(value) { this.setZoom(this.zoomLevel, value); },
191 get ZoomManager() this.topWindow.ZoomManager,
194 * @property {string} The current document's title.
196 get title() this.doc.title,
199 * @property {number} The buffer's horizontal scroll percentile.
201 get scrollXPercent() {
202 let elem = Buffer.Scrollable(this.findScrollable(0, true));
203 if (elem.scrollWidth - elem.clientWidth === 0)
205 return elem.scrollLeft * 100 / (elem.scrollWidth - elem.clientWidth);
209 * @property {number} The buffer's vertical scroll percentile.
211 get scrollYPercent() {
212 let elem = Buffer.Scrollable(this.findScrollable(0, false));
213 if (elem.scrollHeight - elem.clientHeight === 0)
215 return elem.scrollTop * 100 / (elem.scrollHeight - elem.clientHeight);
219 * @property {{ x: number, y: number }} The buffer's current scroll position
220 * as reported by {@link Buffer.getScrollPosition}.
222 get scrollPosition() Buffer.getScrollPosition(this.findScrollable(0, false)),
225 * Returns a list of all frames in the given window or current buffer.
227 allFrames: function allFrames(win, focusedFirst) {
229 (function rec(frame) {
230 if (true || frame.document.body instanceof Ci.nsIDOMHTMLBodyElement)
232 Array.forEach(frame.frames, rec);
236 return frames.filter(function (f) f === this.focusedFrame).concat(
237 frames.filter(function (f) f !== this.focusedFrame));
242 * @property {Window} Returns the currently focused frame.
245 let frame = this.localStore.focusedFrame;
246 return frame && frame.get() || this.win;
248 set focusedFrame(frame) {
249 this.localStore.focusedFrame = util.weakReference(frame);
253 * Returns the currently selected word. If the selection is
254 * null, it tries to guess the word that the caret is
259 get currentWord() Buffer.currentWord(this.focusedFrame),
260 getCurrentWord: deprecated("buffer.currentWord", function getCurrentWord() Buffer.currentWord(this.focusedFrame, true)),
263 * Returns true if a scripts are allowed to focus the given input
264 * element or input elements in the given window.
266 * @param {Node|Window}
269 focusAllowed: function focusAllowed(elem) {
270 if (elem instanceof Ci.nsIDOMWindow && !DOM(elem).isEditable)
273 let { options } = this.modules;
275 let doc = elem.ownerDocument || elem.document || elem;
276 switch (options.get("strictfocus").getKey(doc.documentURIObject || util.newURI(doc.documentURI), "moderate")) {
278 return overlay.getData(elem)["focus-allowed"]
279 || elem.frameElement && overlay.getData(elem.frameElement)["focus-allowed"];
281 return overlay.getData(doc, "focus-allowed")
282 || elem.frameElement && overlay.getData(elem.frameElement.ownerDocument)["focus-allowed"];
289 * Focuses the given element. In contrast to a simple
290 * elem.focus() call, this function works for iframes and
293 * @param {Node} elem The element to focus.
295 focusElement: function focusElement(elem) {
296 let win = elem.ownerDocument && elem.ownerDocument.defaultView || elem;
297 overlay.setData(elem, "focus-allowed", true);
298 overlay.setData(win.document, "focus-allowed", true);
300 if (isinstance(elem, [Ci.nsIDOMHTMLFrameElement,
301 Ci.nsIDOMHTMLIFrameElement]))
302 elem = elem.contentWindow;
305 overlay.setData(elem.document, "focus-allowed", true);
307 if (elem instanceof Ci.nsIDOMHTMLInputElement && elem.type == "file") {
308 Buffer.openUploadPrompt(elem);
309 this.lastInputField = elem;
312 if (isinstance(elem, [Ci.nsIDOMHTMLInputElement,
313 Ci.nsIDOMXULTextBoxElement]))
314 var flags = services.focus.FLAG_BYMOUSE;
316 flags = services.focus.FLAG_SHOWRING;
318 // Hack to deal with current versions of Firefox misplacing
320 if (!overlay.getData(elem, "had-focus", false) && elem.value &&
321 elem instanceof Ci.nsIDOMHTMLInputElement &&
322 DOM(elem).isEditable &&
323 elem.selectionStart != null &&
324 elem.selectionStart == elem.selectionEnd)
325 elem.selectionStart = elem.selectionEnd = elem.value.length;
327 DOM(elem).focus(flags);
329 if (elem instanceof Ci.nsIDOMWindow) {
330 let sel = elem.getSelection();
331 if (sel && !sel.rangeCount)
332 sel.addRange(RangeFind.endpoint(
333 RangeFind.nodeRange(elem.document.body || elem.document.documentElement),
337 let range = RangeFind.nodeRange(elem);
338 let sel = (elem.ownerDocument || elem).defaultView.getSelection();
339 if (!sel.rangeCount || !RangeFind.intersects(range, sel.getRangeAt(0))) {
340 range.collapse(true);
341 sel.removeAllRanges();
347 if (elem instanceof Ci.nsIDOMHTMLAreaElement) {
349 let [x, y] = elem.getAttribute("coords").split(",").map(parseFloat);
351 DOM(elem).mouseover({ screenX: x, screenY: y });
359 * Find the *count*th last link on a page matching one of the given
360 * regular expressions, or with a @rel or @rev attribute matching
361 * the given relation. Each frame is searched beginning with the
362 * last link and progressing to the first, once checking for
363 * matching @rel or @rev properties, and then once for each given
364 * regular expression. The first match is returned. All frames of
365 * the page are searched, beginning with the currently focused.
367 * If follow is true, the link is followed.
369 * @param {string} rel The relationship to look for.
370 * @param {[RegExp]} regexps The regular expressions to search for.
371 * @param {number} count The nth matching link to follow.
372 * @param {bool} follow Whether to follow the matching link.
373 * @param {string} path The CSS to use for the search. @optional
375 findLink: function findLink(rel, regexps, count, follow, path) {
376 let { Hints, dactyl, options } = this.modules;
378 let selector = path || options.get("hinttags").stringDefaultValue;
380 function followFrame(frame) {
381 function iter(elems) {
382 for (let i = 0; i < elems.length; i++)
383 if (elems[i].rel.toLowerCase() === rel || elems[i].rev.toLowerCase() === rel)
387 let elems = frame.document.getElementsByTagName("link");
388 for (let elem in iter(elems))
391 elems = frame.document.getElementsByTagName("a");
392 for (let elem in iter(elems))
395 function a(regexp, elem) regexp.test(elem.textContent) === regexp.result ||
396 Array.some(elem.childNodes, function (child) regexp.test(child.alt) === regexp.result);
397 function b(regexp, elem) regexp.test(elem.title);
399 let res = Array.filter(frame.document.querySelectorAll(selector), Hints.isVisible);
400 for (let test in values([a, b]))
401 for (let regexp in values(regexps))
402 for (let i in util.range(res.length, 0, -1))
403 if (test(regexp, res[i]))
407 for (let frame in values(this.allFrames(null, true)))
408 for (let elem in followFrame(frame))
411 this.followLink(elem, dactyl.CURRENT_TAB);
418 followDocumentRelationship: deprecated("buffer.findLink",
419 function followDocumentRelationship(rel) {
420 let { options } = this.modules;
422 this.findLink(rel, options[rel + "pattern"], 0, true);
426 * Fakes a click on a link.
428 * @param {Node} elem The element to click.
429 * @param {number} where Where to open the link. See
430 * {@link dactyl.open}.
432 followLink: function followLink(elem, where) {
433 let { dactyl } = this.modules;
435 let doc = elem.ownerDocument;
436 let win = doc.defaultView;
437 let { left: offsetX, top: offsetY } = elem.getBoundingClientRect();
439 if (isinstance(elem, [Ci.nsIDOMHTMLFrameElement,
440 Ci.nsIDOMHTMLIFrameElement]))
441 return this.focusElement(elem);
443 if (isinstance(elem, Ci.nsIDOMHTMLLinkElement))
444 return dactyl.open(elem.href, where);
446 if (elem instanceof Ci.nsIDOMHTMLAreaElement) { // for imagemap
447 let coords = elem.getAttribute("coords").split(",");
448 offsetX = Number(coords[0]) + 1;
449 offsetY = Number(coords[1]) + 1;
451 else if (elem instanceof Ci.nsIDOMHTMLInputElement && elem.type == "file") {
452 Buffer.openUploadPrompt(elem);
456 let { dactyl } = this.modules;
458 let ctrlKey = false, shiftKey = false;
459 switch (dactyl.forceTarget || where) {
461 case dactyl.NEW_BACKGROUND_TAB:
463 shiftKey = dactyl.forceBackground != null ? dactyl.forceBackground
464 : where != dactyl.NEW_BACKGROUND_TAB;
466 case dactyl.NEW_WINDOW:
469 case dactyl.CURRENT_TAB:
473 this.focusElement(elem);
475 prefs.withContext(function () {
476 prefs.set("browser.tabs.loadInBackground", true);
478 screenX: offsetX, screenY: offsetY,
479 ctrlKey: ctrlKey, shiftKey: shiftKey, metaKey: ctrlKey
482 DOM(elem).mousedown(params).mouseup(params);
483 if (!config.haveGecko("2b"))
484 DOM(elem).click(params);
486 let sel = util.selectionController(win);
487 sel.getSelection(sel.SELECTION_FOCUS_REGION).collapseToStart();
492 * Resets the caret position so that it resides within the current
495 resetCaret: function resetCaret() {
496 function visible(range) util.intersection(DOM(range).rect, viewport);
498 function getRanges(rect) {
499 let nodes = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils)
500 .nodesFromRect(rect.x, rect.y, 0, rect.width, rect.height, 0, false, false);
501 return Array.filter(nodes, function (n) n instanceof Ci.nsIDOMText)
502 .map(RangeFind.nodeContents);
505 let win = this.focusedFrame;
506 let doc = win.document;
507 let sel = win.getSelection();
508 let { viewport } = DOM(win);
510 if (sel.rangeCount) {
511 var range = sel.getRangeAt(0);
512 if (visible(range).height > 0)
515 var { rect } = DOM(range);
516 var reverse = rect.bottom > viewport.bottom;
518 rect = { x: rect.left, y: 0, width: rect.width, height: win.innerHeight };
521 let w = win.innerWidth;
522 rect = { x: w / 3, y: 0, width: w / 3, height: win.innerHeight };
525 var reduce = function (a, b) DOM(a).rect.top < DOM(b).rect.top ? a : b;
529 reduce = function (a, b) DOM(b).rect.bottom > DOM(a).rect.bottom ? b : a;
531 y = win.innerHeight - 1;
534 let ranges = getRanges(rect);
536 ranges = getRanges({ x: 0, y: y, width: win.innerWidth, height: 0 });
539 range = ranges.reduce(reduce);
542 range.collapse(!reverse);
543 sel.removeAllRanges();
546 if (visible(range).height > 0)
549 var { startContainer, startOffset } = range;
550 sel.modify("move", dir, "line");
551 range = sel.getRangeAt(0);
553 while (startContainer != range.startContainer || startOffset != range.startOffset);
555 sel.modify("move", reverse ? "forward" : "backward", "lineboundary");
560 sel.collapse(doc.body || doc.querySelector("body") || doc.documentElement,
565 * @property {nsISelection} The current document's normal selection.
567 get selection() this.win.getSelection(),
570 * @property {nsISelectionController} The current document's selection
573 get selectionController() util.selectionController(this.focusedFrame),
576 * Opens the appropriate context menu for *elem*.
578 * @param {Node} elem The context element.
580 openContextMenu: deprecated("DOM#contextmenu", function openContextMenu(elem) DOM(elem).contextmenu()),
583 * Saves a page link to disk.
585 * @param {HTMLAnchorElement} elem The page link to save.
587 saveLink: function saveLink(elem) {
588 let { completion, dactyl, io } = this.modules;
591 let doc = elem.ownerDocument;
592 let uri = util.newURI(elem.href || elem.src, null, util.newURI(elem.baseURI));
593 let referrer = util.newURI(doc.documentURI, doc.characterSet);
596 services.security.checkLoadURIWithPrincipal(doc.nodePrincipal, uri,
597 services.security.STANDARD);
599 io.CommandFileMode(_("buffer.prompt.saveLink") + " ", {
600 onSubmit: function (path) {
601 let file = io.File(path);
602 if (file.exists() && file.isDirectory())
603 file.append(Buffer.getDefaultNames(elem)[0][0]);
607 file.create(File.NORMAL_FILE_TYPE, octal(644));
610 util.assert(false, _("save.invalidDestination", e.name));
613 self.saveURI(uri, file);
616 completer: function (context) completion.savePage(context, elem)
625 * Saves the contents of a URI to disk.
627 * @param {nsIURI} uri The URI to save
628 * @param {nsIFile} file The file into which to write the result.
630 saveURI: function saveURI(uri, file, callback, self) {
631 var persist = services.Persist();
632 persist.persistFlags = persist.PERSIST_FLAGS_FROM_CACHE
633 | persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
635 let window = this.topWindow;
636 let downloadListener = new window.DownloadListener(window,
637 services.Transfer(uri, File(file).URI, "",
638 null, null, null, persist));
640 persist.progressListener = update(Object.create(downloadListener), {
641 onStateChange: util.wrapCallback(function onStateChange(progress, request, flags, status) {
642 if (callback && (flags & Ci.nsIWebProgressListener.STATE_STOP) && status == 0)
643 util.trapErrors(callback, self, uri, file, progress, request, flags, status);
645 return onStateChange.superapply(this, arguments);
649 persist.saveURI(uri, null, null, null, null, file);
653 * Scrolls the currently active element horizontally. See
654 * {@link Buffer.scrollHorizontal} for parameters.
656 scrollHorizontal: function scrollHorizontal(increment, number)
657 Buffer.scrollHorizontal(this.findScrollable(number, true), increment, number),
660 * Scrolls the currently active element vertically. See
661 * {@link Buffer.scrollVertical} for parameters.
663 scrollVertical: function scrollVertical(increment, number)
664 Buffer.scrollVertical(this.findScrollable(number, false), increment, number),
667 * Scrolls the currently active element to the given horizontal and
668 * vertical percentages. See {@link Buffer.scrollToPercent} for
671 scrollToPercent: function scrollToPercent(horizontal, vertical)
672 Buffer.scrollToPercent(this.findScrollable(0, vertical == null), horizontal, vertical),
675 * Scrolls the currently active element to the given horizontal and
676 * vertical positions. See {@link Buffer.scrollToPosition} for
679 scrollToPosition: function scrollToPosition(horizontal, vertical)
680 Buffer.scrollToPosition(this.findScrollable(0, vertical == null), horizontal, vertical),
682 _scrollByScrollSize: function _scrollByScrollSize(count, direction) {
683 let { options } = this.modules;
686 options["scroll"] = count;
687 this.scrollByScrollSize(direction);
691 * Scrolls the buffer vertically 'scroll' lines.
693 * @param {boolean} direction The direction to scroll. If true then
694 * scroll up and if false scroll down.
695 * @param {number} count The multiple of 'scroll' lines to scroll.
698 scrollByScrollSize: function scrollByScrollSize(direction, count) {
699 let { options } = this.modules;
701 direction = direction ? 1 : -1;
704 if (options["scroll"] > 0)
705 this.scrollVertical("lines", options["scroll"] * direction);
707 this.scrollVertical("pages", direction / 2);
711 * Find the best candidate scrollable element for the given
712 * direction and orientation.
714 * @param {number} dir The direction in which the element must be
715 * able to scroll. Negative numbers represent up or left, while
716 * positive numbers represent down or right.
717 * @param {boolean} horizontal If true, look for horizontally
718 * scrollable elements, otherwise look for vertically scrollable
721 findScrollable: function findScrollable(dir, horizontal) {
722 function find(elem) {
723 while (elem && !(elem instanceof Ci.nsIDOMElement) && elem.parentNode)
724 elem = elem.parentNode;
725 for (; elem instanceof Ci.nsIDOMElement; elem = elem.parentNode)
726 if (Buffer.isScrollable(elem, dir, horizontal))
733 var elem = this.focusedFrame.document.activeElement;
734 if (elem == elem.ownerDocument.body)
740 var sel = this.focusedFrame.getSelection();
743 if (!elem && sel && sel.rangeCount)
744 elem = sel.getRangeAt(0).startContainer;
748 if (!(elem instanceof Ci.nsIDOMElement)) {
749 let doc = this.findScrollableWindow().document;
750 elem = find(doc.body || doc.getElementsByTagName("body")[0] ||
751 doc.documentElement);
753 let doc = this.focusedFrame.document;
754 return util.assert(elem || doc.body || doc.documentElement);
758 * Find the best candidate scrollable frame in the current buffer.
760 findScrollableWindow: function findScrollableWindow() {
761 let { document } = this.topWindow;
763 let win = document.commandDispatcher.focusedWindow;
764 if (win && (win.scrollMaxX > 0 || win.scrollMaxY > 0))
767 let win = this.focusedFrame;
768 if (win && (win.scrollMaxX > 0 || win.scrollMaxY > 0))
772 if (win.scrollMaxX > 0 || win.scrollMaxY > 0)
775 for (let frame in array.iterValues(win.frames))
776 if (frame.scrollMaxX > 0 || frame.scrollMaxY > 0)
783 * Finds the next visible element for the node path in 'jumptags'
786 * @param {string} arg The element in 'jumptags' to use for the search.
787 * @param {number} count The number of elements to jump.
789 * @param {boolean} reverse If true, search backwards. @optional
790 * @param {boolean} offScreen If true, include only off-screen elements. @optional
792 findJump: function findJump(arg, count, reverse, offScreen) {
793 let { marks, options } = this.modules;
799 let path = options["jumptags"][arg];
800 util.assert(path, _("error.invalidArgument", arg));
802 let distance = reverse ? function (rect) -rect.top : function (rect) rect.top;
803 let elems = [[e, distance(e.getBoundingClientRect())] for (e in path.matcher(this.focusedFrame.document))]
804 .filter(function (e) e[1] > FUDGE)
805 .sort(function (a, b) a[1] - b[1])
807 if (offScreen && !reverse)
808 elems = elems.filter(function (e) e[1] > this, this.topWindow.innerHeight);
810 let idx = Math.min((count || 1) - 1, elems.length);
811 util.assert(idx in elems);
813 let elem = elems[idx][0];
814 elem.scrollIntoView(true);
816 let sel = elem.ownerDocument.defaultView.getSelection();
817 sel.removeAllRanges();
818 sel.addRange(RangeFind.endpoint(RangeFind.nodeRange(elem), true));
821 // TODO: allow callback for filtering out unwanted frames? User defined?
823 * Shifts the focus to another frame within the buffer. Each buffer
824 * contains at least one frame.
826 * @param {number} count The number of frames to skip through. A negative
827 * count skips backwards.
829 shiftFrameFocus: function shiftFrameFocus(count) {
830 if (!(this.doc instanceof Ci.nsIDOMHTMLDocument))
833 let frames = this.allFrames();
835 if (frames.length == 0) // currently top is always included
838 // remove all hidden frames
839 frames = frames.filter(function (frame) !(frame.document.body instanceof Ci.nsIDOMHTMLFrameSetElement))
840 .filter(function (frame) !frame.frameElement ||
841 let (rect = frame.frameElement.getBoundingClientRect())
842 rect.width && rect.height);
844 // find the currently focused frame index
845 let current = Math.max(0, frames.indexOf(this.focusedFrame));
847 // calculate the next frame to focus
848 let next = current + count;
849 if (next < 0 || next >= frames.length)
851 next = Math.constrain(next, 0, frames.length - 1);
853 // focus next frame and scroll into view
854 DOM(frames[next]).focus();
855 if (frames[next] != this.win)
856 DOM(frames[next].frameElement).scrollIntoView();
858 // add the frame indicator
859 let doc = frames[next].document;
860 let indicator = DOM(<div highlight="FrameIndicator"/>, doc)
861 .appendTo(doc.body || doc.documentElement || doc);
863 util.timeout(function () { indicator.remove(); }, 500);
866 //doc.body.setAttributeNS(NS.uri, "activeframe", "true");
867 //util.timeout(function () { doc.body.removeAttributeNS(NS.uri, "activeframe"); }, 500);
870 // similar to pageInfo
871 // TODO: print more useful information, just like the DOM inspector
873 * Displays information about the specified element.
875 * @param {Node} elem The element to query.
877 showElementInfo: function showElementInfo(elem) {
878 let { dactyl } = this.modules;
880 XML.ignoreWhitespace = XML.prettyPrinting = false;
881 dactyl.echo(<><!--L-->Element:<br/>{util.objectToString(elem, true)}</>);
885 * Displays information about the current buffer.
887 * @param {boolean} verbose Display more verbose information.
888 * @param {string} sections A string limiting the displayed sections.
889 * @default The value of 'pageinfo'.
891 showPageInfo: function showPageInfo(verbose, sections) {
892 let { commandline, dactyl, options } = this.modules;
896 // Ctrl-g single line output
898 let file = this.win.location.pathname.split("/").pop() || _("buffer.noName");
899 let title = this.win.document.title || _("buffer.noTitle");
901 let info = template.map(
902 (sections || options["pageinfo"])
903 .map(function (opt) Buffer.pageInfo[opt].action.call(self)),
904 function (res) res && iter(res).join(", ") || undefined,
907 if (bookmarkcache.isBookmarked(this.URL))
908 info += ", " + _("buffer.bookmarked");
910 let pageInfoText = <>{file.quote()} [{info}] {title}</>;
911 dactyl.echo(pageInfoText, commandline.FORCE_SINGLELINE);
915 let list = template.map(sections || options["pageinfo"], function (option) {
916 let { action, title } = Buffer.pageInfo[option];
917 return template.table(title, action.call(self, true));
920 commandline.commandOutput(list);
924 * Stops loading and animations in the current content.
926 stop: function stop() {
927 let { config } = this.modules;
932 this.docShell.stop(this.docShell.STOP_ALL);
936 * Opens a viewer to inspect the source of the currently selected
939 viewSelectionSource: function viewSelectionSource() {
940 // copied (and tuned somewhat) from browser.jar -> nsContextMenu.js
941 let { document, window } = this.topWindow;
943 let win = document.commandDispatcher.focusedWindow;
944 if (win == this.topWindow)
945 win = this.focusedFrame;
947 let charset = win ? "charset=" + win.document.characterSet : null;
949 window.openDialog("chrome://global/content/viewPartialSource.xul",
950 "_blank", "scrollbars,resizable,chrome,dialog=no",
951 null, charset, win.getSelection(), "selection");
955 * Opens a viewer to inspect the source of the current buffer or the
956 * specified *url*. Either the default viewer or the configured external
959 * @param {string|object|null} loc If a string, the URL of the source,
960 * otherwise an object with some or all of the following properties:
962 * url: The URL to view.
963 * doc: The document to view.
964 * line: The line to select.
965 * column: The column to select.
967 * If no URL is provided, the current document is used.
968 * @default The current buffer.
969 * @param {boolean} useExternalEditor View the source in the external editor.
971 viewSource: function viewSource(loc, useExternalEditor) {
972 let { dactyl, editor, history, options } = this.modules;
974 let window = this.topWindow;
976 let doc = this.focusedFrame.document;
979 if (options.get("editor").has("line") || !loc.url)
980 this.viewSourceExternally(loc.doc || loc.url || doc, loc);
982 window.openDialog("chrome://global/content/viewSource.xul",
983 "_blank", "all,dialog=no",
984 loc.url, null, null, loc.line);
987 if (useExternalEditor)
988 this.viewSourceExternally(loc || doc);
990 let url = loc || doc.location.href;
991 const PREFIX = "view-source:";
992 if (url.indexOf(PREFIX) == 0)
993 url = url.substr(PREFIX.length);
997 let sh = history.session;
998 if (sh[sh.index].URI.spec == url)
999 this.docShell.gotoIndex(sh.index);
1001 dactyl.open(url, { hide: true });
1007 * Launches an editor to view the source of the given document. The
1008 * contents of the document are saved to a temporary local file and
1009 * removed when the editor returns. This function returns
1012 * @param {Document} doc The document to view.
1013 * @param {function|object} callback If a function, the callback to be
1014 * called with two arguments: the nsIFile of the file, and temp, a
1015 * boolean which is true if the file is temporary. Otherwise, an object
1016 * with line and column properties used to determine where to open the
1020 viewSourceExternally: Class("viewSourceExternally",
1021 XPCOM([Ci.nsIWebProgressListener, Ci.nsISupportsWeakReference]), {
1022 init: function init(doc, callback) {
1023 this.callback = callable(callback) ? callback :
1024 function (file, temp) {
1025 let { editor } = overlay.activeModules;
1027 editor.editFileExternally(update({ file: file.path }, callback || {}),
1028 function () { temp && file.remove(false); });
1032 let uri = isString(doc) ? util.newURI(doc) : util.newURI(doc.location.href);
1033 let ext = uri.fileExtension || "txt";
1034 if (doc.contentType)
1035 ext = services.mime.getPrimaryExtension(doc.contentType, ext);
1038 return io.withTempFiles(function (temp) {
1039 let encoder = services.HtmlEncoder();
1040 encoder.init(doc, "text/unicode", encoder.OutputRaw|encoder.OutputPreformatted);
1041 temp.write(encoder.encodeToString(), ">");
1042 return this.callback(temp, true);
1043 }, this, true, ext);
1045 let file = util.getFile(uri);
1047 this.callback(file, false);
1049 this.file = io.createTempFile();
1050 var persist = services.Persist();
1051 persist.persistFlags = persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
1052 persist.progressListener = this;
1053 persist.saveURI(uri, null, null, null, null, this.file);
1058 onStateChange: function onStateChange(progress, request, flags, status) {
1059 if ((flags & this.STATE_STOP) && status == 0) {
1061 var ok = this.callback(this.file, true);
1065 this.file.remove(false);
1073 * Increases the zoom level of the current buffer.
1075 * @param {number} steps The number of zoom levels to jump.
1076 * @param {boolean} fullZoom Whether to use full zoom or text zoom.
1078 zoomIn: function zoomIn(steps, fullZoom) {
1079 this.bumpZoomLevel(steps, fullZoom);
1083 * Decreases the zoom level of the current buffer.
1085 * @param {number} steps The number of zoom levels to jump.
1086 * @param {boolean} fullZoom Whether to use full zoom or text zoom.
1088 zoomOut: function zoomOut(steps, fullZoom) {
1089 this.bumpZoomLevel(-steps, fullZoom);
1093 * Adjusts the page zoom of the current buffer to the given absolute
1096 * @param {number} value The new zoom value as a possibly fractional
1097 * percentage of the page's natural size.
1098 * @param {boolean} fullZoom If true, zoom all content of the page,
1099 * including raster images. If false, zoom only text. If omitted,
1100 * use the current zoom function. @optional
1101 * @throws {FailedAssertion} if the given *value* is not within the
1102 * closed range [Buffer.ZOOM_MIN, Buffer.ZOOM_MAX].
1104 setZoom: function setZoom(value, fullZoom) {
1105 let { dactyl, statusline } = this.modules;
1106 let { ZoomManager } = this;
1108 if (fullZoom === undefined)
1109 fullZoom = ZoomManager.useFullZoom;
1111 ZoomManager.useFullZoom = fullZoom;
1115 this.contentViewer.textZoom = fullZoom ? 1 : value;
1116 this.contentViewer.fullZoom = !fullZoom ? 1 : value;
1118 catch (e if e == Cr.NS_ERROR_ILLEGAL_VALUE) {
1119 return dactyl.echoerr(_("zoom.illegal"));
1122 if (services.has("contentPrefs") && !storage.privateMode
1123 && prefs.get("browser.zoom.siteSpecific")) {
1124 services.contentPrefs[value != 1 ? "setPref" : "removePref"]
1125 (this.uri, "browser.content.full-zoom", value);
1126 services.contentPrefs[value != 1 ? "setPref" : "removePref"]
1127 (this.uri, "dactyl.content.full-zoom", fullZoom);
1130 statusline.updateZoomLevel();
1134 * Updates the zoom level of this buffer from a content preference.
1136 updateZoom: util.wrapCallback(function updateZoom() {
1140 if (services.has("contentPrefs") && prefs.get("browser.zoom.siteSpecific"))
1141 services.contentPrefs.getPref(uri, "dactyl.content.full-zoom", function (val) {
1142 if (val != null && uri.equals(self.uri) && val != prefs.get("browser.zoom.full"))
1143 [self.contentViewer.textZoom, self.contentViewer.fullZoom] =
1144 [self.contentViewer.fullZoom, self.contentViewer.textZoom];
1149 * Adjusts the page zoom of the current buffer relative to the
1150 * current zoom level.
1152 * @param {number} steps The integral number of natural fractions by which
1153 * to adjust the current page zoom. If positive, the zoom level is
1154 * increased, if negative it is decreased.
1155 * @param {boolean} fullZoom If true, zoom all content of the page,
1156 * including raster images. If false, zoom only text. If omitted, use
1157 * the current zoom function. @optional
1158 * @throws {FailedAssertion} if the buffer's zoom level is already at its
1159 * extreme in the given direction.
1161 bumpZoomLevel: function bumpZoomLevel(steps, fullZoom) {
1162 let { ZoomManager } = this;
1164 if (fullZoom === undefined)
1165 fullZoom = ZoomManager.useFullZoom;
1167 let values = ZoomManager.zoomValues;
1168 let cur = values.indexOf(ZoomManager.snap(this.zoomLevel / 100));
1169 let i = Math.constrain(cur + steps, 0, values.length - 1);
1171 util.assert(i != cur || fullZoom != ZoomManager.useFullZoom);
1173 this.setZoom(Math.round(values[i] * 100), fullZoom);
1176 getAllFrames: deprecated("buffer.allFrames", "allFrames"),
1177 scrollTop: deprecated("buffer.scrollToPercent", function scrollTop() this.scrollToPercent(null, 0)),
1178 scrollBottom: deprecated("buffer.scrollToPercent", function scrollBottom() this.scrollToPercent(null, 100)),
1179 scrollStart: deprecated("buffer.scrollToPercent", function scrollStart() this.scrollToPercent(0, null)),
1180 scrollEnd: deprecated("buffer.scrollToPercent", function scrollEnd() this.scrollToPercent(100, null)),
1181 scrollColumns: deprecated("buffer.scrollHorizontal", function scrollColumns(cols) this.scrollHorizontal("columns", cols)),
1182 scrollPages: deprecated("buffer.scrollHorizontal", function scrollPages(pages) this.scrollVertical("pages", pages)),
1183 scrollTo: deprecated("Buffer.scrollTo", function scrollTo(x, y) this.win.scrollTo(x, y)),
1184 textZoom: deprecated("buffer.zoomValue/buffer.fullZoom", function textZoom() this.contentViewer.markupDocumentViewer.textZoom * 100)
1186 PageInfo: Struct("PageInfo", "name", "title", "action")
1192 * Adds a new section to the page information output.
1194 * @param {string} option The section's value in 'pageinfo'.
1195 * @param {string} title The heading for this section's
1197 * @param {function} func The function to generate this
1200 addPageInfoSection: function addPageInfoSection(option, title, func) {
1201 this.pageInfo[option] = Buffer.PageInfo(option, title, func);
1204 Scrollable: function Scrollable(elem) {
1205 if (elem instanceof Ci.nsIDOMElement)
1207 if (isinstance(elem, [Ci.nsIDOMWindow, Ci.nsIDOMDocument]))
1209 __proto__: elem.documentElement || elem.ownerDocument.documentElement,
1211 win: elem.defaultView || elem.ownerDocument.defaultView,
1213 get clientWidth() this.win.innerWidth,
1214 get clientHeight() this.win.innerHeight,
1216 get scrollWidth() this.win.scrollMaxX + this.win.innerWidth,
1217 get scrollHeight() this.win.scrollMaxY + this.win.innerHeight,
1219 get scrollLeft() this.win.scrollX,
1220 set scrollLeft(val) { this.win.scrollTo(val, this.win.scrollY) },
1222 get scrollTop() this.win.scrollY,
1223 set scrollTop(val) { this.win.scrollTo(this.win.scrollX, val) }
1228 get ZOOM_MIN() prefs.get("zoom.minPercent"),
1229 get ZOOM_MAX() prefs.get("zoom.maxPercent"),
1231 setZoom: deprecated("buffer.setZoom", function setZoom()
1232 let ({ buffer } = overlay.activeModules) buffer.setZoom.apply(buffer, arguments)),
1233 bumpZoomLevel: deprecated("buffer.bumpZoomLevel", function bumpZoomLevel()
1234 let ({ buffer } = overlay.activeModules) buffer.bumpZoomLevel.apply(buffer, arguments)),
1237 * Returns the currently selected word in *win*. If the selection is
1238 * null, it tries to guess the word that the caret is positioned in.
1242 currentWord: function currentWord(win, select) {
1243 let { Editor, options } = Buffer(win).modules;
1245 let selection = win.getSelection();
1246 if (selection.rangeCount == 0)
1249 let range = selection.getRangeAt(0).cloneRange();
1250 if (range.collapsed) {
1251 let re = options.get("iskeyword").regexp;
1252 Editor.extendRange(range, true, re, true);
1253 Editor.extendRange(range, false, re, true);
1256 selection.removeAllRanges();
1257 selection.addRange(range);
1259 return DOM.stringify(range);
1262 getDefaultNames: function getDefaultNames(node) {
1263 let url = node.href || node.src || node.documentURI;
1264 let currExt = url.replace(/^.*?(?:\.([a-z0-9]+))?$/i, "$1").toLowerCase();
1267 if (isinstance(node, [Ci.nsIDOMDocument,
1268 Ci.nsIDOMHTMLImageElement])) {
1269 let type = node.contentType || node.QueryInterface(Ci.nsIImageLoadingContent)
1270 .getRequest(0).mimeType;
1272 if (type === "text/plain")
1273 ext = "." + (currExt || "txt");
1275 ext = "." + services.mime.getPrimaryExtension(type, currExt);
1278 ext = "." + currExt;
1280 let re = ext ? RegExp("(\\." + currExt + ")?$", "i") : /$/;
1284 names.push([node.title,
1285 _("buffer.save.pageName")]);
1288 names.push([node.alt,
1289 _("buffer.save.altText")]);
1291 if (!isinstance(node, Ci.nsIDOMDocument) && node.textContent)
1292 names.push([node.textContent,
1293 _("buffer.save.linkText")]);
1295 names.push([decodeURIComponent(url.replace(/.*?([^\/]*)\/*$/, "$1")),
1296 _("buffer.save.filename")]);
1298 return names.filter(function ([leaf, title]) leaf)
1299 .map(function ([leaf, title]) [leaf.replace(config.OS.illegalCharacters, encodeURIComponent)
1300 .replace(re, ext), title]);
1303 findScrollableWindow: deprecated("buffer.findScrollableWindow", function findScrollableWindow()
1304 let ({ buffer } = overlay.activeModules) buffer.findScrollableWindow.apply(buffer, arguments)),
1305 findScrollable: deprecated("buffer.findScrollable", function findScrollable()
1306 let ({ buffer } = overlay.activeModules) buffer.findScrollable.apply(buffer, arguments)),
1308 isScrollable: function isScrollable(elem, dir, horizontal) {
1309 if (!DOM(elem).isScrollable(horizontal ? "horizontal" : "vertical"))
1312 return this.canScroll(elem, dir, horizontal);
1315 canScroll: function canScroll(elem, dir, horizontal) {
1316 let pos = "scrollTop", size = "clientHeight", max = "scrollHeight", layoutSize = "offsetHeight",
1317 overflow = "overflowX", border1 = "borderTopWidth", border2 = "borderBottomWidth";
1319 pos = "scrollLeft", size = "clientWidth", max = "scrollWidth", layoutSize = "offsetWidth",
1320 overflow = "overflowX", border1 = "borderLeftWidth", border2 = "borderRightWidth";
1322 let style = DOM(elem).style;
1323 let borderSize = Math.round(parseFloat(style[border1]) + parseFloat(style[border2]));
1324 let realSize = elem[size];
1326 // Stupid Gecko eccentricities. May fail for quirks mode documents.
1327 if (elem[size] + borderSize == elem[max] || elem[size] == 0) // Stupid, fallible heuristic.
1330 if (style[overflow] == "hidden")
1331 realSize += borderSize;
1332 return dir < 0 && elem[pos] > 0 || dir > 0 && elem[pos] + realSize < elem[max] || !dir && realSize < elem[max];
1336 * Scroll the contents of the given element to the absolute *left*
1337 * and *top* pixel offsets.
1339 * @param {Element} elem The element to scroll.
1340 * @param {number|null} left The left absolute pixel offset. If
1341 * null, to not alter the horizontal scroll offset.
1342 * @param {number|null} top The top absolute pixel offset. If
1343 * null, to not alter the vertical scroll offset.
1344 * @param {string} reason The reason for the scroll event. See
1345 * {@link marks.push}. @optional
1347 scrollTo: function scrollTo(elem, left, top, reason) {
1348 let doc = elem.ownerDocument || elem.document || elem;
1350 let { buffer, marks, options } = util.topWindow(doc.defaultView).dactyl.modules;
1352 if (~[elem, elem.document, elem.ownerDocument].indexOf(buffer.focusedFrame.document))
1355 if (options["scrollsteps"] > 1)
1356 return this.smoothScrollTo(elem, left, top);
1358 elem = Buffer.Scrollable(elem);
1360 elem.scrollLeft = left;
1362 elem.scrollTop = top;
1366 * Like scrollTo, but scrolls more smoothly and does not update
1369 smoothScrollTo: function smoothScrollTo(node, x, y) {
1370 let { options } = overlay.activeModules;
1372 let time = options["scrolltime"];
1373 let steps = options["scrollsteps"];
1375 let elem = Buffer.Scrollable(node);
1377 if (node.dactylScrollTimer)
1378 node.dactylScrollTimer.cancel();
1381 x = elem.scrollLeft;
1385 x = node.dactylScrollDestX = Math.min(x, elem.scrollWidth - elem.clientWidth);
1386 y = node.dactylScrollDestY = Math.min(y, elem.scrollHeight - elem.clientHeight);
1387 let [startX, startY] = [elem.scrollLeft, elem.scrollTop];
1390 if (n++ === steps) {
1391 elem.scrollLeft = x;
1393 delete node.dactylScrollDestX;
1394 delete node.dactylScrollDestY;
1397 elem.scrollLeft = startX + (x - startX) / steps * n;
1398 elem.scrollTop = startY + (y - startY) / steps * n;
1399 node.dactylScrollTimer = util.timeout(next, time / steps);
1405 * Scrolls the currently given element horizontally.
1407 * @param {Element} elem The element to scroll.
1408 * @param {string} unit The increment by which to scroll.
1409 * Possible values are: "columns", "pages"
1410 * @param {number} number The possibly fractional number of
1411 * increments to scroll. Positive values scroll to the right while
1412 * negative values scroll to the left.
1413 * @throws {FailedAssertion} if scrolling is not possible in the
1416 scrollHorizontal: function scrollHorizontal(node, unit, number) {
1417 let fontSize = parseInt(DOM(node).style.fontSize);
1419 let elem = Buffer.Scrollable(node);
1421 if (unit == "columns")
1422 increment = fontSize; // Good enough, I suppose.
1423 else if (unit == "pages")
1424 increment = elem.clientWidth - fontSize;
1428 util.assert(number < 0 ? elem.scrollLeft > 0 : elem.scrollLeft < elem.scrollWidth - elem.clientWidth);
1430 let left = node.dactylScrollDestX !== undefined ? node.dactylScrollDestX : elem.scrollLeft;
1431 node.dactylScrollDestX = undefined;
1433 Buffer.scrollTo(node, left + number * increment, null, "h-" + unit);
1437 * Scrolls the given element vertically.
1439 * @param {Element} elem The element to scroll.
1440 * @param {string} unit The increment by which to scroll.
1441 * Possible values are: "lines", "pages"
1442 * @param {number} number The possibly fractional number of
1443 * increments to scroll. Positive values scroll upward while
1444 * negative values scroll downward.
1445 * @throws {FailedAssertion} if scrolling is not possible in the
1448 scrollVertical: function scrollVertical(node, unit, number) {
1449 let fontSize = parseInt(DOM(node).style.lineHeight);
1451 let elem = Buffer.Scrollable(node);
1453 if (unit == "lines")
1454 increment = fontSize;
1455 else if (unit == "pages")
1456 increment = elem.clientHeight - fontSize;
1460 util.assert(number < 0 ? elem.scrollTop > 0 : elem.scrollTop < elem.scrollHeight - elem.clientHeight);
1462 let top = node.dactylScrollDestY !== undefined ? node.dactylScrollDestY : elem.scrollTop;
1463 node.dactylScrollDestY = undefined;
1465 Buffer.scrollTo(node, null, top + number * increment, "v-" + unit);
1469 * Scrolls the currently active element to the given horizontal and
1470 * vertical percentages.
1472 * @param {Element} elem The element to scroll.
1473 * @param {number|null} horizontal The possibly fractional
1474 * percentage of the current viewport width to scroll to. If null,
1475 * do not scroll horizontally.
1476 * @param {number|null} vertical The possibly fractional percentage
1477 * of the current viewport height to scroll to. If null, do not
1478 * scroll vertically.
1480 scrollToPercent: function scrollToPercent(node, horizontal, vertical) {
1481 let elem = Buffer.Scrollable(node);
1482 Buffer.scrollTo(node,
1483 horizontal == null ? null
1484 : (elem.scrollWidth - elem.clientWidth) * (horizontal / 100),
1485 vertical == null ? null
1486 : (elem.scrollHeight - elem.clientHeight) * (vertical / 100));
1490 * Scrolls the currently active element to the given horizontal and
1491 * vertical position.
1493 * @param {Element} elem The element to scroll.
1494 * @param {number|null} horizontal The possibly fractional
1495 * line ordinal to scroll to.
1496 * @param {number|null} vertical The possibly fractional
1497 * column ordinal to scroll to.
1499 scrollToPosition: function scrollToPosition(elem, horizontal, vertical) {
1500 let style = DOM(elem.body || elem).style;
1501 Buffer.scrollTo(elem,
1502 horizontal == null ? null :
1503 horizontal == 0 ? 0 : this._exWidth(elem) * horizontal,
1504 vertical == null ? null : parseFloat(style.lineHeight) * vertical);
1508 * Returns the current scroll position as understood by
1509 * {@link #scrollToPosition}.
1511 * @param {Element} elem The element to scroll.
1513 getScrollPosition: function getPosition(node) {
1514 let style = DOM(node.body || node).style;
1516 let elem = Buffer.Scrollable(node);
1518 x: elem.scrollLeft && elem.scrollLeft / this._exWidth(node),
1519 y: elem.scrollTop / parseFloat(style.lineHeight)
1523 _exWidth: function _exWidth(elem) {
1525 let div = DOM(<elem style="width: 1ex !important; position: absolute !important; padding: 0 !important; display: block;"/>,
1526 elem.ownerDocument).appendTo(elem.body || elem);
1528 return parseFloat(div.style.width);
1535 return parseFloat(DOM(elem).fontSize) / 1.618;
1539 openUploadPrompt: function openUploadPrompt(elem) {
1540 let { io } = overlay.activeModules;
1542 io.CommandFileMode(_("buffer.prompt.uploadFile") + " ", {
1543 onSubmit: function onSubmit(path) {
1544 let file = io.File(path);
1545 util.assert(file.exists());
1547 DOM(elem).val(file.path).change();
1549 }).open(elem.value);
1552 init: function init(dactyl, modules, window) {
1553 init.superapply(this, arguments);
1555 dactyl.commands["buffer.viewSource"] = function (event) {
1556 let elem = event.originalTarget;
1557 let obj = { url: elem.getAttribute("href"), line: Number(elem.getAttribute("line")) };
1558 if (elem.hasAttribute("column"))
1559 obj.column = elem.getAttribute("column");
1561 modules.buffer.viewSource(obj);
1564 commands: function initCommands(dactyl, modules, window) {
1565 let { buffer, commands, config, options } = modules;
1567 commands.add(["frameo[nly]"],
1568 "Show only the current frame's page",
1570 dactyl.open(buffer.focusedFrame.location.href);
1574 commands.add(["ha[rdcopy]"],
1575 "Print current document",
1579 // FIXME: arg handling is a bit of a mess, check for filename
1580 dactyl.assert(!arg || arg[0] == ">" && !config.OS.isWindows,
1581 _("error.trailingCharacters"));
1583 const PRINTER = "PostScript/default";
1584 const BRANCH = "print.printer_" + PRINTER + ".";
1586 prefs.withContext(function () {
1588 prefs.set("print.print_printer", PRINTER);
1590 prefs.set( "print.print_to_file", true);
1591 prefs.set(BRANCH + "print_to_file", true);
1593 prefs.set( "print.print_to_filename", io.File(arg.substr(1)).path);
1594 prefs.set(BRANCH + "print_to_filename", io.File(arg.substr(1)).path);
1596 dactyl.echomsg(_("print.toFile", arg.substr(1)));
1599 dactyl.echomsg(_("print.sending"));
1601 prefs.set("print.always_print_silent", args.bang);
1602 prefs.set("print.show_print_progress", !args.bang);
1604 config.browser.contentWindow.print();
1608 dactyl.echomsg(_("print.printed", arg.substr(1)));
1610 dactyl.echomsg(_("print.sent"));
1618 commands.add(["pa[geinfo]"],
1619 "Show various page information",
1622 let opt = options.get("pageinfo");
1624 dactyl.assert(!arg || opt.validator(opt.parse(arg)),
1625 _("error.invalidArgument", arg));
1626 buffer.showPageInfo(true, arg);
1630 completer: function (context) {
1631 modules.completion.optionValue(context, "pageinfo", "+", "");
1632 context.title = ["Page Info"];
1636 commands.add(["pagest[yle]", "pas"],
1637 "Select the author style sheet to apply",
1639 let arg = args[0] || "";
1641 let titles = buffer.alternateStyleSheets.map(function (stylesheet) stylesheet.title);
1643 dactyl.assert(!arg || titles.indexOf(arg) >= 0,
1644 _("error.invalidArgument", arg));
1646 if (options["usermode"])
1647 options["usermode"] = false;
1649 window.stylesheetSwitchAll(buffer.focusedFrame, arg);
1653 completer: function (context) modules.completion.alternateStyleSheet(context),
1657 commands.add(["re[load]"],
1658 "Reload the current web page",
1659 function (args) { modules.tabs.reload(config.browser.mCurrentTab, args.bang); },
1665 // TODO: we're prompted if download.useDownloadDir isn't set and no arg specified - intentional?
1666 commands.add(["sav[eas]", "w[rite]"],
1667 "Save current document to disk",
1669 let { commandline, io } = modules;
1670 let { doc, win } = buffer;
1672 let chosenData = null;
1673 let filename = args[0];
1675 let command = commandline.command;
1677 if (filename[0] == "!")
1678 return buffer.viewSourceExternally(buffer.focusedFrame.document,
1680 let output = io.system(filename.substr(1), file);
1681 commandline.command = command;
1682 commandline.commandOutput(<span highlight="CmdOutput">{output}</span>);
1685 if (/^>>/.test(filename)) {
1686 let file = io.File(filename.replace(/^>>\s*/, ""));
1687 dactyl.assert(args.bang || file.exists() && file.isWritable(),
1688 _("io.notWriteable", file.path.quote()));
1690 return buffer.viewSourceExternally(buffer.focusedFrame.document,
1691 function (tmpFile) {
1693 file.write(tmpFile, ">>");
1696 dactyl.echoerr(_("io.notWriteable", file.path.quote()));
1701 let file = io.File(filename);
1703 if (filename.substr(-1) === File.PATH_SEP || file.exists() && file.isDirectory())
1704 file.append(Buffer.getDefaultNames(doc)[0][0]);
1706 dactyl.assert(args.bang || !file.exists(), _("io.exists"));
1708 chosenData = { file: file, uri: util.newURI(doc.location.href) };
1711 // if browser.download.useDownloadDir = false then the "Save As"
1712 // dialog is used with this as the default directory
1713 // TODO: if we're going to do this shouldn't it be done in setCWD or the value restored?
1714 prefs.set("browser.download.lastDir", io.cwd.path);
1717 var contentDisposition = win.QueryInterface(Ci.nsIInterfaceRequestor)
1718 .getInterface(Ci.nsIDOMWindowUtils)
1719 .getDocumentMetadata("content-disposition");
1723 window.internalSave(doc.location.href, doc, null, contentDisposition,
1724 doc.contentType, false, null, chosenData,
1725 doc.referrer ? window.makeURI(doc.referrer) : null,
1731 completer: function (context) {
1732 let { buffer, completion } = modules;
1734 if (context.filter[0] == "!")
1736 if (/^>>/.test(context.filter))
1737 context.advance(/^>>\s*/.exec(context.filter)[0].length);
1739 completion.savePage(context, buffer.doc);
1740 context.fork("file", 0, completion, "file");
1745 commands.add(["st[op]"],
1746 "Stop loading the current web page",
1747 function () { buffer.stop(); },
1750 commands.add(["vie[wsource]"],
1751 "View source code of current document",
1752 function (args) { buffer.viewSource(args[0], args.bang); },
1756 completer: function (context) modules.completion.url(context, "bhf")
1759 commands.add(["zo[om]"],
1760 "Set zoom value of current web page",
1767 else if (/^\d+$/.test(arg))
1768 level = parseInt(arg, 10);
1769 else if (/^[+-]\d+$/.test(arg))
1770 level = Math.round(buffer.zoomLevel + parseInt(arg, 10));
1772 dactyl.assert(false, _("error.trailingCharacters"));
1774 buffer.setZoom(level, args.bang);
1781 completion: function initCompletion(dactyl, modules, window) {
1782 let { CompletionContext, buffer, completion } = modules;
1784 completion.alternateStyleSheet = function alternateStylesheet(context) {
1785 context.title = ["Stylesheet", "Location"];
1787 // unify split style sheets
1788 let styles = iter([s.title, []] for (s in values(buffer.alternateStyleSheets))).toObject();
1790 buffer.alternateStyleSheets.forEach(function (style) {
1791 styles[style.title].push(style.href || _("style.inline"));
1794 context.completions = [[title, href.join(", ")] for ([title, href] in Iterator(styles))];
1797 completion.savePage = function savePage(context, node) {
1798 context.fork("generated", context.filter.replace(/[^/]*$/, "").length,
1799 this, function (context) {
1800 context.generate = function () {
1801 this.incomplete = true;
1802 this.completions = Buffer.getDefaultNames(node);
1803 util.httpGet(node.href || node.src || node.documentURI, {
1805 callback: function callback(xhr) {
1806 context.incomplete = false;
1808 if (/filename="(.*?)"/.test(xhr.getResponseHeader("Content-Disposition")))
1809 context.completions.push([decodeURIComponent(RegExp.$1), _("buffer.save.suggested")]);
1812 context.completions = context.completions.slice();
1815 notificationCallbacks: Class(XPCOM([Ci.nsIChannelEventSink, Ci.nsIInterfaceRequestor]), {
1816 getInterface: function getInterface(iid) this.QueryInterface(iid),
1818 asyncOnChannelRedirect: function (oldChannel, newChannel, flags, callback) {
1819 if (newChannel instanceof Ci.nsIHttpChannel)
1820 newChannel.requestMethod = "HEAD";
1821 callback.onRedirectVerifyCallback(Cr.NS_OK);
1829 events: function initEvents(dactyl, modules, window) {
1830 let { buffer, config, events } = modules;
1832 events.listen(config.browser, "scroll", buffer.closure._updateBufferPosition, false);
1834 mappings: function initMappings(dactyl, modules, window) {
1835 let { Editor, Events, buffer, editor, events, ex, mappings, modes, options, tabs } = modules;
1837 mappings.add([modes.NORMAL],
1838 ["y", "<yank-location>"], "Yank current location to the clipboard",
1840 let { doc, uri } = buffer;
1841 if (uri instanceof Ci.nsIURL)
1842 uri.query = uri.query.replace(/(?:^|&)utm_[^&]+/g, "")
1845 let link = DOM("link[href][rev=canonical], link[href][rel=shortlink]", doc);
1846 let url = link.length && options.get("yankshort").getKey(uri) ? link.attr("href") : uri.spec;
1847 dactyl.clipboardWrite(url, true);
1850 mappings.add([modes.NORMAL],
1851 ["<C-a>", "<increment-url-path>"], "Increment last number in URL",
1852 function (args) { buffer.incrementURL(Math.max(args.count, 1)); },
1855 mappings.add([modes.NORMAL],
1856 ["<C-x>", "<decrement-url-path>"], "Decrement last number in URL",
1857 function (args) { buffer.incrementURL(-Math.max(args.count, 1)); },
1860 mappings.add([modes.NORMAL], ["gu", "<open-parent-path>"],
1861 "Go to parent directory",
1862 function (args) { buffer.climbUrlPath(Math.max(args.count, 1)); },
1865 mappings.add([modes.NORMAL], ["gU", "<open-root-path>"],
1866 "Go to the root of the website",
1867 function () { buffer.climbUrlPath(-1); });
1869 mappings.add([modes.COMMAND], [".", "<repeat-key>"],
1870 "Repeat the last key event",
1872 if (mappings.repeat) {
1873 for (let i in util.interruptibleRange(0, Math.max(args.count, 1), 100))
1879 mappings.add([modes.NORMAL], ["i", "<Insert>"],
1881 function () { modes.push(modes.CARET); });
1883 mappings.add([modes.NORMAL], ["<C-c>", "<stop-load>"],
1884 "Stop loading the current web page",
1885 function () { ex.stop(); });
1888 mappings.add([modes.NORMAL], ["j", "<Down>", "<C-e>", "<scroll-down-line>"],
1889 "Scroll document down",
1890 function (args) { buffer.scrollVertical("lines", Math.max(args.count, 1)); },
1893 mappings.add([modes.NORMAL], ["k", "<Up>", "<C-y>", "<scroll-up-line>"],
1894 "Scroll document up",
1895 function (args) { buffer.scrollVertical("lines", -Math.max(args.count, 1)); },
1898 mappings.add([modes.COMMAND], dactyl.has("mail") ? ["h", "<scroll-left-column>"] : ["h", "<Left>", "<scroll-left-column>"],
1899 "Scroll document to the left",
1900 function (args) { buffer.scrollHorizontal("columns", -Math.max(args.count, 1)); },
1903 mappings.add([modes.NORMAL], dactyl.has("mail") ? ["l", "<scroll-right-column>"] : ["l", "<Right>", "<scroll-right-column>"],
1904 "Scroll document to the right",
1905 function (args) { buffer.scrollHorizontal("columns", Math.max(args.count, 1)); },
1908 mappings.add([modes.NORMAL], ["0", "^", "<scroll-begin>"],
1909 "Scroll to the absolute left of the document",
1910 function () { buffer.scrollToPercent(0, null); });
1912 mappings.add([modes.NORMAL], ["$", "<scroll-end>"],
1913 "Scroll to the absolute right of the document",
1914 function () { buffer.scrollToPercent(100, null); });
1916 mappings.add([modes.NORMAL], ["gg", "<Home>", "<scroll-top>"],
1917 "Go to the top of the document",
1918 function (args) { buffer.scrollToPercent(null, args.count != null ? args.count : 0); },
1921 mappings.add([modes.NORMAL], ["G", "<End>", "<scroll-bottom>"],
1922 "Go to the end of the document",
1925 var elem = options.get("linenumbers")
1926 .getLine(buffer.focusedFrame.document,
1929 elem.scrollIntoView(true);
1930 else if (args.count)
1931 buffer.scrollToPosition(null, args.count);
1933 buffer.scrollToPercent(null, 100);
1937 mappings.add([modes.NORMAL], ["%", "<scroll-percent>"],
1938 "Scroll to {count} percent of the document",
1940 dactyl.assert(args.count > 0 && args.count <= 100);
1941 buffer.scrollToPercent(null, args.count);
1945 mappings.add([modes.NORMAL], ["<C-d>", "<scroll-down>"],
1946 "Scroll window downwards in the buffer",
1947 function (args) { buffer._scrollByScrollSize(args.count, true); },
1950 mappings.add([modes.NORMAL], ["<C-u>", "<scroll-up>"],
1951 "Scroll window upwards in the buffer",
1952 function (args) { buffer._scrollByScrollSize(args.count, false); },
1955 mappings.add([modes.NORMAL], ["<C-b>", "<PageUp>", "<S-Space>", "<scroll-up-page>"],
1956 "Scroll up a full page",
1957 function (args) { buffer.scrollVertical("pages", -Math.max(args.count, 1)); },
1960 mappings.add([modes.NORMAL], ["<Space>"],
1961 "Scroll down a full page",
1963 if (isinstance((services.focus.focusedWindow || buffer.win).document.activeElement,
1964 [Ci.nsIDOMHTMLInputElement,
1965 Ci.nsIDOMHTMLButtonElement,
1966 Ci.nsIDOMXULButtonElement]))
1969 buffer.scrollVertical("pages", Math.max(args.count, 1));
1973 mappings.add([modes.NORMAL], ["<C-f>", "<PageDown>", "<scroll-down-page>"],
1974 "Scroll down a full page",
1975 function (args) { buffer.scrollVertical("pages", Math.max(args.count, 1)); },
1978 mappings.add([modes.NORMAL], ["]f", "<previous-frame>"],
1980 function (args) { buffer.shiftFrameFocus(Math.max(args.count, 1)); },
1983 mappings.add([modes.NORMAL], ["[f", "<next-frame>"],
1984 "Focus previous frame",
1985 function (args) { buffer.shiftFrameFocus(-Math.max(args.count, 1)); },
1988 mappings.add([modes.NORMAL], ["["],
1989 "Jump to the previous element as defined by 'jumptags'",
1990 function (args) { buffer.findJump(args.arg, args.count, true); },
1991 { arg: true, count: true });
1993 mappings.add([modes.NORMAL], ["g]"],
1994 "Jump to the next off-screen element as defined by 'jumptags'",
1995 function (args) { buffer.findJump(args.arg, args.count, false, true); },
1996 { arg: true, count: true });
1998 mappings.add([modes.NORMAL], ["]"],
1999 "Jump to the next element as defined by 'jumptags'",
2000 function (args) { buffer.findJump(args.arg, args.count, false); },
2001 { arg: true, count: true });
2003 mappings.add([modes.NORMAL], ["{"],
2004 "Jump to the previous paragraph",
2005 function (args) { buffer.findJump("p", args.count, true); },
2008 mappings.add([modes.NORMAL], ["}"],
2009 "Jump to the next paragraph",
2010 function (args) { buffer.findJump("p", args.count, false); },
2013 mappings.add([modes.NORMAL], ["]]", "<next-page>"],
2014 "Follow the link labeled 'next' or '>' if it exists",
2016 buffer.findLink("next", options["nextpattern"], (args.count || 1) - 1, true);
2020 mappings.add([modes.NORMAL], ["[[", "<previous-page>"],
2021 "Follow the link labeled 'prev', 'previous' or '<' if it exists",
2023 buffer.findLink("previous", options["previouspattern"], (args.count || 1) - 1, true);
2027 mappings.add([modes.NORMAL], ["gf", "<view-source>"],
2028 "Toggle between rendered and source view",
2029 function () { buffer.viewSource(null, false); });
2031 mappings.add([modes.NORMAL], ["gF", "<view-source-externally>"],
2032 "View source with an external editor",
2033 function () { buffer.viewSource(null, true); });
2035 mappings.add([modes.NORMAL], ["gi", "<focus-input>"],
2036 "Focus last used input field",
2038 let elem = buffer.lastInputField;
2040 if (args.count >= 1 || !elem || !events.isContentNode(elem)) {
2041 let xpath = ["frame", "iframe", "input", "xul:textbox", "textarea[not(@disabled) and not(@readonly)]"];
2043 let frames = buffer.allFrames(null, true);
2045 let elements = array.flatten(frames.map(function (win) [m for (m in DOM.XPath(xpath, win.document))]))
2046 .filter(function (elem) {
2047 if (isinstance(elem, [Ci.nsIDOMHTMLFrameElement,
2048 Ci.nsIDOMHTMLIFrameElement]))
2049 return Editor.getEditor(elem.contentWindow);
2053 if (elem[0].readOnly || !DOM(elem).isEditable)
2056 let style = elem.style;
2057 let rect = elem.rect;
2058 return elem.isVisible &&
2059 (elem[0] instanceof Ci.nsIDOMXULTextBoxElement || style.MozUserFocus != "ignore") &&
2060 rect.width && rect.height;
2063 dactyl.assert(elements.length > 0);
2064 elem = elements[Math.constrain(args.count, 1, elements.length) - 1];
2066 buffer.focusElement(elem);
2067 DOM(elem).scrollIntoView();
2072 let url = dactyl.clipboardRead();
2073 dactyl.assert(url, _("error.clipboardEmpty"));
2075 let proto = /^([-\w]+):/.exec(url);
2076 if (proto && services.PROTOCOL + proto[1] in Cc && !RegExp(options["urlseparator"]).test(url))
2077 return url.replace(/\s+/g, "");
2081 mappings.add([modes.NORMAL], ["gP"],
2082 "Open (put) a URL based on the current clipboard contents in a new background buffer",
2084 dactyl.open(url(), { from: "paste", where: dactyl.NEW_TAB, background: true });
2087 mappings.add([modes.NORMAL], ["p", "<MiddleMouse>", "<open-clipboard-url>"],
2088 "Open (put) a URL based on the current clipboard contents in the current buffer",
2093 mappings.add([modes.NORMAL], ["P", "<tab-open-clipboard-url>"],
2094 "Open (put) a URL based on the current clipboard contents in a new buffer",
2096 dactyl.open(url(), { from: "paste", where: dactyl.NEW_TAB });
2100 mappings.add([modes.NORMAL], ["r", "<reload>"],
2101 "Reload the current web page",
2102 function () { tabs.reload(tabs.getTab(), false); });
2104 mappings.add([modes.NORMAL], ["R", "<full-reload>"],
2105 "Reload while skipping the cache",
2106 function () { tabs.reload(tabs.getTab(), true); });
2109 mappings.add([modes.NORMAL], ["Y", "<yank-selection>"],
2110 "Copy selected text or current word",
2112 let sel = buffer.currentWord;
2114 editor.setRegister(null, sel, true);
2118 mappings.add([modes.NORMAL], ["zi", "+", "<text-zoom-in>"],
2119 "Enlarge text zoom of current web page",
2120 function (args) { buffer.zoomIn(Math.max(args.count, 1), false); },
2123 mappings.add([modes.NORMAL], ["zm", "<text-zoom-more>"],
2124 "Enlarge text zoom of current web page by a larger amount",
2125 function (args) { buffer.zoomIn(Math.max(args.count, 1) * 3, false); },
2128 mappings.add([modes.NORMAL], ["zo", "-", "<text-zoom-out>"],
2129 "Reduce text zoom of current web page",
2130 function (args) { buffer.zoomOut(Math.max(args.count, 1), false); },
2133 mappings.add([modes.NORMAL], ["zr", "<text-zoom-reduce>"],
2134 "Reduce text zoom of current web page by a larger amount",
2135 function (args) { buffer.zoomOut(Math.max(args.count, 1) * 3, false); },
2138 mappings.add([modes.NORMAL], ["zz", "<text-zoom>"],
2139 "Set text zoom value of current web page",
2140 function (args) { buffer.setZoom(args.count > 1 ? args.count : 100, false); },
2143 mappings.add([modes.NORMAL], ["ZI", "zI", "<full-zoom-in>"],
2144 "Enlarge full zoom of current web page",
2145 function (args) { buffer.zoomIn(Math.max(args.count, 1), true); },
2148 mappings.add([modes.NORMAL], ["ZM", "zM", "<full-zoom-more>"],
2149 "Enlarge full zoom of current web page by a larger amount",
2150 function (args) { buffer.zoomIn(Math.max(args.count, 1) * 3, true); },
2153 mappings.add([modes.NORMAL], ["ZO", "zO", "<full-zoom-out>"],
2154 "Reduce full zoom of current web page",
2155 function (args) { buffer.zoomOut(Math.max(args.count, 1), true); },
2158 mappings.add([modes.NORMAL], ["ZR", "zR", "<full-zoom-reduce>"],
2159 "Reduce full zoom of current web page by a larger amount",
2160 function (args) { buffer.zoomOut(Math.max(args.count, 1) * 3, true); },
2163 mappings.add([modes.NORMAL], ["zZ", "<full-zoom>"],
2164 "Set full zoom value of current web page",
2165 function (args) { buffer.setZoom(args.count > 1 ? args.count : 100, true); },
2169 mappings.add([modes.NORMAL], ["<C-g>", "<page-info>"],
2170 "Print the current file name",
2171 function () { buffer.showPageInfo(false); });
2173 mappings.add([modes.NORMAL], ["g<C-g>", "<more-page-info>"],
2174 "Print file information",
2175 function () { buffer.showPageInfo(true); });
2177 options: function initOptions(dactyl, modules, window) {
2178 let { Option, buffer, completion, config, options } = modules;
2180 options.add(["encoding", "enc"],
2181 "The current buffer's character encoding",
2184 scope: Option.SCOPE_LOCAL,
2185 getter: function () buffer.docShell.QueryInterface(Ci.nsIDocCharset).charset,
2186 setter: function (val) {
2187 if (options["encoding"] == val)
2190 // Stolen from browser.jar/content/browser/browser.js, more or less.
2192 buffer.docShell.QueryInterface(Ci.nsIDocCharset).charset = val;
2193 window.PlacesUtils.history.setCharsetForURI(buffer.uri, val);
2194 buffer.docShell.reload(Ci.nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE);
2196 catch (e) { dactyl.reportError(e); }
2199 completer: function (context) completion.charset(context)
2202 options.add(["iskeyword", "isk"],
2203 "Regular expression defining which characters constitute words",
2204 "string", '[^\\s.,!?:;/"\'^$%&?()[\\]{}<>#*+|=~_-]',
2206 setter: function (value) {
2207 this.regexp = util.regexp(value);
2210 validator: function (value) RegExp(value)
2213 options.add(["jumptags", "jt"],
2214 "XPath or CSS selector strings of jumpable elements for extended hint modes",
2216 "p": "p,table,ul,ol,blockquote",
2217 "h": "h1,h2,h3,h4,h5,h6"
2221 setter: function (vals) {
2222 for (let [k, v] in Iterator(vals))
2223 vals[k] = update(new String(v), { matcher: DOM.compileMatcher(Option.splitList(v)) });
2226 validator: function (value) DOM.validateMatcher.call(this, value)
2227 && Object.keys(value).every(function (v) v.length == 1)
2230 options.add(["linenumbers", "ln"],
2231 "Patterns used to determine line numbers used by G",
2233 "code.google.com": '#nums [id^="nums_table"] a[href^="#"]',
2234 "github.com": '.line_numbers>*',
2235 "mxr.mozilla.org": 'a.l',
2236 "pastebin.com": '#code_frame>div>ol>li',
2237 "addons.mozilla.org": '.gutter>.line>a',
2238 "*": '/* Hgweb/Gitweb */ .completecodeline a.codeline, a.linenr'
2241 getLine: function getLine(doc, line) {
2242 let uri = util.newURI(doc.documentURI);
2243 for (let filter in values(this.value))
2244 if (filter(uri, doc)) {
2245 if (/^func:/.test(filter.result))
2246 var res = dactyl.userEval("(" + Option.dequote(filter.result.substr(5)) + ")")(doc, line);
2248 res = iter.nth(filter.matcher(doc),
2249 function (elem) (elem.nodeValue || elem.textContent).trim() == line && DOM(elem).display != "none",
2251 || iter.nth(filter.matcher(doc), util.identity, line - 1);
2261 setter: function (vals) {
2262 for (let value in values(vals))
2263 if (!/^func:/.test(value.result))
2264 value.matcher = DOM.compileMatcher(Option.splitList(value.result));
2268 validator: function validate(values) {
2269 return this.testValues(values, function (value) {
2270 if (/^func:/.test(value))
2271 return callable(dactyl.userEval("(" + Option.dequote(value.substr(5)) + ")"));
2273 return DOM.testMatcher(Option.dequote(value));
2278 options.add(["nextpattern"],
2279 "Patterns to use when guessing the next page in a document sequence",
2280 "regexplist", UTF8(/'\bnext\b',^>$,^(>>|»)$,^(>|»),(>|»)$,'\bmore\b'/.source),
2281 { regexpFlags: "i" });
2283 options.add(["previouspattern"],
2284 "Patterns to use when guessing the previous page in a document sequence",
2285 "regexplist", UTF8(/'\bprev|previous\b',^<$,^(<<|«)$,^(<|«),(<|«)$/.source),
2286 { regexpFlags: "i" });
2288 options.add(["pageinfo", "pa"],
2289 "Define which sections are shown by the :pageinfo command",
2290 "charlist", "gesfm",
2291 { get values() values(Buffer.pageInfo).toObject() });
2293 options.add(["scroll", "scr"],
2294 "Number of lines to scroll with <C-u> and <C-d> commands",
2296 { validator: function (value) value >= 0 });
2298 options.add(["showstatuslinks", "ssli"],
2299 "Where to show the destination of the link under the cursor",
2303 "": "Don't show link destinations",
2304 "status": "Show link destinations in the status line",
2305 "command": "Show link destinations in the command line"
2309 options.add(["scrolltime", "sct"],
2310 "The time, in milliseconds, in which to smooth scroll to a new position",
2313 options.add(["scrollsteps", "scs"],
2314 "The number of steps in which to smooth scroll to a new position",
2317 PREF: "general.smoothScroll",
2319 initValue: function () {},
2321 getter: function getter(value) !prefs.get(this.PREF) ? 1 : value,
2323 setter: function setter(value) {
2324 prefs.set(this.PREF, value > 1);
2329 validator: function (value) value > 0
2332 options.add(["usermode", "um"],
2333 "Show current website without styling defined by the author",
2336 setter: function (value) buffer.contentViewer.authorStyleDisabled = value,
2337 getter: function () buffer.contentViewer.authorStyleDisabled
2340 options.add(["yankshort", "ys"],
2341 "Yank the canonical short URL of a web page where provided",
2342 "sitelist", ["youtube.com", "bugzilla.mozilla.org"]);
2346 Buffer.addPageInfoSection("e", "Search Engines", function (verbose) {
2350 for (let { document: doc } in values(this.allFrames())) {
2351 let engines = DOM("link[href][rel=search][type='application/opensearchdescription+xml']", doc);
2352 nEngines += engines.length;
2355 for (let link in engines)
2356 yield [link.title || /*L*/ "Engine " + n++,
2357 <a xmlns={XHTML} href={link.href}
2358 onclick="if (event.button == 0) { window.external.AddSearchProvider(this.href); return false; }"
2359 highlight="URL">{link.href}</a>];
2362 if (!verbose && nEngines)
2363 yield nEngines + /*L*/" engine" + (nEngines > 1 ? "s" : "");
2366 Buffer.addPageInfoSection("f", "Feeds", function (verbose) {
2368 "application/rss+xml": "RSS",
2369 "application/atom+xml": "Atom",
2371 "application/xml": "XML",
2372 "application/rdf+xml": "XML"
2375 function isValidFeed(data, principal, isFeed) {
2376 if (!data || !principal)
2380 var type = data.type && data.type.toLowerCase();
2381 type = type.replace(/^\s+|\s*(?:;.*)?$/g, "");
2383 isFeed = ["application/rss+xml", "application/atom+xml"].indexOf(type) >= 0 ||
2384 // really slimy: general XML types with magic letters in the title
2385 type in feedTypes && /\brss\b/i.test(data.title);
2390 services.security.checkLoadURIStrWithPrincipal(principal, data.href,
2391 services.security.DISALLOW_INHERIT_PRINCIPAL);
2405 for (let [i, win] in Iterator(this.allFrames())) {
2406 let doc = win.document;
2408 for (let link in DOM("link[href][rel=feed], link[href][rel=alternate][type]", doc)) {
2409 let rel = link.rel.toLowerCase();
2410 let feed = { title: link.title, href: link.href, type: link.type || "" };
2411 if (isValidFeed(feed, doc.nodePrincipal, rel == "feed")) {
2413 let type = feedTypes[feed.type] || "RSS";
2415 yield [feed.title, template.highlightURL(feed.href, true) + <span class="extra-info"> ({type})</span>];
2421 if (!verbose && nFeed)
2422 yield nFeed + /*L*/" feed" + (nFeed > 1 ? "s" : "");
2425 Buffer.addPageInfoSection("g", "General Info", function (verbose) {
2426 let doc = this.focusedFrame.document;
2429 const ACCESS_READ = Ci.nsICache.ACCESS_READ;
2430 let cacheKey = doc.documentURI;
2432 for (let proto in array.iterValues(["HTTP", "FTP"])) {
2434 var cacheEntryDescriptor = services.cache.createSession(proto, 0, true)
2435 .openCacheEntry(cacheKey, ACCESS_READ, false);
2441 let pageSize = []; // [0] bytes; [1] kbytes
2442 if (cacheEntryDescriptor) {
2443 pageSize[0] = util.formatBytes(cacheEntryDescriptor.dataSize, 0, false);
2444 pageSize[1] = util.formatBytes(cacheEntryDescriptor.dataSize, 2, true);
2445 if (pageSize[1] == pageSize[0])
2446 pageSize.length = 1; // don't output "xx Bytes" twice
2449 let lastModVerbose = new Date(doc.lastModified).toLocaleString();
2450 let lastMod = new Date(doc.lastModified).toLocaleFormat("%x %X");
2452 if (lastModVerbose == "Invalid Date" || new Date(doc.lastModified).getFullYear() == 1970)
2453 lastModVerbose = lastMod = null;
2457 yield (pageSize[1] || pageSize[0]) + /*L*/" bytes";
2462 yield ["Title", doc.title];
2463 yield ["URL", template.highlightURL(doc.location.href, true)];
2465 let ref = "referrer" in doc && doc.referrer;
2467 yield ["Referrer", template.highlightURL(ref, true)];
2470 yield ["File Size", pageSize[1] ? pageSize[1] + " (" + pageSize[0] + ")"
2473 yield ["Mime-Type", doc.contentType];
2474 yield ["Encoding", doc.characterSet];
2475 yield ["Compatibility", doc.compatMode == "BackCompat" ? "Quirks Mode" : "Full/Almost Standards Mode"];
2477 yield ["Last Modified", lastModVerbose];
2480 Buffer.addPageInfoSection("m", "Meta Tags", function (verbose) {
2484 // get meta tag data, sort and put into pageMeta[]
2485 let metaNodes = this.focusedFrame.document.getElementsByTagName("meta");
2487 return Array.map(metaNodes, function (node) [(node.name || node.httpEquiv), template.highlightURL(node.content)])
2488 .sort(function (a, b) util.compareIgnoreCase(a[0], b[0]));
2491 Buffer.addPageInfoSection("s", "Security", function (verbose) {
2492 let { statusline } = this.modules
2494 let identity = this.topWindow.gIdentityHandler;
2496 if (!verbose || !identity)
2499 // Modified from Firefox
2500 function location(data) array.compact([
2501 data.city, data.state, data.country
2504 switch (statusline.security) {
2507 var data = identity.getIdentityData();
2509 yield ["Host", identity.getEffectiveHost()];
2511 if (statusline.security === "extended")
2512 yield ["Owner", data.subjectOrg];
2514 yield ["Owner", _("pageinfo.s.ownerUnverified", data.subjectOrg)];
2516 if (location(data).length)
2517 yield ["Location", location(data)];
2519 yield ["Verified by", data.caOrg];
2521 if (identity._overrideService.hasMatchingOverride(identity._lastLocation.hostname,
2522 (identity._lastLocation.port || 443),
2524 yield ["User exception", /*L*/"true"];
2529 } catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
2533 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: