zshzsh-zle

How can I keybind Ctrl-C to vi-kill-line only when in viins mode?


What I want to achieve is to bind Ctrl-C to clearing the line without issuing a newline (à la ipython) only when editing the command line, while keeping Ctrl-C as the interrupt signal triggerer when a command is running. I'm using bindkey -v, ie vi-mode line editing, but I believe it's not relevant.

As a side note, I wish this feature will not create situations where Ctrl-C would not interrupt a running command.

I'm digging into this on my spare time, so I'll be interested in any clues. If I find something robust enough I'll post it as an answer indeed.


Solution

  • Any function named TRAPINT inside your .zshrc will trap interrupt signals sent by Ctrl-C. Inside there, you will want to test if you are in insert mode, which can be achieved by testing the ${KEYMAP} variable. If it isn't, you should pass the return value of the parent process (see this answer for a hint on this). This leads us to the following snippet :

    TRAPINT() { 
        if [[ "${KEYMAP}" = "viins" -o "${KEYMAP}" = "main" ]]; then
            zle kill-whole-line
            zle reset-prompt
        else
            return ${128+$1}
        fi
    }
    

    This will work if you use vi-mode line editing. It should also catch emacs-mode, where KEYMAP should be set to main, although I did not test this specific use case. zle reset-prompt is sometimes needed to update the display.