]> git.donarmstrong.com Git - dactyl.git/blob - common/content/tabs.js
Import r6923 from upstream hg supporting Firefox up to 22.0a1
[dactyl.git] / common / content / tabs.js
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-2012 Kris Maglione <maglione.k at Gmail>
4 //
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
7 "use strict";
8
9 /** @scope modules */
10
11 // TODO: many methods do not work with Thunderbird correctly yet
12
13 /**
14  * @instance tabs
15  */
16 var Tabs = Module("tabs", {
17     init: function () {
18         // used for the "gb" and "gB" mappings to remember the last :buffer[!] command
19         this._lastBufferSwitchArgs = "";
20         this._lastBufferSwitchSpecial = true;
21
22         this.xulTabs = document.getElementById("tabbrowser-tabs");
23
24         // hide tabs initially to prevent flickering when 'stal' would hide them
25         // on startup
26         if (config.has("tabbrowser"))
27             config.tabStrip.collapsed = true;
28
29         this.tabStyle = styles.system.add("tab-strip-hiding", config.styleableChrome,
30                                           (config.tabStrip.id ? "#" + config.tabStrip.id : ".tabbrowser-strip") +
31                                               "{ visibility: collapse; }",
32                                           false, true);
33
34         dactyl.commands["tabs.select"] = function (event) {
35             tabs.switchTo(event.originalTarget.getAttribute("identifier"));
36         };
37
38         this.tabBinding = styles.system.add("tab-binding", "chrome://browser/content/browser.xul", literal(/*
39                 xul|tab { -moz-binding: url(chrome://dactyl/content/bindings.xml#tab) !important; }
40             */).replace(/tab-./g, function (m) config.OS.isMacOSX ? "tab-mac" : m),
41             false, true);
42
43         this.timeout(function () {
44             for (let { linkedBrowser: { contentDocument } } in values(this.allTabs))
45                 if (contentDocument.readyState === "complete")
46                     dactyl.initDocument(contentDocument);
47         }, 1000);
48
49         if (window.TabsInTitlebar)
50             window.TabsInTitlebar.allowedBy("dactyl", false);
51     },
52
53     signals: {
54         enter: function enter() {
55             if (window.TabsInTitlebar)
56                 window.TabsInTitlebar.allowedBy("dactyl", true);
57         }
58     },
59
60     _alternates: Class.Memoize(function () [config.tabbrowser.mCurrentTab, null]),
61
62     cleanup: function cleanup() {
63         for (let [i, tab] in Iterator(this.allTabs)) {
64             let node = function node(class_) document.getAnonymousElementByAttribute(tab, "class", class_);
65             for (let elem in values(["dactyl-tab-icon-number", "dactyl-tab-number"].map(node)))
66                 if (elem)
67                     elem.parentNode.parentNode.removeChild(elem.parentNode);
68
69             delete tab.dactylOrdinal;
70             tab.removeAttribute("dactylOrdinal");
71         }
72     },
73
74     updateTabCount: function updateTabCount() {
75         for (let [i, tab] in Iterator(this.visibleTabs)) {
76             if (dactyl.has("Gecko2")) {
77                 let node = function node(class_) document.getAnonymousElementByAttribute(tab, "class", class_);
78                 if (!node("dactyl-tab-number")) {
79                     let img = node("tab-icon-image");
80                     if (img) {
81                         let dom = DOM([
82                             ["xul:hbox", { highlight: "tab-number" },
83                                 ["xul:label", { key: "icon", align: "center", highlight: "TabIconNumber",
84                                                 class: "dactyl-tab-icon-number" }]],
85                             ["xul:hbox", { highlight: "tab-number" },
86                                 ["html:div", { key: "label", highlight: "TabNumber",
87                                                class: "dactyl-tab-number" }]]],
88                             document).appendTo(img.parentNode);
89
90                         update(tab, {
91                             get dactylOrdinal() Number(dom.nodes.icon.value),
92                             set dactylOrdinal(i) {
93                                 dom.nodes.icon.value = dom.nodes.label.textContent = i;
94                                 this.setAttribute("dactylOrdinal", i);
95                             }
96                         });
97                     }
98                 }
99             }
100             tab.dactylOrdinal = i + 1;
101         }
102         statusline.updateTabCount(true);
103     },
104
105     _onTabSelect: function _onTabSelect() {
106         // TODO: is all of that necessary?
107         //       I vote no. --Kris
108         modes.reset();
109         statusline.updateTabCount(true);
110         this.updateSelectionHistory();
111     },
112
113     get allTabs() Array.slice(config.tabbrowser.tabContainer.childNodes),
114
115     /**
116      * @property {Object} The previously accessed tab or null if no tab
117      *     other than the current one has been accessed.
118      */
119     get alternate() this.allTabs.indexOf(this._alternates[1]) > -1 ? this._alternates[1] : null,
120
121     /**
122      * @property {Iterator(Object)} A genenerator that returns all browsers
123      *     in the current window.
124      */
125     get browsers() {
126         let browsers = config.tabbrowser.browsers;
127         for (let i = 0; i < browsers.length; i++)
128             if (browsers[i] !== undefined) // Bug in Google's Page Speed add-on.
129                 yield [i, browsers[i]];
130     },
131
132     /**
133      * @property {number} The number of tabs in the current window.
134      */
135     get count() config.tabbrowser.mTabs.length,
136
137     /**
138      * @property {Object} The local options store for the current tab.
139      */
140     get options() this.localStore.options,
141
142     get visibleTabs() config.tabbrowser.visibleTabs || this.allTabs.filter(function (tab) !tab.hidden),
143
144     /**
145      * Returns the local state store for the tab at the specified *tabIndex*.
146      * If *tabIndex* is not specified then the current tab is used.
147      *
148      * @param {number} tabIndex
149      * @returns {Object}
150      */
151     // FIXME: why not a tab arg? Why this and the property?
152     //      : To the latter question, because this works for any tab, the
153     //        property doesn't. And the property is so oft-used that it's
154     //        convenient. To the former question, because I think this is mainly
155     //        useful for autocommands, and they get index arguments. --Kris
156     getLocalStore: function getLocalStore(tabIndex) {
157         let tab = this.getTab(tabIndex);
158         if (!tab.dactylStore)
159             tab.dactylStore = Object.create(this.localStorePrototype);
160         return tab.dactylStore.instance = tab.dactylStore;
161     },
162
163     /**
164      * @property {Object} The local state store for the currently selected
165      *     tab.
166      */
167     get localStore() this.getLocalStore(),
168
169     localStorePrototype: memoize({
170         instance: {},
171         get options() ({})
172     }),
173
174     /**
175      * @property {[Object]} The array of closed tabs for the current
176      *     session.
177      */
178     get closedTabs() JSON.parse(services.sessionStore.getClosedTabData(window)),
179
180     /**
181      * Clones the specified *tab* and append it to the tab list.
182      *
183      * @param {Object} tab The tab to clone.
184      * @param {boolean} activate Whether to select the newly cloned tab.
185      */
186     cloneTab: function cloneTab(tab, activate) {
187         let newTab = config.tabbrowser.addTab("about:blank", { ownerTab: tab });
188         Tabs.copyTab(newTab, tab);
189
190         if (activate)
191             config.tabbrowser.mTabContainer.selectedItem = newTab;
192
193         return newTab;
194     },
195
196     /**
197      * Detaches the specified *tab* and open it in a new window. If no tab is
198      * specified the currently selected tab is detached.
199      *
200      * @param {Object} tab The tab to detach.
201      */
202     detachTab: function detachTab(tab) {
203         if (!tab)
204             tab = config.tabbrowser.mTabContainer.selectedItem;
205
206         services.windowWatcher
207                 .openWindow(window, window.getBrowserURL(), null, "chrome,dialog=no,all", tab);
208     },
209
210     /**
211      * Returns the index of the tab containing *content*.
212      *
213      * @param {Object} content Either a content window or a content
214      *     document.
215      */
216     // FIXME: Only called once...necessary?
217     getContentIndex: function getContentIndex(content) {
218         for (let [i, browser] in this.browsers) {
219             if (browser.contentWindow == content || browser.contentDocument == content)
220                 return i;
221         }
222         return -1;
223     },
224
225     /**
226      * If TabView exists, returns the Panorama window. If the Panorama
227      * is has not yet initialized, this function will not return until
228      * it has.
229      *
230      * @returns {Window}
231      */
232     getGroups: function getGroups(func) {
233         let iframe = document.getElementById("tab-view");
234         this._groups = iframe ? iframe.contentWindow : null;
235
236         if ("_groups" in this && !func)
237             return this._groups;
238
239         if (func)
240             func = bind(function (func) { func(this._groups) }, this, func);
241
242         if (window.TabView && window.TabView._initFrame)
243             window.TabView._initFrame(func);
244
245         this._groups = iframe ? iframe.contentWindow : null;
246         if (this._groups && !func)
247             util.waitFor(function () this._groups.TabItems, this);
248         return this._groups;
249     },
250
251     /**
252      * Returns the tab at the specified *index* or the currently selected tab
253      * if *index* is not specified. This is a 0-based index.
254      *
255      * @param {number|Node} index The index of the tab required or the tab itself
256      * @param {boolean} visible If true, consider only visible tabs rather than
257      *      all tabs.
258      * @returns {Object}
259      */
260     getTab: function getTab(index, visible) {
261         if (index instanceof Node)
262             return index;
263         if (index != null)
264             return this[visible ? "visibleTabs" : "allTabs"][index];
265         return config.tabbrowser.mCurrentTab;
266     },
267
268     /**
269      * Returns the index of *tab* or the index of the currently selected tab if
270      * *tab* is not specified. This is a 0-based index.
271      *
272      * @param {<xul:tab/>} tab A tab from the current tab list.
273      * @param {boolean} visible Whether to consider only visible tabs.
274      * @returns {number}
275      */
276     index: function index(tab, visible) {
277         let tabs = this[visible ? "visibleTabs" : "allTabs"];
278         return tabs.indexOf(tab || config.tabbrowser.mCurrentTab);
279     },
280
281     /**
282      * @param spec can either be:
283      * - an absolute integer
284      * - "" for the current tab
285      * - "+1" for the next tab
286      * - "-3" for the tab, which is 3 positions left of the current
287      * - "$" for the last tab
288      */
289     indexFromSpec: function indexFromSpec(spec, wrap, offset) {
290         if (spec instanceof Node)
291             return this.allTabs.indexOf(spec);
292
293         let tabs     = this.visibleTabs;
294         let position = this.index(null, true);
295
296         if (spec == null)
297             return -1;
298
299         if (spec === "")
300             return position;
301
302         if (/^\d+$/.test(spec))
303             position = parseInt(spec, 10) + (offset || 0);
304         else if (spec === "$")
305             position = tabs.length - 1;
306         else if (/^[+-]\d+$/.test(spec))
307             position += parseInt(spec, 10);
308         else
309             return -1;
310
311         if (position >= tabs.length)
312             position = wrap ? position % tabs.length : tabs.length - 1;
313         else if (position < 0)
314             position = wrap ? (position % tabs.length) + tabs.length : 0;
315
316         return this.allTabs.indexOf(tabs[position]);
317     },
318
319     /**
320      * Removes all tabs from the tab list except the specified *tab*.
321      *
322      * @param {Object} tab The tab to keep.
323      */
324     keepOnly: function keepOnly(tab) {
325         config.tabbrowser.removeAllTabsBut(tab);
326     },
327
328     /**
329      * Lists all tabs matching *filter*.
330      *
331      * @param {string} filter A filter matching a substring of the tab's
332      *     document title or URL.
333      */
334     list: function list(filter) {
335         completion.listCompleter("buffer", filter);
336     },
337
338
339     /**
340      * Return an iterator of tabs matching the given filter. If no
341      * *filter* or *count* is provided, returns the currently selected
342      * tab. If *filter* is a number or begins with a number followed
343      * by a colon, the tab of that ordinal is returned. Otherwise,
344      * tabs matching the filter as below are returned.
345      *
346      * @param {string} filter The filter. If *regexp*, this is a
347      *      regular expression against which the tab's URL or title
348      *      must match. Otherwise, it is a site filter.
349      *      @optional
350      * @param {number|null} count If non-null, return only the
351      *      *count*th matching tab.
352      *      @optional
353      * @param {boolean} regexp Whether to interpret *filter* as a
354      *      regular expression.
355      * @param {boolean} all If true, match against all tabs. If
356      *      false, match only tabs in the current tab group.
357      */
358     match: function match(filter, count, regexp, all) {
359         if (!filter && count == null)
360             yield tabs.getTab();
361         else if (!filter)
362             yield dactyl.assert(tabs.getTab(count - 1));
363         else {
364             let matches = /^(\d+)(?:$|:)/.exec(filter);
365             if (matches)
366                 yield dactyl.assert(count == null &&
367                                     tabs.getTab(parseInt(matches[1], 10) - 1, !all));
368             else {
369                 if (regexp)
370                     regexp = util.regexp(filter, "i");
371                 else
372                     var matcher = Styles.matchFilter(filter);
373
374                 for (let tab in values(tabs[all ? "allTabs" : "visibleTabs"])) {
375                     let browser = tab.linkedBrowser;
376                     let uri = browser.currentURI;
377                     let title;
378                     if (uri.spec == "about:blank")
379                         title = "(Untitled)";
380                     else
381                         title = browser.contentTitle;
382
383                     if (matcher && matcher(uri)
384                         || regexp && (regexp.test(title) || regexp.test(uri.spec)))
385                         if (count == null || --count == 0)
386                             yield tab;
387                 }
388             }
389         }
390     },
391
392     /**
393      * Moves a tab to a new position in the tab list.
394      *
395      * @param {Object} tab The tab to move.
396      * @param {string} spec See {@link Tabs.indexFromSpec}.
397      * @param {boolean} wrap Whether an out of bounds *spec* causes the
398      *     destination position to wrap around the start/end of the tab list.
399      */
400     move: function move(tab, spec, wrap) {
401         let index = tabs.indexFromSpec(spec, wrap, -1);
402         config.tabbrowser.moveTabTo(tab, index);
403     },
404
405     /**
406      * Removes the specified *tab* from the tab list.
407      *
408      * @param {Object} tab The tab to remove.
409      * @param {number} count How many tabs to remove.
410      * @param {boolean} focusLeftTab Focus the tab to the left of the removed tab.
411      */
412     remove: function remove(tab, count, focusLeftTab) {
413         count = count || 1;
414         let res = this.count > count;
415
416         let tabs = this.visibleTabs;
417         if (tabs.indexOf(tab) < 0)
418             tabs = this.allTabs;
419         let index = tabs.indexOf(tab);
420
421         let next = index + (focusLeftTab ? -count : count);
422         if (!(next in tabs))
423             next = index + (focusLeftTab ? 1 : -1);
424         if (next in tabs) {
425             this._alternates[0] = tabs[next];
426             config.tabbrowser.mTabContainer.selectedItem = tabs[next];
427         }
428
429         if (focusLeftTab)
430             tabs.slice(Math.max(0, index + 1 - count), index + 1).forEach(config.closure.removeTab);
431         else
432             tabs.slice(index, index + count).forEach(config.closure.removeTab);
433         return res;
434     },
435
436     /**
437      * Reloads the specified tab.
438      *
439      * @param {Object} tab The tab to reload.
440      * @param {boolean} bypassCache Whether to bypass the cache when
441      *     reloading.
442      */
443     reload: function reload(tab, bypassCache) {
444         try {
445             if (bypassCache) {
446                 const flags = Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY | Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
447                 config.tabbrowser.getBrowserForTab(tab).reloadWithFlags(flags);
448             }
449             else
450                 config.tabbrowser.reloadTab(tab);
451         }
452         catch (e if !(e instanceof Error)) {}
453     },
454
455     /**
456      * Reloads all tabs.
457      *
458      * @param {boolean} bypassCache Whether to bypass the cache when
459      *     reloading.
460      */
461     reloadAll: function reloadAll(bypassCache) {
462         this.visibleTabs.forEach(function (tab) {
463             try {
464                 tabs.reload(tab, bypassCache);
465             }
466             catch (e) {
467                 dactyl.reportError(e, true);
468             }
469         });
470     },
471
472     /**
473      * Selects the tab at the position specified by *spec*.
474      *
475      * @param {string} spec See {@link Tabs.indexFromSpec}
476      * @param {boolean} wrap Whether an out of bounds *spec* causes the
477      *     selection position to wrap around the start/end of the tab list.
478      */
479     select: function select(spec, wrap) {
480         let index = tabs.indexFromSpec(spec, wrap);
481         if (index == -1)
482             dactyl.beep();
483         else
484             config.tabbrowser.mTabContainer.selectedIndex = index;
485     },
486
487     /**
488      * Selects the alternate tab.
489      */
490     selectAlternateTab: function selectAlternateTab() {
491         dactyl.assert(tabs.alternate != null && tabs.getTab() != tabs.alternate,
492                       _("buffer.noAlternate"));
493         tabs.select(tabs.alternate);
494     },
495
496     /**
497      * Stops loading the specified tab.
498      *
499      * @param {Object} tab The tab to stop loading.
500      */
501     stop: function stop(tab) {
502         if (config.stop)
503             config.stop(tab);
504         else
505             tab.linkedBrowser.stop();
506     },
507
508     /**
509      * Stops loading all tabs.
510      */
511     stopAll: function stopAll() {
512         for (let [, browser] in this.browsers)
513             browser.stop();
514     },
515
516     /**
517      * Selects the tab containing the specified *buffer*.
518      *
519      * @param {string} buffer A string which matches the URL or title of a
520      *     buffer, if it is null, the last used string is used again.
521      * @param {boolean} allowNonUnique Whether to select the first of
522      *     multiple matches.
523      * @param {number} count If there are multiple matches select the
524      *     *count*th match.
525      * @param {boolean} reverse Whether to search the buffer list in
526      *     reverse order.
527      *
528      */
529     // FIXME: help!
530     switchTo: function switchTo(buffer, allowNonUnique, count, reverse) {
531         if (buffer != null) {
532             // store this command, so it can be repeated with "B"
533             this._lastBufferSwitchArgs = buffer;
534             this._lastBufferSwitchSpecial = allowNonUnique;
535         }
536         else {
537             buffer = this._lastBufferSwitchArgs;
538             if (allowNonUnique == null) // XXX
539                 allowNonUnique = this._lastBufferSwitchSpecial;
540         }
541
542         if (buffer == "#")
543             return tabs.selectAlternateTab();
544
545         reverse = Boolean(reverse);
546         count = Math.max(1, count || 1) * (1 + -2 * reverse);
547
548         let matches = buffer.match(/^(\d+):?/);
549         if (matches)
550             return tabs.select(this.allTabs[parseInt(matches[1], 10) - 1], false);
551
552         matches = array.nth(tabs.allTabs, function (t) (t.linkedBrowser.lastURI || {}).spec === buffer, 0);
553         if (matches)
554             return tabs.select(matches, false);
555
556         matches = completion.runCompleter("buffer", buffer).map(function (obj) obj.tab);
557
558         if (matches.length == 0)
559             dactyl.echoerr(_("buffer.noMatching", buffer));
560         else if (matches.length > 1 && !allowNonUnique)
561             dactyl.echoerr(_("buffer.multipleMatching", buffer));
562         else {
563             let start = matches.indexOf(tabs.getTab());
564             if (start == -1 && reverse)
565                 start++;
566
567             let index = (start + count) % matches.length;
568             if (index < 0)
569                 index = matches.length + index;
570             tabs.select(matches[index], false);
571         }
572     },
573
574     // NOTE: when restarting a session FF selects the first tab and then the
575     // tab that was selected when the session was created.  As a result the
576     // alternate after a restart is often incorrectly tab 1 when there
577     // shouldn't be one yet.
578     /**
579      * Sets the current and alternate tabs, updating the tab selection
580      * history.
581      *
582      * @param {Array(Object)} tabs The current and alternate tab.
583      * @see tabs#alternate
584      */
585     updateSelectionHistory: function updateSelectionHistory(tabs) {
586         if (!tabs) {
587             if (this.getTab() == this._alternates[0]
588                 || this.alternate && this.allTabs.indexOf(this._alternates[0]) == -1
589                 || this.alternate && config.tabbrowser._removingTabs && config.tabbrowser._removingTabs.indexOf(this._alternates[0]) >= 0)
590                 tabs = [this.getTab(), this.alternate];
591         }
592         this._alternates = tabs || [this.getTab(), this._alternates[0]];
593     }
594 }, {
595     copyTab: function (to, from) {
596         if (!from)
597             from = config.tabbrowser.mTabContainer.selectedItem;
598
599         let tabState = services.sessionStore.getTabState(from);
600         services.sessionStore.setTabState(to, tabState);
601     }
602 }, {
603     load: function initLoad() {
604         tabs.updateTabCount();
605     },
606     commands: function initCommands() {
607         [
608             {
609                 name: ["bd[elete]"],
610                 description: "Delete matching buffers",
611                 visible: false
612             },
613             {
614                 name: ["tabc[lose]"],
615                 description: "Delete matching tabs",
616                 visible: true
617             }
618         ].forEach(function (params) {
619             commands.add(params.name, params.description,
620                 function (args) {
621                     let removed = 0;
622                     for (let tab in tabs.match(args[0], args.count, args.bang, !params.visible)) {
623                         config.removeTab(tab);
624                         removed++;
625                     }
626
627                     if (args[0])
628                         if (removed > 0)
629                             dactyl.echomsg(_("buffer.fewerTab" + (removed == 1 ? "" : "s"), removed), 9);
630                         else
631                             dactyl.echoerr(_("buffer.noMatching", args[0]));
632                 }, {
633                     argCount: "?",
634                     bang: true,
635                     count: true,
636                     completer: function (context) completion.buffer(context),
637                     literal: 0,
638                     privateData: true
639                 });
640         });
641
642         commands.add(["pin[tab]"],
643             "Pin tab as an application tab",
644             function (args) {
645                 for (let tab in tabs.match(args[0], args.count))
646                     config.browser[!args.bang || !tab.pinned ? "pinTab" : "unpinTab"](tab);
647             },
648             {
649                 argCount: "?",
650                 bang: true,
651                 count: true,
652                 completer: function (context, args) {
653                     if (!args.bang)
654                         context.filters.push(function ({ item }) !item.tab.pinned);
655                     completion.buffer(context);
656                 }
657             });
658
659         commands.add(["unpin[tab]"],
660             "Unpin tab as an application tab",
661             function (args) {
662                 for (let tab in tabs.match(args[0], args.count))
663                     config.browser.unpinTab(tab);
664             },
665             {
666                 argCount: "?",
667                 count: true,
668                 completer: function (context, args) {
669                     context.filters.push(function ({ item }) item.tab.pinned);
670                     completion.buffer(context);
671                 }
672             });
673
674         commands.add(["keepa[lt]"],
675             "Execute a command without changing the current alternate buffer",
676             function (args) {
677                 try {
678                     dactyl.execute(args[0], null, true);
679                 }
680                 finally {
681                     tabs.updateSelectionHistory([tabs.getTab(), tabs.alternate]);
682                 }
683             }, {
684                 argCount: "1",
685                 completer: function (context) completion.ex(context),
686                 literal: 0,
687                 subCommand: 0
688             });
689
690         commands.add(["tab"],
691             "Execute a command and tell it to output in a new tab",
692             function (args) {
693                 dactyl.withSavedValues(["forceTarget"], function () {
694                     this.forceTarget = dactyl.NEW_TAB;
695                     dactyl.execute(args[0], null, true);
696                 });
697             }, {
698                 argCount: "1",
699                 completer: function (context) completion.ex(context),
700                 literal: 0,
701                 subCommand: 0
702             });
703
704         commands.add(["background", "bg"],
705             "Execute a command opening any new tabs in the background",
706             function (args) {
707                 dactyl.withSavedValues(["forceBackground"], function () {
708                     this.forceBackground = true;
709                     dactyl.execute(args[0], null, true);
710                 });
711             }, {
712                 argCount: "1",
713                 completer: function (context) completion.ex(context),
714                 literal: 0,
715                 subCommand: 0
716             });
717
718         commands.add(["tabd[o]", "bufd[o]"],
719             "Execute a command in each tab",
720             function (args) {
721                 for (let tab in values(tabs.visibleTabs)) {
722                     tabs.select(tab);
723                     dactyl.execute(args[0], null, true);
724                 }
725             }, {
726                 argCount: "1",
727                 completer: function (context) completion.ex(context),
728                 literal: 0,
729                 subCommand: 0
730             });
731
732         commands.add(["tabl[ast]", "bl[ast]"],
733             "Switch to the last tab",
734             function () tabs.select("$", false),
735             { argCount: "0" });
736
737         // TODO: "Zero count" if 0 specified as arg
738         commands.add(["tabp[revious]", "tp[revious]", "tabN[ext]", "tN[ext]", "bp[revious]", "bN[ext]"],
739             "Switch to the previous tab or go [count] tabs back",
740             function (args) {
741                 let count = args.count;
742                 let arg   = args[0];
743
744                 // count is ignored if an arg is specified, as per Vim
745                 if (arg) {
746                     if (/^\d+$/.test(arg))
747                         tabs.select("-" + arg, true);
748                     else
749                         dactyl.echoerr(_("error.trailingCharacters"));
750                 }
751                 else if (count > 0)
752                     tabs.select("-" + count, true);
753                 else
754                     tabs.select("-1", true);
755             }, {
756                 argCount: "?",
757                 count: true
758             });
759
760         // TODO: "Zero count" if 0 specified as arg
761         commands.add(["tabn[ext]", "tn[ext]", "bn[ext]"],
762             "Switch to the next or [count]th tab",
763             function (args) {
764                 let count = args.count;
765                 let arg   = args[0];
766
767                 if (arg || count > 0) {
768                     let index;
769
770                     // count is ignored if an arg is specified, as per Vim
771                     if (arg) {
772                         dactyl.assert(/^\d+$/.test(arg), _("error.trailingCharacters"));
773                         index = arg - 1;
774                     }
775                     else
776                         index = count - 1;
777
778                     if (index < tabs.count)
779                         tabs.select(index, true);
780                     else
781                         dactyl.beep();
782                 }
783                 else
784                     tabs.select("+1", true);
785             }, {
786                 argCount: "?",
787                 count: true
788             });
789
790         commands.add(["tabr[ewind]", "tabfir[st]", "br[ewind]", "bf[irst]"],
791             "Switch to the first tab",
792             function () { tabs.select(0, false); },
793             { argCount: "0" });
794
795         if (config.has("tabbrowser")) {
796             commands.add(["b[uffer]"],
797                 "Switch to a buffer",
798                 function (args) { tabs.switchTo(args[0], args.bang, args.count); }, {
799                     argCount: "?",
800                     bang: true,
801                     count: true,
802                     completer: function (context) completion.buffer(context),
803                     literal: 0,
804                     privateData: true
805                 });
806
807             commands.add(["buffers", "files", "ls", "tabs"],
808                 "Show a list of all buffers",
809                 function (args) { tabs.list(args[0] || ""); }, {
810                     argCount: "?",
811                     literal: 0
812                 });
813
814             commands.add(["quita[ll]", "qa[ll]"],
815                 "Quit this " + config.appName + " window",
816                 function (args) { window.close(); },
817                 { argCount: "0" });
818
819             commands.add(["reloada[ll]"],
820                 "Reload all tab pages",
821                 function (args) { tabs.reloadAll(args.bang); }, {
822                     argCount: "0",
823                     bang: true
824                 });
825
826             commands.add(["stopa[ll]"],
827                 "Stop loading all tab pages",
828                 function () { tabs.stopAll(); },
829                 { argCount: "0" });
830
831             // TODO: add count and bang multimatch support - unify with :buffer nonsense
832             commands.add(["tabm[ove]"],
833                 "Move the current tab to the position of tab N",
834                 function (args) {
835                     let arg = args[0];
836
837                     if (tabs.indexFromSpec(arg) == -1) {
838                         let list = [tab for (tab in tabs.match(args[0], args.count, true))];
839                         dactyl.assert(list.length, _("error.invalidArgument", arg));
840                         dactyl.assert(list.length == 1, _("buffer.multipleMatching", arg));
841                         arg = list[0];
842                     }
843                     tabs.move(tabs.getTab(), arg, args.bang);
844                 }, {
845                     argCount: "1",
846                     bang: true,
847                     completer: function (context, args) completion.buffer(context, true),
848                     literal: 0
849                 });
850
851             commands.add(["tabo[nly]"],
852                 "Close all other tabs",
853                 function () { tabs.keepOnly(tabs.getTab()); },
854                 { argCount: "0" });
855
856             commands.add(["tabopen", "t[open]", "tabnew"],
857                 "Open one or more URLs in a new tab",
858                 function (args) {
859                     dactyl.open(args[0] || "about:blank",
860                                 { from: "tabopen", where: dactyl.NEW_TAB, background: args.bang });
861                 }, {
862                     bang: true,
863                     completer: function (context) completion.url(context),
864                     domains: function (args) commands.get("open").domains(args),
865                     literal: 0,
866                     privateData: true
867                 });
868
869             commands.add(["tabde[tach]"],
870                 "Detach current tab to its own window",
871                 function () { tabs.detachTab(null); },
872                 { argCount: "0" });
873
874             commands.add(["tabdu[plicate]"],
875                 "Duplicate current tab",
876                 function (args) {
877                     let tab = tabs.getTab();
878
879                     let activate = args.bang ? true : false;
880                     if (options.get("activate").has("tabopen"))
881                         activate = !activate;
882
883                     for (let i in util.range(0, Math.max(1, args.count)))
884                         tabs.cloneTab(tab, activate);
885                 }, {
886                     argCount: "0",
887                     bang: true,
888                     count: true
889                 });
890
891             // TODO: match window by title too?
892             //     : accept the full :tabmove arg spec for the tab index arg?
893             //     : better name or merge with :tabmove?
894             commands.add(["taba[ttach]"],
895                 "Attach the current tab to another window",
896                 function (args) {
897                     dactyl.assert(args.length <= 2 && !args.some(function (i) !/^\d+(?:$|:)/.test(i)),
898                                   _("error.trailingCharacters"));
899
900                     let [winIndex, tabIndex] = args.map(function (arg) parseInt(arg));
901                     if (args["-group"]) {
902                         util.assert(args.length == 1);
903                         window.TabView.moveTabTo(tabs.getTab(), winIndex);
904                         return;
905                     }
906
907                     let win = dactyl.windows[winIndex - 1];
908                     let sourceTab = tabs.getTab();
909
910                     dactyl.assert(win, _("window.noIndex", winIndex));
911                     dactyl.assert(win != window, _("window.cantAttachSame"));
912
913                     let modules     = win.dactyl.modules;
914                     let { browser } = modules.config;
915
916                     if (args[1]) {
917                         let tabList = modules.tabs.visibleTabs;
918                         let target  = dactyl.assert(tabList[tabIndex]);
919                         tabIndex = Array.indexOf(tabs.allTabs, target) - 1;
920                     }
921
922                     let newTab = browser.addTab("about:blank");
923                     browser.stop();
924                     // XXX: the implementation of DnD in tabbrowser.xml suggests
925                     // that we may not be guaranteed of having a docshell here
926                     // without this reference?
927                     browser.docShell;
928
929                     let last = modules.tabs.allTabs.length - 1;
930
931                     if (args[1])
932                         browser.moveTabTo(newTab, tabIndex);
933                     browser.selectedTab = newTab; // required
934                     browser.swapBrowsersAndCloseOther(newTab, sourceTab);
935                 }, {
936                     argCount: "+",
937                     literal: 1,
938                     completer: function (context, args) {
939                         switch (args.completeArg) {
940                         case 0:
941                             if (args["-group"])
942                                 completion.tabGroup(context);
943                             else {
944                                 context.filters.push(function ({ item }) item != window);
945                                 completion.window(context);
946                             }
947                             break;
948                         case 1:
949                             if (!args["-group"]) {
950                                 let win = dactyl.windows[Number(args[0]) - 1];
951                                 if (!win || !win.dactyl)
952                                     context.message = _("Error", _("window.noIndex", winIndex));
953                                 else
954                                     win.dactyl.modules.commands.get("tabmove").completer(context);
955                             }
956                             break;
957                         }
958                     },
959                     options: [
960                         {
961                             names: ["-group", "-g"],
962                             description: "Attach to a group rather than a window",
963                             type: CommandOption.NOARG
964                         }
965                     ]
966                 });
967         }
968
969         if (dactyl.has("tabs_undo")) {
970             commands.add(["u[ndo]"],
971                 "Undo closing of a tab",
972                 function (args) {
973                     if (args.length)
974                         args = args[0];
975                     else
976                         args = args.count || 0;
977
978                     let m = /^(\d+)(:|$)/.exec(args || '1');
979                     if (m)
980                         window.undoCloseTab(Number(m[1]) - 1);
981                     else if (args) {
982                         for (let [i, item] in Iterator(tabs.closedTabs))
983                             if (item.state.entries[item.state.index - 1].url == args) {
984                                 window.undoCloseTab(i);
985                                 return;
986                             }
987
988                         dactyl.echoerr(_("buffer.noClosed"));
989                     }
990                 }, {
991                     argCount: "?",
992                     completer: function (context) {
993                         context.anchored = false;
994                         context.compare = CompletionContext.Sort.unsorted;
995                         context.filters = [CompletionContext.Filter.textDescription];
996                         context.keys = { text: function ([i, { state: s }]) (i + 1) + ": " + s.entries[s.index - 1].url, description: "[1].title", icon: "[1].image" };
997                         context.completions = Iterator(tabs.closedTabs);
998                     },
999                     count: true,
1000                     literal: 0,
1001                     privateData: true
1002                 });
1003
1004             commands.add(["undoa[ll]"],
1005                 "Undo closing of all closed tabs",
1006                 function (args) {
1007                     for (let i in Iterator(tabs.closedTabs))
1008                         window.undoCloseTab(0);
1009
1010                 },
1011                 { argCount: "0" });
1012
1013         }
1014
1015         if (dactyl.has("session")) {
1016             commands.add(["wqa[ll]", "wq", "xa[ll]"],
1017                 "Save the session and quit",
1018                 function () { dactyl.quit(true); },
1019                 { argCount: "0" });
1020         }
1021     },
1022     completion: function initCompletion() {
1023
1024         completion.buffer = function buffer(context, visible) {
1025             let { tabs } = modules;
1026
1027             let filter = context.filter.toLowerCase();
1028
1029             let defItem = { parent: { getTitle: function () "" } };
1030
1031             let tabGroups = {};
1032             tabs.getGroups();
1033             tabs[visible ? "visibleTabs" : "allTabs"].forEach(function (tab, i) {
1034                 let group = (tab.tabItem || tab._tabViewTabItem || defItem).parent || defItem.parent;
1035                 if (!Set.has(tabGroups, group.id))
1036                     tabGroups[group.id] = [group.getTitle(), []];
1037
1038                 group = tabGroups[group.id];
1039                 group[1].push([i, tab.linkedBrowser]);
1040             });
1041
1042             context.pushProcessor(0, function (item, text, next) [
1043                 ["span", { highlight: "Indicator", style: "display: inline-block;" },
1044                     item.indicator],
1045                 next.call(this, item, text)
1046             ]);
1047             context.process[1] = function (item, text) template.bookmarkDescription(item, template.highlightFilter(text, this.filter));
1048
1049             context.anchored = false;
1050             context.keys = {
1051                 text: "text",
1052                 description: "url",
1053                 indicator: function (item) item.tab === tabs.getTab()  ? "%" :
1054                                            item.tab === tabs.alternate ? "#" : " ",
1055                 icon: "icon",
1056                 id: "id",
1057                 command: function () "tabs.select"
1058             };
1059             context.compare = CompletionContext.Sort.number;
1060             context.filters[0] = CompletionContext.Filter.textDescription;
1061
1062             for (let [id, vals] in Iterator(tabGroups))
1063                 context.fork(id, 0, this, function (context, [name, browsers]) {
1064                     context.title = [name || "Buffers"];
1065                     context.generate = function ()
1066                         Array.map(browsers, function ([i, browser]) {
1067                             let indicator = " ";
1068                             if (i == tabs.index())
1069                                 indicator = "%";
1070                             else if (i == tabs.index(tabs.alternate))
1071                                 indicator = "#";
1072
1073                             let tab = tabs.getTab(i, visible);
1074                             let url = browser.contentDocument.location.href;
1075                             i = i + 1;
1076
1077                             return {
1078                                 text: [i + ": " + (tab.label || /*L*/"(Untitled)"), i + ": " + url],
1079                                 tab: tab,
1080                                 id: i,
1081                                 url: url,
1082                                 icon: tab.image || BookmarkCache.DEFAULT_FAVICON
1083                             };
1084                         });
1085                 }, vals);
1086         };
1087
1088         completion.tabGroup = function tabGroup(context) {
1089             context.title = ["Tab Groups"];
1090             context.keys = {
1091                 text: "id",
1092                 description: function (group) group.getTitle() ||
1093                     group.getChildren().map(function (t) t.tab.label).join(", ")
1094             };
1095             context.generate = function () {
1096                 context.incomplete = true;
1097                 tabs.getGroups(function ({ GroupItems }) {
1098                     context.incomplete = false;
1099                     context.completions = GroupItems.groupItems;
1100                 });
1101             };
1102         };
1103     },
1104     events: function initEvents() {
1105         let tabContainer = config.tabbrowser.mTabContainer;
1106         function callback() {
1107             tabs.timeout(function () { this.updateTabCount(); });
1108         }
1109         for (let event in values(["TabMove", "TabOpen", "TabClose"]))
1110             events.listen(tabContainer, event, callback, false);
1111         events.listen(tabContainer, "TabSelect", tabs.closure._onTabSelect, false);
1112     },
1113     mappings: function initMappings() {
1114
1115         mappings.add([modes.COMMAND], ["<C-t>", "<new-tab-next>"],
1116             "Execute the next mapping in a new tab",
1117             function ({ count }) {
1118                 dactyl.forceTarget = dactyl.NEW_TAB;
1119                 mappings.afterCommands((count || 1) + 1, function () {
1120                     dactyl.forceTarget = null;
1121                 });
1122             },
1123             { count: true });
1124
1125         mappings.add([modes.NORMAL], ["g0", "g^"],
1126             "Go to the first tab",
1127             function () { tabs.select(0); });
1128
1129         mappings.add([modes.NORMAL], ["g$"],
1130             "Go to the last tab",
1131             function () { tabs.select("$"); });
1132
1133         mappings.add([modes.NORMAL], ["gt"],
1134             "Go to the next tab",
1135             function ({ count }) {
1136                 if (count != null)
1137                     tabs.select(count - 1, false);
1138                 else
1139                     tabs.select("+1", true);
1140             },
1141             { count: true });
1142
1143         mappings.add([modes.NORMAL], ["<C-n>", "<C-Tab>", "<C-PageDown>"],
1144             "Go to the next tab",
1145             function ({ count }) { tabs.select("+" + (count || 1), true); },
1146             { count: true });
1147
1148         mappings.add([modes.NORMAL], ["gT", "<C-p>", "<C-S-Tab>", "<C-PageUp>"],
1149            "Go to previous tab",
1150             function ({ count }) { tabs.select("-" + (count || 1), true); },
1151             { count: true });
1152
1153         if (config.has("tabbrowser")) {
1154             mappings.add([modes.NORMAL], ["b"],
1155                 "Open a prompt to switch buffers",
1156                 function ({ count }) {
1157                     if (count != null)
1158                         tabs.switchTo(String(count));
1159                     else
1160                         CommandExMode().open("buffer! ");
1161                 },
1162                 { count: true });
1163
1164             mappings.add([modes.NORMAL], ["B"],
1165                 "Show buffer list",
1166                 function () { tabs.list(false); });
1167
1168             mappings.add([modes.NORMAL], ["d"],
1169                 "Delete current buffer",
1170                 function ({ count }) { tabs.remove(tabs.getTab(), count, false); },
1171                 { count: true });
1172
1173             mappings.add([modes.NORMAL], ["D"],
1174                 "Delete current buffer, focus tab to the left",
1175                 function ({ count }) { tabs.remove(tabs.getTab(), count, true); },
1176                 { count: true });
1177
1178             mappings.add([modes.NORMAL], ["gb"],
1179                 "Repeat last :buffer command",
1180                 function ({ count }) { tabs.switchTo(null, null, count, false); },
1181                 { count: true });
1182
1183             mappings.add([modes.NORMAL], ["gB"],
1184                 "Repeat last :buffer command in reverse direction",
1185                 function ({ count }) { tabs.switchTo(null, null, count, true); },
1186                 { count: true });
1187
1188             // TODO: feature dependencies - implies "session"?
1189             if (dactyl.has("tabs_undo")) {
1190                 mappings.add([modes.NORMAL], ["u"],
1191                     "Undo closing of a tab",
1192                     function ({ count }) { ex.undo({ "#": count }); },
1193                     { count: true });
1194             }
1195
1196             mappings.add([modes.NORMAL], ["<C-^>", "<C-6>"],
1197                 "Select the alternate tab or the [count]th tab",
1198                 function ({ count }) {
1199                     if (count != null)
1200                         tabs.switchTo(String(count), false);
1201                     else
1202                         tabs.selectAlternateTab();
1203                 },
1204                 { count: true });
1205         }
1206     },
1207     options: function initOptions() {
1208         options.add(["showtabline", "stal"],
1209             "Define when the tab bar is visible",
1210             "string", true,
1211             {
1212                 setter: function (value) {
1213                     if (value === "never")
1214                         tabs.tabStyle.enabled = true;
1215                     else {
1216                         prefs.safeSet("browser.tabs.autoHide", value === "multitab",
1217                                       _("option.safeSet", "showtabline"));
1218                         tabs.tabStyle.enabled = false;
1219                     }
1220
1221                     if (value !== "multitab" || !dactyl.has("Gecko2"))
1222                         if (tabs.xulTabs)
1223                             tabs.xulTabs.visible = value !== "never";
1224                         else
1225                             config.tabStrip.collapsed = false;
1226
1227                     if (config.tabbrowser.tabContainer._positionPinnedTabs)
1228                         config.tabbrowser.tabContainer._positionPinnedTabs();
1229                     return value;
1230                 },
1231                 values: {
1232                     "never":    "Never show the tab bar",
1233                     "multitab": "Show the tab bar when there are multiple tabs",
1234                     "always":   "Always show the tab bar"
1235                 }
1236             });
1237
1238         if (config.has("tabbrowser")) {
1239             let activateGroups = [
1240                 ["all", "Activate everything"],
1241                 ["addons", ":addo[ns] command"],
1242                 ["bookmarks", "Tabs loaded from bookmarks", "loadBookmarksInBackground"],
1243                 ["diverted", "Links with targets set to new tabs", "loadDivertedInBackground"],
1244                 ["downloads", ":downl[oads] command"],
1245                 ["extoptions", ":exto[ptions] command"],
1246                 ["help", ":h[elp] command"],
1247                 ["homepage", "gH mapping"],
1248                 ["links", "Middle- or Control-clicked links", "loadInBackground"],
1249                 ["quickmark", "go and gn mappings"],
1250                 ["tabopen", ":tabopen[!] command"],
1251                 ["paste", "P and gP mappings"]
1252             ];
1253             options.add(["activate", "act"],
1254                 "Define when newly created tabs are automatically activated",
1255                 "stringlist", [g[0] for (g in values(activateGroups.slice(1))) if (!g[2] || !prefs.get("browser.tabs." + g[2]))].join(","),
1256                 {
1257                     values: activateGroups,
1258                     has: Option.has.toggleAll,
1259                     setter: function (newValues) {
1260                         let valueSet = Set(newValues);
1261                         for (let group in values(activateGroups))
1262                             if (group[2])
1263                                 prefs.safeSet("browser.tabs." + group[2],
1264                                               !(valueSet["all"] ^ valueSet[group[0]]),
1265                                               _("option.safeSet", "activate"));
1266                         return newValues;
1267                     }
1268                 });
1269
1270             options.add(["newtab"],
1271                 "Define which commands should output in a new tab by default",
1272                 "stringlist", "",
1273                 {
1274                     values: {
1275                         "all": "All commands",
1276                         "extoptions": ":exto[ptions] command",
1277                         "help": ":h[elp] command",
1278                         "prefs": ":pref[erences]! or :prefs! command"
1279                     },
1280                     has: Option.has.toggleAll
1281                 });
1282
1283             // TODO: Is this really applicable to Melodactyl?
1284             options.add(["popups", "pps"],
1285                 "Where to show requested popup windows",
1286                 "stringlist", "tab",
1287                 {
1288                     setter: function (values) {
1289                         let open = 1, restriction = 0;
1290                         for (let [, opt] in Iterator(values)) {
1291                             if (opt == "tab")
1292                                 open = 3;
1293                             else if (opt == "window")
1294                                 open = 2;
1295                             else if (opt == "resized")
1296                                 restriction = 2;
1297                         }
1298
1299                         prefs.safeSet("browser.link.open_newwindow", open,
1300                                       _("option.safeSet", "popups"));
1301                         prefs.safeSet("browser.link.open_newwindow.restriction", restriction,
1302                                       _("option.safeSet", "popups"));
1303                         return values;
1304                     },
1305                     values: {
1306                         "tab":     "Open popups in a new tab",
1307                         "window":  "Open popups in a new window",
1308                         "resized": "Open resized popups in a new window"
1309                     }
1310                 });
1311         }
1312     }
1313 });
1314
1315 // vim: set fdm=marker sw=4 ts=4 et: