防止 zsh 在 CWD 中使用别名(提示)

Ame*_*ina 6 zsh oh-my-zsh

我使用oh-my-zsh(最新版本的zshoh-my-zsh)激活了以下个性化主题 :

local return_code="%(?..%{$fg[red]%}%? %{$reset_color%})"

local user_host='%{$terminfo[bold]$fg[green]%}%n @ %m%{$reset_color%}'
local current_dir='%{$terminfo[bold]$fg[cyan]%} %~%{$reset_color%}'
local rvm_ruby=''
local git_branch='$(git_prompt_info)%{$reset_color%}'

PROMPT="${user_host} %D{[%a, %b %d %I:%M:%S]} ${current_dir} ${rvm_ruby} ${git_branch}
%B$%b "
RPS1="${return_code}"

ZSH_THEME_GIT_PROMPT_PREFIX="%{$fg[yellow]%}‹"
ZSH_THEME_GIT_PROMPT_SUFFIX="› %{$reset_color%}"
Run Code Online (Sandbox Code Playgroud)

我注意到在提示中,每当我有一个目录的别名时,它都会将别名的名称显示为我的当前目录,而不是实际路径。虽然这是一个有趣的功能,但我想禁用它。

我对 比较陌生oh-my-zsh,我不确定这是否是oh-my-zshzsh功能,但我该如何禁用它?

Gil*_*il' 6

所述提示转义序列 %~(包含在$current_dir)扩展为当前目录,同时缩写考虑。缩写是:

  • ~ 用于您的主目录;
  • ~joe对于用户的主目录joe
  • ~foo对于命名目录:别名为foowith的目录hash -d foo=…
  • ~[bar]对于动态命名目录

您可以使用%/代替%~. 这从不使用任何目录缩写。

如果你想更高级,可以执行自己的代码来确定当前目录的显示方式。一种方法是在提示字符串中使用参数替换。这需要设置prompt_subst选项,oh-my-zsh 会这样做(否则:)setopt prompt_subst。当前目录在参数中始终可用PWD。这是一个简单的版本,它只会将您的主目录缩短为~

local current_dir='%{$terminfo[bold]$fg[cyan]%} ${${PWD/#%$HOME/~}/#$HOME\//~/}%{$reset_color%}'
Run Code Online (Sandbox Code Playgroud)

${${PWD/#%$HOME/\~}/#$HOME\//\~/}表示:如果$PWD与 完全相同$HOME,则将结果设置为~,否则将结果设置为$PWD;然后,如果当前结果以 开头$HOME/,则将该前缀替换为~/,否则保持结果不变。

更清晰的方法是维护一个包含当前目录的漂亮打印版本的参数。chpwd在每次当前目录更改时执行的钩子函数中更新此参数。还要在您的.zshrc.

只有一个chpwd函数,所以不要覆盖 oh-my-zsh 的。Oh-my-zshchpwd调用数组中的函数chpwd_functions,因此将您的函数添加到数组中。

function my_update_pretty_PWD {
  case $PWD in
    $HOME(/*)#) pretty_PWD=\~${PWD#$HOME};;
    *) pretty_PWD=$PWD;;
  esac
}
chpwd_functions+=(my_update_pretty_PWD)
my_update_pretty_PWD
local current_dir='%{$terminfo[bold]$fg[cyan]%} ${pretty_PWD}%{$reset_color%}'
Run Code Online (Sandbox Code Playgroud)

如果要缩写用户的主目录而不是命名目录,可以在子shell中清除主目录,并使用% 参数扩展标志在子shell中执行自动缩写。

function my_update_pretty_PWD {
  pretty_PWD=$(hash -rd; print -lr -- ${(%)PWD})
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您更喜欢内联方法:

local current_dir='%{$terminfo[bold]$fg[cyan]%} $(hash -rd; print -lr -- ${(%)PWD})%{$reset_color%}'
Run Code Online (Sandbox Code Playgroud)