完全に自分用のメモですが、よろしければどうぞ的なやつです。
環境は Mac OS Ventura 13.2です。
以下を参考に動かないところは動くように、また自分の好みに少しだけ修正しました。(先人に感謝)
動かなかったのはcdr+pecoです。一番下に修正箇所について記載しておきました。
自分の好みにしたのはhistory+pecoです。コマンドを選択する度に画面がclearされるのが嫌だったので、そこだけ直しました。
pecoを使って端末操作を爆速にする
zshとpecoでコマンド入力作業を快適に
pecoを用いたコマンド履歴出す機能を作るときに調査したことまとめ
事前にbrewで以下の3つをインストールしておきます。
brew install zsh-autosuggestions
brew install zsh-syntax-highlighting
brew install peco
~/.zshrcファイルを適当なエディタで開いて以下を追記します。もしファイルがないなら作ります。
# History設定
HISTFILE=~/.zsh_history
HISTSIZE=100000
SAVEHIST=100000
setopt share_history
setopt hist_ignore_dups
setopt hist_ignore_all_dups
setopt hist_ignore_space
setopt hist_reduce_blanks
setopt print_eight_bit
# -------------------------------------------------
# -------------------------------------------------
# プラグイン有効化
source $(brew --prefix)/share/zsh-autosuggestions/zsh-autosuggestions.zsh
source $(brew --prefix)/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
# -------------------------------------------------
alias distinct='awk '\''!a[$0]++'\'
# -------------------------------------------------
# pecoの活用1
# ctrl + r で過去に実行したコマンドを選択できるようにする。
function peco-select-history() {
BUFFER=$(\history -n -r 1 | distinct | peco --query "$LBUFFER")
CURSOR=$#BUFFER
zle reset-prompt
}
zle -N peco-select-history
bindkey '^r' peco-select-history
# cdr
if [[ -n $(echo ${^fpath}/chpwd_recent_dirs(N)) && -n $(echo ${^fpath}/cdr(N)) ]]; then
autoload -Uz chpwd_recent_dirs cdr add-zsh-hook
add-zsh-hook chpwd chpwd_recent_dirs
zstyle ':completion:*' recent-dirs-insert both
zstyle ':chpwd:*' recent-dirs-default true
zstyle ':chpwd:*' recent-dirs-max 1000
zstyle ':chpwd:*' recent-dirs-file "$HOME/.cache/chpwd-recent-dirs"
fi
function peco-cdr () {
local selected_dir="$(cdr -l | sed -E 's/^[0-9]+ *//' | peco --prompt="cdr >" --query "$LBUFFER")"
if [ -n "$selected_dir" ]; then
BUFFER="cd ${selected_dir}"
zle accept-line
fi
}
zle -N peco-cdr
bindkey '^E' peco-cdr
cdrですが、Macのsedが古いため-Eオプションが必要です。こちらの情報を参考にしました。
Macのsedで使える正規表現はPOSIX BRE(Basic Regular Expressions)
ついでに少しだけ正規表現を(自分にとって)わかりやすく修正しました。
最後に、必要はないと思いますが念の為。修正した.zshrcを起動中のターミナルに反映させるには次のコマンドです。
source ~/.zshrc