在zsh自动补全中不能使用'〜' [英] can't use '~' in zsh autocompletion

查看:64
本文介绍了在zsh自动补全中不能使用'〜'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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/b/c/的所有子目录/a,/a/b,/a/b/cd以及以/,〜/或../(或./)开头的任何绝对路径.我希望这是有道理的.

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 并按 Tab ,然后Zsh将其完成为 cd prezto .之后,按 Enter 会将您直接带到/Users/marlon/.zsh/prezto/.
  • 或者说也存在/Users/marlon/.zsh/prezto/modules/prompt/external/agnoster/.当您位于前一个目录中时,可以执行 cd提示符/外部/agnoster 直接转到后者,然后Zsh将为您完成此路径的每一步.
  • You can now type cd pre and press Tab, and Zsh will complete it to cd prezto. After that, pressing Enter 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 do cd prompt/external/agnoster to go directly to the latter, and Zsh will complete this path for you every step of the way.

这篇关于在zsh自动补全中不能使用'〜'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