highsciguy
highsciguy

Reputation: 2647

Execute command when vim filter command is interrupted

I use filter commands in vim to call bash scripts that I need to interrupt sometimes. I do this by hitting Ctrl+C in the vim window. The bash script terminates then (at least vim stops the filter command) but the text I passed to the filter command (usually a visual selection) will be missing. I would like vim to return to the state before the filter command if I interrupt execution by Ctrl+C or the bash script finishes with exit state other than 0. Note that I know that I can press u to undo, but I would like to modify the filter command to do this since I could forget to press u and loose the text without noticing.

Upvotes: 0

Views: 252

Answers (1)

Vi.
Vi.

Reputation: 38734

You can set signal and/or exit handlers in bash. man bash, /trap.*sigspec

Something like:

trap "your_commands"  SIGINT
my_program

To make it "preserve" the text, you probably need something like that:

TIN=`mktemp`
TOUT=`mktemp`
cat > $TIN
trap "cat $TIN; rm -f $TIN; rm -f $TOUT" EXIT
do_something < $TIN > $TOUT || cp $TIN $TOUT
mv $TOUT $TIN

Checked in my Vim, seems to be working. (tested with sed and sleep as do_something)

Upvotes: 1

Related Questions