gpt4 book ai didi

zsh - 编写 ZSH 自动完成功能

转载 作者:行者123 更新时间:2023-12-03 14:14:56 25 4
gpt4 key购买 nike

我最近编写了一个方便的 Zsh 函数,它可以创建一个没有参数的新 tmux session 。如果提供了参数并且 session 已经存在,则附加它。否则,将使用提供的名称创建一个新 session 。

# If the session is in the list of current tmux sessions, it is attached. Otherwise, a new session 
# is created and attached with the argument as its name.
ta() {

# create the session if it doesn't already exist
tmux has-session -t $1 2>/dev/null
if [[ $? != 0 ]]; then
tmux new-session -d -s $1
fi

# if a tmux session is already attached, switch to the new session; otherwise, attach the new
# session
if { [ "$TERM" = "screen" ] && [ -n "$TMUX" ]; } then
tmux switch -t $1
else
tmux attach -t $1
fi
}

这很好用,但我想为它添加自动完成功能,所以当我按下 Tab 键时,它会为我列出当前的 session 。这是我到目前为止所拥有的:
# List all the the sessions' names.
tln() {
tmux list-sessions | perl -n -e'/^([^:]+)/ && print $1 . "\n"'
}

compctl -K tln ta

当我点击 Tab 时,它会列出 session 名称,但它不允许我在它们之间切换。我错过了什么?

最佳答案

您没有仔细阅读文档:

Call the given function to get the completions. Unless the name starts with an underscore, the function is passed two arguments: the prefix and the suffix of the word on which completion is to be attempted, in other words those characters before the cursor position, and those from the cursor position onwards. The whole command line can be accessed with the -c and -l flags of the read builtin. The function should set the variable reply to an array containing the completions (one completion per element); note that reply should not be made local to the function. From such a function the command line can be accessed with the -c and -l flags to the read builtin. For example,



.您不得从完成函数向 stdout 输出任何内容。您必须改为设置数组变量 reply :
reply=( $(tmux list-sessions | cut -d: -f1) )

.请注意,您没有理由在此处调用 perl, cut更合适。我没有看到任何不匹配的行 ^([^:]+)在 tmux 输出中。

关于zsh - 编写 ZSH 自动完成功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17767208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com