Home > database >  Run gofmt on vim without plugin
Run gofmt on vim without plugin

Time:05-07

I want to run gofmt on save on vim without installing any plugin. This is what I have tried (inspired by gofmt

CodePudding user response:

You can update the script as below:

function! GoFmt()
  system('gofmt -e -w ' . expand('%'))
  edit!
endfunction

Gofmt is a tool that automatically formats Go source code. Gofmt is both a code formatter and a linter.

From doc

-e Print all (including spurious) errors.

-w Do not print reformatted sources to standard output. If a file's formatting is different from gofmt's, overwrite it with gofmt's version. If an error occurred during overwriting, the original file is restored from an automatic backup.

The above script will update the file if there are no errors


If applicable, create a quickfix list with the errors reported by gofmt.

function! GoFmt()
  cexpr system('gofmt -e -w ' . expand('%'))
  edit!
endfunction

cexpr to create a quickfix list read more about it using vim help doc help :cexpr, system to run system command read more about it using vim help doc help :system, expand Expand wildcards and special keywords into string read more about it using vim help doc help :expand, % is a special keyword which refer to current file.

edit! is used to reload file contents.

Then you can quickly jump over the errors using quickfix list you can learn more about it from this blog post.

  • Related