我使用 zsh 并编写了一个函数来替换 cd 功能。在一些帮助下,我让它按照我想要的方式工作(大部分)。这是后续我的另一个问题之一 https://stackoverflow.com/questions/64463599/cant-use-in-zsh-autocompletion。
该函数几乎按照我想要的方式工作,但我在语法突出显示和自动完成方面仍然存在一些问题。
对于示例,假设您的目录如下所示:
/
a/
b/
c/
d/
some_dir/
我还假设已获取以下代码:
cl () {
local first=$( echo $1 | cut -d/ -f1 )
if [ -d $first ]; then
pushd $1 >/dev/null # If the first argument is an existing normal directory, move there
else
pushd ${PWD%/$first/*}/$1 >/dev/null # Otherwise, move to a parent directory or a child of that parent directory
fi
}
_cl() {
_cd
pth=${words[2]}
opts=""
new=${pth##*/}
local expl
# Generate the visual formatting and store it in `$expl`
_description -V ancestor-directories expl 'ancestor directories'
[[ "$pth" != *"/"*"/"* ]] && middle="" || middle="${${pth%/*}#*/}/"
if [[ "$pth" != *"/"* ]]; then
# If this is the start of the path
# In this case we should also show the parent directories
local ancestor=$PWD:h
while (( $#ancestor > 1 )); do
# -f: Treat this as a file (incl. dirs), so you get proper highlighting.
# -Q: Don't quote (escape) any of the characters.
# -W: Specify the parent of the dir we're adding.
# ${ancestor:h}: The parent ("head") of $ancestor.
# ${ancestor:t}: The short name ("tail") of $ancestor.
compadd "$expl[@]" -fQ -W "${ancestor:h}/" - "${ancestor:t}"
# Move on to the next parent.
ancestor=$ancestor:h
done
else
# $first is the first part of the path the user typed in.
# it it is part of the current direoctory, we know the user is trying to go back to a directory
first=${pth%%/*}
# $middle is the rest of the provided path
if [ ! -d $first ]; then
# path starts with parent directory
dir=${PWD%/$first/*}/$first
first=$first/
# List all sub directories of the $dir/$middle directory
if [ -d "$dir/$middle" ]; then
for d in $(ls -a $dir/$middle); do
if [ -d $dir/$middle/$d ] && [[ "$d" != "." ]] && [[ "$d" != ".." ]]; then
compadd "$expl[@]" -fQ -W $dir/ - $first$middle$d
fi
done
fi
fi
fi
}
compdef _cl cl
问题:
我使用语法突出显示,但我输入的路径只是白色(当转到父目录时。正常的 cd 功能是彩色的)。
Example:
$ cd /a
$ cl c # 'c' is colored
$ pwd
/a/c
$ cl a/b # 'a/b' is not colored
$ cl a/[tab] # 'a/b', 'a/c' and 'a/some_dir' are not colored
如何让这些路径着色?
这是不可能开箱即用的zsh-syntax-highlighting plugin https://github.com/zsh-users/zsh-syntax-highlighting。它仅检查您输入的内容是否是
- A) 有效的绝对路径或
- B) 相对于当前工作目录的有效路径。
这不是特定于您的命令。当为其他有效的命令指定路径参数时,突出显示也会失败,但这些命令不是绝对路径或相对于当前工作目录的有效路径。
例如:
% cd /a/b
% cd b c # perfectly valid args, but will not get highlighted as valid paths
% pwd
/a/c
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)