3

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

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

4

1 回答 1

11

您没有仔细阅读文档:

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,

. You must not output anything to stdout from completion function. You must instead set the array variable reply:

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

. Note that there is no reason for you to invoke perl here, cut is more suitable. I do not see any lines not matching ^([^:]+) in the tmux output.

于 2013-07-20T23:26:45.337 回答