Here’s an example:
1. First, open your .zshrc file in a text editor (e.g., nano ~/.zshrc).
2. Add these lines at the bottom to enable and autoload vcs_info before displaying the prompt:
# This script enables and autoloads vcs_info before displaying the prompt in the .zshrc file.
# First, we need to enable vcs_info by using the -Uz option in the autoload command.
autoload -Uz vcs_info
# Next, we need to ensure that vcs_info is always loaded before displaying the prompt by using the precmd function.
# This function will be executed before displaying the prompt.
precmd () { vcs_info }
3. Next, add this line to format your version control status information with color using zstyle:
# This line sets the format for version control status information using zstyle
zstyle ':vcs_info:*' formats ' %s(%F{red}%b%f)' # git(main)
# The %s represents the name of the version control system, %F{red} sets the color to red, and %b represents the current branch. %f resets the color back to default. This will display the current branch in red within parentheses after the version control system name.
In this example, we are setting the format string for vcs_info to display the current version control system (e.g., “git”) and branch name (“main”), with color using ANSI escape codes (i.e., %F{red}%b%f).
4. Finally, add your customized prompt string by modifying the PS1 variable:
# Setting the prompt string variable PS1 to display the username (%n), hostname (%m), current directory (%/), and version control system information (vcs_info_msg_0_) with color using ANSI escape codes (%F{red} and %f).
PS1='%n@%m %F{red}%/%f$vcs_info_msg_0_ $ ' # david@macbook /tmp/repo (main) $
In this example, we are setting the prompt string to display your username (“david”), hostname (“macbook”), current directory path (“/tmp/repo”), and version control status information with color using ANSI escape codes. The “$vcs_info_msg_0_” variable is used to insert the output of vcs_info into the prompt string.
5. Save your changes, close the text editor, and open a new terminal window or run “source ~/.zshrc” in an existing one to apply the changes.
6. You can customize this format string further by adding additional tokens (e.g., %u for user name) or modifying the color codes (e.g., %F{green}%m%f). For more information on available tokens, check out the zsh documentation.