Search code examples
fish

How to map ctrl-z to fg in fish


I am trying to implement a feature from the following article:

How to boost your vim productivity

in the fish shell. The Author in the Article uses the following code to map Ctrl+Z in zsh to the "fg" command.

fancy-ctrl-z () {
  if [[ $#BUFFER -eq 0 ]]; then
    BUFFER="fg"
    zle accept-line
  else
    zle push-input
    zle clear-screen
  fi
}
zle -N fancy-ctrl-z
bindkey '^Z' fancy-ctrl-z

The intention is to quickly switch between a vim instance in the foreground and the shell.

So Ctrl+Z backgrounds vim, and switches to the shell, then Ctrl+Z again should foreground vim again, so switching quickly is possible.

How would I replicate that in fish?


Solution

  • fish currently doesn't let you catch SIGTSTP, which is what Ctrl+Z sends. You can however bind another key. For example, you could write:

    bind \ck 'fg %'
    

    This makes control-K switch back to the last backgrounded process.

    It looks like the zsh fancy-ctrl-z function has a separate mode where it clears the screen if there's input on the command line. I'm not sure what that's about, but that can be replicated in fish if you want, something like:

    bind \ck 'if test -z (commandline) ; fg %; else ; clear; commandline ""; end'