Nigel Ramsay

Wellington, New Zealand

How to configure VS Code to format Elixir code

29 January 2018

Code auto-formatted with Elixir 1.6 Code auto-formatted with Elixir 1.6

Here is a step by step guide on how to configure Visual Studio Code to automatically format your Elixir code using the new built-in formatter included in version 1.6.

Step 1: upgrade your version of Elixir

Obviously, you will need to have the most recent version of Elixir installed locally. If you are using OSX, then you have likely installed Elixir using Homebrew. If this is the case, the the following is all you need to do:

brew upgrade elixir

You can then confirm you have the upgrade by typing:

elixir --version

You should see a message such as:

Erlang/OTP 20 [erts-9.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Elixir 1.6.0 (compiled with OTP 20)

Step 2: confirm the formatter works

The formatter is delivered as a mix task and can be easily tested by running something like:

mix format <filename>

Give it a go on a file in your project and see the changes it makes.

Step 3: configure default formatting rules

The format task looks for a file in your project directory named .formatter.exs with rules for which file types and locations should be formatted. Our Elixir project at Addressfinder is pretty standard, so you can probably start with ours:

[  
  inputs: ["mix.exs", "{config,lib,test}/\*\*/\*.{ex,exs}"]  
]

With this file present, mix format will format all the above files.

Note: it’s very fast!

Step 4: install the VS Code extension

Open up VS Code, and open the extensions pane from the sidebar. You need to search for and install an extension called vscode-elixir-formatter.

This extension requires you to reload VS Code, so make sure you do this.

You can manually activate the formatter by bringing up the command palette (⌘+⇧+P) and searching for “Format Document”.

This will format the current file using Elixir’s format task.

Step 5: automatically format on save

Open the User Settings (⌘+,) and set the following config:

"editor.formatOnSave": true

You can optionally add the following setting to format your code as you go:

"editor.formatOnType": true

Optional Extra: enforcing formatted code within your CI

The format task has an optional parameter --check-formatted. This can be added to your .travis.yml file, and be used to require that all source code is auto-formatted correctly.

You should try this out locally first, before adding it to your project:

mix format --check-formatted

If the check fails, you will receive an error message such as:

** (Mix) mix format failed due to --check-formatted.  
The following files were not formatted:

* lib/address_builder/au/build/paf_address_util.ex

Travis will detect this error and mark the build as a fail.

Summary

We’ve been loving Elixir’s new code formatter, and we encourage people to upgrade Elixir 1.6 soon and give it a go.

Useful resources: