How to set Terminal tab title to show the current git branch (using zsh)?

How to set Terminal tab title to show the current git branch (using zsh)?

ZSH allows for nice customized command line prompts that show the current git branch. I'd like to also show the current git branch in the title of the Terminal window or tab (the text in the bar at the very top of the window). I'm using the Terminal app included with Mac OS.

I've seen answers about how to put your current directory in the title, but can't seem to find how to put the git branch up there.

Is this possible? If so, how?

答案1

The fundamental idea is the same. There are two ways to do this, the simple way and the complex way.

If you're looking for the simple way, you can use a precmd function to do this before each prompt:

change_title_bar () {
    local statusline="$(git rev-parse --abbrev-ref HEAD)"
    case $TERM in
        xterm*|gnome*)
            print -Pn "\e]0;$statusline\a";;
        screen*|tmux*)
            print -Pn "\ek$statusline\e\\";;
    esac
}

precmd () {
    change_title_bar
    # any other precmd things you want to do
}

The slightly more complicated way is to set up vcs_info and get the information out of it:

zstyle ':vcs_info:*' enable git
zstyle ':vcs_info:*' actionformats "%b"
zstyle ':vcs_info:*' formats       "%b"

change_title_bar () {
    local statusline='${vcs_info_msg_0_}'
    case $TERM in
        xterm*|gnome*)
            print -Pn "\e]0;$statusline\a";;
        screen*|tmux*)
            print -Pn "\ek$statusline\e\\";;
    esac
}

precmd () {
    change_title_bar
    # any other precmd things you want to do
}

The latter is more efficient, because zsh will have extracted it already, but you may or may not wish to use vcs_info. And there are other ways to improve on this, such as using terminfo to extract the specific sequences if you like.

相关内容