Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang Formatter and Vim - How to destroy history record?

Tags:

vim

go

Go (Golang) programming language comes with a tool called go fmt. Its a code formatter, which formats your code automagically (alignments, alphabetic sorting, tabbing, spacing, idioms...). Its really awesome.

So I've found this little autocommand which utilizes it in Vim, each time buffer is saved to file. au FileType go au BufWritePre <buffer> Fmt Fmt is a function that comes with Go vim plugin.

This is really great, but it has 1 problem. Each time formatter writes to buffer, it creates a jump in undo/redo history. Which becomes very painful when trying to undo/redo changes, since every 2nd change is formatter (making cursor jump to line 1).

So I am wondering, is there any way to discard latest change from undo/redo history after triggering Fmt?

EDIT: Ok, so far I have: au FileType go au BufWritePre <buffer> undojoin | Fmt But its not all good yet. According to :h undojoin, undojoin is not allowed after undo. And sure enough, it fires an error when I try to :w after an undo.

So how do I achieve something like this pseudo-code:

if lastAction != undo then
    au FileType go au BufWritePre <buffer> undojoin | Fmt
end

If I get this last bit figured out, I think I have a solution.

like image 853
if __name__ is None Avatar asked Aug 30 '13 12:08

if __name__ is None


1 Answers

I think this is almost there, accomplishes what you ask, but I see it's deleting one undo point (I think this is expected from undojoin):

function! GoFmt()
    try                
        exe "undojoin"
        exe "Fmt"
    catch              
    endtry
endfunction
au FileType go au BufWritePre <buffer> call GoFmt()

EDIT

Based on MattyW answer I recalled another alternative:

au FileType go au BufWritePre <buffer> %!gofmt

:%!<some command> executes a shell command over the buffer, so I do it before writing it to file. But also, it's gonna put the cursor at top of file...

like image 76
pepper_chico Avatar answered Sep 29 '22 18:09

pepper_chico