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>
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 defineModule("buffer", {
10 exports: ["Buffer", "buffer"],
11 require: ["prefs", "services", "util"]
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"]);
24 * A class to manage the primary web content buffer. The name comes
25 * from Vim's term, 'buffer', which signifies instances of open
29 var Buffer = Module("Buffer", {
30 Local: function Local(dactyl, modules, window) ({
32 return window.content;
34 let win = services.focus.focusedWindow;
35 if (!win || win == window || util.topWindow(win) != window)
36 return window.content;
37 if (win.top == window)
43 init: function init(win) {
48 get addPageInfoSection() Buffer.closure.addPageInfoSection,
50 get pageInfo() Buffer.pageInfo,
52 // called when the active document is scrolled
53 _updateBufferPosition: function _updateBufferPosition() {
54 this.modules.statusline.updateBufferPosition();
55 this.modules.commandline.clear(true);
59 * @property {Array} The alternative style sheets for the current
60 * buffer. Only returns style sheets for the 'screen' media type.
62 get alternateStyleSheets() {
63 let stylesheets = array.flatten(
64 this.allFrames().map(function (w) Array.slice(w.document.styleSheets)));
66 return stylesheets.filter(
67 function (stylesheet) /^(screen|all|)$/i.test(stylesheet.media.mediaText) && !/^\s*$/.test(stylesheet.title)
72 * Gets a content preference for the given buffer.
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.
80 getPref: function getPref(pref, callback) {
82 if (config.haveGecko("19.0a1"))
83 services.contentPrefs.getPref(this.uri, pref,
84 sanitizer.getContext(this.win), callback);
86 services.contentPrefs.getPref(this.uri, pref, callback);
90 * Sets a content preference for the given buffer.
92 * @param {string} pref The preference to set.
93 * @param {string} value The value to store.
95 setPref: function setPref(pref, value) {
96 services.contentPrefs.setPref(
97 this.uri, pref, value, sanitizer.getContext(this.win));
101 * Clear a content preference for the given buffer.
103 * @param {string} pref The preference to clear.
105 clearPref: function clearPref(pref) {
106 services.contentPrefs.removePref(
107 this.uri, pref, sanitizer.getContext(this.win));
110 climbUrlPath: function climbUrlPath(count) {
111 let { dactyl } = this.modules;
113 let url = this.documentURI.clone();
114 dactyl.assert(url instanceof Ci.nsIURL);
116 while (count-- && url.path != "/")
117 url.path = url.path.replace(/[^\/]*\/*$/, "");
119 dactyl.assert(!url.equals(this.documentURI));
120 dactyl.open(url.spec);
123 incrementURL: function incrementURL(count) {
124 let { dactyl } = this.modules;
126 let matches = this.uri.spec.match(/(.*?)(\d+)(\D*)$/);
127 dactyl.assert(matches);
128 let oldNum = matches[2];
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;
137 dactyl.open(matches.slice(1).join(""));
141 * @property {number} True when the buffer is fully loaded.
143 get loaded() Math.min.apply(null,
145 .map(function (frame) ["loading", "interactive", "complete"]
146 .indexOf(frame.document.readyState))),
149 * @property {Object} The local state store for the currently selected
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;
161 localStorePrototype: memoize({
168 * @property {Node} The last focused input field in the buffer. Used
169 * by the "gi" key binding.
171 get lastInputField() {
172 let field = this.localStore.lastInputField && this.localStore.lastInputField.get();
174 let doc = field && field.ownerDocument;
175 let win = doc && doc.defaultView;
176 return win && doc === win.document ? field : null;
178 set lastInputField(value) { this.localStore.lastInputField = util.weakReference(value); },
181 * @property {nsIURI} The current top-level document.
183 get doc() this.win.document,
185 get docShell() util.docShell(this.win),
187 get modules() this.topWindow.dactyl.modules,
190 topWindow: Class.Memoize(function () util.topWindow(this.win)),
193 * @property {nsIURI} The current top-level document's URI.
195 get uri() util.newURI(this.win.location.href),
198 * @property {nsIURI} The current top-level document's URI, sans any
199 * fragment identifier.
201 get documentURI() this.doc.documentURIObject || util.newURI(this.doc.documentURI),
204 * @property {string} The current top-level document's URL.
206 get URL() update(new String(this.win.location.href), util.newURI(this.win.location.href)),
209 * @property {number} The buffer's height in pixels.
211 get pageHeight() this.win.innerHeight,
213 get contentViewer() this.docShell.contentViewer
214 .QueryInterface(Components.interfaces.nsIMarkupDocumentViewer),
217 * @property {number} The current browser's zoom level, as a
218 * percentage with 100 as 'normal'.
221 let v = this.contentViewer;
222 return v[v.textZoom == 1 ? "fullZoom" : "textZoom"] * 100;
224 set zoomLevel(value) { this.setZoom(value, this.fullZoom); },
227 * @property {boolean} Whether the current browser is using full
228 * zoom, as opposed to text zoom.
230 get fullZoom() this.ZoomManager.useFullZoom,
231 set fullZoom(value) { this.setZoom(this.zoomLevel, value); },
233 get ZoomManager() this.topWindow.ZoomManager,
236 * @property {string} The current document's title.
238 get title() this.doc.title,
241 * @property {number} The buffer's horizontal scroll percentile.
243 get scrollXPercent() {
244 let elem = Buffer.Scrollable(this.findScrollable(0, true));
245 if (elem.scrollWidth - elem.clientWidth === 0)
247 return elem.scrollLeft * 100 / (elem.scrollWidth - elem.clientWidth);
251 * @property {number} The buffer's vertical scroll percentile.
253 get scrollYPercent() {
254 let elem = Buffer.Scrollable(this.findScrollable(0, false));
255 if (elem.scrollHeight - elem.clientHeight === 0)
257 return elem.scrollTop * 100 / (elem.scrollHeight - elem.clientHeight);
261 * @property {{ x: number, y: number }} The buffer's current scroll position
262 * as reported by {@link Buffer.getScrollPosition}.
264 get scrollPosition() Buffer.getScrollPosition(this.findScrollable(0, false)),
267 * Returns a list of all frames in the given window or current buffer.
269 allFrames: function allFrames(win, focusedFirst) {
271 (function rec(frame) {
272 if (true || frame.document.body instanceof Ci.nsIDOMHTMLBodyElement)
274 Array.forEach(frame.frames, rec);
278 return frames.filter(function (f) f === this.focusedFrame, this).concat(
279 frames.filter(function (f) f !== this.focusedFrame, this));
284 * @property {Window} Returns the currently focused frame.
287 let frame = this.localStore.focusedFrame;
288 return frame && frame.get() || this.win;
290 set focusedFrame(frame) {
291 this.localStore.focusedFrame = util.weakReference(frame);
295 * Returns the currently selected word. If the selection is
296 * null, it tries to guess the word that the caret is
301 get currentWord() Buffer.currentWord(this.focusedFrame),
302 getCurrentWord: deprecated("buffer.currentWord", function getCurrentWord() Buffer.currentWord(this.focusedFrame, true)),
305 * Returns true if a scripts are allowed to focus the given input
306 * element or input elements in the given window.
308 * @param {Node|Window}
311 focusAllowed: function focusAllowed(elem) {
312 if (elem instanceof Ci.nsIDOMWindow && !DOM(elem).isEditable)
315 let { options } = this.modules;
317 let doc = elem.ownerDocument || elem.document || elem;
318 switch (options.get("strictfocus").getKey(doc.documentURIObject || util.newURI(doc.documentURI), "moderate")) {
320 return overlay.getData(elem)["focus-allowed"]
321 || elem.frameElement && overlay.getData(elem.frameElement)["focus-allowed"];
323 return overlay.getData(doc, "focus-allowed")
324 || elem.frameElement && overlay.getData(elem.frameElement.ownerDocument)["focus-allowed"];
331 * Focuses the given element. In contrast to a simple
332 * elem.focus() call, this function works for iframes and
335 * @param {Node} elem The element to focus.
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);
342 if (isinstance(elem, [Ci.nsIDOMHTMLFrameElement,
343 Ci.nsIDOMHTMLIFrameElement]))
344 elem = elem.contentWindow;
347 overlay.setData(elem.document, "focus-allowed", true);
349 if (elem instanceof Ci.nsIDOMHTMLInputElement && elem.type == "file") {
350 Buffer.openUploadPrompt(elem);
351 this.lastInputField = elem;
354 if (isinstance(elem, [Ci.nsIDOMHTMLInputElement,
355 Ci.nsIDOMXULTextBoxElement]))
356 var flags = services.focus.FLAG_BYMOUSE;
358 flags = services.focus.FLAG_SHOWRING;
360 // Hack to deal with current versions of Firefox misplacing
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;
369 DOM(elem).focus(flags);
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),
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();
389 if (elem instanceof Ci.nsIDOMHTMLAreaElement) {
391 let [x, y] = elem.getAttribute("coords").split(",").map(parseFloat);
393 DOM(elem).mouseover({ screenX: x, screenY: y });
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.
409 * If follow is true, the link is followed.
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
417 findLink: function findLink(rel, regexps, count, follow, path) {
418 let { Hints, dactyl, options } = this.modules;
420 let selector = path || options.get("hinttags").stringDefaultValue;
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)
429 let elems = frame.document.getElementsByTagName("link");
430 for (let elem in iter(elems))
433 elems = frame.document.getElementsByTagName("a");
434 for (let elem in iter(elems))
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;
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]))
449 for (let frame in values(this.allFrames(null, true)))
450 for (let elem in followFrame(frame))
453 this.followLink(elem, dactyl.CURRENT_TAB);
460 followDocumentRelationship: deprecated("buffer.findLink",
461 function followDocumentRelationship(rel) {
462 let { options } = this.modules;
464 this.findLink(rel, options[rel + "pattern"], 0, true);
468 * Fakes a click on a link.
470 * @param {Node} elem The element to click.
471 * @param {number} where Where to open the link. See
472 * {@link dactyl.open}.
474 followLink: function followLink(elem, where) {
475 let { dactyl } = this.modules;
477 let doc = elem.ownerDocument;
478 let win = doc.defaultView;
479 let { left: offsetX, top: offsetY } = elem.getBoundingClientRect();
481 if (isinstance(elem, [Ci.nsIDOMHTMLFrameElement,
482 Ci.nsIDOMHTMLIFrameElement]))
483 return this.focusElement(elem);
485 if (isinstance(elem, Ci.nsIDOMHTMLLinkElement))
486 return dactyl.open(elem.href, where);
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;
493 else if (elem instanceof Ci.nsIDOMHTMLInputElement && elem.type == "file") {
494 Buffer.openUploadPrompt(elem);
498 let { dactyl } = this.modules;
500 let ctrlKey = false, shiftKey = false;
502 switch (dactyl.forceTarget || where) {
504 case dactyl.NEW_BACKGROUND_TAB:
506 shiftKey = dactyl.forceBackground != null ? dactyl.forceBackground
507 : where != dactyl.NEW_BACKGROUND_TAB;
509 case dactyl.NEW_WINDOW:
512 case dactyl.CURRENT_TAB:
516 this.focusElement(elem);
518 prefs.withContext(function () {
519 prefs.set("browser.tabs.loadInBackground", true);
521 button: button, screenX: offsetX, screenY: offsetY,
522 ctrlKey: ctrlKey, shiftKey: shiftKey, metaKey: ctrlKey
525 DOM(elem).mousedown(params).mouseup(params);
526 if (!config.haveGecko("2b"))
527 DOM(elem).click(params);
529 let sel = util.selectionController(win);
530 sel.getSelection(sel.SELECTION_FOCUS_REGION).collapseToStart();
535 * Resets the caret position so that it resides within the current
538 resetCaret: function resetCaret() {
539 function visible(range) util.intersection(DOM(range).rect, viewport);
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);
548 let win = this.focusedFrame;
549 let doc = win.document;
550 let sel = win.getSelection();
551 let { viewport } = DOM(win);
553 if (sel.rangeCount) {
554 var range = sel.getRangeAt(0);
555 if (visible(range).height > 0)
558 var { rect } = DOM(range);
559 var reverse = rect.bottom > viewport.bottom;
561 rect = { x: rect.left, y: 0, width: rect.width, height: win.innerHeight };
564 let w = win.innerWidth;
565 rect = { x: w / 3, y: 0, width: w / 3, height: win.innerHeight };
568 var reduce = function (a, b) DOM(a).rect.top < DOM(b).rect.top ? a : b;
572 reduce = function (a, b) DOM(b).rect.bottom > DOM(a).rect.bottom ? b : a;
574 y = win.innerHeight - 1;
577 let ranges = getRanges(rect);
579 ranges = getRanges({ x: 0, y: y, width: win.innerWidth, height: 0 });
582 range = ranges.reduce(reduce);
585 range.collapse(!reverse);
586 sel.removeAllRanges();
589 if (visible(range).height > 0)
592 var { startContainer, startOffset } = range;
593 sel.modify("move", dir, "line");
594 range = sel.getRangeAt(0);
596 while (startContainer != range.startContainer || startOffset != range.startOffset);
598 sel.modify("move", reverse ? "forward" : "backward", "lineboundary");
603 sel.collapse(doc.body || doc.querySelector("body") || doc.documentElement,
608 * @property {nsISelection} The current document's normal selection.
610 get selection() this.win.getSelection(),
613 * @property {nsISelectionController} The current document's selection
616 get selectionController() util.selectionController(this.focusedFrame),
619 * @property {string|null} The canonical short URL for the current
623 let { uri, doc } = this;
625 for each (let shortener in Buffer.uriShorteners)
627 let shortened = shortener(uri, doc);
629 return shortened.spec;
635 let link = DOM("link[href][rev=canonical], \
636 link[href][rel=shortlink]", doc);
638 return link.attr("href");
644 * Opens the appropriate context menu for *elem*.
646 * @param {Node} elem The context element.
648 openContextMenu: deprecated("DOM#contextmenu", function openContextMenu(elem) DOM(elem).contextmenu()),
651 * Saves a page link to disk.
653 * @param {HTMLAnchorElement} elem The page link to save.
654 * @param {boolean} overwrite If true, overwrite any existing file.
656 saveLink: function saveLink(elem, overwrite) {
657 let { completion, dactyl, io } = this.modules;
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);
665 services.security.checkLoadURIWithPrincipal(doc.nodePrincipal, uri,
666 services.security.STANDARD);
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]);
674 util.assert(!file.exists() || overwrite, _("io.existsNoOverride", file.path));
678 file.create(File.NORMAL_FILE_TYPE, octal(644));
681 util.assert(false, _("save.invalidDestination", e.name));
684 self.saveURI({ uri: uri, file: file, context: elem });
687 completer: function (context) completion.savePage(context, elem)
696 * Saves the contents of a URI to disk.
698 * @param {nsIURI} uri The URI to save
699 * @param {nsIFile} file The file into which to write the result.
701 saveURI: function saveURI(params) {
702 if (params instanceof Ci.nsIURI)
704 params = { uri: arguments[0], file: arguments[1],
705 callback: arguments[2], self: arguments[3] };
707 var persist = services.Persist();
708 persist.persistFlags = persist.PERSIST_FLAGS_FROM_CACHE
709 | persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
711 let window = this.topWindow;
712 let privacy = sanitizer.getContext(params.context || this.win);
713 let file = File(params.file);
715 file.create(Ci.nsIFile.NORMAL_FILE_TYPE, octal(666));
717 let downloadListener = new window.DownloadListener(window,
718 services.Transfer(params.uri, file.URI, "", null, null, null,
719 persist, privacy && privacy.usePrivateBrowsing));
721 var { callback, self } = params;
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);
729 return onStateChange.superapply(this, arguments);
733 persist.progressListener = downloadListener;
735 persist.saveURI(params.uri, null, null, null, null,
740 * Scrolls the currently active element horizontally. See
741 * {@link Buffer.scrollHorizontal} for parameters.
743 scrollHorizontal: function scrollHorizontal(increment, number)
744 Buffer.scrollHorizontal(this.findScrollable(number, true), increment, number),
747 * Scrolls the currently active element vertically. See
748 * {@link Buffer.scrollVertical} for parameters.
750 scrollVertical: function scrollVertical(increment, number)
751 Buffer.scrollVertical(this.findScrollable(number, false), increment, number),
754 * Scrolls the currently active element to the given horizontal and
755 * vertical percentages. See {@link Buffer.scrollToPercent} for
758 scrollToPercent: function scrollToPercent(horizontal, vertical, dir)
759 Buffer.scrollToPercent(this.findScrollable(dir || 0, vertical == null), horizontal, vertical),
762 * Scrolls the currently active element to the given horizontal and
763 * vertical positions. See {@link Buffer.scrollToPosition} for
766 scrollToPosition: function scrollToPosition(horizontal, vertical)
767 Buffer.scrollToPosition(this.findScrollable(0, vertical == null), horizontal, vertical),
769 _scrollByScrollSize: function _scrollByScrollSize(count, direction) {
770 let { options } = this.modules;
773 options["scroll"] = count;
774 this.scrollByScrollSize(direction);
778 * Scrolls the buffer vertically 'scroll' lines.
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.
785 scrollByScrollSize: function scrollByScrollSize(direction, count) {
786 let { options } = this.modules;
788 direction = direction ? 1 : -1;
791 if (options["scroll"] > 0)
792 this.scrollVertical("lines", options["scroll"] * direction);
794 this.scrollVertical("pages", direction / 2);
798 * Find the best candidate scrollable element for the given
799 * direction and orientation.
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
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))
820 var elem = this.focusedFrame.document.activeElement;
821 if (elem == elem.ownerDocument.body)
827 var sel = this.focusedFrame.getSelection();
831 if (!elem && sel && sel.rangeCount)
832 elem = sel.getRangeAt(0).startContainer;
836 for (let e in DOM(Buffer.SCROLLABLE_SEARCH_SELECTOR,
837 this.focusedFrame.document)) {
838 if (Buffer.isScrollable(e, dir, horizontal)) {
840 let a = r.width * r.height;
848 util.trapErrors("focus", elem);
853 if (!(elem instanceof Ci.nsIDOMElement)) {
854 let doc = this.findScrollableWindow().document;
855 elem = find(doc.body || doc.getElementsByTagName("body")[0] ||
856 doc.documentElement);
858 let doc = this.focusedFrame.document;
859 return util.assert(elem || doc.body || doc.documentElement);
863 * Find the best candidate scrollable frame in the current buffer.
865 findScrollableWindow: function findScrollableWindow() {
866 let { document } = this.topWindow;
868 let win = document.commandDispatcher.focusedWindow;
869 if (win && (win.scrollMaxX > 0 || win.scrollMaxY > 0))
872 let win = this.focusedFrame;
873 if (win && (win.scrollMaxX > 0 || win.scrollMaxY > 0))
877 if (win.scrollMaxX > 0 || win.scrollMaxY > 0)
880 for (let frame in array.iterValues(win.frames))
881 if (frame.scrollMaxX > 0 || frame.scrollMaxY > 0)
888 * Finds the next visible element for the node path in 'jumptags'
891 * @param {string} arg The element in 'jumptags' to use for the search.
892 * @param {number} count The number of elements to jump.
894 * @param {boolean} reverse If true, search backwards. @optional
895 * @param {boolean} offScreen If true, include only off-screen elements. @optional
897 findJump: function findJump(arg, count, reverse, offScreen) {
898 let { marks, options } = this.modules;
904 let path = options["jumptags"][arg];
905 util.assert(path, _("error.invalidArgument", arg));
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]);
912 if (offScreen && !reverse)
913 elems = elems.filter(function (e) e[1] > this, this.topWindow.innerHeight);
915 let idx = Math.min((count || 1) - 1, elems.length);
916 util.assert(idx in elems);
918 let elem = elems[idx][0];
919 elem.scrollIntoView(true);
921 let sel = elem.ownerDocument.defaultView.getSelection();
922 sel.removeAllRanges();
923 sel.addRange(RangeFind.endpoint(RangeFind.nodeRange(elem), true));
926 // TODO: allow callback for filtering out unwanted frames? User defined?
928 * Shifts the focus to another frame within the buffer. Each buffer
929 * contains at least one frame.
931 * @param {number} count The number of frames to skip through. A negative
932 * count skips backwards.
934 shiftFrameFocus: function shiftFrameFocus(count) {
935 if (!(this.doc instanceof Ci.nsIDOMHTMLDocument))
938 let frames = this.allFrames();
940 if (frames.length == 0) // currently top is always included
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);
949 // find the currently focused frame index
950 let current = Math.max(0, frames.indexOf(this.focusedFrame));
952 // calculate the next frame to focus
953 let next = current + count;
954 if (next < 0 || next >= frames.length)
956 next = Math.constrain(next, 0, frames.length - 1);
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();
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);
968 util.timeout(function () { indicator.remove(); }, 500);
971 //doc.body.setAttributeNS(NS, "activeframe", "true");
972 //util.timeout(function () { doc.body.removeAttributeNS(NS, "activeframe"); }, 500);
975 // similar to pageInfo
976 // TODO: print more useful information, just like the DOM inspector
978 * Displays information about the specified element.
980 * @param {Node} elem The element to query.
982 showElementInfo: function showElementInfo(elem) {
983 let { dactyl } = this.modules;
985 dactyl.echo(["", /*L*/"Element:", ["br"], util.objectToString(elem, true)]);
989 * Displays information about the current buffer.
991 * @param {boolean} verbose Display more verbose information.
992 * @param {string} sections A string limiting the displayed sections.
993 * @default The value of 'pageinfo'.
995 showPageInfo: function showPageInfo(verbose, sections) {
996 let { commandline, dactyl, options } = this.modules;
998 // Ctrl-g single line output
1000 let file = this.win.location.pathname.split("/").pop() || _("buffer.noName");
1001 let title = this.win.document.title || _("buffer.noTitle");
1003 let info = template.map(
1004 (sections || options["pageinfo"])
1005 .map((opt) => Buffer.pageInfo[opt].action.call(this)),
1006 function (res) res && iter(res).join(", ") || undefined,
1009 if (bookmarkcache.isBookmarked(this.URL))
1010 info += ", " + _("buffer.bookmarked");
1012 let pageInfoText = [file.quote(), " [", info, "] ", title].join("");
1013 dactyl.echo(pageInfoText, commandline.FORCE_SINGLELINE);
1017 let list = template.map(sections || options["pageinfo"], (option) => {
1018 let { action, title } = Buffer.pageInfo[option];
1019 return template.table(title, action.call(this, true));
1022 commandline.commandOutput(list);
1026 * Stops loading and animations in the current content.
1028 stop: function stop() {
1029 let { config } = this.modules;
1034 this.docShell.stop(this.docShell.STOP_ALL);
1038 * Opens a viewer to inspect the source of the currently selected
1041 viewSelectionSource: function viewSelectionSource() {
1042 // copied (and tuned somewhat) from browser.jar -> nsContextMenu.js
1043 let { document, window } = this.topWindow;
1045 let win = document.commandDispatcher.focusedWindow;
1046 if (win == this.topWindow)
1047 win = this.focusedFrame;
1049 let charset = win ? "charset=" + win.document.characterSet : null;
1051 window.openDialog("chrome://global/content/viewPartialSource.xul",
1052 "_blank", "scrollbars,resizable,chrome,dialog=no",
1053 null, charset, win.getSelection(), "selection");
1057 * Opens a viewer to inspect the source of the current buffer or the
1058 * specified *url*. Either the default viewer or the configured external
1061 * @param {string|object|null} loc If a string, the URL of the source,
1062 * otherwise an object with some or all of the following properties:
1064 * url: The URL to view.
1065 * doc: The document to view.
1066 * line: The line to select.
1067 * column: The column to select.
1069 * If no URL is provided, the current document is used.
1070 * @default The current buffer.
1071 * @param {boolean} useExternalEditor View the source in the external editor.
1073 viewSource: function viewSource(loc, useExternalEditor) {
1074 let { dactyl, editor, history, options } = this.modules;
1076 let window = this.topWindow;
1078 let doc = this.focusedFrame.document;
1080 if (isObject(loc)) {
1081 if (options.get("editor").has("line") || !loc.url)
1082 this.viewSourceExternally(loc.doc || loc.url || doc, loc);
1084 window.openDialog("chrome://global/content/viewSource.xul",
1085 "_blank", "all,dialog=no",
1086 loc.url, null, null, loc.line);
1089 if (useExternalEditor)
1090 this.viewSourceExternally(loc || doc);
1092 let url = loc || doc.location.href;
1093 const PREFIX = "view-source:";
1094 if (url.indexOf(PREFIX) == 0)
1095 url = url.substr(PREFIX.length);
1099 let sh = history.session;
1100 if (sh[sh.index].URI.spec == url)
1101 this.docShell.gotoIndex(sh.index);
1103 dactyl.open(url, { hide: true });
1109 * Launches an editor to view the source of the given document. The
1110 * contents of the document are saved to a temporary local file and
1111 * removed when the editor returns. This function returns
1114 * @param {Document} doc The document to view.
1115 * @param {function|object} callback If a function, the callback to be
1116 * called with two arguments: the nsIFile of the file, and temp, a
1117 * boolean which is true if the file is temporary. Otherwise, an object
1118 * with line and column properties used to determine where to open the
1122 viewSourceExternally: Class("viewSourceExternally",
1123 XPCOM([Ci.nsIWebProgressListener, Ci.nsISupportsWeakReference]), {
1124 init: function init(doc, callback) {
1125 this.callback = callable(callback) ? callback :
1126 function (file, temp) {
1127 let { editor } = overlay.activeModules;
1129 editor.editFileExternally(update({ file: file.path }, callback || {}),
1130 function () { temp && file.remove(false); });
1134 if (isString(doc)) {
1135 var privacyContext = null;
1136 var uri = util.newURI(doc);
1139 privacyContext = sanitizer.getContext(doc);
1140 uri = util.newURI(doc.location.href);
1143 let ext = uri.fileExtension || "txt";
1144 if (doc.contentType)
1146 ext = services.mime.getPrimaryExtension(doc.contentType, ext);
1151 return io.withTempFiles(function (temp) {
1152 let encoder = services.HtmlEncoder();
1153 encoder.init(doc, "text/unicode", encoder.OutputRaw|encoder.OutputPreformatted);
1154 temp.write(encoder.encodeToString(), ">");
1155 return this.callback(temp, true);
1156 }, this, true, ext);
1158 let file = util.getFile(uri);
1160 this.callback(file, false);
1162 this.file = io.createTempFile();
1163 var persist = services.Persist();
1164 persist.persistFlags = persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
1165 persist.progressListener = this;
1166 persist.saveURI(uri, null, null, null, null, this.file,
1172 onStateChange: function onStateChange(progress, request, flags, status) {
1173 if ((flags & this.STATE_STOP) && status == 0) {
1175 var ok = this.callback(this.file, true);
1179 this.file.remove(false);
1187 * Increases the zoom level of the current buffer.
1189 * @param {number} steps The number of zoom levels to jump.
1190 * @param {boolean} fullZoom Whether to use full zoom or text zoom.
1192 zoomIn: function zoomIn(steps, fullZoom) {
1193 this.bumpZoomLevel(steps, fullZoom);
1197 * Decreases the zoom level of the current buffer.
1199 * @param {number} steps The number of zoom levels to jump.
1200 * @param {boolean} fullZoom Whether to use full zoom or text zoom.
1202 zoomOut: function zoomOut(steps, fullZoom) {
1203 this.bumpZoomLevel(-steps, fullZoom);
1207 * Adjusts the page zoom of the current buffer to the given absolute
1210 * @param {number} value The new zoom value as a possibly fractional
1211 * percentage of the page's natural size.
1212 * @param {boolean} fullZoom If true, zoom all content of the page,
1213 * including raster images. If false, zoom only text. If omitted,
1214 * use the current zoom function. @optional
1215 * @throws {FailedAssertion} if the given *value* is not within the
1216 * closed range [Buffer.ZOOM_MIN, Buffer.ZOOM_MAX].
1218 setZoom: function setZoom(value, fullZoom) {
1219 let { dactyl, statusline, storage } = this.modules;
1220 let { ZoomManager } = this;
1222 if (fullZoom === undefined)
1223 fullZoom = ZoomManager.useFullZoom;
1225 ZoomManager.useFullZoom = fullZoom;
1229 this.contentViewer.textZoom = fullZoom ? 1 : value;
1230 this.contentViewer.fullZoom = !fullZoom ? 1 : value;
1232 catch (e if e == Cr.NS_ERROR_ILLEGAL_VALUE) {
1233 return dactyl.echoerr(_("zoom.illegal"));
1236 if (prefs.get("browser.zoom.siteSpecific")) {
1237 var privacy = sanitizer.getContext(this.win);
1239 this.clearPref("browser.content.full-zoom");
1240 this.clearPref("dactyl.content.full-zoom");
1243 this.setPref("browser.content.full-zoom", value);
1244 this.setPref("dactyl.content.full-zoom", fullZoom);
1248 statusline.updateZoomLevel();
1252 * Updates the zoom level of this buffer from a content preference.
1254 updateZoom: util.wrapCallback(function updateZoom() {
1257 if (prefs.get("browser.zoom.siteSpecific")) {
1258 this.getPref("dactyl.content.full-zoom", (val) => {
1259 if (val != null && uri.equals(this.uri) && val != prefs.get("browser.zoom.full"))
1260 [this.contentViewer.textZoom, this.contentViewer.fullZoom] =
1261 [this.contentViewer.fullZoom, this.contentViewer.textZoom];
1267 * Adjusts the page zoom of the current buffer relative to the
1268 * current zoom level.
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.
1279 bumpZoomLevel: function bumpZoomLevel(steps, fullZoom) {
1280 let { ZoomManager } = this;
1282 if (fullZoom === undefined)
1283 fullZoom = ZoomManager.useFullZoom;
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);
1289 util.assert(i != cur || fullZoom != ZoomManager.useFullZoom);
1291 this.setZoom(Math.round(values[i] * 100), fullZoom);
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)
1305 * The pattern used to search for a scrollable element when we have
1306 * no starting point.
1308 SCROLLABLE_SEARCH_SELECTOR: "html, body, div",
1310 PageInfo: Struct("PageInfo", "name", "title", "action")
1316 * Adds a new section to the page information output.
1318 * @param {string} option The section's value in 'pageinfo'.
1319 * @param {string} title The heading for this section's
1321 * @param {function} func The function to generate this
1324 addPageInfoSection: function addPageInfoSection(option, title, func) {
1325 this.pageInfo[option] = Buffer.PageInfo(option, title, func);
1331 * Adds a new URI shortener for documents matching the given filter.
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.
1339 addURIShortener: function addURIShortener(filter, shortener) {
1340 if (isString(filter))
1341 filter = Group.compileFilter(filter);
1343 this.uriShorteners.push(function uriShortener(uri, doc) {
1344 if (filter(uri, doc))
1345 return shortener(uri, doc);
1349 Scrollable: function Scrollable(elem) {
1350 if (elem instanceof Ci.nsIDOMElement)
1352 if (isinstance(elem, [Ci.nsIDOMWindow, Ci.nsIDOMDocument]))
1354 __proto__: elem.documentElement || elem.ownerDocument.documentElement,
1356 win: elem.defaultView || elem.ownerDocument.defaultView,
1358 get clientWidth() this.win.innerWidth,
1359 get clientHeight() this.win.innerHeight,
1361 get scrollWidth() this.win.scrollMaxX + this.win.innerWidth,
1362 get scrollHeight() this.win.scrollMaxY + this.win.innerHeight,
1364 get scrollLeftMax() this.win.scrollMaxX,
1365 get scrollRightMax() this.win.scrollMaxY,
1367 get scrollLeft() this.win.scrollX,
1368 set scrollLeft(val) { this.win.scrollTo(val, this.win.scrollY); },
1370 get scrollTop() this.win.scrollY,
1371 set scrollTop(val) { this.win.scrollTo(this.win.scrollX, val); }
1376 get ZOOM_MIN() prefs.get("zoom.minPercent"),
1377 get ZOOM_MAX() prefs.get("zoom.maxPercent"),
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)),
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.
1390 currentWord: function currentWord(win, select) {
1391 let { Editor, options } = Buffer(win).modules;
1393 let selection = win.getSelection();
1394 if (selection.rangeCount == 0)
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);
1404 selection.removeAllRanges();
1405 selection.addRange(range);
1407 return DOM.stringify(range);
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();
1415 if (isinstance(node, [Ci.nsIDOMDocument,
1416 Ci.nsIDOMHTMLImageElement])) {
1417 let type = node.contentType || node.QueryInterface(Ci.nsIImageLoadingContent)
1418 .getRequest(0).mimeType;
1420 if (type === "text/plain")
1421 ext = "." + (currExt || "txt");
1423 ext = "." + services.mime.getPrimaryExtension(type, currExt);
1426 ext = "." + currExt;
1428 let re = ext ? RegExp("(\\." + currExt + ")?$", "i") : /$/;
1432 names.push([node.title,
1433 _("buffer.save.pageName")]);
1436 names.push([node.alt,
1437 _("buffer.save.altText")]);
1439 if (!isinstance(node, Ci.nsIDOMDocument) && node.textContent)
1440 names.push([node.textContent,
1441 _("buffer.save.linkText")]);
1443 names.push([decodeURIComponent(url.replace(/.*?([^\/]*)\/*$/, "$1")),
1444 _("buffer.save.filename")]);
1446 return names.filter(function ([leaf, title]) leaf)
1447 .map(function ([leaf, title]) [leaf.replace(config.OS.illegalCharacters, encodeURIComponent)
1448 .replace(re, ext), title]);
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)),
1456 isScrollable: function isScrollable(elem, dir, horizontal) {
1457 if (!DOM(elem).isScrollable(horizontal ? "horizontal" : "vertical"))
1460 return this.canScroll(elem, dir, horizontal);
1463 canScroll: function canScroll(elem, dir, horizontal) {
1464 let pos = "scrollTop", size = "clientHeight", end = "scrollHeight", layoutSize = "offsetHeight",
1465 overflow = "overflowX", border1 = "borderTopWidth", border2 = "borderBottomWidth";
1467 pos = "scrollLeft", size = "clientWidth", end = "scrollWidth", layoutSize = "offsetWidth",
1468 overflow = "overflowX", border1 = "borderLeftWidth", border2 = "borderRightWidth";
1471 return elem[pos] > 0;
1473 let max = pos + "Max";
1475 if (elem[pos] < elem[max])
1479 return elem[pos] > 0;
1482 let style = DOM(elem).style;
1483 let borderSize = Math.round(parseFloat(style[border1]) + parseFloat(style[border2]));
1484 let realSize = elem[size];
1486 // Stupid Gecko eccentricities. May fail for quirks mode documents.
1487 if (elem[size] + borderSize >= elem[end] || elem[size] == 0) // Stupid, fallible heuristic.
1490 if (style[overflow] == "hidden")
1491 realSize += borderSize;
1492 return dir > 0 && elem[pos] + realSize < elem[end] || !dir && realSize < elem[end];
1496 * Scroll the contents of the given element to the absolute *left*
1497 * and *top* pixel offsets.
1499 * @param {Element} elem The element to scroll.
1500 * @param {number|null} left The left absolute pixel offset. If
1501 * null, to not alter the horizontal scroll offset.
1502 * @param {number|null} top The top absolute pixel offset. If
1503 * null, to not alter the vertical scroll offset.
1504 * @param {string} reason The reason for the scroll event. See
1505 * {@link marks.push}. @optional
1507 scrollTo: function scrollTo(elem, left, top, reason) {
1508 let doc = elem.ownerDocument || elem.document || elem;
1510 let { buffer, marks, options } = util.topWindow(doc.defaultView).dactyl.modules;
1512 if (~[elem, elem.document, elem.ownerDocument].indexOf(buffer.focusedFrame.document))
1515 if (options["scrollsteps"] > 1)
1516 return this.smoothScrollTo(elem, left, top);
1518 elem = Buffer.Scrollable(elem);
1520 elem.scrollLeft = left;
1522 elem.scrollTop = top;
1526 * Like scrollTo, but scrolls more smoothly and does not update
1529 smoothScrollTo: function smoothScrollTo(node, x, y) {
1530 let { options } = overlay.activeModules;
1532 let time = options["scrolltime"];
1533 let steps = options["scrollsteps"];
1535 let elem = Buffer.Scrollable(node);
1537 if (node.dactylScrollTimer)
1538 node.dactylScrollTimer.cancel();
1541 x = elem.scrollLeft;
1545 x = node.dactylScrollDestX = Math.min(x, elem.scrollWidth - elem.clientWidth);
1546 y = node.dactylScrollDestY = Math.min(y, elem.scrollHeight - elem.clientHeight);
1547 let [startX, startY] = [elem.scrollLeft, elem.scrollTop];
1550 if (n++ === steps) {
1551 elem.scrollLeft = x;
1553 delete node.dactylScrollDestX;
1554 delete node.dactylScrollDestY;
1557 elem.scrollLeft = startX + (x - startX) / steps * n;
1558 elem.scrollTop = startY + (y - startY) / steps * n;
1559 node.dactylScrollTimer = util.timeout(next, time / steps);
1565 * Scrolls the currently given element horizontally.
1567 * @param {Element} elem The element to scroll.
1568 * @param {string} unit The increment by which to scroll.
1569 * Possible values are: "columns", "pages"
1570 * @param {number} number The possibly fractional number of
1571 * increments to scroll. Positive values scroll to the right while
1572 * negative values scroll to the left.
1573 * @throws {FailedAssertion} if scrolling is not possible in the
1576 scrollHorizontal: function scrollHorizontal(node, unit, number) {
1577 let fontSize = parseInt(DOM(node).style.fontSize);
1579 let elem = Buffer.Scrollable(node);
1581 if (unit == "columns")
1582 increment = fontSize; // Good enough, I suppose.
1583 else if (unit == "pages")
1584 increment = elem.clientWidth - fontSize;
1588 util.assert(number < 0 ? elem.scrollLeft > 0 : elem.scrollLeft < elem.scrollWidth - elem.clientWidth);
1590 let left = node.dactylScrollDestX !== undefined ? node.dactylScrollDestX : elem.scrollLeft;
1591 node.dactylScrollDestX = undefined;
1593 Buffer.scrollTo(node, left + number * increment, null, "h-" + unit);
1597 * Scrolls the given element vertically.
1599 * @param {Node} node The node to scroll.
1600 * @param {string} unit The increment by which to scroll.
1601 * Possible values are: "lines", "pages"
1602 * @param {number} number The possibly fractional number of
1603 * increments to scroll. Positive values scroll upward while
1604 * negative values scroll downward.
1605 * @throws {FailedAssertion} if scrolling is not possible in the
1608 scrollVertical: function scrollVertical(node, unit, number) {
1609 let fontSize = parseInt(DOM(node).style.lineHeight);
1611 let elem = Buffer.Scrollable(node);
1613 if (unit == "lines")
1614 increment = fontSize;
1615 else if (unit == "pages")
1616 increment = elem.clientHeight - fontSize;
1620 util.assert(number < 0 ? elem.scrollTop > 0 : elem.scrollTop < elem.scrollHeight - elem.clientHeight);
1622 let top = node.dactylScrollDestY !== undefined ? node.dactylScrollDestY : elem.scrollTop;
1623 node.dactylScrollDestY = undefined;
1625 Buffer.scrollTo(node, null, top + number * increment, "v-" + unit);
1629 * Scrolls the currently active element to the given horizontal and
1630 * vertical percentages.
1632 * @param {Element} elem The element to scroll.
1633 * @param {number|null} horizontal The possibly fractional
1634 * percentage of the current viewport width to scroll to. If null,
1635 * do not scroll horizontally.
1636 * @param {number|null} vertical The possibly fractional percentage
1637 * of the current viewport height to scroll to. If null, do not
1638 * scroll vertically.
1640 scrollToPercent: function scrollToPercent(node, horizontal, vertical) {
1641 let elem = Buffer.Scrollable(node);
1642 Buffer.scrollTo(node,
1643 horizontal == null ? null
1644 : (elem.scrollWidth - elem.clientWidth) * (horizontal / 100),
1645 vertical == null ? null
1646 : (elem.scrollHeight - elem.clientHeight) * (vertical / 100));
1650 * Scrolls the currently active element to the given horizontal and
1651 * vertical position.
1653 * @param {Element} elem The element to scroll.
1654 * @param {number|null} horizontal The possibly fractional
1655 * line ordinal to scroll to.
1656 * @param {number|null} vertical The possibly fractional
1657 * column ordinal to scroll to.
1659 scrollToPosition: function scrollToPosition(elem, horizontal, vertical) {
1660 let style = DOM(elem.body || elem).style;
1661 Buffer.scrollTo(elem,
1662 horizontal == null ? null :
1663 horizontal == 0 ? 0 : this._exWidth(elem) * horizontal,
1664 vertical == null ? null : parseFloat(style.lineHeight) * vertical);
1668 * Returns the current scroll position as understood by
1669 * {@link #scrollToPosition}.
1671 * @param {Element} elem The element to scroll.
1673 getScrollPosition: function getPosition(node) {
1674 let style = DOM(node.body || node).style;
1676 let elem = Buffer.Scrollable(node);
1678 x: elem.scrollLeft && elem.scrollLeft / this._exWidth(node),
1679 y: elem.scrollTop / parseFloat(style.lineHeight)
1683 _exWidth: function _exWidth(elem) {
1685 let div = DOM(["elem", { style: "width: 1ex !important; position: absolute !important; padding: 0 !important; display: block;" }],
1686 elem.ownerDocument).appendTo(elem.body || elem);
1688 return parseFloat(div.style.width);
1695 return parseFloat(DOM(elem).fontSize) / 1.618;
1699 openUploadPrompt: function openUploadPrompt(elem) {
1700 let { io } = overlay.activeModules;
1702 io.CommandFileMode(_("buffer.prompt.uploadFile") + " ", {
1703 onSubmit: function onSubmit(path) {
1704 let file = io.File(path);
1705 util.assert(file.exists());
1707 DOM(elem).val(file.path).change();
1709 }).open(elem.value);
1712 init: function init(dactyl, modules, window) {
1713 init.superapply(this, arguments);
1715 dactyl.commands["buffer.viewSource"] = function (event) {
1716 let elem = event.originalTarget;
1717 let obj = { url: elem.getAttribute("href"), line: Number(elem.getAttribute("line")) };
1718 if (elem.hasAttribute("column"))
1719 obj.column = elem.getAttribute("column");
1721 modules.buffer.viewSource(obj);
1724 commands: function initCommands(dactyl, modules, window) {
1725 let { buffer, commands, config, options } = modules;
1727 commands.add(["frameo[nly]"],
1728 "Show only the current frame's page",
1730 dactyl.open(buffer.focusedFrame.location.href);
1734 commands.add(["ha[rdcopy]"],
1735 "Print current document",
1739 // FIXME: arg handling is a bit of a mess, check for filename
1740 dactyl.assert(!arg || arg[0] == ">" && !config.OS.isWindows,
1741 _("error.trailingCharacters"));
1743 const PRINTER = "PostScript/default";
1744 const BRANCH = "printer_" + PRINTER + ".";
1745 const BRANCHES = ["print.", BRANCH, "print." + BRANCH];
1746 function set(pref, value) {
1747 BRANCHES.forEach(function (branch) { prefs.set(branch + pref, value); });
1750 prefs.withContext(function () {
1752 prefs.set("print.print_printer", PRINTER);
1754 set("print_to_file", true);
1755 set("print_to_filename", io.File(arg.substr(1)).path);
1757 dactyl.echomsg(_("print.toFile", arg.substr(1)));
1760 dactyl.echomsg(_("print.sending"));
1762 prefs.set("print.always_print_silent", args.bang);
1764 prefs.set("print.show_print_progress", !args.bang);
1766 config.browser.contentWindow.print();
1769 dactyl.echomsg(_("print.sent"));
1774 completer: function (context, args) {
1775 if (args.bang && /^>/.test(context.filter))
1776 context.fork("file", 1, modules.completion, "file");
1781 commands.add(["pa[geinfo]"],
1782 "Show various page information",
1785 let opt = options.get("pageinfo");
1787 dactyl.assert(!arg || opt.validator(opt.parse(arg)),
1788 _("error.invalidArgument", arg));
1789 buffer.showPageInfo(true, arg);
1793 completer: function (context) {
1794 modules.completion.optionValue(context, "pageinfo", "+", "");
1795 context.title = ["Page Info"];
1799 commands.add(["pagest[yle]", "pas"],
1800 "Select the author style sheet to apply",
1802 let arg = args[0] || "";
1804 let titles = buffer.alternateStyleSheets.map(function (stylesheet) stylesheet.title);
1806 dactyl.assert(!arg || titles.indexOf(arg) >= 0,
1807 _("error.invalidArgument", arg));
1809 if (options["usermode"])
1810 options["usermode"] = false;
1812 window.stylesheetSwitchAll(buffer.focusedFrame, arg);
1816 completer: function (context) modules.completion.alternateStyleSheet(context),
1820 commands.add(["re[load]"],
1821 "Reload the current web page",
1822 function (args) { modules.tabs.reload(config.browser.mCurrentTab, args.bang); },
1828 // TODO: we're prompted if download.useDownloadDir isn't set and no arg specified - intentional?
1829 commands.add(["sav[eas]", "w[rite]"],
1830 "Save current document to disk",
1832 let { commandline, io } = modules;
1833 let { doc, win } = buffer;
1835 let chosenData = null;
1836 let filename = args[0];
1838 let command = commandline.command;
1840 if (filename[0] == "!")
1841 return buffer.viewSourceExternally(buffer.focusedFrame.document,
1843 let output = io.system(filename.substr(1), file);
1844 commandline.command = command;
1845 commandline.commandOutput(["span", { highlight: "CmdOutput" }, output]);
1848 if (/^>>/.test(filename)) {
1849 let file = io.File(filename.replace(/^>>\s*/, ""));
1850 dactyl.assert(args.bang || file.exists() && file.isWritable(),
1851 _("io.notWriteable", file.path.quote()));
1853 return buffer.viewSourceExternally(buffer.focusedFrame.document,
1854 function (tmpFile) {
1856 file.write(tmpFile, ">>");
1859 dactyl.echoerr(_("io.notWriteable", file.path.quote()));
1864 let file = io.File(filename);
1866 if (filename.substr(-1) === File.PATH_SEP || file.exists() && file.isDirectory())
1867 file.append(Buffer.getDefaultNames(doc)[0][0]);
1869 dactyl.assert(args.bang || !file.exists(), _("io.exists"));
1871 chosenData = { file: file.file, uri: util.newURI(doc.location.href) };
1874 // if browser.download.useDownloadDir = false then the "Save As"
1875 // dialog is used with this as the default directory
1876 // TODO: if we're going to do this shouldn't it be done in setCWD or the value restored?
1877 prefs.set("browser.download.lastDir", io.cwd.path);
1880 var contentDisposition = win.QueryInterface(Ci.nsIInterfaceRequestor)
1881 .getInterface(Ci.nsIDOMWindowUtils)
1882 .getDocumentMetadata("content-disposition");
1886 window.internalSave(doc.location.href, doc, null, contentDisposition,
1887 doc.contentType, false, null, chosenData,
1888 doc.referrer ? window.makeURI(doc.referrer) : null,
1894 completer: function (context) {
1895 let { buffer, completion } = modules;
1897 if (context.filter[0] == "!")
1899 if (/^>>/.test(context.filter))
1900 context.advance(/^>>\s*/.exec(context.filter)[0].length);
1902 completion.savePage(context, buffer.doc);
1903 context.fork("file", 0, completion, "file");
1908 commands.add(["st[op]"],
1909 "Stop loading the current web page",
1910 function () { buffer.stop(); },
1913 commands.add(["vie[wsource]"],
1914 "View source code of current document",
1915 function (args) { buffer.viewSource(args[0], args.bang); },
1919 completer: function (context) modules.completion.url(context, "bhf")
1922 commands.add(["zo[om]"],
1923 "Set zoom value of current web page",
1930 else if (/^\d+$/.test(arg))
1931 level = parseInt(arg, 10);
1932 else if (/^[+-]\d+$/.test(arg))
1933 level = Math.round(buffer.zoomLevel + parseInt(arg, 10));
1935 dactyl.assert(false, _("error.trailingCharacters"));
1937 buffer.setZoom(level, args.bang);
1944 completion: function initCompletion(dactyl, modules, window) {
1945 let { CompletionContext, buffer, completion } = modules;
1947 completion.alternateStyleSheet = function alternateStylesheet(context) {
1948 context.title = ["Stylesheet", "Location"];
1950 // unify split style sheets
1951 let styles = iter([s.title, []] for (s in values(buffer.alternateStyleSheets))).toObject();
1953 buffer.alternateStyleSheets.forEach(function (style) {
1954 styles[style.title].push(style.href || _("style.inline"));
1957 context.completions = [[title, href.join(", ")] for ([title, href] in Iterator(styles))];
1960 completion.savePage = function savePage(context, node) {
1961 context.fork("generated", context.filter.replace(/[^/]*$/, "").length,
1962 this, function (context) {
1963 context.generate = function () {
1964 this.incomplete = true;
1965 this.completions = Buffer.getDefaultNames(node);
1966 util.httpGet(node.href || node.src || node.documentURI, {
1968 callback: function callback(xhr) {
1969 context.incomplete = false;
1971 if (/filename="(.*?)"/.test(xhr.getResponseHeader("Content-Disposition")))
1972 context.completions.push([decodeURIComponent(RegExp.$1),
1973 _("buffer.save.suggested")]);
1976 context.completions = context.completions.slice();
1979 notificationCallbacks: Class(XPCOM([Ci.nsIChannelEventSink, Ci.nsIInterfaceRequestor]), {
1980 getInterface: function getInterface(iid) this.QueryInterface(iid),
1982 asyncOnChannelRedirect: function (oldChannel, newChannel, flags, callback) {
1983 if (newChannel instanceof Ci.nsIHttpChannel)
1984 newChannel.requestMethod = "HEAD";
1985 callback.onRedirectVerifyCallback(Cr.NS_OK);
1993 events: function initEvents(dactyl, modules, window) {
1994 let { buffer, config, events } = modules;
1996 events.listen(config.browser, "scroll", buffer.closure._updateBufferPosition, false);
1998 mappings: function initMappings(dactyl, modules, window) {
1999 let { Editor, Events, buffer, editor, events, ex, mappings, modes, options, tabs } = modules;
2001 mappings.add([modes.NORMAL],
2002 ["y", "<yank-location>"], "Yank current location to the clipboard",
2004 let { doc, uri } = buffer;
2005 if (uri instanceof Ci.nsIURL)
2006 uri.query = uri.query.replace(/(?:^|&)utm_[^&]+/g, "")
2009 let url = options.get("yankshort").getKey(uri) && buffer.shortURL || uri.spec;
2010 dactyl.clipboardWrite(url, true);
2013 mappings.add([modes.NORMAL],
2014 ["<C-a>", "<increment-url-path>"], "Increment last number in URL",
2015 function ({ count }) { buffer.incrementURL(Math.max(count, 1)); },
2018 mappings.add([modes.NORMAL],
2019 ["<C-x>", "<decrement-url-path>"], "Decrement last number in URL",
2020 function ({ count }) { buffer.incrementURL(-Math.max(count, 1)); },
2023 mappings.add([modes.NORMAL], ["gu", "<open-parent-path>"],
2024 "Go to parent directory",
2025 function ({ count }) { buffer.climbUrlPath(Math.max(count, 1)); },
2028 mappings.add([modes.NORMAL], ["gU", "<open-root-path>"],
2029 "Go to the root of the website",
2030 function () { buffer.climbUrlPath(-1); });
2032 mappings.add([modes.COMMAND], [".", "<repeat-key>"],
2033 "Repeat the last key event",
2034 function ({ count }) {
2035 if (mappings.repeat) {
2036 for (let i in util.interruptibleRange(0, Math.max(count, 1), 100))
2042 mappings.add([modes.NORMAL], ["i", "<Insert>"],
2044 function () { modes.push(modes.CARET); });
2046 mappings.add([modes.NORMAL], ["<C-c>", "<stop-load>"],
2047 "Stop loading the current web page",
2048 function () { ex.stop(); });
2051 mappings.add([modes.NORMAL], ["j", "<Down>", "<C-e>", "<scroll-down-line>"],
2052 "Scroll document down",
2053 function ({ count }) { buffer.scrollVertical("lines", Math.max(count, 1)); },
2056 mappings.add([modes.NORMAL], ["k", "<Up>", "<C-y>", "<scroll-up-line>"],
2057 "Scroll document up",
2058 function ({ count }) { buffer.scrollVertical("lines", -Math.max(count, 1)); },
2061 mappings.add([modes.NORMAL], dactyl.has("mail") ? ["h", "<scroll-left-column>"] : ["h", "<Left>", "<scroll-left-column>"],
2062 "Scroll document to the left",
2063 function ({ count }) { buffer.scrollHorizontal("columns", -Math.max(count, 1)); },
2066 mappings.add([modes.NORMAL], dactyl.has("mail") ? ["l", "<scroll-right-column>"] : ["l", "<Right>", "<scroll-right-column>"],
2067 "Scroll document to the right",
2068 function ({ count }) { buffer.scrollHorizontal("columns", Math.max(count, 1)); },
2071 mappings.add([modes.NORMAL], ["0", "^", "<scroll-begin>"],
2072 "Scroll to the absolute left of the document",
2073 function () { buffer.scrollToPercent(0, null); });
2075 mappings.add([modes.NORMAL], ["$", "<scroll-end>"],
2076 "Scroll to the absolute right of the document",
2077 function () { buffer.scrollToPercent(100, null); });
2079 mappings.add([modes.NORMAL], ["gg", "<Home>", "<scroll-top>"],
2080 "Go to the top of the document",
2081 function ({ count }) { buffer.scrollToPercent(null, count != null ? count : 0,
2082 count != null ? 0 : -1); },
2085 mappings.add([modes.NORMAL], ["G", "<End>", "<scroll-bottom>"],
2086 "Go to the end of the document",
2087 function ({ count }) {
2089 var elem = options.get("linenumbers")
2090 .getLine(buffer.focusedFrame.document,
2093 elem.scrollIntoView(true);
2095 buffer.scrollToPosition(null, count);
2097 buffer.scrollToPercent(null, 100, 1);
2101 mappings.add([modes.NORMAL], ["%", "<scroll-percent>"],
2102 "Scroll to {count} percent of the document",
2103 function ({ count }) {
2104 dactyl.assert(count > 0 && count <= 100);
2105 buffer.scrollToPercent(null, count);
2109 mappings.add([modes.NORMAL], ["<C-d>", "<scroll-down>"],
2110 "Scroll window downwards in the buffer",
2111 function ({ count }) { buffer._scrollByScrollSize(count, true); },
2114 mappings.add([modes.NORMAL], ["<C-u>", "<scroll-up>"],
2115 "Scroll window upwards in the buffer",
2116 function ({ count }) { buffer._scrollByScrollSize(count, false); },
2119 mappings.add([modes.NORMAL], ["<C-b>", "<PageUp>", "<S-Space>", "<scroll-up-page>"],
2120 "Scroll up a full page",
2121 function ({ count }) { buffer.scrollVertical("pages", -Math.max(count, 1)); },
2124 mappings.add([modes.NORMAL], ["<Space>"],
2125 "Scroll down a full page",
2126 function ({ count }) {
2127 if (isinstance((services.focus.focusedWindow || buffer.win).document.activeElement,
2128 [Ci.nsIDOMHTMLInputElement,
2129 Ci.nsIDOMHTMLButtonElement,
2130 Ci.nsIDOMXULButtonElement]))
2133 buffer.scrollVertical("pages", Math.max(count, 1));
2137 mappings.add([modes.NORMAL], ["<C-f>", "<PageDown>", "<scroll-down-page>"],
2138 "Scroll down a full page",
2139 function ({ count }) { buffer.scrollVertical("pages", Math.max(count, 1)); },
2142 mappings.add([modes.NORMAL], ["]f", "<previous-frame>"],
2144 function ({ count }) { buffer.shiftFrameFocus(Math.max(count, 1)); },
2147 mappings.add([modes.NORMAL], ["[f", "<next-frame>"],
2148 "Focus previous frame",
2149 function ({ count }) { buffer.shiftFrameFocus(-Math.max(count, 1)); },
2152 mappings.add([modes.NORMAL], ["["],
2153 "Jump to the previous element as defined by 'jumptags'",
2154 function ({ arg, count }) { buffer.findJump(arg, count, true); },
2155 { arg: true, count: true });
2157 mappings.add([modes.NORMAL], ["g]"],
2158 "Jump to the next off-screen element as defined by 'jumptags'",
2159 function ({ arg, count }) { buffer.findJump(arg, count, false, true); },
2160 { arg: true, count: true });
2162 mappings.add([modes.NORMAL], ["]"],
2163 "Jump to the next element as defined by 'jumptags'",
2164 function ({ arg, count }) { buffer.findJump(arg, count, false); },
2165 { arg: true, count: true });
2167 mappings.add([modes.NORMAL], ["{"],
2168 "Jump to the previous paragraph",
2169 function ({ count }) { buffer.findJump("p", count, true); },
2172 mappings.add([modes.NORMAL], ["}"],
2173 "Jump to the next paragraph",
2174 function ({ count }) { buffer.findJump("p", count, false); },
2177 mappings.add([modes.NORMAL], ["]]", "<next-page>"],
2178 "Follow the link labeled 'next' or '>' if it exists",
2179 function ({ count }) {
2180 buffer.findLink("next", options["nextpattern"], (count || 1) - 1, true);
2184 mappings.add([modes.NORMAL], ["[[", "<previous-page>"],
2185 "Follow the link labeled 'prev', 'previous' or '<' if it exists",
2186 function ({ count }) {
2187 buffer.findLink("prev", options["previouspattern"], (count || 1) - 1, true);
2191 mappings.add([modes.NORMAL], ["gf", "<view-source>"],
2192 "Toggle between rendered and source view",
2193 function () { buffer.viewSource(null, false); });
2195 mappings.add([modes.NORMAL], ["gF", "<view-source-externally>"],
2196 "View source with an external editor",
2197 function () { buffer.viewSource(null, true); });
2199 mappings.add([modes.NORMAL], ["gi", "<focus-input>"],
2200 "Focus last used input field",
2201 function ({ count }) {
2202 let elem = buffer.lastInputField;
2204 if (count >= 1 || !elem || !events.isContentNode(elem)) {
2205 let xpath = ["frame", "iframe", "input", "xul:textbox", "textarea[not(@disabled) and not(@readonly)]"];
2207 let frames = buffer.allFrames(null, true);
2209 let elements = array.flatten(frames.map(function (win) [m for (m in DOM.XPath(xpath, win.document))]))
2210 .filter(function (elem) {
2211 if (isinstance(elem, [Ci.nsIDOMHTMLFrameElement,
2212 Ci.nsIDOMHTMLIFrameElement]))
2213 return Editor.getEditor(elem.contentWindow);
2217 if (elem[0].readOnly || !DOM(elem).isEditable)
2220 let style = elem.style;
2221 let rect = elem.rect;
2222 return elem.isVisible &&
2223 (elem[0] instanceof Ci.nsIDOMXULTextBoxElement || style.MozUserFocus != "ignore") &&
2224 rect.width && rect.height;
2227 dactyl.assert(elements.length > 0);
2228 elem = elements[Math.constrain(count, 1, elements.length) - 1];
2230 buffer.focusElement(elem);
2231 DOM(elem).scrollIntoView();
2236 let url = dactyl.clipboardRead();
2237 dactyl.assert(url, _("error.clipboardEmpty"));
2239 let proto = /^([-\w]+):/.exec(url);
2240 if (proto && services.PROTOCOL + proto[1] in Cc && !RegExp(options["urlseparator"]).test(url))
2241 return url.replace(/\s+/g, "");
2245 mappings.add([modes.NORMAL], ["gP"],
2246 "Open (put) a URL based on the current clipboard contents in a new background buffer",
2248 dactyl.open(url(), { from: "paste", where: dactyl.NEW_TAB, background: true });
2251 mappings.add([modes.NORMAL], ["p", "<MiddleMouse>", "<open-clipboard-url>"],
2252 "Open (put) a URL based on the current clipboard contents in the current buffer",
2257 mappings.add([modes.NORMAL], ["P", "<tab-open-clipboard-url>"],
2258 "Open (put) a URL based on the current clipboard contents in a new buffer",
2260 dactyl.open(url(), { from: "paste", where: dactyl.NEW_TAB });
2264 mappings.add([modes.NORMAL], ["r", "<reload>"],
2265 "Reload the current web page",
2266 function () { tabs.reload(tabs.getTab(), false); });
2268 mappings.add([modes.NORMAL], ["R", "<full-reload>"],
2269 "Reload while skipping the cache",
2270 function () { tabs.reload(tabs.getTab(), true); });
2273 mappings.add([modes.NORMAL], ["Y", "<yank-selection>"],
2274 "Copy selected text or current word",
2276 let sel = buffer.currentWord;
2278 editor.setRegister(null, sel, true);
2282 mappings.add([modes.NORMAL], ["zi", "+", "<text-zoom-in>"],
2283 "Enlarge text zoom of current web page",
2284 function ({ count }) { buffer.zoomIn(Math.max(count, 1), false); },
2287 mappings.add([modes.NORMAL], ["zm", "<text-zoom-more>"],
2288 "Enlarge text zoom of current web page by a larger amount",
2289 function ({ count }) { buffer.zoomIn(Math.max(count, 1) * 3, false); },
2292 mappings.add([modes.NORMAL], ["zo", "-", "<text-zoom-out>"],
2293 "Reduce text zoom of current web page",
2294 function ({ count }) { buffer.zoomOut(Math.max(count, 1), false); },
2297 mappings.add([modes.NORMAL], ["zr", "<text-zoom-reduce>"],
2298 "Reduce text zoom of current web page by a larger amount",
2299 function ({ count }) { buffer.zoomOut(Math.max(count, 1) * 3, false); },
2302 mappings.add([modes.NORMAL], ["zz", "<text-zoom>"],
2303 "Set text zoom value of current web page",
2304 function ({ count }) { buffer.setZoom(count > 1 ? count : 100, false); },
2307 mappings.add([modes.NORMAL], ["ZI", "zI", "<full-zoom-in>"],
2308 "Enlarge full zoom of current web page",
2309 function ({ count }) { buffer.zoomIn(Math.max(count, 1), true); },
2312 mappings.add([modes.NORMAL], ["ZM", "zM", "<full-zoom-more>"],
2313 "Enlarge full zoom of current web page by a larger amount",
2314 function ({ count }) { buffer.zoomIn(Math.max(count, 1) * 3, true); },
2317 mappings.add([modes.NORMAL], ["ZO", "zO", "<full-zoom-out>"],
2318 "Reduce full zoom of current web page",
2319 function ({ count }) { buffer.zoomOut(Math.max(count, 1), true); },
2322 mappings.add([modes.NORMAL], ["ZR", "zR", "<full-zoom-reduce>"],
2323 "Reduce full zoom of current web page by a larger amount",
2324 function ({ count }) { buffer.zoomOut(Math.max(count, 1) * 3, true); },
2327 mappings.add([modes.NORMAL], ["zZ", "<full-zoom>"],
2328 "Set full zoom value of current web page",
2329 function ({ count }) { buffer.setZoom(count > 1 ? count : 100, true); },
2333 mappings.add([modes.NORMAL], ["<C-g>", "<page-info>"],
2334 "Print the current file name",
2335 function () { buffer.showPageInfo(false); });
2337 mappings.add([modes.NORMAL], ["g<C-g>", "<more-page-info>"],
2338 "Print file information",
2339 function () { buffer.showPageInfo(true); });
2341 options: function initOptions(dactyl, modules, window) {
2342 let { Option, buffer, completion, config, options } = modules;
2344 options.add(["encoding", "enc"],
2345 "The current buffer's character encoding",
2348 scope: Option.SCOPE_LOCAL,
2349 getter: function () buffer.docShell.QueryInterface(Ci.nsIDocCharset).charset,
2350 setter: function (val) {
2351 if (options["encoding"] == val)
2354 // Stolen from browser.jar/content/browser/browser.js, more or less.
2356 buffer.docShell.QueryInterface(Ci.nsIDocCharset).charset = val;
2357 window.PlacesUtils.history.setCharsetForURI(buffer.uri, val);
2358 buffer.docShell.reload(Ci.nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE);
2360 catch (e) { dactyl.reportError(e); }
2363 completer: function (context) completion.charset(context)
2366 options.add(["iskeyword", "isk"],
2367 "Regular expression defining which characters constitute words",
2368 "string", '[^\\s.,!?:;/"\'^$%&?()[\\]{}<>#*+|=~_-]',
2370 setter: function (value) {
2371 this.regexp = util.regexp(value);
2374 validator: function (value) RegExp(value)
2377 options.add(["jumptags", "jt"],
2378 "XPath or CSS selector strings of jumpable elements for extended hint modes",
2380 "p": "p,table,ul,ol,blockquote",
2381 "h": "h1,h2,h3,h4,h5,h6"
2385 setter: function (vals) {
2386 for (let [k, v] in Iterator(vals))
2387 vals[k] = update(new String(v), { matcher: DOM.compileMatcher(Option.splitList(v)) });
2390 validator: function (value) DOM.validateMatcher.call(this, value)
2391 && Object.keys(value).every(function (v) v.length == 1)
2394 options.add(["linenumbers", "ln"],
2395 "Patterns used to determine line numbers used by G",
2397 // Make sure to update the docs when you change this.
2398 "view-source:*": 'body,[id^=line]',
2399 "code.google.com": '#nums [id^="nums_table"] a[href^="#"]',
2400 "github.com": '.line_numbers>*',
2401 "mxr.mozilla.org": 'a.l',
2402 "pastebin.com": '#code_frame>div>ol>li',
2403 "addons.mozilla.org": '.gutter>.line>a',
2404 "bugzilla.mozilla.org": ".bz_comment:not(.bz_first_comment):not(.ih_history)",
2405 "*": '/* Hgweb/Gitweb */ .completecodeline a.codeline, a.linenr'
2408 getLine: function getLine(doc, line) {
2409 let uri = util.newURI(doc.documentURI);
2410 for (let filter in values(this.value))
2411 if (filter(uri, doc)) {
2412 if (/^func:/.test(filter.result))
2413 var res = dactyl.userEval("(" + Option.dequote(filter.result.substr(5)) + ")")(doc, line);
2415 res = iter.nth(filter.matcher(doc),
2416 function (elem) (elem.nodeValue || elem.textContent).trim() == line && DOM(elem).display != "none",
2418 || iter.nth(filter.matcher(doc), util.identity, line - 1);
2428 setter: function (vals) {
2429 for (let value in values(vals))
2430 if (!/^func:/.test(value.result))
2431 value.matcher = DOM.compileMatcher(Option.splitList(value.result));
2435 validator: function validate(values) {
2436 return this.testValues(values, function (value) {
2437 if (/^func:/.test(value))
2438 return callable(dactyl.userEval("(" + Option.dequote(value.substr(5)) + ")"));
2440 return DOM.testMatcher(Option.dequote(value));
2445 options.add(["nextpattern"],
2446 "Patterns to use when guessing the next page in a document sequence",
2447 "regexplist", UTF8(/'^Next [>»]','^Next »','\bnext\b',^>$,^(>>|»)$,^(>|»),(>|»)$,'\bmore\b'/.source),
2448 { regexpFlags: "i" });
2450 options.add(["previouspattern"],
2451 "Patterns to use when guessing the previous page in a document sequence",
2452 "regexplist", UTF8(/'[<«] Prev$','« Prev$','\bprev(ious)?\b',^<$,^(<<|«)$,^(<|«),(<|«)$/.source),
2453 { regexpFlags: "i" });
2455 options.add(["pageinfo", "pa"],
2456 "Define which sections are shown by the :pageinfo command",
2457 "charlist", "gesfm",
2458 { get values() values(Buffer.pageInfo).toObject() });
2460 options.add(["scroll", "scr"],
2461 "Number of lines to scroll with <C-u> and <C-d> commands",
2463 { validator: function (value) value >= 0 });
2465 options.add(["showstatuslinks", "ssli"],
2466 "Where to show the destination of the link under the cursor",
2470 "": "Don't show link destinations",
2471 "status": "Show link destinations in the status line",
2472 "command": "Show link destinations in the command line"
2476 options.add(["scrolltime", "sct"],
2477 "The time, in milliseconds, in which to smooth scroll to a new position",
2480 options.add(["scrollsteps", "scs"],
2481 "The number of steps in which to smooth scroll to a new position",
2484 PREF: "general.smoothScroll",
2486 initValue: function () {},
2488 getter: function getter(value) !prefs.get(this.PREF) ? 1 : value,
2490 setter: function setter(value) {
2491 prefs.set(this.PREF, value > 1);
2496 validator: function (value) value > 0
2499 options.add(["usermode", "um"],
2500 "Show current website without styling defined by the author",
2503 setter: function (value) buffer.contentViewer.authorStyleDisabled = value,
2504 getter: function () buffer.contentViewer.authorStyleDisabled
2507 options.add(["yankshort", "ys"],
2508 "Yank the canonical short URL of a web page where provided",
2509 "sitelist", ["youtube.com", "bugzilla.mozilla.org"]);
2513 Buffer.addPageInfoSection("e", "Search Engines", function (verbose) {
2517 for (let { document: doc } in values(this.allFrames())) {
2518 let engines = DOM("link[href][rel=search][type='application/opensearchdescription+xml']", doc);
2519 nEngines += engines.length;
2522 for (let link in engines)
2523 yield [link.title || /*L*/ "Engine " + n++,
2524 ["a", { href: link.href, highlight: "URL",
2525 onclick: "if (event.button == 0) { window.external.AddSearchProvider(this.href); return false; }" },
2529 if (!verbose && nEngines)
2530 yield nEngines + /*L*/" engine" + (nEngines > 1 ? "s" : "");
2533 Buffer.addPageInfoSection("f", "Feeds", function (verbose) {
2535 "application/rss+xml": "RSS",
2536 "application/atom+xml": "Atom",
2538 "application/xml": "XML",
2539 "application/rdf+xml": "XML"
2542 function isValidFeed(data, principal, isFeed) {
2543 if (!data || !principal)
2547 var type = data.type && data.type.toLowerCase();
2548 type = type.replace(/^\s+|\s*(?:;.*)?$/g, "");
2550 isFeed = ["application/rss+xml", "application/atom+xml"].indexOf(type) >= 0 ||
2551 // really slimy: general XML types with magic letters in the title
2552 type in feedTypes && /\brss\b/i.test(data.title);
2557 services.security.checkLoadURIStrWithPrincipal(principal, data.href,
2558 services.security.DISALLOW_INHERIT_PRINCIPAL);
2572 for (let [i, win] in Iterator(this.allFrames())) {
2573 let doc = win.document;
2575 for (let link in DOM("link[href][rel=feed], link[href][rel=alternate][type]", doc)) {
2576 let rel = link.rel.toLowerCase();
2577 let feed = { title: link.title, href: link.href, type: link.type || "" };
2578 if (isValidFeed(feed, doc.nodePrincipal, rel == "feed")) {
2580 let type = feedTypes[feed.type] || "RSS";
2582 yield [feed.title, [template.highlightURL(feed.href, true),
2583 ["span", { class: "extra-info" }, " (" + type + ")"]]];
2589 if (!verbose && nFeed)
2590 yield nFeed + /*L*/" feed" + (nFeed > 1 ? "s" : "");
2593 Buffer.addPageInfoSection("g", "General Info", function (verbose) {
2594 let doc = this.focusedFrame.document;
2597 const ACCESS_READ = Ci.nsICache.ACCESS_READ;
2598 let cacheKey = doc.documentURI;
2600 for (let proto in array.iterValues(["HTTP", "FTP"])) {
2602 var cacheEntryDescriptor = services.cache.createSession(proto, 0, true)
2603 .openCacheEntry(cacheKey, ACCESS_READ, false);
2609 let pageSize = []; // [0] bytes; [1] kbytes
2610 if (cacheEntryDescriptor) {
2611 pageSize[0] = util.formatBytes(cacheEntryDescriptor.dataSize, 0, false);
2612 pageSize[1] = util.formatBytes(cacheEntryDescriptor.dataSize, 2, true);
2613 if (pageSize[1] == pageSize[0])
2614 pageSize.length = 1; // don't output "xx Bytes" twice
2617 let lastModVerbose = new Date(doc.lastModified).toLocaleString();
2618 let lastMod = new Date(doc.lastModified).toLocaleFormat("%x %X");
2620 if (lastModVerbose == "Invalid Date" || new Date(doc.lastModified).getFullYear() == 1970)
2621 lastModVerbose = lastMod = null;
2625 yield (pageSize[1] || pageSize[0]) + /*L*/" bytes";
2630 yield ["Title", doc.title];
2631 yield ["URL", template.highlightURL(doc.location.href, true)];
2633 let { shortURL } = this;
2635 yield ["Short URL", template.highlightURL(shortURL, true)];
2637 let ref = "referrer" in doc && doc.referrer;
2639 yield ["Referrer", template.highlightURL(ref, true)];
2642 yield ["File Size", pageSize[1] ? pageSize[1] + " (" + pageSize[0] + ")"
2645 yield ["Mime-Type", doc.contentType];
2646 yield ["Encoding", doc.characterSet];
2647 yield ["Compatibility", doc.compatMode == "BackCompat" ? "Quirks Mode" : "Full/Almost Standards Mode"];
2649 yield ["Last Modified", lastModVerbose];
2652 Buffer.addPageInfoSection("m", "Meta Tags", function (verbose) {
2656 // get meta tag data, sort and put into pageMeta[]
2657 let metaNodes = this.focusedFrame.document.getElementsByTagName("meta");
2659 return Array.map(metaNodes, function (node) [(node.name || node.httpEquiv),
2660 template.highlightURL(node.content)])
2661 .sort(function (a, b) util.compareIgnoreCase(a[0], b[0]));
2664 Buffer.addPageInfoSection("s", "Security", function (verbose) {
2665 let { statusline } = this.modules;
2667 let identity = this.topWindow.gIdentityHandler;
2669 if (!verbose || !identity)
2672 // Modified from Firefox
2673 function location(data) array.compact([
2674 data.city, data.state, data.country
2677 switch (statusline.security) {
2680 var data = identity.getIdentityData();
2682 yield ["Host", identity.getEffectiveHost()];
2684 if (statusline.security === "extended")
2685 yield ["Owner", data.subjectOrg];
2687 yield ["Owner", _("pageinfo.s.ownerUnverified", data.subjectOrg)];
2689 if (location(data).length)
2690 yield ["Location", location(data)];
2692 yield ["Verified by", data.caOrg];
2694 if (identity._overrideService.hasMatchingOverride(identity._lastLocation.hostname,
2695 (identity._lastLocation.port || 443),
2697 yield ["User exception", /*L*/"true"];
2702 // catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
2706 // vim: set fdm=marker sw=4 sts=4 ts=8 et ft=javascript: