Validate `~/.vimrc`

vimvimrc

I want to validate that my ~/.vimrc file is correct, basically just by launching vim and immediately running quit. I can almost do this with vim -c quit, except that I have to press the enter key. For example,

> cat ~/.vimrc
echoerr 'test'

> vim -c quit
Error detected while processing /home/josh/.vimrc:
line    1:
test
Press ENTER or type command to continue

Is there a way to do this without pressing enter? I guess I could just run echo | vim -c quit, but I was hoping there was a more elegant solution.

Best Answer

You can use a try-catch block to catch errors (which get converted to exceptions), and fail on any exception:

$ cat vimrc-fail                                                
echoerr 'test'                                 
$ cat vimrc-pass
echo 'test'
$ vim -u NONE -c 'try | source vimrc-pass | catch | cq | endtry | q'; echo $?  
0
$ vim -u NONE -c 'try | source vimrc-fail | catch | cq | endtry | q'; echo $?
1

From the help:

:try                            :try :endt :endtry E600 E601 E602
:endt[ry]               Change the error handling for the commands between
                        ":try" and ":endtry" including everything being
                        executed across ":source" commands, function calls,
                        or autocommand invocations.

And from :echoerr:

When used inside a try conditional, the message is raised as an error exception instead (see try-echoerr).

Other notes:

  • -u NONE prevents sourcing the default vimrcs
  • :cq makes Vim return a non-zero exit status

To get the last error message (now actually an exception), use v:exception:

$ vim -u NONE -c 'try | source vimrc-fail | catch | silent exec "!echo " shellescape(v:exception) |cq | endtry | q'; echo $?
Vim(echoerr):test
1
Related Question