Search code examples
macosapplescriptterminal.app

AppleScript for minimizing Terminal windows gets an error


I often have several Terminal windows running, to login to various servers for work. To tidy up the screen, I have an AppleScript that minimizes all the windows other than the frontmost one (analogous with the Apple menu's "Hide Others" for applications). Since upgrading to MacOS Sonoma, it has been getting an error.

The script is

tell application "Terminal"
    repeat with thewindow in (get every window where frontmost is false)
        set miniaturized of thewindow to true
    end repeat
end tell

When I run it, I get the error:

error "Terminal got an error: AppleEvent handler failed." number -10000

In Script Editor, it highlights every window where frontmost is false) when this happens.

What's wrong with that expression?


Solution

  • What happens if you try something like this? I'm not running Sonoma so it's just a suggestion.

    Either way, it might help if you break that line into two parts (and create the list before the repeat loop).

    tell application "Terminal"
        set ev to rest of (get every window)
        
        repeat with win in ev
            set miniaturized of win to true
        end repeat  
        
    end tell
    

    Update: If you need certainty, you can add a specific check for frontmost as your comment suggests but the property seems to be flaky.

    Here is a way to break it down. I have three open windows, the front window ID is 2639.

    tell application "Terminal"
        set fw to front window
        set fid to id of fw
        --> 2639
        
        set ev to rest of (get every window)
        --> {window id 5330, window id 5120, window id 2639} -- every window
        ev -- rest of windows
        --> {window id 5330 of application "Terminal", window id 5120 of application "Terminal"}
        -- Note that the second output includes the owning application… this is probably why your additional command didn't work
        
        set wids to rest of (get id of every window)
        --> {5330, 5120, 2639} -- every window id
        wids -- id of non-frontmost windows
        {5120, 5330}
        
        wids contains fid -- i.e. {5120, 5330} contains 2639
        --> false
        
    end tell
    
    

    Is there anything else in your script? Or do you have anything going on that would change the order of the windows while the script runs?