Vim: using an external command and processing errors

I am trying to use an external command to handle some formatting on a number of lines in Vim, but cannot find a way to handle errors from an external command.

These errors usually occur when the shell returns something other than 0, and this causes Vim to display something along the lines:

shell returned 1 

In addition, it replaces the lines that I wanted to format with the actual error message. This also happens if I do this:

 :set equalprg=myformatter\ --format-flag\ 

How can I safely catch an error for an external command and display any error message?

Note. It is not a question of how to use an external command to format some text in Vim, but rather, how to catch an error and display a message.

+6
source share
1 answer

There might be a better way to do this, but I got this draft of work (see below for equalprg). It basically redirects gq , rewriting 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 is in ~/test.sh :

 echo "error!! alskdjf alskdf alskdj flaskdjf" 1>&2 exit 1 

Edit:

I only realized that I did not answer your question haha ​​at all. My solution for equalprg even less elegant, but it can satisfy your needs. To use this , you must install equalprg . Either comment out the nnoremap line, or set indentexpr=EqualPrg() if you want to switch between an external tool and internal indentation formatting.

 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 
+4
source

Source: https://habr.com/ru/post/909451/


All Articles