Programmatically read both per-tab Terminal.app titles

applescriptcocoascriptterminal

When bringing up the Inspector (⌘I) in Terminal.app to edit the title (⇧⌘I), there are actually two titles that can be entered. The first is known as the Tab Title and affects the terminal window title (but only when that tab is selected). The second is the Tab Subtitle and affects the text in the tab header only. [The naming seems strange, with Tab Title affecting the title of the window, and Tab Subtitle affecting the title of the tab.]

Preferring osascript, but open to other approaches, I wish to programmatically get both of these titles for each tab. In going through AppleScript dictionaries, Cocoa framework docs, etc., I have only found how to read the Tab Title, surfaced as the "custom title" (custom_title) property of the tab. This is the one that all search hits on getting/setting the title via osascript refer to. Even though there are other title properties in the window and tab.current_settings it seems that they all reference only this first title field and there is therefore some redundancy.

I am setting each title programmatically using terminal escape sequences, as I similarly do not know how to set the Tab Subtitle.

Although it is possible to use UI scripting, I expect that such an approach will have to visibly cycle through all Terminal windows/tabs in order to read them all when producing the overall output that I desire. I would prefer something that can get at the data without causing selection/focus changes.

My last option seems a little heavyweight (though may still be preferable to UI scripting) which is to export the settings (Shell > Export Settings…) which produces a large XML file which does include both fields. Surprisingly the data structures in this file match the AppleScript structures almost identically, except that it includes the field I'm otherwise missing.

Being quite new to programming on the Apple platform, can anyone enlighten me to how I can get at this data that seems it should exist in the place I am looking but that I am unable to find?

Best Answer

Try:

tell application "Terminal"
    set myTabs to every tab of window 1
    set myData to {}
    repeat with aTab in myTabs
        set aTab's selected to true
        delay 0.2
        set windowTitle to name of window 1
        set customTitle to aTab's custom title
        set end of myData to "Window:" & windowTitle & return & "Custom Title:" & customTitle & return & return
    end repeat
    display dialog (myData as text)
end tell