0

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
  • 2
    Quick and dirty solution... follow :1,$!yapf with if v:shell_error | undo | endif :)
    – B Layer
    Apr 23, 2022 at 4:03

1 Answer 1

2

I pieced together this workaround from lots of stackexchange posts and vim wiki content:

" yapf integration
function FormatFile()
  let buffer_content = join(getline(1, '$'), "\n")
  let filter_output = systemlist("yapf", buffer_content)
  if v:shell_error == 0
    let view = winsaveview()
    call deletebufline('.', 1, '$')
    call setline(1, filter_output)
    call winrestview(view)
  endif
endfunction
autocmd BufWritePre *.py call FormatFile()
1
  • 2
    you may want winsaveview and winrestview to handle the cursor positioning/etc.
    – D. Ben Knoble
    Apr 22, 2022 at 17:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.