]> git.donarmstrong.com Git - dactyl.git/blob - common/content/tabs.js
Import r6948 from upstream hg supporting Firefox up to 24.*
[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      * Return an iterator of tabs matching the given filter. If no
340      * *filter* or *count* is provided, returns the currently selected
341      * tab. If *filter* is a number or begins with a number followed
342      * by a colon, the tab of that ordinal is returned. Otherwise,
343      * tabs matching the filter as below are returned.
344      *
345      * @param {string} filter The filter. If *regexp*, this is a
346      *      regular expression against which the tab's URL or title
347      *      must match. Otherwise, it is a site filter.
348      *      @optional
349      * @param {number|null} count If non-null, return only the
350      *      *count*th matching tab.
351      *      @optional
352      * @param {boolean} regexp Whether to interpret *filter* as a
353      *      regular expression.
354      * @param {boolean} all If true, match against all tabs. If
355      *      false, match only tabs in the current tab group.
356      */
357     match: function match(filter, count, regexp, all) {
358         if (!filter && count == null)
359             yield tabs.getTab();
360         else if (!filter)
361             yield dactyl.assert(tabs.getTab(count - 1));
362         else {
363             let matches = /^(\d+)(?:$|:)/.exec(filter);
364             if (matches)
365                 yield dactyl.assert(count == null &&
366                                     tabs.getTab(parseInt(matches[1], 10) - 1, !all));
367             else {
368                 if (regexp)
369                     regexp = util.regexp(filter, "i");
370                 else
371                     var matcher = Styles.matchFilter(filter);
372
373                 for (let tab in values(tabs[all ? "allTabs" : "visibleTabs"])) {
374                     let browser = tab.linkedBrowser;
375                     let uri = browser.currentURI;
376                     let title;
377                     if (uri.spec == "about:blank")
378                         title = "(Untitled)";
379                     else
380                         title = browser.contentTitle;
381
382                     if (matcher && matcher(uri)
383                         || regexp && (regexp.test(title) || regexp.test(uri.spec)))
384                         if (count == null || --count == 0)
385                             yield tab;
386                 }
387             }
388         }
389     },
390
391     /**
392      * Moves a tab to a new position in the tab list.
393      *
394      * @param {Object} tab The tab to move.
395      * @param {string} spec See {@link Tabs.indexFromSpec}.
396      * @param {boolean} wrap Whether an out of bounds *spec* causes the
397      *     destination position to wrap around the start/end of the tab list.
398      */
399     move: function move(tab, spec, wrap) {
400         let index = tabs.indexFromSpec(spec, wrap, -1);
401         config.tabbrowser.moveTabTo(tab, index);
402     },
403
404     /**
405      * Removes the specified *tab* from the tab list.
406      *
407      * @param {Object} tab The tab to remove.
408      * @param {number} count How many tabs to remove.
409      * @param {boolean} focusLeftTab Focus the tab to the left of the removed tab.
410      */
411     remove: function remove(tab, count, focusLeftTab) {
412         count = count || 1;
413         let res = this.count > count;
414
415         let tabs = this.visibleTabs;
416         if (tabs.indexOf(tab) < 0)
417             tabs = this.allTabs;
418         let index = tabs.indexOf(tab);
419
420         let next = index + (focusLeftTab ? -count : count);
421         if (!(next in tabs))
422             next = index + (focusLeftTab ? 1 : -1);
423         if (next in tabs) {
424             this._alternates[0] = tabs[next];
425             config.tabbrowser.mTabContainer.selectedItem = tabs[next];
426         }
427
428         if (focusLeftTab)
429             tabs.slice(Math.max(0, index + 1 - count), index + 1).forEach(config.closure.removeTab);
430         else
431             tabs.slice(index, index + count).forEach(config.closure.removeTab);
432         return res;
433     },
434
435     /**
436      * Reloads the specified tab.
437      *
438      * @param {Object} tab The tab to reload.
439      * @param {boolean} bypassCache Whether to bypass the cache when
440      *     reloading.
441      */
442     reload: function reload(tab, bypassCache) {
443         try {
444             if (bypassCache) {
445                 const flags = Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY | Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
446                 config.tabbrowser.getBrowserForTab(tab).reloadWithFlags(flags);
447             }
448             else
449                 config.tabbrowser.reloadTab(tab);
450         }
451         catch (e if !(e instanceof Error)) {}
452     },
453
454     /**
455      * Reloads all tabs.
456      *
457      * @param {boolean} bypassCache Whether to bypass the cache when
458      *     reloading.
459      */
460     reloadAll: function reloadAll(bypassCache) {
461         this.visibleTabs.forEach(function (tab) {
462             try {
463                 tabs.reload(tab, bypassCache);
464             }
465             catch (e) {
466                 dactyl.reportError(e, true);
467             }
468         });
469     },
470
471     /**
472      * Selects the tab at the position specified by *spec*.
473      *
474      * @param {string} spec See {@link Tabs.indexFromSpec}
475      * @param {boolean} wrap Whether an out of bounds *spec* causes the
476      *     selection position to wrap around the start/end of the tab list.
477      */
478     select: function select(spec, wrap) {
479         let index = tabs.indexFromSpec(spec, wrap);
480         if (index == -1)
481             dactyl.beep();
482         else
483             config.tabbrowser.mTabContainer.selectedIndex = index;
484     },
485
486     /**
487      * Selects the alternate tab.
488      */
489     selectAlternateTab: function selectAlternateTab() {
490         dactyl.assert(tabs.alternate != null && tabs.getTab() != tabs.alternate,
491                       _("buffer.noAlternate"));
492         tabs.select(tabs.alternate);
493     },
494
495     /**
496      * Stops loading the specified tab.
497      *
498      * @param {Object} tab The tab to stop loading.
499      */
500     stop: function stop(tab) {
501         if (config.stop)
502             config.stop(tab);
503         else
504             tab.linkedBrowser.stop();
505     },
506
507     /**
508      * Stops loading all tabs.
509      */
510     stopAll: function stopAll() {
511         for (let [, browser] in this.browsers)
512             browser.stop();
513     },
514
515     /**
516      * Selects the tab containing the specified *buffer*.
517      *
518      * @param {string} buffer A string which matches the URL or title of a
519      *     buffer, if it is null, the last used string is used again.
520      * @param {boolean} allowNonUnique Whether to select the first of
521      *     multiple matches.
522      * @param {number} count If there are multiple matches select the
523      *     *count*th match.
524      * @param {boolean} reverse Whether to search the buffer list in
525      *     reverse order.
526      *
527      */
528     // FIXME: help!
529     switchTo: function switchTo(buffer, allowNonUnique, count, reverse) {
530         if (buffer != null) {
531             // store this command, so it can be repeated with "B"
532             this._lastBufferSwitchArgs = buffer;
533             this._lastBufferSwitchSpecial = allowNonUnique;
534         }
535         else {
536             buffer = this._lastBufferSwitchArgs;
537             if (allowNonUnique == null) // XXX
538                 allowNonUnique = this._lastBufferSwitchSpecial;
539         }
540
541         if (buffer == "#")
542             return tabs.selectAlternateTab();
543
544         reverse = Boolean(reverse);
545         count = Math.max(1, count || 1) * (1 + -2 * reverse);
546
547         let matches = buffer.match(/^(\d+):?/);
548         if (matches)
549             return tabs.select(this.allTabs[parseInt(matches[1], 10) - 1], false);
550
551         matches = array.nth(tabs.allTabs, function (t) (t.linkedBrowser.lastURI || {}).spec === buffer, 0);
552         if (matches)
553             return tabs.select(matches, false);
554
555         matches = completion.runCompleter("buffer", buffer).map(function (obj) obj.tab);
556
557         if (matches.length == 0)
558             dactyl.echoerr(_("buffer.noMatching", buffer));
559         else if (matches.length > 1 && !allowNonUnique)
560             dactyl.echoerr(_("buffer.multipleMatching", buffer));
561         else {
562             let start = matches.indexOf(tabs.getTab());
563             if (start == -1 && reverse)
564                 start++;
565
566             let index = (start + count) % matches.length;
567             if (index < 0)
568                 index = matches.length + index;
569             tabs.select(matches[index], false);
570         }
571     },
572
573     // NOTE: when restarting a session FF selects the first tab and then the
574     // tab that was selected when the session was created.  As a result the
575     // alternate after a restart is often incorrectly tab 1 when there
576     // shouldn't be one yet.
577     /**
578      * Sets the current and alternate tabs, updating the tab selection
579      * history.
580      *
581      * @param {Array(Object)} tabs The current and alternate tab.
582      * @see tabs#alternate
583      */
584     updateSelectionHistory: function updateSelectionHistory(tabs) {
585         if (!tabs) {
586             if (this.getTab() == this._alternates[0]
587                 || this.alternate && this.allTabs.indexOf(this._alternates[0]) == -1
588                 || this.alternate && config.tabbrowser._removingTabs && config.tabbrowser._removingTabs.indexOf(this._alternates[0]) >= 0)
589                 tabs = [this.getTab(), this.alternate];
590         }
591         this._alternates = tabs || [this.getTab(), this._alternates[0]];
592     }
593 }, {
594     copyTab: function (to, from) {
595         if (!from)
596             from = config.tabbrowser.mTabContainer.selectedItem;
597
598         let tabState = services.sessionStore.getTabState(from);
599         services.sessionStore.setTabState(to, tabState);
600     }
601 }, {
602     load: function initLoad() {
603         tabs.updateTabCount();
604     },
605     commands: function initCommands() {
606         [
607             {
608                 name: ["bd[elete]"],
609                 description: "Delete matching buffers",
610                 visible: false
611             },
612             {
613                 name: ["tabc[lose]"],
614                 description: "Delete matching tabs",
615                 visible: true
616             }
617         ].forEach(function (params) {
618             commands.add(params.name, params.description,
619                 function (args) {
620                     let removed = 0;
621                     for (let tab in tabs.match(args[0], args.count, args.bang, !params.visible)) {
622                         config.removeTab(tab);
623                         removed++;
624                     }
625
626                     if (args[0])
627                         if (removed > 0)
628                             dactyl.echomsg(_("buffer.fewerTab" + (removed == 1 ? "" : "s"), removed), 9);
629                         else
630                             dactyl.echoerr(_("buffer.noMatching", args[0]));
631                 }, {
632                     argCount: "?",
633                     bang: true,
634                     count: true,
635                     completer: function (context) completion.buffer(context),
636                     literal: 0,
637                     privateData: true
638                 });
639         });
640
641         commands.add(["pin[tab]"],
642             "Pin tab as an application tab",
643             function (args) {
644                 for (let tab in tabs.match(args[0], args.count))
645                     config.browser[!args.bang || !tab.pinned ? "pinTab" : "unpinTab"](tab);
646             },
647             {
648                 argCount: "?",
649                 bang: true,
650                 count: true,
651                 completer: function (context, args) {
652                     if (!args.bang)
653                         context.filters.push(function ({ item }) !item.tab.pinned);
654                     completion.buffer(context);
655                 }
656             });
657
658         commands.add(["unpin[tab]"],
659             "Unpin tab as an application tab",
660             function (args) {
661                 for (let tab in tabs.match(args[0], args.count))
662                     config.browser.unpinTab(tab);
663             },
664             {
665                 argCount: "?",
666                 count: true,
667                 completer: function (context, args) {
668                     context.filters.push(function ({ item }) item.tab.pinned);
669                     completion.buffer(context);
670                 }
671             });
672
673         commands.add(["keepa[lt]"],
674             "Execute a command without changing the current alternate buffer",
675             function (args) {
676                 try {
677                     dactyl.execute(args[0], null, true);
678                 }
679                 finally {
680                     tabs.updateSelectionHistory([tabs.getTab(), tabs.alternate]);
681                 }
682             }, {
683                 argCount: "1",
684                 completer: function (context) completion.ex(context),
685                 literal: 0,
686                 subCommand: 0
687             });
688
689         commands.add(["tab"],
690             "Execute a command and tell it to output in a new tab",
691             function (args) {
692                 dactyl.withSavedValues(["forceTarget"], function () {
693                     this.forceTarget = dactyl.NEW_TAB;
694                     dactyl.execute(args[0], null, true);
695                 });
696             }, {
697                 argCount: "1",
698                 completer: function (context) completion.ex(context),
699                 literal: 0,
700                 subCommand: 0
701             });
702
703         commands.add(["background", "bg"],
704             "Execute a command opening any new tabs in the background",
705             function (args) {
706                 dactyl.withSavedValues(["forceBackground"], function () {
707                     this.forceBackground = true;
708                     dactyl.execute(args[0], null, true);
709                 });
710             }, {
711                 argCount: "1",
712                 completer: function (context) completion.ex(context),
713                 literal: 0,
714                 subCommand: 0
715             });
716
717         commands.add(["tabd[o]", "bufd[o]"],
718             "Execute a command in each tab",
719             function (args) {
720                 for (let tab in values(tabs.visibleTabs)) {
721                     tabs.select(tab);
722                     dactyl.execute(args[0], null, true);
723                 }
724             }, {
725                 argCount: "1",
726                 completer: function (context) completion.ex(context),
727                 literal: 0,
728                 subCommand: 0
729             });
730
731         commands.add(["tabl[ast]", "bl[ast]"],
732             "Switch to the last tab",
733             function () tabs.select("$", false),
734             { argCount: "0" });
735
736         // TODO: "Zero count" if 0 specified as arg
737         commands.add(["tabp[revious]", "tp[revious]", "tabN[ext]", "tN[ext]", "bp[revious]", "bN[ext]"],
738             "Switch to the previous tab or go [count] tabs back",
739             function (args) {
740                 let count = args.count;
741                 let arg   = args[0];
742
743                 // count is ignored if an arg is specified, as per Vim
744                 if (arg) {
745                     if (/^\d+$/.test(arg))
746                         tabs.select("-" + arg, true);
747                     else
748                         dactyl.echoerr(_("error.trailingCharacters"));
749                 }
750                 else if (count > 0)
751                     tabs.select("-" + count, true);
752                 else
753                     tabs.select("-1", true);
754             }, {
755                 argCount: "?",
756                 count: true
757             });
758
759         // TODO: "Zero count" if 0 specified as arg
760         commands.add(["tabn[ext]", "tn[ext]", "bn[ext]"],
761             "Switch to the next or [count]th tab",
762             function (args) {
763                 let count = args.count;
764                 let arg   = args[0];
765
766                 if (arg || count > 0) {
767                     let index;
768
769                     // count is ignored if an arg is specified, as per Vim
770                     if (arg) {
771                         dactyl.assert(/^\d+$/.test(arg), _("error.trailingCharacters"));
772                         index = arg - 1;
773                     }
774                     else
775                         index = count - 1;
776
777                     if (index < tabs.count)
778                         tabs.select(index, true);
779                     else
780                         dactyl.beep();
781                 }
782                 else
783                     tabs.select("+1", true);
784             }, {
785                 argCount: "?",
786                 count: true
787             });
788
789         commands.add(["tabr[ewind]", "tabfir[st]", "br[ewind]", "bf[irst]"],
790             "Switch to the first tab",
791             function () { tabs.select(0, false); },
792             { argCount: "0" });
793
794         if (config.has("tabbrowser")) {
795             commands.add(["b[uffer]"],
796                 "Switch to a buffer",
797                 function (args) { tabs.switchTo(args[0], args.bang, args.count); }, {
798                     argCount: "?",
799                     bang: true,
800                     count: true,
801                     completer: function (context) completion.buffer(context),
802                     literal: 0,
803                     privateData: true
804                 });
805
806             commands.add(["buffers", "files", "ls", "tabs"],
807                 "Show a list of all buffers",
808                 function (args) { tabs.list(args[0] || ""); }, {
809                     argCount: "?",
810                     literal: 0
811                 });
812
813             commands.add(["quita[ll]", "qa[ll]"],
814                 "Quit this " + config.appName + " window",
815                 function (args) { window.close(); },
816                 { argCount: "0" });
817
818             commands.add(["reloada[ll]"],
819                 "Reload all tab pages",
820                 function (args) { tabs.reloadAll(args.bang); }, {
821                     argCount: "0",
822                     bang: true
823                 });
824
825             commands.add(["stopa[ll]"],
826                 "Stop loading all tab pages",
827                 function () { tabs.stopAll(); },
828                 { argCount: "0" });
829
830             // TODO: add count and bang multimatch support - unify with :buffer nonsense
831             commands.add(["tabm[ove]"],
832                 "Move the current tab to the position of tab N",
833                 function (args) {
834                     let arg = args[0];
835
836                     if (tabs.indexFromSpec(arg) == -1) {
837                         let list = [tab for (tab in tabs.match(args[0], args.count, true))];
838                         dactyl.assert(list.length, _("error.invalidArgument", arg));
839                         dactyl.assert(list.length == 1, _("buffer.multipleMatching", arg));
840                         arg = list[0];
841                     }
842                     tabs.move(tabs.getTab(), arg, args.bang);
843                 }, {
844                     argCount: "1",
845                     bang: true,
846                     completer: function (context, args) completion.buffer(context, true),
847                     literal: 0
848                 });
849
850             commands.add(["tabo[nly]"],
851                 "Close all other tabs",
852                 function () { tabs.keepOnly(tabs.getTab()); },
853                 { argCount: "0" });
854
855             commands.add(["tabopen", "t[open]", "tabnew"],
856                 "Open one or more URLs in a new tab",
857                 function (args) {
858                     dactyl.open(args[0] || "about:blank",
859                                 { from: "tabopen", where: dactyl.NEW_TAB, background: args.bang });
860                 }, {
861                     bang: true,
862                     completer: function (context) completion.url(context),
863                     domains: function (args) commands.get("open").domains(args),
864                     literal: 0,
865                     privateData: true
866                 });
867
868             commands.add(["tabde[tach]"],
869                 "Detach current tab to its own window",
870                 function () { tabs.detachTab(null); },
871                 { argCount: "0" });
872
873             commands.add(["tabdu[plicate]"],
874                 "Duplicate current tab",
875                 function (args) {
876                     let tab = tabs.getTab();
877
878                     let activate = args.bang ? true : false;
879                     if (options.get("activate").has("tabopen"))
880                         activate = !activate;
881
882                     for (let i in util.range(0, Math.max(1, args.count)))
883                         tabs.cloneTab(tab, activate);
884                 }, {
885                     argCount: "0",
886                     bang: true,
887                     count: true
888                 });
889
890             // TODO: match window by title too?
891             //     : accept the full :tabmove arg spec for the tab index arg?
892             //     : better name or merge with :tabmove?
893             commands.add(["taba[ttach]"],
894                 "Attach the current tab to another window",
895                 function (args) {
896                     dactyl.assert(args.length <= 2 && !args.some(function (i) !/^\d+(?:$|:)/.test(i)),
897                                   _("error.trailingCharacters"));
898
899                     let [winIndex, tabIndex] = args.map(function (arg) parseInt(arg));
900                     if (args["-group"]) {
901                         util.assert(args.length == 1);
902                         window.TabView.moveTabTo(tabs.getTab(), winIndex);
903                         return;
904                     }
905
906                     let win = dactyl.windows[winIndex - 1];
907                     let sourceTab = tabs.getTab();
908
909                     dactyl.assert(win, _("window.noIndex", winIndex));
910                     dactyl.assert(win != window, _("window.cantAttachSame"));
911
912                     let modules     = win.dactyl.modules;
913                     let { browser } = modules.config;
914
915                     if (args[1]) {
916                         let tabList = modules.tabs.visibleTabs;
917                         let target  = dactyl.assert(tabList[tabIndex]);
918                         tabIndex = Array.indexOf(tabs.allTabs, target) - 1;
919                     }
920
921                     let newTab = browser.addTab("about:blank");
922                     browser.stop();
923                     // XXX: the implementation of DnD in tabbrowser.xml suggests
924                     // that we may not be guaranteed of having a docshell here
925                     // without this reference?
926                     browser.docShell;
927
928                     let last = modules.tabs.allTabs.length - 1;
929
930                     if (args[1])
931                         browser.moveTabTo(newTab, tabIndex);
932                     browser.selectedTab = newTab; // required
933                     browser.swapBrowsersAndCloseOther(newTab, sourceTab);
934                 }, {
935                     argCount: "+",
936                     literal: 1,
937                     completer: function (context, args) {
938                         switch (args.completeArg) {
939                         case 0:
940                             if (args["-group"])
941                                 completion.tabGroup(context);
942                             else {
943                                 context.filters.push(function ({ item }) item != window);
944                                 completion.window(context);
945                             }
946                             break;
947                         case 1:
948                             if (!args["-group"]) {
949                                 let win = dactyl.windows[Number(args[0]) - 1];
950                                 if (!win || !win.dactyl)
951                                     context.message = _("Error", _("window.noIndex", winIndex));
952                                 else
953                                     win.dactyl.modules.commands.get("tabmove").completer(context);
954                             }
955                             break;
956                         }
957                     },
958                     options: [
959                         {
960                             names: ["-group", "-g"],
961                             description: "Attach to a group rather than a window",
962                             type: CommandOption.NOARG
963                         }
964                     ]
965                 });
966         }
967
968         if (dactyl.has("tabs_undo")) {
969             commands.add(["u[ndo]"],
970                 "Undo closing of a tab",
971                 function (args) {
972                     if (args.length)
973                         args = args[0];
974                     else
975                         args = args.count || 0;
976
977                     let m = /^(\d+)(:|$)/.exec(args || '1');
978                     if (m)
979                         window.undoCloseTab(Number(m[1]) - 1);
980                     else if (args) {
981                         for (let [i, item] in Iterator(tabs.closedTabs))
982                             if (item.state.entries[item.state.index - 1].url == args) {
983                                 window.undoCloseTab(i);
984                                 return;
985                             }
986
987                         dactyl.echoerr(_("buffer.noClosed"));
988                     }
989                 }, {
990                     argCount: "?",
991                     completer: function (context) {
992                         context.anchored = false;
993                         context.compare = CompletionContext.Sort.unsorted;
994                         context.filters = [CompletionContext.Filter.textDescription];
995                         context.keys = { text: function ([i, { state: s }]) (i + 1) + ": " + s.entries[s.index - 1].url, description: "[1].title", icon: "[1].image" };
996                         context.completions = Iterator(tabs.closedTabs);
997                     },
998                     count: true,
999                     literal: 0,
1000                     privateData: true
1001                 });
1002
1003             commands.add(["undoa[ll]"],
1004                 "Undo closing of all closed tabs",
1005                 function (args) {
1006                     for (let i in Iterator(tabs.closedTabs))
1007                         window.undoCloseTab(0);
1008
1009                 },
1010                 { argCount: "0" });
1011
1012         }
1013
1014         if (dactyl.has("session")) {
1015             commands.add(["wqa[ll]", "wq", "xa[ll]"],
1016                 "Save the session and quit",
1017                 function () { dactyl.quit(true); },
1018                 { argCount: "0" });
1019         }
1020     },
1021     completion: function initCompletion() {
1022
1023         completion.buffer = function buffer(context, visible) {
1024             let { tabs } = modules;
1025
1026             let filter = context.filter.toLowerCase();
1027
1028             let defItem = { parent: { getTitle: function () "" } };
1029
1030             let tabGroups = {};
1031             tabs.getGroups();
1032             tabs[visible ? "visibleTabs" : "allTabs"].forEach(function (tab, i) {
1033                 let group = (tab.tabItem || tab._tabViewTabItem || defItem).parent || defItem.parent;
1034                 if (!Set.has(tabGroups, group.id))
1035                     tabGroups[group.id] = [group.getTitle(), []];
1036
1037                 group = tabGroups[group.id];
1038                 group[1].push([i, tab.linkedBrowser]);
1039             });
1040
1041             context.pushProcessor(0, function (item, text, next) [
1042                 ["span", { highlight: "Indicator", style: "display: inline-block;" },
1043                     item.indicator],
1044                 next.call(this, item, text)
1045             ]);
1046             context.process[1] = function (item, text) template.bookmarkDescription(item, template.highlightFilter(text, this.filter));
1047
1048             context.anchored = false;
1049             context.keys = {
1050                 text: "text",
1051                 description: "url",
1052                 indicator: function (item) item.tab === tabs.getTab()  ? "%" :
1053                                            item.tab === tabs.alternate ? "#" : " ",
1054                 icon: "icon",
1055                 id: "id",
1056                 command: function () "tabs.select"
1057             };
1058             context.compare = CompletionContext.Sort.number;
1059             context.filters[0] = CompletionContext.Filter.textDescription;
1060
1061             for (let [id, vals] in Iterator(tabGroups))
1062                 context.fork(id, 0, this, function (context, [name, browsers]) {
1063                     context.title = [name || "Buffers"];
1064                     context.generate = function ()
1065                         Array.map(browsers, function ([i, browser]) {
1066                             let indicator = " ";
1067                             if (i == tabs.index())
1068                                 indicator = "%";
1069                             else if (i == tabs.index(tabs.alternate))
1070                                 indicator = "#";
1071
1072                             let tab = tabs.getTab(i, visible);
1073                             let url = browser.contentDocument.location.href;
1074                             i = i + 1;
1075
1076                             return {
1077                                 text: [i + ": " + (tab.label || /*L*/"(Untitled)"), i + ": " + url],
1078                                 tab: tab,
1079                                 id: i,
1080                                 url: url,
1081                                 icon: tab.image || BookmarkCache.DEFAULT_FAVICON
1082                             };
1083                         });
1084                 }, vals);
1085         };
1086
1087         completion.tabGroup = function tabGroup(context) {
1088             context.title = ["Tab Groups"];
1089             context.keys = {
1090                 text: "id",
1091                 description: function (group) group.getTitle() ||
1092                     group.getChildren().map(function (t) t.tab.label).join(", ")
1093             };
1094             context.generate = function () {
1095                 context.incomplete = true;
1096                 tabs.getGroups(function ({ GroupItems }) {
1097                     context.incomplete = false;
1098                     context.completions = GroupItems.groupItems;
1099                 });
1100             };
1101         };
1102     },
1103     events: function initEvents() {
1104         let tabContainer = config.tabbrowser.mTabContainer;
1105         function callback() {
1106             tabs.timeout(function () { this.updateTabCount(); });
1107         }
1108         for (let event in values(["TabMove", "TabOpen", "TabClose"]))
1109             events.listen(tabContainer, event, callback, false);
1110         events.listen(tabContainer, "TabSelect", tabs.closure._onTabSelect, false);
1111     },
1112     mappings: function initMappings() {
1113
1114         mappings.add([modes.COMMAND], ["<C-t>", "<new-tab-next>"],
1115             "Execute the next mapping in a new tab",
1116             function ({ count }) {
1117                 dactyl.forceTarget = dactyl.NEW_TAB;
1118                 mappings.afterCommands((count || 1) + 1, function () {
1119                     dactyl.forceTarget = null;
1120                 });
1121             },
1122             { count: true });
1123
1124         mappings.add([modes.NORMAL], ["g0", "g^"],
1125             "Go to the first tab",
1126             function () { tabs.select(0); });
1127
1128         mappings.add([modes.NORMAL], ["g$"],
1129             "Go to the last tab",
1130             function () { tabs.select("$"); });
1131
1132         mappings.add([modes.NORMAL], ["gt"],
1133             "Go to the next tab",
1134             function ({ count }) {
1135                 if (count != null)
1136                     tabs.select(count - 1, false);
1137                 else
1138                     tabs.select("+1", true);
1139             },
1140             { count: true });
1141
1142         mappings.add([modes.NORMAL], ["<C-n>", "<C-Tab>", "<C-PageDown>"],
1143             "Go to the next tab",
1144             function ({ count }) { tabs.select("+" + (count || 1), true); },
1145             { count: true });
1146
1147         mappings.add([modes.NORMAL], ["gT", "<C-p>", "<C-S-Tab>", "<C-PageUp>"],
1148            "Go to previous tab",
1149             function ({ count }) { tabs.select("-" + (count || 1), true); },
1150             { count: true });
1151
1152         if (config.has("tabbrowser")) {
1153             mappings.add([modes.NORMAL], ["b"],
1154                 "Open a prompt to switch buffers",
1155                 function ({ count }) {
1156                     if (count != null)
1157                         tabs.switchTo(String(count));
1158                     else
1159                         CommandExMode().open("buffer! ");
1160                 },
1161                 { count: true });
1162
1163             mappings.add([modes.NORMAL], ["B"],
1164                 "Show buffer list",
1165                 function () { tabs.list(false); });
1166
1167             mappings.add([modes.NORMAL], ["d"],
1168                 "Delete current buffer",
1169                 function ({ count }) { tabs.remove(tabs.getTab(), count, false); },
1170                 { count: true });
1171
1172             mappings.add([modes.NORMAL], ["D"],
1173                 "Delete current buffer, focus tab to the left",
1174                 function ({ count }) { tabs.remove(tabs.getTab(), count, true); },
1175                 { count: true });
1176
1177             mappings.add([modes.NORMAL], ["gb"],
1178                 "Repeat last :buffer command",
1179                 function ({ count }) { tabs.switchTo(null, null, count, false); },
1180                 { count: true });
1181
1182             mappings.add([modes.NORMAL], ["gB"],
1183                 "Repeat last :buffer command in reverse direction",
1184                 function ({ count }) { tabs.switchTo(null, null, count, true); },
1185                 { count: true });
1186
1187             // TODO: feature dependencies - implies "session"?
1188             if (dactyl.has("tabs_undo")) {
1189                 mappings.add([modes.NORMAL], ["u"],
1190                     "Undo closing of a tab",
1191                     function ({ count }) { ex.undo({ "#": count }); },
1192                     { count: true });
1193             }
1194
1195             mappings.add([modes.NORMAL], ["<C-^>", "<C-6>"],
1196                 "Select the alternate tab or the [count]th tab",
1197                 function ({ count }) {
1198                     if (count != null)
1199                         tabs.switchTo(String(count), false);
1200                     else
1201                         tabs.selectAlternateTab();
1202                 },
1203                 { count: true });
1204         }
1205     },
1206     options: function initOptions() {
1207         options.add(["showtabline", "stal"],
1208             "Define when the tab bar is visible",
1209             "string", true,
1210             {
1211                 setter: function (value) {
1212                     if (value === "never")
1213                         tabs.tabStyle.enabled = true;
1214                     else {
1215                         prefs.safeSet("browser.tabs.autoHide", value === "multitab",
1216                                       _("option.safeSet", "showtabline"));
1217                         tabs.tabStyle.enabled = false;
1218                     }
1219
1220                     if (value !== "multitab" || !dactyl.has("Gecko2"))
1221                         if (tabs.xulTabs)
1222                             tabs.xulTabs.visible = value !== "never";
1223                         else
1224                             config.tabStrip.collapsed = false;
1225
1226                     if (config.tabbrowser.tabContainer._positionPinnedTabs)
1227                         config.tabbrowser.tabContainer._positionPinnedTabs();
1228                     return value;
1229                 },
1230                 values: {
1231                     "never":    "Never show the tab bar",
1232                     "multitab": "Show the tab bar when there are multiple tabs",
1233                     "always":   "Always show the tab bar"
1234                 }
1235             });
1236
1237         if (config.has("tabbrowser")) {
1238             let activateGroups = [
1239                 ["all", "Activate everything"],
1240                 ["addons", ":addo[ns] command"],
1241                 ["bookmarks", "Tabs loaded from bookmarks", "loadBookmarksInBackground"],
1242                 ["diverted", "Links with targets set to new tabs", "loadDivertedInBackground"],
1243                 ["downloads", ":downl[oads] command"],
1244                 ["extoptions", ":exto[ptions] command"],
1245                 ["help", ":h[elp] command"],
1246                 ["homepage", "gH mapping"],
1247                 ["links", "Middle- or Control-clicked links", "loadInBackground"],
1248                 ["quickmark", "go and gn mappings"],
1249                 ["tabopen", ":tabopen[!] command"],
1250                 ["paste", "P and gP mappings"]
1251             ];
1252             options.add(["activate", "act"],
1253                 "Define when newly created tabs are automatically activated",
1254                 "stringlist", [g[0] for (g in values(activateGroups.slice(1))) if (!g[2] || !prefs.get("browser.tabs." + g[2]))].join(","),
1255                 {
1256                     values: activateGroups,
1257                     has: Option.has.toggleAll,
1258                     setter: function (newValues) {
1259                         let valueSet = Set(newValues);
1260                         for (let group in values(activateGroups))
1261                             if (group[2])
1262                                 prefs.safeSet("browser.tabs." + group[2],
1263                                               !(valueSet["all"] ^ valueSet[group[0]]),
1264                                               _("option.safeSet", "activate"));
1265                         return newValues;
1266                     }
1267                 });
1268
1269             options.add(["newtab"],
1270                 "Define which commands should output in a new tab by default",
1271                 "stringlist", "",
1272                 {
1273                     values: {
1274                         "all": "All commands",
1275                         "extoptions": ":exto[ptions] command",
1276                         "help": ":h[elp] command",
1277                         "prefs": ":pref[erences]! or :prefs! command"
1278                     },
1279                     has: Option.has.toggleAll
1280                 });
1281
1282             // TODO: Is this really applicable to Melodactyl?
1283             options.add(["popups", "pps"],
1284                 "Where to show requested popup windows",
1285                 "stringlist", "tab",
1286                 {
1287                     setter: function (values) {
1288                         let open = 1, restriction = 0;
1289                         for (let [, opt] in Iterator(values)) {
1290                             if (opt == "tab")
1291                                 open = 3;
1292                             else if (opt == "window")
1293                                 open = 2;
1294                             else if (opt == "resized")
1295                                 restriction = 2;
1296                         }
1297
1298                         prefs.safeSet("browser.link.open_newwindow", open,
1299                                       _("option.safeSet", "popups"));
1300                         prefs.safeSet("browser.link.open_newwindow.restriction", restriction,
1301                                       _("option.safeSet", "popups"));
1302                         return values;
1303                     },
1304                     values: {
1305                         "tab":     "Open popups in a new tab",
1306                         "window":  "Open popups in a new window",
1307                         "resized": "Open resized popups in a new window"
1308                     }
1309                 });
1310         }
1311     }
1312 });
1313
1314 // vim: set fdm=marker sw=4 sts=4 ts=8 et: