ZSH:Enter上的行为

  • 本文关键字:Enter ZSH zsh
  • 更新时间 :
  • 英文 :


我意识到,当我在终端中时,我希望在空输入上按Enter在我使用git存储库时制作 lsgit status

我该如何实现?我的意思是,在zsh中的Empty input -> Enter上有自定义行为?


编辑:感谢您的帮助。这是我对preexec ...

的看法
precmd() {
  echo $0;
  if ["${0}" -eq ""]; then
    if [ -d .git ]; then
      git status
    else
      ls
    fi;
  else
    $1
  fi;
}

on enter zsh 调用 accept-line窗口小部件,这会导致缓冲区执行为命令。

您可以编写自己的小部件,以实现您想要的行为并重新启用 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

仅在实际上有命令的情况下,运行zle accept-line是足够的,但是在输出后, zsh 不会在输出后放置新提示。尽管可以用zle redisplay重新绘制提示,但如果您使用的是多行提示符,则可能会覆盖输出的最后一行。(当然,也有解决方法,但没有什么比仅使用zle accept-line的简单。

警告:这是您外壳的(最重要的?)。虽然这本身没有错(否则我不会在这里发布),但如果my-accept-line不完美运行,它确实有机会使您的外壳无法使用。例如,如果丢失了zle accept-line,则无法使用 Enter 确认任何命令(例如重新定义my-accept-line或启动编辑器)。因此,请在将其放入~/.zshrc之前对其进行测试。

此外,默认情况下,accept-line也与 ctrl J 绑定。我建议这样做,以便有一种简单的方法来运行默认的accept-line

在我的 .zshrc中,我使用precmd和preexec的组合:

http://zsh.sourceforge.net/doc/release/functions.html#hook-functions

我还发现git-prompt非常有用:

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

最新更新