Skip to content

Instantly share code, notes, and snippets.

@vito
Last active December 21, 2015 06:18
Show Gist options
  • Save vito/6262695 to your computer and use it in GitHub Desktop.
Save vito/6262695 to your computer and use it in GitHub Desktop.
automatic go fmt that preserves the user's "undo" (based on http://golang.org/misc/vim/ftplugin/go/fmt.vim)
function! s:GoFormatKeepingUndo()
let view = winsaveview()
silent! undojoin | silent %!gofmt
if v:shell_error
let errors = []
for line in getline(1, line('$'))
let tokens = matchlist(line, '^\(.\{-}\):\(\d\+\):\(\d\+\)\s*\(.*\)')
if !empty(tokens)
call add(errors, {"filename": @%,
\"lnum": tokens[2],
\"col": tokens[3],
\"text": tokens[4]})
endif
endfor
if empty(errors)
% | " Couldn't detect gofmt error format, output errors
endif
undo
if !empty(errors)
call setloclist(0, errors, 'r')
endif
echohl Error | echomsg "Gofmt returned error" | echohl None
endif
call winrestview(view)
endfunction
autocmd FileType go autocmd BufWritePre <buffer> call s:GoFormatKeepingUndo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment