Keyboard Maestro Variables: Remember Current Application

November 21, 2011 by Gabe | [mmd] |

I was recently wasting some time playing with an idea. I wanted an easy and quick way to grab some text in any arbitrary application and pop over to MultiMarkdown Composer to do some editing. I also wanted a way to pop the text back into the original app when I was done.

You might be yelling at the screen right now telling me to just use the cmd-tab to switch back and paste the text. Don’t yell at me. What if I had quickly jumped to Safari to check a link, or looked for a contact or previous mail message? So much for the super quick cmd-tab application switcher.

Well, there’s an easy way to do this with Keyboard Maestro and it involves a bit of variable magic. So why not learn a little something about my favorite macro application?

This solution is two separate macros. The first macro grabs the text and the name of the application. The second macro takes the edited text and returns to the original app for insertion.

Macro One

Set the variable “currentApp” to the currently running application name. Next, simulate cmd-A and cmd-C to get the text. The macro then switches to MultiMarkdown Composer and simulates cmd-N and cmd-V to create a new document and insert the text.

KM Macro 1

Macro Two

Now we’re done editing and looking up links and taking a break and playing AlphaBaby with our three year old. We want to send the text back to whatever application we were originally working in. Luckily, Keyboard Maestro variables persist across restarts and shutdowns, which is more than I can say about my memory.

The second macro performs a cmd-A and cmd-C to grab all of our polished text.[1] The trick is that bit of AppleScript in the middle.

KM Macro 2

tell application “Keyboard Maestro Engine”

set kmVarApp to (process tokens “%Variable%currentApp%”) as text

end tell

tell application kmVarApp

activate

end tell

This script accesses the Keyboard Maestro variable using the “process tokens” function provided by the Keyboard Maestro Engine. That allows access to any variable or token available in KM. The script then launches the application by name.

Finally, the macro does the cmd-A and cmd-V to insert the new text. Boom.

We’re done here.


  1. This works from the preview window as well.

blog comments powered by Disqus