Keymaps for inserting code snippets?


In Sublime, I can create a keymap to insert a BR tag like this

"keys": ["alt+enter"],
"command": "insert_snippet",
"args": {
    "contents": "<br>"

How can something like this be done in Atom? I read the docs on keymaps and it seems limited to built-in commands.

Getting help with custom key biding

To make a new command, you can create a new package, or you could add a command to your init scripts.

‘Atom’ -> ‘Open Your Init Script’

for example someone had posted this earlier which I use:

atom.workspaceView.command 'editor:toggle-current-row-folding', ->
  e = atom.workspace.getActiveEditor()
  bufferRow = e.bufferPositionForScreenPosition(e.getCursorScreenPosition()).row
  if e.isFoldedAtBufferRow(bufferRow)


Yikes! How does a BR tag come out of all that?


If you just want the simple <br> you can insert that into your and then bind editor:insert-br in your keybindings.


atom.workspaceView.command 'editor:insert-br', ->

The more advanced version for html tags could look like this:


atom.workspaceView.command 'editor:insert-tag-snippet', ->
  snippetBody = '<${1:div}>$2</${1:div}>$0'
  atom.packages.activePackages.snippets?.mainModule?.insert snippetBody


  'alt-enter': 'editor:insert-tag-snippet'


That makes much more sense to me, thanks.

I tried it, but alt-enter (actually option-return) does not insert the snippet as expected. No errors are thrown either. Did I miss a step?


Got it. Stupid mistake on my part.

Many thanks, this will be very useful for me to completely move to Atom.


Hi Guys I know this is way too long ago to think that someone will reply, but can someone please explain to me how to get this snippet with a keybinding to actually work?


After pasting the function into my, I added the keybinding to my keymap.cson. Since Atom loads on window load, you have to either restart Atom or reload the window. I chose to open my command palette and reload the window.

I was immediately met with an error, which told me something about getting a property of null, so I went off to the Atom API. Within three minutes of searching, right at the top of the list of available commands, I found the Command Registry documentation, which shows that something between the date this was posted and now has changed.

So, in order to get this to work, using the same command as above, the function should be changed to

atom.commands.add 'atom-text-editor', 'editor:insert-tag-snippet': ->
  snippetBody = '<${1:div}>$2</${1:div}>$0'
  atom.packages.activePackages.snippets?.mainModule?.insert snippetBody

Notice the difference in the initial API reference and the colon before the arrow function. I am not sure why the arrow is required for this to work, as I honestly don’t know my bum from my elbow when it comes to CoffeeScript, but trial and error showed me that it is necessary.

Once the proper function is added to, simply restart Atom (or reload the window) and test your new snippet anywhere you please.