【问题标题】:Writing a ZSH autocomplete function编写 ZSH 自动完成功能
【发布时间】:2013-07-20 22:13:56
【问题描述】:

我最近编写了一个方便的 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

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

【问题讨论】:

    标签: zsh zsh-completion oh-my-zsh


    【解决方案1】:

    您没有仔细阅读文档:

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

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

    reply=( $(tmux list-sessions | cut -d: -f1) )
    

    。注意这里没有理由让你调用 perl,cut 更合适。我在 tmux 输出中没有看到任何与 ^([^:]+) 不匹配的行。

    【讨论】:

      猜你喜欢
      • 2014-06-17
      • 2022-08-15
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多