How do I assign a keyboard shortcut to recorded macro in Sublime Text

43

19

I have a bunch of macros which I have recorded and saved in Sublime Text 2. I'm trying to assign keyboard shortcuts to each of those, but I'm kind of lost as to how to go about doing this,

I had a look at

but that explains how to set Key bindings for existing commands.

What should I set to have it run a macro?

Sathyajith Bhat

Posted 2013-06-18T12:45:15.897

Reputation: 58 436

2this applies equally to ST3 - thanks! – ptim – 2015-02-14T00:31:47.433

Answers

61

To instruct Sublime Text to run macros, you need to pass "run_macro_file" as parameter to "command", with argument being the filename of the macro.

First, merely recording a macro doesn't save it to a file, you'll have to save the macro to a file. This can be done by clicking on Tools → Save Macro & then give a filename. Macros are generally saved in %appdata%\Sublime Text 2\Packages\User folder.

Next, to assign the keyboard shortcut, open the Keybindings file from Preferences → Key Bindings - User.

Now, the general format for a keybinding is as below:

{ "keys": [<key sequence>], "command": "run_macro_file", "args": {"file": "Packages/User/<file name>.sublime-macro"} }

So, if you want to assign Ctrl+Shift+X to a macro which has been saved as "add comma to end", the keybinding line will look like so:

[
    { "keys": ["ctrl+shift+x"], "command": "run_macro_file", "args": {"file": "Packages/User/add comma to end.sublime-macro"} }
]

Sathyajith Bhat

Posted 2013-06-18T12:45:15.897

Reputation: 58 436

2

You restrict the scope in which the shortcut will be active with context.. here's an example from Emmet: https://github.com/sergeche/emmet-sublime/blob/master/Default%20(OSX).sublime-keymap#L472

– ptim – 2015-02-14T00:30:57.653

@ptim Does this imply that you can restrict some macro to only be active for, e.g., Python scripts? – gustafbstrom – 2016-11-17T13:49:54.183

1

@gustafbstrom - kinda! yes, but the restriction is actually on the key binding, not the macro :) http://docs.sublimetext.info/en/latest/reference/key_bindings.html#structure-of-a-key-binding

– ptim – 2016-11-18T00:56:28.090

1still works with sublime v3. Path is relative so "Packages/User/my_commands.sublime-macro" is working. tested on mac. – marlo – 2018-06-07T01:01:55.397

Tested on Sublime Text 3 Portable on Windows. Works too. Path is relative. – Ifan Iqbal – 2019-10-01T00:43:15.700