Sometimes you want to quickly calculate a number while typing. Here’s how you can maintain the typing flow and calculate numbers with Keyboard Maestro.
We want the macro to replace the math formula with the result whenever we type the formula that ends with a question mark. Here are some examples:
30*(50+20)? 100^2? 75*30?
We’re going to select “This string is typed” as a trigger to decide when to call this macro. Change the dropdown to “regular expression match” and enter this expression:
If you’re not familiar with regular expressions, you can learn more about it in this post. What we’re doing here is to tell Keyboard Maestro:
- Run the macro only when any digit
\dand math signs like
+\-*/()^appear at least once and repeat regardless of the order. You can see that we wrapped these values in a bracket as
[\d.,+\-*/()^]+followed by a plus sign.
- Run the macro only when the matched string ends with a question mark
- The backslash is used to escape special characters in regular expressions such as question mark, plus, and minus sign.
The triggered macro will copy the selected line and extract only the detected math formula. It will remove the question mark and pass it to Filter Variable “Formula” with Calculate and save the result back to Formula variable.
In the last step, the macro replaces the detected formula in the clipboard with the result and then paste it back to the application source.
There are some lessons to build a macro here. You can extract strings with regular expressions, manipulate them, and send them back to the source.