problem with undojoin snippet
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
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.
Can we have this in the README?
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
:undojoindoes not fail,:Neoformat(the one inside the:tryblock is executed just fine) - If
:undojoindoes fail, then the:Neoformatfrom within the:catchblock 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