Skip to content

Use rustfmt as equalprg in Vim/neovim #2840

Closed
@andreyorst

Description

@andreyorst

I'm not sure where I should open this issue: here, or at rust.vim, but the problem I've encountered is about rustfmt itself.

Can I use rustfmt as equalprg in neovim or vim?
From :h equalprg

'equalprg' 'ep'		string	(default "")
			global or local to buffer |global-local|
	External program to use for "=" command.  When this option is empty
	the internal formatting functions are used; either 'lisp', 'cindent'
	or 'indentexpr'.  When Vim was compiled without internal formatting,
	the "indent" program is used.

So I've set it up with set equalprg=rustfmt but it doesn't work how I would expect it to.
For example:

  1. Create a project with $ cargo new
  2. Open src/main.rs in vim/neovim
  3. :set equalprg=rustfmt

Now you should be ready to format your code. So for example select all lines in the buffer with ggvG and hit =. Code will be formatted. However, If you select single line, the formatting is all wrong. Consider ( is a cursor):

fn main() {
    println!("Hello, world!");}

Pressing == wil result into:

fn main() {
println!("Hello, world!");
}

Default Vim behavior is different. It uses cindent, and code will be indented in the right way, because cindent is aware of surrounding code. However this is common situation, because clang-format does the same thing.
But there is more:

fn main() {println!("Hello, world!");
}

pressing == here will result into:

error: this file contains an un-closed delimiter
 --> <stdin>:1:13
  |
1 | fn main() {
  |             ^
  |
help: did you mean to close this delimiter?
 --> <stdin>:1:11
  |
1 | fn main() {
  |           ^

    println!("Hello, world!");
}

The code gets deleted, and replaced with error messages. The same situation will occur if you select only first two lines. This is not the case for clang-format, it still handles formatting well. Does rustfmt support partial formatting?

rustfmt 0.4.2-stable (febbb36 2018-04-12)
rust.vim commit: 7034eda0d96b89f2af35c90cb8db0ed52e7313d9
neovim:
NVIM v0.3.1-149-g44a284d71
Build type: RelWithDebInfo
LuaJIT 2.0.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions