Is it possible to "Open a File" in the application designated by a variable?

I just wrote a macro to make ⌘D switch between ~/Desktop and ~/Downloads. I want the keystroke to work properly in both Finder and Path Finder, so I had to use nested if/then/else actions:

Is there any way to get rid of those inner ifs, either by choosing "with front application" or by stashing an app name in a variable? If not, consider this a feature request to enhance the "with" application picker in one or both of those ways.

Sadly the Open File action does not support a “with front application” option (it probably should, but it doesn’t).

Two comments - you should probably use ~ instead of /Users/username (so ~/Downloads and ~/Desktop) - it makes it clearer and shorter and avoids any dependency on your username which might change if you share your macros (syncing to another Mac or sharing with others on the forum for example). ~ is just shorthand for “your home directory” and should work in any path in Keyboard Maestro as well as paths in most scripting languages (but not all in all cases).

You could avoid the nested Ifs by doing something like this:

  • If front window title is “Desktop” then
    • Set variable Target to “~/Downloads”
  • Else
    • Set variable Target to “~/Desktop”
  • If front application is “Finder” then
    • Open file “%Variable%Target%” with Finder
  • Else
    • Open file “%Variable%Target%” with Path Finder

Thank you for the confirmation and the tips! I built the outer if/then action first and didn’t think about redoing it and making that one use a variable.

Hey Lanny,

This is one of those jobs that can be done more organically with AppleScript.

Finder and Path Finder → Toggle between Desktop folder and Downloads folder.kmmacros (3.5 KB)

And while Keyboard Maestro won't (at present) open a file with the frontmost application, it can be done with AppleScript.

set fileAlias to alias ((path to desktop as text) & "Crunchy Roll.txt")
set frontAppHFS to path to frontmost application as text
tell application frontAppHFS to open fileAlias


1 Like