Software > Tips and Tricks for Keyboard Maestro

Tips and Tricks for Keyboard Maestro

Tips and Tricks for Keyboard Maestro



Keyboard Maestro (4.3.1 at the time of original writing) is a fantastic macro program that I've been happily using (and beta testing) for years and for tons of different things. I won't list its features here, because there's too many of them (and you can find that list on its website) but I'm pretty sure that if you're reading this, you know about it already.

I'm so used to using KM that it has become almost completely intuitive to me, but reading and answering questions on KM's mailing list, I realized that some things which are obvious to me aren't so to everybody.

So I decided to share some of my experience with KM and compiled this list of tips and tricks. Enjoy! And if you find this page really useful and wonder how you might show your appreciation, well clicking the PayPal button at the bottom and making a small donation would do it quite nicely. :)

Updates:
Keyboard Maestro 5 has been released in July 2011, with lots and lots (and lots) of new features. There are many updates and new tips in the present document related to Keyboard Maestro 5, and they are indicated by this icon:
5
Keyboard Maestro 6 has been released in May 2013, again with tons of new features. Tips related with Keyboard Maestro 6 or added after its release will be indicated by this icon: 6

Contents

General organization

Organizing groups

I use KM's menu a lot. Most of my macros have for triggers a hotkey and the status menu item, so the hotkey is displayed in the menu when I need a reminder. And macros that are used too rarely to have a hotkey are in the menu too, of course. To organize all this, I have three different kinds of groups:

  1. groups whose macros are available in a given application and displayed in the menu
  2. groups that are available in all applications (AKA global groups) and displayed in the menu
  3. groups that are available in all applications but aren't displayed in the menu

All the group of the first kind are named like "• Application Name", so with the menu preferences I use (see below), for each frontmost application the macros specific to that application appear in a submenu named something like "• Application Name" displayed at the top of KM's menu (for example, see the • Mail submenu in the second screenshot below).

The groups of the second kind are named the usual way (for example "Clipboard"). I have a different group for each kind of task. For example "Clipboard" contains all my macros that deal with clipboards, "Text" contains only macros that affect text selections, "Launch" contains macros that launch applications or documents, and so on.

The last kind of group is named all in capitals, like "SWITCHERS", where I keep the macros to switch between applications and windows. "TAB SWITCHERS", where I keep the macros to switch between tabs in Safari and Fluid instances (I often use KM to remap hotkeys that are unpracticable on my AZERTY keyboards), or "RESTARTER" where I keep macros that run when an application launches to restore its windows.

That way I always know where to look for a given macro, and my KM menu and editor are neatly organized.

6 In KM6 you can give icons to groups and macros, which is pretty cool. It makes it even easier to find the group you're looking for:

TOC

Organizing the menus

My preferences for displaying the Status Menu are set to "Always Show Status Menu" and "Display Status Menu: Hierarchically" (from the General pane of the Preferences window). Along with using and naming groups as I explained above, it allows me to organize the menu nicely. But there's also a couple of tricks to organize the menu items themselves, like in the Text submenu below.

The first trick is that you can prefix a macro name with a number, followed by a closing parenthesis, and that prefix will be used for sorting the macros but won't be displayed in the menu or in palettes (thanks again to Peter for implementing that feature when I was the only one bugging him about it!). Here's what that Text submenu looks like from KM Editor:

The second trick is to use those prefixes to make separators out of empty macros, like "10)-" and "20)-" above. Since KM 5, you can use a dash as macro name, which is displayed in the menu as a separator.

5 Also new in KM 5, AFAIK, is the possibility to prefix group names in the same way, so you can reorder them too in the menu. The separator trick doesn't work with them, though.

TOC

Macros

Let's get into macros, now. Lots of them are made to simplify or automate tasks that are specific to me or to my workflows and would be of no use to anyone else. But I also have some macros that are more generalist and could be used by others.

Remote Editing

The first couple of macros is for KM itself. I use a lot the Execute AppleScript and Execute Shell Script actions, storing my scripts in KM (as opposed to having them in a file and just pointing KM to this file). The thing is, KM's text editor, in these actions, is only 5 lines tall, and sometimes that's not enough to work comfortably ( 5 update: this is no longer true in KM 5 whose text fields grow as you type). So I made a couple of macros to edit those scripts remotely.

"• KM Editor" group (available only in Keyboard Maestro)
"Start Remote Editing" macro
Trigger: ^E
Actions:
Type the ⌘A Keystroke Type the ⌘C Keystroke Activate Application: TextEdit.app Type the ⌘N Keystroke Type the ⌘V Keystroke Delete Current Clipboard

"• TextEdit" group (available only in TextEdit)
"End Remote Editing" macro
Trigger: ^S
Actions:
Type the ⌘A Keystroke Type the ⌘C Keystroke Type the ⌘W Keystroke Type the ⌘D Keystroke (note: on Lion, replace that with ⌘⌫ — that's Cmd-Delete) Activate Application: Keyboard Maestro.app Type the ⌘A Keystroke Type the ⌘V Keystroke Delete Current Clipboard

When I want to edit a script remotely, I just put the insertion point anywhere in the script, press ^E, and the script's text is selected, copied, and pasted into a new TextEdit document. When I'm done editing it, I press ^S and the text is selected and copied, the TextEdit window is closed without saving, the edited script is pasted into KM, replacing the previous version, and the clipboard is cleaned up.

5 You can find these macros in KM's Macro Library (available from Keyboard Maestro Editor's Window menu) under the name "Edit Scripts in TextEdit").

TOC

Private Clipboard 5

KM's clipboard history is extremely handy, but sometimes there are things you don't want to keep in the history, like passwords, for example. So I wrote a set of macros that gives KM a feature very similar to Safari's Private Browsing. I call it Private Clipboard.

6 Note: KM 6.1 conceals passwords in the clipboard history, which should make my Private Clipboard unnecessary if that's all you'd use it for.

This is made of three macros. The first one, Private Clipboard, does the main job, while the other two, Turn Private Clipboard ON and Turn Private Clipboard OFF are obviously used to turn it ON and OFF (but not only).

When it's ON, Private Clipboard will run in the background and keep deleting the clipboard one minute after it has changed. Here it is:

"Clipboard" group (available in all applications)
"Private Clipboard" macro
Trigger: While logged in: Repeat every 10 seconds
between 00:00 and 23:59
Actions:
If Conditions Met Execute Actions
If all of the following are true:
The clipboard is not __EMPTY__
execute the following actions:
If Conditions Met Execute Actions
If all of the following are true:
The variable
oldClip
is not %CurrentClipboard%
execute the following actions:
Comment: the clipboard's content changed Set Variable to Text
Set variable oldClip
to: %CurrentClipboard%
Set Variable to Calculation
Set variable countDown
to: 5
otherwise execute the following actions:
Comment: the clipboard's content didn't change If Conditions Met Execute Actions
If all of the following are true:
The variable
countDown
is 0
execute the following actions:
Comments: deleting the clipboard While Conditions Met Execute Actions
While all of the following are true:
The clipboard
does not contain __EMPTY__
execute the following actions: Delete Past Clipboard 0
Set Variable to Text
Set variable oldClip
to: %CurrentClipboard%
Set Variable to Calculation
Set variable countDown
to: 5
otherwise execute the following actions:
Comment: continuing the countDown Set Variable to Calculation
Set variable countDown
to: countDown - 1

Important: this macro must first be disabled in Keyboard Maestro Editor (click the √ button to get it greyed out).

Here's the macro to turn the Private Clipboard ON

"Clipboard" group (available in all applications)
"Turn Private Clipboard ON" macro
Trigger: Status Menu
Actions:
Set Clipboard to Text __EMPTY__ Enable Macro "Private Clipboard" Enable Macro "Turn Private Clipboard OFF" Disable Macro "Turn Private Clipboard ON"

Important: this macro must first be enabled in Keyboard Maestro Editor.

And finally here's the macro to turn the Private Clipboard OFF

"Clipboard" group (available in all applications)
"Turn Private Clipboard OFF" macro
Trigger: Status Menu
Actions: Disable Macro "Private Clipboard" While Conditions Met Execute Actions
While all of the following are true:
The clipboard
does not contain __EMPTY__
execute the following actions: Delete Past Clipboard 0
Delete Past Clipboard 0 Set Variable to Text
Set variable oldClip
to:   (empty)
Enable Macro "Turn Private Clipboard ON" Disable Macro "Turn Private Clipboard OFF"

Important: This macro too must first be disabled in Keyboard Maestro Editor.

How does it work, then? Here's how:

You start with the Private Clipboard disabled. When you select Turn Private Clipboard ON from the Status Menu, the text __EMPTY__ is copied to your clipboard, to protect your current history. Then the Private Clipboard macro starts running, the Turn Private Clipboard OFF macro gets enabled, and the Turn Private Clipboard ON macro gets disabled. So the next time you go to the Status Menu, the menu item you'll find there is Turn Private Clipboard OFF. And therefore you'll know the Private Clipboard is ON.

As I said above, the clipboard will then be deleted 60 seconds after it changed, each time it changes. And that includes everything you copied after you turned the Private Clipboard ON.

Finally, when you select the Turn Private Clipboard OFF menu item, the macro first deletes everything you copied until the clipboard contains __EMPTY__, then it deletes that __EMPTY__ entry too, and enables the Turn Private Clipboard ON again.

If you want to save yourself the trouble of building these macros, you can also download them.

TOC

Paste Without Styles

Sometimes you copy a link from an email or a webpage, and when you paste it somewhere, instead of the URL you'd expect, you get a link (clickable but not showing the URL). Or the text you paste brings its original font and style with it, and when you start typing again, you type in that same font and style.

To avoid these, I have this macro named "Paste Without Style" that just pastes the plain text version of the clipboard. It goes like this:

"Clipboard" group (available in all applications)
"Paste Without Styles" macro
Trigger: ^⌘V
Actions:
Filter Clipboard With: Remove Styles Type the ⌘V Keystroke Delete Current Clipboard

TOC

Multiple Clipboards

When you have to copy several snippets of text from one window to paste them into another, the usual way is to go back and forth between those windows, copying/pasting all those snippets one by one. Its much quicker (and handier) to copy them all, switch to the other window and then paste them all. Here's how I do it:

First, I have 8 named clipboards, named "Clipboard 1", "Clipboard 2", and so on (they can be created from the Clipboards pane of the Preferences window). Then, in my Clipboards group (available in all applications), I have 8 macros named "Copy 1", "Copy 2", and so on, whose sole action is (respectively) Copy to Clipboard 'Clipboard 1', Copy to Clipboard 'Clipboard 2', etc. (this is done with the action "Use a Named Clipboard"). All these macros have for trigger the keystroke ^C. I also have 8 similar macros named "Paste 1", "Paste 2", etc., whose action is Paste from Clipboard 'Clipboard 1', Paste from Clipboard 'Clipboard 2", and so on (again, from the action "Use a Named Clipboard"). All these are triggered by the keystroke ^V.

Now you may wonder what's the point of using the same trigger for 8 macros. Well, the point is that when a hotkey triggers several macros, KM displays a palette as displayed above (let's call it the "conflict palette") that lets you choose which of these macros to run, just with a click or the press of a number key. So if I have 2 snippets of text to copy/paste, it goes like this:

  • Select some text;
  • press ^C then 1;
  • select some other text;
  • press ^C then 2;
  • switch to the destination window;
  • put the insertion point somewhere;
  • press ^V then 1;
  • put the insertion point somewhere else;
  • press ^V then 2.

Important:

This is not intended to replace the system clipboard, but to complement it. Named clipboards and the system clipboard are separate and don't communicate with each others (unless you create a macro that makes them do so). Therefore, when you copy something to the system clipboard it won't be available to named clipboards and vice versa.

TOC

Application Launcher

How about a hotkey to open a palette showing various applications that you can launch or take to the front with one click or the press of a number key? Nothing's easier, using the conflict palette:

"LAUNCH APP" group (available in all applications)
"01)1. SysPrefs" macro
Trigger: ⌥⌘L
Action:
Activate: System Preferences.app "02)2. Keyboard Maestro" macro
Trigger: ⌥⌘L
Action:
Activate: Keyboard Maestro.app "03)3. BBEdit" macro
Trigger: ⌥⌘L
Action:
Activate: BBEdit.app (and so on).

That's it. Now if I want to launch System Preferences, I press ⌥⌘L, then 1. Keyboard Maestro? I press ⌥⌘L then 2, and so on.

5 KM 5 also provides a new method for that: the Application Launcher action (it can be found in the Switchers Category). It doesn't allow as much control as the method above, as you can only select groups of applications to display ( Recent Applications, Running Applications, Applications and/or Utilities) but it displays them in a nice Cover Flow kind of view. Check it out!

TOC

Open Anything…

Want a hotkey that simply opens a navigation services dialog (same as pressing ⌘0 in any application) from where you can open or launch anything (including files and folders that aren't visible in the Finder)?

"Launch" group (available in all applications)
"Open Anything..." macro
Trigger: ⌃O
Action:

Execute AppleScript (text script, ignore results)
tell application "System Events"
    activate
    set f to choose file with invisibles
    set p to POSIX path of f
    do shell script "open " & quoted form of p
end tell

Note: Target System Events when you need to display a dialog from an AppleScript script triggered by KM, because the way KM runs AppleScript doesn't allow user interaction (make sure that "Enable access for assistive devices" is checked in the Universal Access preferences pane, though, or it wouldn't work). Alternatively, you can also target Finder.

Also, you can remove "with invisibles" if you don't want to see invisible items. Or you could have two versions of the macro, one that shows invisible items and one that doesn't (⌃⌥O and ⌃O respectively would be good hotkeys for these, then).

TOC

Get/Set Finder Label 6

