Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically halt execution in Vimscript?

Tags:

exception

vim

I'm trying to catch an exception in Vimscript and halt execution in the function where error occurs. I can catch the error fine, but the function where it happens is several levels down in the call stack so all that happens is another error occurs in the calling function. The error message I put in the 'catch' of the original function never gets seen, and regular Vim error is generated in a calling function. I can put try/catches in all the way up the chain, but it seems like I should be able to stop execution right where it happens.

Here's an example to illustrate what I mean:

function Function1()
     call Function2()
endfunction

function Function2()
     call Function3()
endfunction

function Function3()
    try
       [...]
    catch
       echo "An error occurred.  Execution should be stopped . . ."
       " I've tried putting 'normal <ctrl-C>' but it doesn't seem to 
       " do anything. . .  Execution silently goes back to function2, 
       " where another (uncaught) error occurs
    endtry
endfunction
like image 293
Herbert Sitz Avatar asked Oct 10 '22 17:10

Herbert Sitz


1 Answers

If I understood you correctly, you want to abort execution if there is an error in some function, but also show custom error message instead of default one. In this case you should use throw, try replacing :echo in the :catch block with it. You can also use the following hack in order to both keep vim error message and show your one:

function Function3()
    try
        [...]
        let succeeded=1
    finally
        if !exists('succeeded')
            echo "An error occurred.  Execution should be stopped . . ."
        endif
    endtry
endfunction

By the way, correct syntax for using special keys in :normal is :execute "normal! \<C-c>", not :normal! <Ctrl-c>.

like image 168
ZyX Avatar answered Oct 13 '22 10:10

ZyX