2013-08-30 12:16
浏览 60

Golang Formatter和Vim-如何销毁历史记录?

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

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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • dongyuzhu2244 2013-08-30 15:19

    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()
            exe "undojoin"
            exe "Fmt"
    au FileType go au BufWritePre <buffer> call GoFmt()


    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...

    解决 无用
    打赏 举报

相关推荐 更多相似问题