Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: Using an external command and handling errors

Tags:

shell

vim

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.

like image 898
alfredodeza Avatar asked Feb 27 '12 14:02

alfredodeza


1 Answers

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

Edit:

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
like image 155
Conner Avatar answered Oct 02 '22 23:10

Conner