Using rustfmt in Vim

Nov 03, 2015

rustfmt just added support for receiving code on stdin. This means that you can now pipe things into rustfmt on stdin and receive a plain formatted version of your input on stdout, the UNIX way.

echo "pub fn main(){println!(\"hello\");}" | rustfmt cat src/lib.rs | rustfmt

This enables us to write editor plugins that call rustfmt and replace the file content with the result from stdout.

Here's how to do it in Vim, my editor of heart.

Integrating with Vim-Autoformat

Vim-Autoformat is a neat plugin that allows you to define custom formatters to run on your code while you're editing it in Vim.

Only a few steps are required to make it work with rustfmt.

Install rustfmt, instructions can be found here: https://github.com/nrc/rustfmt#installation multirust run nightly cargo install --git https://github.com/nrc/rustfmt Install vim-autoformat with a plugin manager of your choice, I use vim-plug Plug 'Chiel92/vim-autoformat' Add rustfmt to the list of formatters. vim-autoformat comes with a set of predefined formatters for popular languages, but until my pull request adding Rust is merged we'll have to add it ourselves.

Fortunately, it's quite easy. Just add the following two lines to your .vimrc:

let g:formatdef_rustfmt = '"rustfmt"' let g:formatters_rust = ['rustfmt']

Now you can call :Autoformat to automatically format your Rust code. Optionally you can map it to something more convenient, I use <Leader>f

nmap <Leader>f :Autoformat<CR>

Or you can instruct Vim to automatically format on save, which is only convenient if the formatter is fast enough. ( rustfmt is blazing fast)

au BufWrite * :Autoformat