I wanted to set the Finder Label of a file from a macro and realized there was no action to do it (I thought the Set File Attribute action allowed it, but it doesn't). So I made a couple of Plugin Actions to get and set the label:

In both cases the path can be set to a HFS path (such as Macintosh HD:Users:username:Desktop:file.txt), a POSIX path (such as /Volumes/Macintosh HD/Users/username/Desktop/file.txt), or to a variable that contains one of these (like in the examples above).

Similarly, the Label can be set to a label index (a number from 0 to 7, with 0 meaning no label) or to a token (like a variable such as %FileLabel% or a calculation such as %Calculate%FileLabel+1%).

Download Get Finder Label (8.3 KB)
Download Set Finder Label (8.6 KB)

To install Plugin Actions, just drop onto Keyboard Maestro's icon the zip files you downloaded.

BTW, making Plugin Actions like these is very easy, if you know a bit of scripting. If you're interested, I wrote a tutorial showing how to do it.

TOC

Do you have to regularly type menu glyphs (like ⌥, ⌘, ⇥, ⌫ or ↩)? If you do, you gotta admit that it's not quite handy. Here's my solution:

"Menu Glyphs" group (available in all applications)
"←" macro
Trigger: Menu
Action:
Insert text by pasting "→" macro
Trigger: Menu
Action:
Insert text by pasting "↑" macro
Trigger: Menu
Action:
Insert text by pasting etc.

Note that the text has to be inserted by pasting rather than typing. Or to save you the trouble, you can download my Menu Glyphs group from here.

5 That macros group is now available also through KM 5's Macro Library under the name "Menu Glyphs" (you can access the Library from Keyboard Maestro Editor's Window menu).

TOC

Transforming the Selection

Most commands in my Text submenu visible in the first screenshot (even though I moved out a bunch of macros to make the screenshot smaller) use the Filter Clipboard action, which is very handy. Basically, they go like this:

"Text" group (available in all applications)
"Lowercase Selection" macro
Triggers: ⌃L, Status Menu
Actions:
Type the ⌘C Keystroke Filter Clipboard: Lowercase Type the ⌘V Keystroke Delete Current Clipboard

Check out the options in the Filter Clipboard action. There's a lot of great stuff, in there!

TOC

Web Popups

KM provides a Google action (in the Miscellaneous category), that pops up a little dialog where you can type a Google search query whose results will be displayed directly in your default browser. Pretty cool! But it only works with Google. What if you often wanted to run a quick query on Wikipedia, Urban Dictionary, Acronym Finder, or whatever? A solution is to use Automator's Website Popup action, and of course to call it from KM.

That Automator action doesn't work like KM's, though. Instead of opening the result of a query into your web browser, it will open a dialog showing a given webpage (for example Wikipedia). From there, you can type in the site's search field and see the result in that same dialog.

The good thing is that you can define the size of that dialog and the user agent used for sending the request. So if the site you want to access has a specific layout for the iPhone, you can use that layout (as shown below).

Here's how to make such a Web Popup:

  1. Launch Automator and create a new workflow
  2. Set "Service receives" to "no input" in "any application" and keep "Replaces selected text" unchecked.
  3. Find the "Get Specified URLs" action (in the Internet library) and drop it into the right part of the window.
  4. Add to it the URL of the site you want to access.
  5. Find the "Website Popup" action (still in the Internet library) and drop it below Get Specified URLs.
  6. Set the size and position of the dialog and the user agent to use. Set Output to "Current URL".
  7. Find the Display Webpage action (again in the Internet library) and drop it below the Website Popup action. This will cause the current page to open in your default browser when you click the OK button (clicking Cancel will close the dialog too but won't do anything else).
  8. Alternatively, you could replace the Display Webpage action with Copy to Clipboard, and replace Output Current URL with Selected Text in the Website Popup action.
  9. Save the workflow (a good place to keep these is ~/Library/Workflows).

Then, in KM, use the Execute an Automator Workflow to trigger it from a hotkey, the menu, or a palette.

TOC

Reopening Windows

I mentioned earlier my RESTARTER group from which I restore automatically the windows of some applications when they're launched. In most cases it involves an AppleScript script to record the list of open windows when the application quits and another to restore them when it launches. I won't get into these scripts here, but the trigger that allows it is the Application trigger (that can trigger a macro when an app launches or quits). The trick is that you have to use this trigger from a global group, because it won't work if you use it from a group available only in the application you target. Of course, it's much easier when the application provides a command to reopen the windows manually, like Safari (not to mention those who can do it automatically like BBEdit or ScriptDebugger).

"RESTARTER" group (available in all applications)
"Restore Safari Windows From Last Session" macro
Trigger: This application: Safari.app Launches
Actions:
Pause for 1 second Activate Application: Safari.app Type the ⌥⌘H keystroke

Note: I assigned that ⌥⌘H hotkey to Safari's History > Restore All Windows From Last Session from the Keyboard prefpane (in System Preferences). The reason why I use the Type a Keystroke action rather than the Select a Menu Item action, is because the latter will fail if the menu item is not available yet, while the former will work because an application that receives a hotkey will kind of keep it on hold until it's ready to respond to it.

5 In KM 5, the new action Wait Until (available from the Control Flow Category) provides a nice workaround to this problem, as it allows to wait for a given menu to be enabled.

TOC

Toggling app's visibility

There are some applications that I like to be able to bring forward and hide with a single hotkey. Here's an example of how I do it:

"Launch" group (available in all applications)
"Toggle Soulver" macro
Trigger: ⌃⌥⌘S
Action:

Execute AppleScript (text script, ignore results)
tell application "System Events"
    if (count every process whose name is "Soulver") = 0 then
        tell application "Soulver" to activate
    else
        if visible of process "Soulver" is true then
            set visible of process "Soulver" to false
        else
            tell application "Soulver" to activate
        end if
    end if
end tell

TOC

Close Without Saving 5

In Snow Leopard and earlier versions of OS X, pressing ⌘D in a save dialog is equivalent to pressing the Don’t Save button. In Lion, it's ⌘⌫ (Cmd-Delete). So to close a document without saving it, you can press ⌘W, then ⌘D (or ⌘W, then ⌘⌫). But it'd be handier with a single hot key, wouldn't it?

Here's the macro I use to close a window without saving its document (note that it demonstrates KM 5's new If Then Else action):

"GLOBAL MACROS" group (available in all applications)
"Close Without Saving" macro
Trigger: ⌃W
Actions:
Close Front Window Pause Until Condition Met
any of the following conditions are true
A button
with this name:
Save
is enabled
If Then Else
If all of the following are true:
A button:
with name containing:
Don’t Save
is enabled
execute the following actions:
Press a Button
press the button named: Don’t Save (*)
Stop macro if button cannot be pressed:
otherwise execute the following actions
If Then Else
If all of the following are true:
A button:
with name containing:
Delete
is enabled
execute the following actions:
Press a Button
press the button named: Delete
Stop macro if button cannot be pressed:

(*) It may not be obvious, but the quote used in the Don’t Save button is the typographic one (A.K.A. "smart quote"). Note that if you use a regular quote in the action, the button won't be detected!

Of course, instead of the Press a Button action, you can also use the Type a Keystroke action to type ⌘D or ⌘⌫, but then you wouldn't know about the typographic quote and you might wonder later why pressing a button that contains it doesn't work. ;-)

Note that closing a window without saving its content is definitive in most application; there's no way back in time! So if you think you might press ⌃W when you actually meant to press ⌘W, you should probably use a more complex hot key, like ⌥⌘W or ⇧⌘W.

TOC

Edit iCal Event 5

The combination of the If Then Else action with the detection of a button is very handy for many things. Here's a macro I made to edit and terminate the edition of an iCal event with a press of the Enter key:

"• iCal" group (available only in iCal)
"Edit Event" macro
Trigger: ⌤
Action:
If Condition Met Execute Action
If all of the following are true:
A button:
with this name:
Done
is enabled
execute the following actions:
Press a Button
press the button named: Done
Stop macro if button cannot be pressed:
otherwise execute the following actions:
Type a Keystroke
Simulate Keystroke: ⌘E

To use it, select an event in iCal, press ⌤ (Enter) to edit the event, then press ⌤ again when you're done.

TOC

Roll a Hyperdice 5

Amongst the new features brought by KM 5 are Variables, Calculations, While loops, and Prompting the user. This macro demonstrates them. It simulates rolling what I call a Hyperdice (a dice with a variable number of sides).

"Launch" group (available in all applications)
"Roll a Hyperdice" macro
Trigger: Status Menu
Action:
While
While all of the following are true:
The calculation
1
returns true (non-zero)
execute the following actions:
Prompt For User Input
Title: Roll a Hyperdice
Prompt:
How many sides does the dice have?
Variables and Default Values:
Dice Sides %Variable%Dice Sides%
Buttons:
OK - Cancel Macro:
Cancel - Cancel Macro:
Prompt For User Input
Title: And the result is...
Prompt:
%Calculate%RAND(Dice Sides)%
Variables and Default Values: none
Buttons:
Done - Cancel Macro:
Again - Cancel Macro:

Notes:
- Setting the calculation to 1 makes the While loop repeat until the macro is cancelled from one of the Prompt actions.
- Using the variable "Dice Sides" to store the user's choice allows KM to remember that choice as variables are persistent (even across sessions and reboots).
- Using the %Variable%Dice Sides% token in the prompt field of the first Prompt For User Input action allows to set the default answer to the user's previous choice.
- Using the combination of the Calculate token and of the Variable token in the prompt field of the second Prompt For User Input action allows to display a variable result (a random number, in this case).

TOC

Send Clipboard 5

Another great new feature of KM 5 is its ability to send a clipboard to another Mac running KM 5. However at that point it doesn't have an action to do it, and you have to use a sequence of manual actions. Thankfully, KM is there precisely to automate that kind of manual sequence. Here's how I do it:

"Clipboard" group (available in every applications)
"Send Clipboard
Trigger: ^⌘S
Actions:
Activate Clipboard History Switcher Pause Until
Pause until all of the following conditions are true:
The front window:
title is:
Clipboard History Switcher
Type the ⌘S Keystroke Pause Until
Pause until all of the following conditions are true:
A button:
with this name:
Send
is enabled
Type the Return Keystroke Pause Until
Pause until all of the following conditions are true:
A button:
with this name:
Send
does not exist
Click Mouse at 6 6 from the Front Window's Top Left Corner

