Augustin Riedinger
Augustin Riedinger

Reputation: 22270

ZSH: Behavior on Enter

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;
}

Upvotes: 7

Views: 3461

Answers (2)

Adaephon
Adaephon

Reputation: 18429

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.

Upvotes: 7

user12341234
user12341234

Reputation: 7223

In my .zshrc I use a combination of precmd and preexec found here:

http://zsh.sourceforge.net/Doc/Release/Functions.html#Hook-Functions

I also find that the git-prompt is super useful:

https://github.com/olivierverdier/zsh-git-prompt

Upvotes: 2

Related Questions