2013-07-20 175 views
3

我最近寫了一個方便的Zsh函數,它創建了一個沒有參數的新的tmux會話。如果提供了一個參數並且會話已經存在,它就會被附加。否則,使用提供的名稱創建新會話。寫一個ZSH自動完成功能

# 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 
} 

這很好,但我想添加autocompletion它,所以當我點擊標籤鍵時,它會列出當前會話爲我。這是我到目前爲止:

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

compctl -K tln ta 

當我點擊標籤時,它列出了會話名稱,但它不允許我在它們之間切換。我錯過了什麼?

回答

8

你沒有仔細閱讀文檔:

調用給定函數來獲取落成。除非名稱以下劃線開頭,否則該函數會傳遞兩個參數:要完成嘗試的單詞的前綴和後綴,換句話說就是光標位置之前的那些字符,以及光標位置之前的那些字符。整個命令行可以通過讀內置的-c和-l標誌來訪問。 函數應該將變量reply設置爲包含完成的數組(每個元素完成一次);請注意,回覆不應該在本地進行。從這樣的函數中,命令行可以通過-c和-l標誌訪問內置讀取。例如,

。你不能輸出任何東西從stdout完成功能。您必須改爲設置陣列變量reply

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

。請注意,你沒有理由在這裏調用perl,cut更合適。我在tmux輸出中看不到任何線路不匹配^([^:]+)

+0

這樣做。謝謝您的幫助! – LandonSchropp