Controlling the C in Vim
October 26th, 2007So one day you decide to write a fancy plugin for Vim. After months of writing and testing, you let a friend try. Knowing it’s well architected in terms of layered function calls, has error handling for interactions with 3rd party applications, and provides an intuitive key-based user interface — nothing could go wrong!
Then comes along the diabolical CTRL-C. The arch nemesis of event-based programming (esp. in Vim). The ability to arbitrarily cancel any operation in progress, at any step along the way.
You’re friend decides to hit this magic key combination and the plugin comes to a screeching halt…. the status bar is showing an old state; the progress bar is half-way completed but shouldn’t even be visible; and who knows if the 3rd party application was even contacted.
Ugh. back to the drawing board.
After digging through the vim :help docs for the 100th time over the last few months, I found the solution! The exception handling facility lets you capture the CTRL-C interrupt in a catch clause. Here’s the pattern:
try
… <set variables>
… <call 3rd party apps>
… <perform logic>
catch /^Vim:Interrupt$/
… <unset variables>
… <fix user display>
… <display warning/error message>
endtry
One drawback though is that you cannot re-throw the exception once in the catch block. Though, this can easily be remedied by throwing a custom exception, which is probably better anyway — so the higher level layers deal with application-based exceptions, rather than low-level SDK exceptions.






October 29th, 2007 at 12:02 pm
Do or do not. There is no try.