Skip to content

Instantly share code, notes, and snippets.

@ptone
Created September 26, 2014 19:04
Show Gist options
  • Save ptone/06a52a0c5987353c41cb to your computer and use it in GitHub Desktop.
Save ptone/06a52a0c5987353c41cb to your computer and use it in GitHub Desktop.
A quick CLI tool to work with too many tabs
#!/bin/bash
export BROWSER='Google Chrome'
stab "$@"
#! /Users/ptone/Projects/Python/virtualenvs/appscript/bin/python
# -*- coding: utf-8 -*-
import codecs
import os
import re
import sys
from appscript import app
BROWSER = os.environ.get('BROWSER', 'Safari')
browser = app(BROWSER)
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
def get_tabs():
windows = browser.windows.get()
tabs = []
for w in windows:
w_tabs = w.tabs.get()
for i, t in enumerate(w_tabs):
t.window = w
if 'Chrome' in BROWSER:
t.index = i + 1
tabs.extend(w_tabs)
tabs.sort(key=lambda t: t.name.get().lower())
return tabs
def list_tabs(tabs=None):
if tabs is None:
tabs = get_tabs()
tabs = get_tabs()
for i, t in enumerate(tabs):
print i, t.name.get()
def open_tab(tabid, tabs=None):
if tabs is None:
tabs = get_tabs()
browser.activate()
tab = tabs[tabid]
window_id = tab.window.id.get()
browser.windows.ID(window_id).index.set(1)
if 'Chrome' in BROWSER:
browser.windows.ID(window_id).active_tab_index.set(tab.index)
elif 'Safari' in BROWSER:
browser.windows.ID(window_id).current_tab.set(tab)
def open_match(s):
tabs = get_tabs()
robj = re.compile(s, re.IGNORECASE)
for i, t in enumerate(tabs):
if robj.search(t.name.get()):
open_tab(i, tabs)
return
print "no matching tabs"
def main():
if len(sys.argv) == 1:
list_tabs()
else:
try:
tabid = int(sys.argv[1])
open_tab(tabid)
except ValueError:
open_match(sys.argv[1])
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment