Using rustfmt in Vim

03 Nov 2015 23:00:00 +0100

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

Now go ahead and integrate rustfmt into your preferred editor! It's a great way to keep your code consistent and a tight editor integration will ensure your workflow is never disrupted and that you will never forget to rustfmt anything again.

转载于:https://my.oschina.net/innovation/blog/817241

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值