Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZSH: Behavior on Enter

Tags:

zsh

I realize, when I'm in my terminal, I would expect to press Enter on empty input to make a ls or a git status when I'm on a git repos.

How can I achieve that? I mean, have a custom behavior on Empty input -> Enter in zsh?


EDIT: Thanks for the help. Here's my take with preexec...

precmd() {
  echo $0;
  if ["${0}" -eq ""]; then
    if [ -d .git ]; then
      git status
    else
      ls
    fi;
  else
    $1
  fi;
}
like image 536
Augustin Riedinger Avatar asked Sep 28 '22 23:09

Augustin Riedinger


1 Answers

On Enter zsh calls the accept-line widget, which causes the buffer to be executed as command.

You can write your own widget in order to implement the behaviour you want and rebind Enter:

my-accept-line () {
    # check if the buffer does not contain any words
    if [ ${#${(z)BUFFER}} -eq 0 ]; then
        # put newline so that the output does not start next
        # to the prompt
        echo
        # check if inside git repository
        if git rev-parse --git-dir > /dev/null 2>&1 ; then
            # if so, execute `git status'
            git status
        else
            # else run `ls'
            ls
        fi
    fi
    # in any case run the `accept-line' widget
    zle accept-line
}
# create a widget from `my-accept-line' with the same name
zle -N my-accept-line
# rebind Enter, usually this is `^M'
bindkey '^M' my-accept-line

While it would be sufficient to run zle accept-line only in cases where there actually was a command, zsh would not put a new prompt after the output. And while it is possible to redraw the prompt with zle redisplay, this will probably overwrite the last line(s) of the output if you are using multi-line prompts. (Of course there are workarounds for that, too, but nothing as simple as just using zle accept-line.

Warning: This redfines an (the most?) essential part of your shell. While there is nothing wrong with that per se (else I would not have posted it here), it has the very real chance to make your shell unusable if my-accept-line does not run flawlessly. For example, if zle accept-line were to be missing, you could not use Enter to confirm any command (e.g. to redefine my-accept-line or to start an editor). So please, test it before putting it into your ~/.zshrc.

Also, by default accept-line is bound to Ctrl+J, too. I would recommend to leave it that way, to have an easy way to run the default accept-line.

like image 169
Adaephon Avatar answered Oct 05 '22 08:10

Adaephon