neoformat icon indicating copy to clipboard operation
neoformat copied to clipboard

problem with undojoin snippet

Open hoschi opened this issue 8 years ago • 3 comments

With the snippet

augroup fmt
  autocmd!
  autocmd BufWritePre * undojoin | Neoformat
augroup END

I get an error when writing the buffer again after undoing a change:

E790: undojoin is not allowed after undo

hoschi avatar Nov 27 '17 13:11 hoschi

I found this https://vi.stackexchange.com/a/13401 and modified it into:

augroup fmt
  autocmd!
  au BufWritePre * try | undojoin | Neoformat | catch /^Vim\%((\a\+)\)\=:E790/ | finally | silent Neoformat | endtry
augroup END
  • catches error above
  • formats code when error catched
  • other errors (e.g. file was changed since last write) are still shown

Only "downside" is that you must hit enter when the file changed outside of vim and you selected "y" to overwrite it and Neoformat is run after that.

hoschi avatar Nov 27 '17 13:11 hoschi

Can we have this in the README?

barraponto avatar Dec 10 '19 05:12 barraponto

I found this https://vi.stackexchange.com/a/13401 and modified it into:

augroup fmt
  autocmd!
  au BufWritePre * try | undojoin | Neoformat | catch /^Vim\%((\a\+)\)\=:E790/ | finally | silent Neoformat | endtry
augroup END
  • catches error above
  • formats code when error catched
  • other errors (e.g. file was changed since last write) are still shown

Only "downside" is that you must hit enter when the file changed outside of vim and you selected "y" to overwrite it and Neoformat is run after that.

Hey, thanks for this. What's the deal with the double call to :Neoformat by the way? One right after :undojoin, and inside the :finally block? I am not entirely sure what's the edge case that it's trying to catch.

I suspect the following to do just fine, right?

  • If :undojoin does not fail, :Neoformat (the one inside the :try block is executed just fine)
  • If :undojoin does fail, then the :Neoformat from within the :catch block is run
  • If something else happens, we give up and let the user deal with it without running :Neoformat
au BufWritePre * try | undojoin | Neoformat | catch /E790/ | Neoformat | endtry

iamFIREcracker avatar Feb 10 '22 10:02 iamFIREcracker