Skip to content

macOS + zsh で peco の設定をカスタマイズする

先日、macOS へ peco をインストールする というメモを書きました。 zsh のプラグインを追加し、peco をカスタマイズする手順をメモしておきます。

検証環境

対象 バージョン
macOS Sequoia 15.4.1
peco 0.5.11

zsh 用プラグインのインストール

peco と zsh 用のプラグインをインストールします。

1
2
3
4
5
brew install \
  peco \
  zsh-autosuggestions \
  zsh-syntax-highlighting \
  zsh-completions

peco の設定

~/.zshrc を修正し、zsh のプラグインを有効化したり peco を設定します。 先日の macOS へ peco をインストールする では peco-select-history() の中で zle clear-screen を使っていたのですが、これでは Ctrl+R で履歴を表示させてシェルに復帰した際、毎回、画面がクリアされてしまいます。 これを zle reset-prompt へ変更することで画面がクリアされないように変更しました。

ショートカッキーは以下のふたつを登録します。

ショートカットキー 説明
Ctrl+R CLI のコマンド履歴を表示する
Ctrl + @ 過去に移動したディレクトリ一覧を表示し、選択したディレクトリへ移動する
~/.zshrc
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# zsh plugins
if type brew &>/dev/null; then
  FPATH=$(brew --prefix)/share/zsh-completions:$FPATH

  autoload -Uz compinit
  compinit
fi
source $(brew --prefix)/share/zsh-autosuggestions/zsh-autosuggestions.zsh
source $(brew --prefix)/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh

# zsh settings
autoload -Uz chpwd_recent_dirs cdr add-zsh-hook
add-zsh-hook chpwd chpwd_recent_dirs
zstyle ':chpwd:*' recent-dirs-max 500

# history
setopt hist_ignore_dups

# peco
function peco-select-history() {
  BUFFER=$(\history -n -r 1 | peco --query "$LBUFFER")
  CURSOR=$#BUFFER
  zle reset-prompt
}
zle -N peco-select-history
bindkey '^r' peco-select-history

function peco-cdr () {
    local selected_dir=$(cdr -l | awk '{ print $2 }' | peco)
    if [ -n "$selected_dir" ]; then
        BUFFER="cd ${selected_dir}"
        zle accept-line
    fi
    zle clear-screen
}
zle -N peco-cdr
bindkey '^@' peco-cdr

alias de='docker container exec -it $(docker container ls | peco | cut -d " " -f 1) /bin/bash'