When you press the trigger, the macro will open the Clipboard History Switcher, send the current clipboard to the preselected target Mac (the one you sent a clipboard before), then close the Clipboard History Switcher.

KM's server must be running on the target machine. So if the receiving machine doesn't seem to get the clipboard, make sure its KM server is running. Also, note that if the target machine is unreachable, KM will keep the clipboard on hold and will send it the next time the machine is reachable, which is quite neat!

TOC

When you click a link in Mail, iChat, whatever, it is sent to your default browser. With Safari, it's the last window you used that opens that link. And if you're using Spaces and that Safari window is in a different space, you'll be taken there. That's not too bad, but most of the time it's not what I want. I want Safari to open a new window in the current space and open that link in that window, so when I'm done I just have to close that window to be back in the application I opened the link from.

I'm doing that mainly with two macros: one available in every applications to open the link, and one available only in Safari to close the window when I'm done. However I don't really want the first macro to be available in every applications, because there are application where I never open links from and I want to use the same hot key for a different macro in these applications. But at the same time, I don't want to duplicate this macro in the group of every application where I'll use it from, because if I had to edit that macro, I'd have to edit many copies of it. So my Open Link in Safari macro is global, but it doesn't have any trigger, and then I have a macro in the group of each application where I want to open links in Safari from, whose sole action is to call the global macro. And finally, I also have a macro (Open New Safari Window, described bellow) that I use to open a new Safari window and set its size and position, so I also call that macro from here.

"GLOBAL" group (available in every applications)
"Open in Safari (global)" macro
Trigger: none
Actions:
Set Variable to Text
Set variable openSafariWindowFrom
to: %CurrentApplication%
Execute Macro: Open New Safari Window Use Variable
Use variable openSafariWindowFrom
to set the front application by name
Pause for 0.5 Seconds Click Mouse at 0 0 from the Current Mouse Location Set Variable To Text
Set variable openSafariWindow
to true
Activate application Safari.app

Here's how it works:

  1. I put the cursor over the link and press the hotkey to trigger the macro (⌘⌤)
  2. the macro stores into a variable the name of the front Application
  3. opens a new Safari window
  4. uses the variable set at step 1 to take back to the front the app I called the macro from
  5. pauses a little to give time to the application to come back to the front
  6. clicks on the link
  7. sets a new variable to true, indicating that the macro was used
  8. and take Safari to the front

And here's an example of how I trigger that macro:

"• Mail" group (available only in Mail)
"Open Link in Safari" macro
Trigger: ⌘⌤ (that's Cmd-Enter)
Actions:
Execute Macro: Open Link in Safari (global)

And then I have the other macro to close the Safari window when I'm done and take me back to the application I started from:

"• Safari" group (available only in Safari)
"Back to Caller" macro
Trigger: ⌃W
Actions:
If Then Else
If all of the following are true
The variable
openSafariWindow
is true
execute the following actions
Set Variable to Text
Set variable frontWindow
to: %FrontWindowName%
Close front window Pause Until
Pause until all of the following are true:
A button
with this name
Close
does not exist
The front window:
title is not
%Variable%frontWindow%
Use Variable
Use variable openSafariWindowFrom
to set the front application by name
Set Variable to Text
Set variable openSafariWindow
to: false
Set Variable to Text
Set variable openSafariWindowFrom
to:   (empty)
otherwise execute the following actions:
Play Sound
Play sound Bottle
out device Sound Effects Output Device
with volume (slider)

OK, so here's what it does:

  1. If the variable openSafariWindow is true, it means the current window was opened by the Open Link in Safari macro. If it's not the case, the macro plays a sound and does nothing else.
  2. Save into a variable the name of the front window.
  3. Try to close the front window. This will fail if more than one tab was open, in which case Safari would give us a confirmation prompt.
  4. Wait until the window closed and the confirmation prompt (if any) has been closed.
  5. Use the variable saved from the Open Link in Safari macro to take back to the front the application we started from.
  6. Reset the openSafariWindowFrom variable.
  7. Reset the openSafariWindow variable.
TOC

Open New Safari Window

This is the macro I mentioned above that I use to open a new Safari window (in the current space) and set its size and position.

"Launch" group (available in every applications)
"Open New Safari Window" macro
Trigger: ⌃S
Actions:
Activate application Safari.app Type the ⌘N Keystroke Move Front Window to 6 48) Resize front window to 1268 pixels horizontally, 77 pixels vertically

TOC

Get Cursor Position 5

Here's a macro to get and display the cursor's coordinates relative to both the screen and the front window, as in this screenshot:

Thanks to KM 5's new tokens, it only takes one action:

"Misc" group (available in every applications)
"Get Cursor Position" macro
Trigger: ⌃⌥⌘M
Actions:
Display Text
Display text in a window
Cursor position relative to:

Screen: → %Calculate%MOUSEX()% / ↓ %Calculate%MOUSEY()%
Window: → %Calculate%MOUSEX()-WINDOW(1,Left)% / ↓ %Calculate%MOUSEY()-WINDOW(1,Top)% / ← %Calculate%WINDOW(1,Right)-MOUSEX()% / ↑ %Calculate%WINDOW(1,Bottom)-MOUSEY()%

