Programmatically Create New Tabs In Leopard’s Terminal
Categories: TechnologyThere’s a very handy script floating around that makes it easy to add an “Open Terminal Here” button to finder windows. It can even make sure the terminal goes into a new tab. For some reason, I wanted the tabs opened by this button to have a particular (non-default) them. Making this work proved trickier than it ought to be, because the script was just sending a command-t keystroke to the terminal in order to open a tab.
Despite a dictionary that looks promising, there does not seem to be a direct way to open new tabs from AppleScript. As a result, you have to resort to UI scripting. Thankfully, Jacob Rus has posted a very nice pair of helper functions that make menu clicks as easy as a list of {”Application”,”Menu”,”Submenu”,”Item”}. So opening tabs with a particular theme becomes:
on make_tab(style)
my menu_click({"Terminal", "Shell", "New Tab", style})
end make_tab
Just in case the pastie post goes away, here are the helper functions:
-- `menu_click`, by Jacob Rus, September 2006
--
-- Accepts a list of form: `{"Finder", "View", "Arrange By", "Date"}`
-- Execute the specified menu item. In this case, assuming the Finder
-- is the active application, arranging the frontmost folder by date.
on menu_click(mList)
local appName, topMenu, r
-- Validate our input
if mList's length < 3 then error "Menu list is not long enough"
-- Set these variables for clarity and brevity later on
set {appName, topMenu} to (items 1 through 2 of mList)
set r to (items 3 through (mList's length) of mList)
-- This overly-long line calls the menu_recurse function with
-- two arguments: r, and a reference to the top-level menu
tell app "System Events" to my menu_click_recurse(r, ((process appName)'s ¬
(menu bar 1)'s (menu bar item topMenu)'s (menu topMenu)))
end menu_click
on menu_click_recurse(mList, parentObject)
local f, r
-- `f` = first item, `r` = rest of items
set f to item 1 of mList
if mList's length > 1 then set r to (items 2 through (mList's length) of mList)
-- either actually click the menu item, or recurse again
tell app "System Events"
if mList's length is 1 then
click parentObject's menu item f
else
my menu_click_recurse(r, (parentObject's (menu item f)'s (menu f)))
end if
end tell
end menu_click_recurse
Leave a Reply
You must be logged in to post a comment.