Search code examples
zshzsh-zle

Recover an interrupted command in zsh


In zsh, if one accidentally interrupted a command (^C), is there a quick way to recover the full interrupted command line?

For example,

PROMPT $ this is a long command ^C
PROMPT $ [cursor here]

I would like to recover "this is a long command" at the cursor position.


Solution

  • One solution is to

    zle-line-init () {
      if [[ -n $ZLE_LINE_ABORTED ]]; then
        local savebuf="$BUFFER" savecur="$CURSOR"
        BUFFER="$ZLE_LINE_ABORTED" 
        CURSOR="$#BUFFER" 
        zle split-undo
        BUFFER="$savebuf" CURSOR="$savecur" 
      fi
    }
    zle -N zle-line-init
    

    Then, in the new input line, undo (C-/ in emacs mode) would give the aborted line.

    reference: http://www.zsh.org/mla/users/2015/msg00652.html

    I've added a more detailed explanation here: https://www.topbug.net/blog/2016/10/03/restore-the-previously-canceled-command-in-zsh/