TOC

Get Window Size 5

And here's its companion macro that gets and displays the front window's size:

"Misc" group (available in every applications)
"Get Front Window Size" macro
Trigger: Status Menu
Actions:
Set Variable to Text
Set variable winSize to %WindowSize%1%
Display Text
Display text in a window
Front window size:

→ %Calculate%winSize[1]% / ↓ %Calculate%winSize[2]%

TOC

Using KM to move a window to a given space 6

Unfortunately, Apple doesn't provide a way to move a window to a given space at the press of a hot key (nor even using AppleScript). A way to do it is to set up Mission Control to switch spaces by pressing ⌃Left Arrow, ⌃Right Arrow, ⌃1, ⌃2, and so on, and then press that hot key while clicking and holding in a window's title bar. However it's far from being handy when you're on a laptop: since there's no ctrl key at the right of the keyboard, if you're right-handed like me, you'll click with your right hand and you'll have to twist your left wrist and spread your fingers wide to press the hot key at the same time, which can be pretty difficult (try ctrl-8 with your left hand, for example).

So I came up with a method that makes it much easier and which I'm very happy with: Press a hot key first, then click in the title bar of the window to move.

The idea is to tell KM which space you want to switch to by using the hot key, pause until you click, and then only trigger the switch. This way you can use both hands to trigger the macro (for example pressing ⌃⌥ with the left hand and 8 with the right one) and then click in the title bar of the window to move until the switch has taken place. The beauty of it is that you can even press the hot key several times (like pressing ⌃⌥Right Arrow three times), and when you'll click and hold in the window's title bar, the switch will occurs three times. Also, the window to move doesn't even have to be frontmost when you press the hot key.

So basically we want a set of macros (one for each space and one for each direction) that just pause until you click, and then play the keystroke that will trigger Mission Control to switch spaces. Obviously, the "Move left a space", "Move right a space", and "Switch to Desktop [n]" hot keys have to be set and enabled in the Mission Control pane of the Keyboard Shortcuts tab of the Keyboard preferences pane. So make sure this is the case and you can use them to switch spaces.

Let's start by creating the Move Window Left a Space macro:

"Global Macro Group" group (available in all applications)
"Move Window Left a Space" macro
Trigger: This hot key
⌃⌥Left Arrow
Actions:
Pause Until
All of the following are true
The calculation MOUSEBUTTON( )
returns true (non-zero)
Type a Keystroke
Simulate Keystroke: ⌃Left Arrow

That's it. You can now select this macro in the Macros column, duplicate it, and update the name, trigger and Keystroke action of the copy for the next macro (i.e Move Window Right a Space, ⌃⌥Right Arrow, ⌃Right Arrow respectively), and so on for each space you use.

Then to move a window one space to the left, press ⌃⌥Left Arrow, release the keyboard, then click and hold in the title bar of the window to move. The switch will occur as soon as you click and you can release the click as soon as the switch is done.

If you want to move the window two spaces to the right, press ⌃⌥Right Arrow, release then press again the Right Arrow, then release ⌃⌥, and finally click and hold in the title bar of the window. The window will be moved two spaces to the right.

Note that I mentioned Mission Control's default hot keys, here (⌃Left Arrow, ⌃Right Arrow, ⌃1, ⌃2, etc.) so if it's not what you're using, update the Simulate Keystroke actions accordingly.

TOC

Misc.

Pausing a macro until the user clicks 6

One way to pause a macro until the user clicks is to use the Pause Until calculation MOUSEBUTTON( ), as I showed in Using KM to move a window to a given space. However this method only seems to work accurately when you use the physical button to click, and a tap on the trackpad won't be detected as a click (or at least not always).

So here's a method that works even with a tap (assuming Tap to click is enabled in the Trackpad prefs pane, of course):

  • Create a new macro named "Detect Click" in a global group and set its trigger to "This device key".
  • Select the key field, and click. On a laptop, the field will then be set to "Apple Internal Keyboard / Trackpad Button 1".
  • Then, select "is pressed" in the menu beside that field.
  • Next, add a Set Variable to Calculation action to this macro, and set it to set the variable "click_detected" to 1.
  • Finally disable that macro by clicking the √ button in the Macros column while the macro is selected.

Now when you want to detect a tap or a click from another macro, all you have to do is set the variable click_detected to 0 (Set Variable to Calculation), enable the Detect Click macro (Set Macro or Group Enable), pause until the variable click_detected is 1 (Pause Until The variable contains), and then disable the Detect Click macro (Set Macro or Group Enable) before resuming.

TOC

Searching for Macros by hot key

