Minimize all but the active of the current application’s windows

applescriptkeyboardwindow-manager

I switch to, for example, Safari and find the window I want. I can Command-Option-H to hide all the other applications, but I also want to minimize all the Safari windows except the one I'm using (the front-most one).

Is there a way to do this? Would settle for an AppleScript I can trigger with Keyboard Maestro.

Best Answer

Here is an AppleScript that achieves the results of what you originally explicitly and specifically asked for, before editing the question after it was answered.

tell application "Safari"
    activate
    tell application "System Events"
        keystroke "h" using {command down, option down}
    end tell
    set miniaturized of (windows whose index is not 1) to true
end tell

Note: The above AppleScript works for me under OS X 10.8.5 and Safari 6.2.8 however I have not tested it on any other version of OS X. That said, I believe it will work fine on other versions of OS X.


Update to address the edit of the original question:

I played around a bit with different methods and what I found was, within the ways I tried, most apps worked while some would not. In other words, I didn't find a universal method that worked with all the apps I normally run. So, I'm adding a block of code that you can try and see if it can work for you.

Ideally simply hiding all other apps and minimizing the non-active windows of the current app so as to have a smooth appearance in action it what's desired however Finder presented a challenge. So in this example code Finder must minimize all it windows first and bring back what was the frontmost while other apps have a nice cascading effect to minimized non-active windows while leaving the frontmost windows as is.

tell application "System Events"
    set frontApp to name of first application process whose frontmost is true
    set windowName to name of first window of application process frontApp
end tell

if not frontApp is "Finder" then
    tell application frontApp
        activate
        tell application "System Events"
            keystroke "h" using {command down, option down}
        end tell
        set miniaturized of (windows whose name is not windowName) to true
    end tell
else
    tell application frontApp
        activate
        tell application "System Events"
            keystroke "h" using {command down, option down}
            keystroke "m" using {command down, option down}
            tell process frontApp to click menu item windowName of menu 1 of menu bar item "Window" of menu bar 1
        end tell
    end tell
end if