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
.
[["$1" -eq ""]]
to["$1" -eq ""]
and putting the code intoprecmd
instead ofpreexec
.$1
, it is always empty, if I use$0
, I still getbad pattern: [zsh
...$0
,$1
and$2
. Here's what I havepreexec: $0=preexec, $1=ll, $2=ls --color=tty -lh
andprecmd: $0=zsh, $1 = $2 = ""
. Also important to note:preexec
is not called when pressing empty string. Andprecmd
doesn't know about the previous command. Not sure I can achieve what I want here then...