问题描述
我使用 zsh 并且我想使用我编写的函数来替换 cd.此功能使您能够移动到父目录:
I use zsh and I want to use a function I wrote to replace cd.This function gives you the ability to move to a parent directory:
$ pwd
/a/b/c/d
$ cl b
$ pwd
/a/b
您也可以移动到父目录的子目录:
You can also move into a subdirectory of a parent directory:
$ pwd
/a/b/c/d
$ cl b/e
$ pwd
/a/b/e
如果路径的第一部分不是父目录,它将像普通的 cd 一样起作用.我希望这是有道理的.
If the first part of the path is not a parent directory, it will just function as normal cd would. I hope that makes sense.
总而言之,在/a/b/c/d时,我希望能够移动到/a、/a/b、/a/b/c、/a/b/c/的所有子目录d 和任何以/、~/或 ../(或 ./)开头的绝对路径.我希望这是有道理的.
In summary, when in /a/b/c/d, I want to be able to move to /a, /a/b, /a/b/c, all subdirectories of /a/b/c/d and any absolute path starting with /, ~/ or ../ (or ./).I hope that makes sense.
这是我写的函数:
cl () {
local first=$( echo $1 | cut -d/ -f1 )
if [ $# -eq 0 ]; then
# cl without any arguments moves back to the previous directory
cd - > /dev/null
elif [ -d $first ]; then
# If the first argument is an existing normal directory, move there
cd $1
else
# Otherwise, move to a parent directory
cd ${PWD%/$first/*}/$1
fi
}
可能有更好的方法(欢迎提供提示),但到目前为止我还没有遇到任何问题.
There is probably a better way to this (tips are welcome), but I haven't had any problems with this so far.
现在我想添加自动完成功能.这是我目前所拥有的:
Now I want to add autocompletion. This is what I have so far:
_cl() {
pth=${words[2]}
opts=""
new=${pth##*/}
[[ "$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
opts+=" "
first=""
d="${${PWD#/}%/*}/"
opts+="${d///// }"
dir=$PWD
else
first=${pth%%/*}
if [[ "$first" == "" ]]; then
# path starts with "/"
dir="/$middle"
elif [[ "$first" == "~" ]]; then
# path starts with "~/"
dir="$HOME/$middle"
elif [ -d $first ]; then
# path starts with a directory in the current directory
dir="$PWD/$first/$middle"
else
# path starts with parent directory
dir=${PWD%/$first/*}/$first/$middle
fi
first=$first/
fi
# List al sub directories of the $dir directory
if [ -d "$dir" ]; then
for d in $(ls -a $dir); do
if [ -d $dir/$d ] && [[ "$d" != "." ]] && [[ "$d" != ".." ]]; then
opts+="$first$middle$d/ "
fi
done
fi
_multi_parts / "(${opts})"
return 0
}
compdef _cl cl
同样,这可能不是最好的方法,但它确实有效......有点.
Again, probably not the best way to do this, but it works... kinda.
问题之一是我输入 cl ~/时,它用 cl ~/替换它,并且不建议我的主文件夹中的任何目录.有没有办法让它起作用?
One of the problems is that what I type cl ~/, it replaces it with cl ~/ and does not suggest any directories in my home folder. Is there a way to get this to work?
编辑
cl () {
local first=$( echo $1 | cut -d/ -f1 )
if [ $# -eq 0 ]; then
# cl without any arguments moves back to the previous directory
local pwd_bu=$PWD
[[ $(dirs) == "~" ]] && return 1
while [[ $PWD == $pwd_bu ]]; do
popd >/dev/null
done
local pwd_nw=$PWD
[[ $(dirs) != "~" ]] && popd >/dev/null
pushd $pwd_bu >/dev/null
pushd $pwd_nw >/dev/null
elif [ -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
这是我自己做的.它确实有效(有点)但有几个问题:
This is as far as I got on my own. It does works (kinda) but has a couple of problems:
- 返回父目录时,补全通常有效.但是当您转到 paretn 目录的子目录时,建议是错误的(它们显示您键入的完整路径,而不仅仅是子目录).结果确实有效
- 我使用语法高亮显示,但我输入的路径只是白色(使用转到父目录时.普通的 cd 函数是彩色的)
- 在我的 zshrc 中,我有一行:
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Za-z}' '+l:|=* r:|=*'
用 cd 这意味着我可以输入load"它将完成下载".使用 cl,这是行不通的.使用普通 cd 功能时不是事件.
Whith cd this means I can type "load" and it will complete to "Downloads". With cl, this does not work. Not event when using the normal cd functionality.
有没有办法解决(其中一些)问题?我希望你们能理解我的问题.我觉得很难解释这个问题.
Is there a way to fix (some of these) problems?I hope you guys understand my questions. I find it hard to explain the problem.
感谢您的帮助!
推荐答案
应该这样做:
_cl() {
# Store the number of matches generated so far.
local -i nmatches=$compstate[nmatches]
# Call the built-in completion for `cd`. No need to reinvent the wheel.
_cd
# ${PWD:h}: The parent ("head") of the present working dir.
local ancestor=$PWD:h expl
# Generate the visual formatting and store it in `$expl`
# -V: Don't sort these items; show them in the order we add them.
_description -V ancestor-directories expl 'ancestor directories'
while (( $#ancestor > 1 )); do
# -f: Treat this as a file (incl. dirs), so you get proper highlighting.
# -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[@]" -f -W ${ancestor:h}/ - $ancestor:t
# Move on to the next parent.
ancestor=$ancestor:h
done
# Return true if we've added any matches.
(( compstate[nmatches] > nmatches ))
}
# Define the function above as generating completions for `cl`.
compdef _cl cl
# Alternatively, instead of the line above:
# 1. Create a file `_cl` inside a dir that's in your `$fpath`.
# 2. Paste the _contents_ of the function `_cl` into this file.
# 3. Add `#compdef cl` add the top of the file.
# `_cl` will now get loaded automatically when you run `compinit`.
另外,我会像这样重写你的 cl
函数,这样它就不再依赖于 cut
或其他外部命令:
Also, I would rewrite your cl
function like this, so it no longer depends on cut
or other external commands:
cl() {
if (( $# == 0 )); then
# `cl` without any arguments moves back to the previous directory.
cd -
elif [[ -d $1 || -d $PWD/$1 ]]; then
# If the argument is an existing absolute path or direct child, move there.
cd $1
else
# Get the longest prefix that ends with the argument.
local ancestor=${(M)${PWD:h}##*$1}
if [[ -d $ancestor ]]; then
# Move there, if it's an existing dir.
cd $ancestor
else
# Otherwise, print to stderr and return false.
print -u2 "$0: no such ancestor '$1'"
return 1
fi
fi
}
替代方案
有一种更简单的方法来完成所有,无需编写cd
替换或任何完成代码:
Alternative Solution
There is an easier way to do all of this, without the need to write a cd
replacement or any completion code:
cdpath() {
# `$PWD` is always equal to the present working directory.
local dir=$PWD
# In addition to searching all children of `$PWD`, `cd` will also search all
# children of all of the dirs in the array `$cdpath`.
cdpath=()
# Add all ancestors of `$PWD` to `$cdpath`.
while (( $#dir > 1 )); do
# `:h` is the direct parent.
dir=$dir:h
cdpath+=( $dir )
done
}
# Run the function above whenever we change directory.
add-zsh-hook chpwd cdpath
Zsh 的 cd
完成代码自动将 $cdpath
考虑在内.甚至不需要配置.:)
Zsh's completion code for cd
automatically takes $cdpath
into account. No need to even configure that. :)
举个例子说明它是如何工作的,假设你在 /Users/marlon/.zsh/prezto/modules/history-substring-search/external/
.
As an example of how this works, let's say you're in /Users/marlon/.zsh/prezto/modules/history-substring-search/external/
.
- 您现在可以输入
cd pre
并按,Zsh将完成它为cd prezto
.之后,按 会将您直接带到/Users/marlon/.zsh/prezto/
. - 或者假设也存在
/Users/marlon/.zsh/prezto/modules/prompt/external/agnoster/
.当你在前一个目录时,你可以做cd prompt/external/agnoster
直接进入到后者,Zsh会为你完成这条路径的每一步.
- You can now type
cd pre
and press , and Zsh will complete it tocd prezto
. After that, pressing will take you directly to/Users/marlon/.zsh/prezto/
. - Or let's say that there also exists
/Users/marlon/.zsh/prezto/modules/prompt/external/agnoster/
. When you're in the former dir, you can docd prompt/external/agnoster
to go directly to the latter, and Zsh will complete this path for you every step of the way.
这篇关于不能在 zsh 自动补全中使用“~"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!