I am trying to use an external command to handle some formatting over a range of lines in Vim but can't seem to find a way to deal with errors from the external command.
These errors are usually when the shell returns something other than 0 and it prompts Vim to display something along the lines of:
shell returned 1
Besides doing that, it replaces the lines I wanted to format with the actual message of the error. This happens as well if I do:
:set equalprg=myformatter\ --format-flag\
How can I safely catch an error for an external command and display whatever the error message is?
Note: this is not a question on how to use an external command to format some text in Vim, but rather, how to catch an error and display the message back.
There may be a better way to do this, but I got this rough draft working (see further below for equalprg). It basically remaps gq
, overwriting it to print the error and then undo it.
set formatprg=~/test.sh
nnoremap gq :setl opfunc=FormatPrg<cr>g@
fun! FormatPrg(...)
silent exe "'[,']!".&formatprg
if v:shell_error == 1
let format_error = join(getline(line("'["), line("']")), "\n")
undo
echo format_error
end
endfun
This is what's in ~/test.sh
:
echo "error!!
alskdjf alskdf
alskdj flaskdjf" 1>&2
exit 1
I just realized that I didn't answer your question at all haha. My solution for equalprg
is even less elegant, but it may suit your needs. To use this you must set equalprg. Either comment out the nnoremap line or set indentexpr=EqualPrg()
if you want to switch back and forth between an external tool and the internal indentation formatter.
set equalprg=~/test.sh
nnoremap = :setl opfunc=EqualPrg<cr>g@
fun! EqualPrg(...)
if &equalprg != ""
silent exe "'[,']!".&equalprg
else
set indentexpr=
exe "norm! `[=`]"
set indentexpr=EqualPrg()
endif
if v:shell_error == 1
let format_error = join(getline(line("'["), line("']")), "\n")
undo
echo format_error
endif
endfun
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With