I have the following lines in ~/.vim/ftplugin/python.vim
:
" yapf integration
function FormatFile()
:normal mp
0,$!yapf
:normal `p
endfunction
autocmd BufWritePre *.py call FormatFile()
Thus, whenever I save a .py
file its contents are filtered through yapf and automatically consistently formatted. However, when there is a syntax error in my file yapf outputs a traceback instead of formatted code and my whole buffer gets replaced by that traceback. This is not desirable as other plugins would inform me about the error less intrusively.
I know that yapf exits with exit code 0 when it successfully outputs formatted code and exits with exit code 1 when it encounters a syntax error. Can I use that fact or any other trick to replace my buffer with the filter output ONLY when the filter is successful?
:1,$!yapf
withif v:shell_error | undo | endif
:)