weblog of key_amb

主にIT関連の技術メモ

peco をセットアップしてみた(Bash編)

Zsh編の方と同じことができるようになりました。

ただし、Bash の version 4 以上が必要で、Mac の場合バージョンアップが必要でした。
そのため、Qiitaに書いたやり方で、Homebrew で入れた Bash をログインシェルにしました。

以下、Mac.bashrc の内容です。

history 検索

Ctrl-r のヒストリ検索を peco に置き換えてしまう。

# search history
peco-select-history() {
  local tac
  if which tac > /dev/null; then
    tac="tac"
  else
    tac="tail -r"
  fi
  local l=$(\history | awk '{$1="";print}' | eval $tac | peco | cut -d' ' -f4-)
  READLINE_LINE="${l}"
  READLINE_POINT=${#l}
}
bind -x '"\C-r": peco-select-history'

ローカルリポジトリのファイル、ディレクトリ検索

Ctrl-u + dディレクトリ探して pushd(cd)。
Ctrl-u + f でパス検索してコマンドラインに挿入。

追記:かち合わないように、デフォルトの Ctrl-uキーバインドを無効化しておく。

# unbind default key-bind
bind -r "\C-u"

# search repository
peco-cd-repository() {
  local dir=$(\find ~/gitrepos ~/my/go/src/github.com -type d -a \! -regex '.*/\.git.*' | peco)
  pushd $dir > /dev/null
}
peco-find-repository() {
  local l=$(\find ~/gitrepos ~/my/go/src/github.com -a \! -regex '.*/\.git.*' | peco)
  READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}${l}${READLINE_LINE:$READLINE_POINT}"
  READLINE_POINT=$(($READLINE_POINT + ${#l}))
}
bind -x '"\C-ud": peco-cd-repository'
bind -x '"\C-uf": peco-find-repository'

カレントディレクトリ以下の検索

Ctrl-u + c でパス検索してコマンドラインに挿入(隠しファイルは除く)。
Ctrl-u + a では隠しファイルも含める。

# search current directory
peco-find() {
  local l=$(\find . -maxdepth 8 -a \! -regex '.*/\..*' | peco)
  READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}${l}${READLINE_LINE:$READLINE_POINT}"
  READLINE_POINT=$(($READLINE_POINT + ${#l}))
}
function peco-find-all() {
  local l=$(\find . -maxdepth 8 | peco)
  READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}${l}${READLINE_LINE:$READLINE_POINT}"
  READLINE_POINT=$(($READLINE_POINT + ${#l}))
}
bind -x '"\C-uc": peco-find'
bind -x '"\C-ua": peco-find-all'

参考

See Also