如何使用 emacs 鍵綁定轉置命令列參數?

如何使用 emacs 鍵綁定轉置命令列參數?

使用 Bash 並設定 emacs 鍵綁定,轉置單字鍵綁定 ( M-t) 不會轉置參數,而是轉置「單字」(根據其自己的單字定義)。

所以如果我有這個:

vimdiff project-number-One/Vagrantfile project-number-Two/Vagrantfile.old

當我輸入時,我的遊標位於第一個和第二個參數之間optiont,我最終得到的是

vimdiff project-number-One/project Vagrantfile-number-Two/Vagrantfile.old

這顯然不是我想要的。我怎樣才能轉置參數?

答案1

在 bash 中,不同的指令有不同的單字概念。C-w殺死前面的空格,但大多數其他命令包括M-t使用標點符號分隔的單字。

將遊標放在第一個參數和第二個參數之間,C-w C-e SPC C-y將調換兩個單字的位置。

如果你想綁定一個鍵來調換空格分隔的單詞,那就更複雜了。看bash 中 emacs 風格的鍵綁定的令人困惑的行為。這是一些經過最低限度測試的程式碼。

transpose_whitespace_words () {
  local prefix=${READLINE_LINE:0:$READLINE_POINT} suffix=${READLINE_LINE:$READLINE_POINT}
  if [[ $suffix =~ ^[^[:space:]] ]] && [[ $prefix =~ [^[:space:]]+$ ]]; then
    prefix=${prefix%${BASH_REMATCH[0]}}
    suffix=${BASH_REMATCH[0]}${suffix}
  fi
  if [[ $suffix =~ ^[[:space:]]+ ]]; then
    prefix=${prefix}${BASH_REMATCH[0]}
    suffix=${suffix#${BASH_REMATCH[0]}}
  fi
  if [[ $prefix =~ ([^[:space:]]+)([[:space:]]+)$ ]]; then
    local word1=${BASH_REMATCH[1]} space=${BASH_REMATCH[2]}
    prefix=${prefix%${BASH_REMATCH[0]}}
    if [[ $suffix =~ [^[:space:]]+ ]]; then
      suffix=${suffix#${BASH_REMATCH[0]}}
      READLINE_LINE=${prefix}${BASH_REMATCH[0]}$space$word1$suffix
      READLINE_POINT=$((${#READLINE_LINE} - ${#suffix}))
    fi
  fi
}
bind -x '"\e\C-t": transpose_whitespace_words'

這在 zsh 中更容易......

答案2

如果您的遊標在那裡:

vimdiff projectOne/Vagrantfile projectTwo/Vagrantfile
                              ^

按 Alt + BTTBBTFTBBTT


或簡單:

Ctrl+ WCtrl+ E,插入空格,然後按Ctrl+Y

答案3

為了快速簡單的解決方案,將其添加到您的 inputrc (為自己選擇合適的鍵):

"\e\C-b": shell-backward-kill-word
"\eh": shell-backward-word
"\e\C-f": shell-forward-word
# Swap the preceding two arguments (control + alt + t)
"\e\C-t": "\e\C-b\eh\C-y"
# Swap the preceding argument with the next (control + alt + p)
"\e\C-p": "\e\C-b\e\C-f\C-y"

如果有shell-*這些函數的版本單字由非引號 shell 元字元分隔

元字元

當不加引號時,用於分隔單字的字元。元字元是空格、製表符、換行符或以下字元之一:「|」、「&」、「;」、「(」、「)」、「<」或「>」。

Ctrl注意:在按+ Alt+之前,遊標必須位於第二個參數之後t,因此它可以有效地將遊標之前的參數推向行首。

$ true foo/bar.xyz even/without\ quotes.ok "too/too far.away"
                                                             ^
$ true foo/bar.xyz "too/too far.away" even/without\ quotes.ok
                                     ^
$ true "too/too far.away" foo/bar.xyz even/without\ quotes.ok
                         ^

Ctrl注意:在按+ Alt+之前,遊標必須位於第一個參數之後p,因此它可以有效地將遊標之前的參數拉向行尾。

$ true "too/too far.away" foo/bar.xyz even/without\ quotes.ok
                         ^
$ true foo/bar.xyz "too/too far.away" even/without\ quotes.ok
                                     ^
$ true foo/bar.xyz even/without\ quotes.ok "too/too far.away"
                                                             ^

答案4

您需要按BTTBBT而不是單個T

相關內容