- Where to Add Snippets
- How to find out the language selector (scope)
- How to format a snippit
In Atom, you can add snippets by going to the Atom menu and going to Snippets...
Here you'll get a "CSON" file where you can type in definitions of the snippets you want to use. Additional instructions for using CSON are contained within this file by default:
# This file uses CoffeeScript Object Notation (CSON).
# If you are unfamiliar with CSON, you can read more about it in the
# Atom Flight Manual:
# http://flight-manual.atom.io/using-atom/sections/basic-customization/#_cson
To begin adding your snippets, you'll need to specify the language scope. This is kind of like a CSS Class Selector in that you should begin the scope with a dot (.). eg: '.source.ruby':
So, to find the scope, you'll need to into your installed packages and find the language you want to create a snippet for. To do this, go to Atom > Preferences > Packages and search for the language you want.
From here, go into the language package by clicking on Settings. Then scroll down the settings until you find the language you want to use (some packages support multiple languages or parts of languages).
Now we have our language scope.
As per the example in the snippet file that's commented out a snippet contains 3 main parts, aside from the scope selector.
'.source.coffee':
'Console log':
'prefix': 'log'
'body': 'console.log $1'
This is simply a display or friendly name for the snippet that will show in the drop-down that appears when you are typing and the code you write matches a snippet. Name your snippet something that makes sense to you.
This is the piece of text that will trigger the snippet as an option. In this example, typing log
will trigger the snippet. From here, if I press TAB, the snippet body will be applied.
This is the guts of our snippet. This is the code template you want to use. In here, tab-stops are identified with a $n where n is the numbered order in which the tab-stops will be followed and $0 is the final position of the cursor when tabbing is finished.
In CSON, you can create a multi-line string by using """
, thereby making it easier to create longer snippets. For example, below I've created a get
snippet for Ruby's Sinatra gem.
'body': """
get "/$1" do
$0
end
"""
When defining this snippet, I've set the first tab-stop to be inside the "/ "
section where we'll want to type a URL for Sinatra to watch for and the final cursor position inside the get block.