The Menu Glyphs macros I mentioned earlier are also very handy to search for macros by hotkey in KM Editor or to find if a given hotkey is already used: select All Macros in the Groups column, then use the Menu Glyphs menu to enter the hotkey (or a part of it) into KM's search field. You can then sort the result by name or by hotkey by clicking on the corresponding triangle in the "Macros" header.

6 KM 6 introduced two new very handy ways of sorting the macros that in my experience makes searching for them less necessary: by Macro Modification and by Macro Execution. You'll find these commands in the View menu.

TOC

Finding objects coordinates

Sometimes there is no other way to act on a user interface element than using the Move or Click Mouse action (it could be a button on a webpage, a contextual menu, etc.). That action is very powerful, but it may be a bit tricky to use because you have to enter by hand the coordinates of the point where you want to click.

A way to work around this difficulty is to use KM's record feature: create a new (temporary) macro, click the Record button, bring to the front the window that contains the UI element on which you want to click, and then only, click on it. Taking the window to the front first is important, because if you don't, the coordinates KM will register will be relative to the screen. And in most cases you want them to be relative to the window itself, otherwise moving the window would break your macro. When you're done, click the little red palette to stop recording, copy the last Move & Click Mouse action KM created for you, delete that temporary macro, and paste the action into your (not temporary) macro. The reason why I use a temporary macro is because KM often records redundant actions (for example when you click on your window to take it to the front, KM records two actions: activating that window's application, and clicking in that window).

This method records the coordinates relative to the top left corner of the window, but sometimes it's not what you want. For example the UI element might be tied to the right side of the window, or to its bottom, so it would move when you resize the window. If the coordinates you used are relative to the top left corner, resizing the window would break your macro. In this case, you have no other choice than entering the coordinates by hand. And a handy way to find these coordinates is to use Mac OS's screenshot feature. Here's how:

  1. Press ⇧⌘4
  2. Move the cursor to the corner of the window where you want the coordinates to originate from
  3. Click the mouse and drag it to the point where you want your click to occur. The coordinates relative to the point of origin of your drag are displayed next to the cursor (with the horizontal coordinate at the top and the vertical one at the bottom).
  4. Press esc to cancel the screenshot, and type the coordinates in KM's action.

5 KM 5 introduced tokens providing the cursor's coordinate, so that allowed me to come up with this macro that displays the cursor's position relative to both the screen and the front window.

TOC

Debugging macros

There are various reasons why a macro can fail to work, and judging by the questions I see on the mailing list, it's not always easy to figure out what's going on. Here's the method I recommend for KM up to 5:

  • Add to that macro a Status Menu Trigger.
  • Take to the front the application where you want to use the macro, and look for that macro in the Status Menu.
  • If it's not there, either the macro is not enabled (click the √ button in the Macros column to enable it), the group that contains it is not enabled (click the √ button in the Groups column to enable it), or the group is not available or not activated in that application (select the group and check its settings).
  • If the macro appears in the menu, try running it from there. If it's triggered, then a possible (although very rare) cause to the problem can be that some application uses the hotkey you chose and intercepts it. Try a different hotkey to make sure it's not the case.
  • If the macro still doesn't do anything when you trigger it from the menu, first, check that its actions aren't disabled (select an action and click the √ button to enable it).
  • If this is not the problem, then most likely one of its early actions fails. If your macro uses an Execute AppleScript or Shell Script action, start by making KM display the result of this action ("display results in a window" or "display results briefly").
  • Otherwise, a way to find out which action fails is to insert at the top of the macro an Alert action (that will display a test dialog). Run the macro to make sure the dialog pops up, then move that alert action down by one position and try running the macro again. Repeat until the dialog no longer appears and then you'll know that the action that fails is the one just before the Alert action.
  • Finally, if your macro runs but inexplicably doesn't do exactly what it's meant to, add a short Pause action (like half a second) before the action(s) that appear to fail. It happens rather often that KM runs faster than the UI it drives and this can cause failures that are difficult to pinpoint. Adding pauses works around this problem and once the macro works as expected, you can shorten and even maybe remove most of the pauses.

Macro Debugger 6

Keyboard Maestro 6 makes it even easier to debug macros by providing the Macro Debugger and debugging actions. I wrote a tutorial, on how to use the debugger, that can be found here.

TOC

 Previous Comments

1. Christi Milligan commented :

Hi Philippe,
Thanks for these great macros for KB. I'm fairly new to this app so I apologize if my question is lame. ;-)

In several of the first couple of clipboard macros, you mention Executing a Macro called "Clipboard Restore." Am I guessing correctly that you actually meant to Execute macro "Private Clipboard?"

Thanks!
Christi

2. FlipMartin commented :

Hi Christi,

"Restore Clipboard" was a macro I made before the "Delete Current Clipboard" action was added to KM. Now you can use that action instead, but you'll have to use it as many times as your macro modified the clipboard. Or you can see another method in the macro I used as example in my Macro Debugger Tutorial.

Sorry about the confusion and thanks for pointing it out. I'll update the page to replace those references.

Cheers,

Philippe

Please Log in if you wish to comment.