Defining Atom Commands in Your Init Script

Published on Sunday, March 02, 2014 in atom

I'm thrilled that Atom—the newly-announced text editor from GitHub—is now out in the wild for more people to enjoy. It's been my editor of choice for the past seven months. Atom is a delight to use. And for the first time, I'm using an editor that I find enjoyable to extend. There's a ton to say about Atom, but for the moment, let's talk about a quick way to start experimenting with extending the default Atom experience.

The majority of your Atom customizations will come in the form of packages. Packages provide an excellent means for defining commands and other customizations. [1] But sometimes I want to quickly define a new command without creating a full-blown package. Cue ~/atom/init.coffee.

Defining your first command

As a simple (and admittedly contrived) example, let's define a command that logs a message to the console. For starters, add the following code to your ~/atom/init.coffee script:

atom.workspaceView.command 'dot-atom:demo', ->
  console.log "Hello from dot-atom:demo"

Atom evaluates init.coffee each time you open a new window. To test out this new command, you can open a new window, or you can reload the current window via the "Window: Reload" command in the Command Palette.

Now, use the Command Palette to locate and execute the new command by name (i.e., "Dot Atom: Demo"), as shown in the gif below. Each time you run the command, you'll see the message logged to the console.

Defining and using a new command is just that simple.

If you'd like to trigger the command via a keyboard shortcut, you can define a keymap for the command in ~/.atom/keymap.cson.

Demo of an Atom command in init.coffee

Going further

Because init.coffee provides full access to Atom's API, it's fertile ground for implementing genuinely useful commands. For example, Lincoln Stoll uses his init.coffee to define a command for generating ctags. In my init.coffee, I define a command that provides alternative behavior for deleting to the end of the line, and I'm experimenting with a few other commands as well. [2]

Whether you need a sandbox for experimenting with new commands before publishing them in a package, or you just want to define a few small commands without the overhead of an entire package, init.coffee is the place to go.

Notes

[1] I've enjoyed writing a handful of packages over the past few months. Now that Atom is in public beta, the package ecosystem is quickly heating up.

[2] As people begin to share their Atom dotfiles on GitHub, it's going to be a blast to discover novel customizations that allow developers to get even more from Atom.

Archive

Now that you've whetted your appetite with the most recent post, perhaps you'd care to dig into the archive.