编写ZSH自动完成函数

编写ZSH自动完成函数,zsh,zsh-completion,oh-my-zsh,Zsh,Zsh Completion,Oh My Zsh,我最近编写了一个方便的Zsh函数,它创建了一个没有参数的新tmux会话。如果提供了参数且会话已存在,则会附加该参数。否则,将使用提供的名称创建新会话 # 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

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

# 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键时,它会为我列出当前会话。以下是我目前掌握的情况:

# List all the the sessions' names.
tln() {
  tmux list-sessions | perl -n -e'/^([^:]+)/ && print $1 . "\n"'
}

compctl -K tln ta

当我点击tab时,它列出了会话名称,但不允许我在它们之间切换。我遗漏了什么?

您没有仔细阅读文档:

调用给定的函数以获取完成项。除非名称以下划线开头,否则函数将传递两个参数:要尝试完成的单词的前缀和后缀,换句话说,是光标位置之前的字符,以及光标位置之后的字符。整个命令行可以通过read内置的-c和-l标志访问函数应将变量
reply
设置为包含补全的数组(每个元素一个补全)
;请注意,应答不应是函数的本地应答。通过这样一个函数,可以使用-c和-l标志访问命令行以读取内置代码。比如说,

。不能从完成函数向标准输出任何内容。您必须改为设置数组变量
reply

reply=( $(tmux list-sessions | cut -d: -f1) )
。请注意,您没有理由在这里调用perl,
cut
更合适。在tmux输出中,我没有看到任何与
^([^::]+)
不匹配的行