Skip to content

Instantly share code, notes, and snippets.

@YumaInaura
Last active August 25, 2018 05:56
Show Gist options
  • Save YumaInaura/eb1d5df65cf255956b61e6967725d030 to your computer and use it in GitHub Desktop.
Save YumaInaura/eb1d5df65cf255956b61e6967725d030 to your computer and use it in GitHub Desktop.
Zsh — Incremental search from command history with up arrow key

Zsh — Incremental search from command history with up arrow key

Preparing

You need zsh and peco.

peco/peco: Simplistic interactive filtering tool

Script

Put below script to your ~/.zsh and source it.

incremental-select-command-history() {
   if [ ! $(which peco) ]; then echo "You need peco" && exit 1; fi

   local original_buffer="$BUFFER"

   BUFFER=$( \
      history 1 | \
      sort -k1,1nr | \
      perl -ne 'BEGIN { my @lines = (); } s/^\s*\d+\*?\s*//; $in=$_; if (!(grep {$in eq $_} @lines)) { push(@lines, $in); print $in; }' | \
      peco --layout=bottom-up --on-cancel=error
   )

   # Keep original input when escape from select
   if [ -z "$BUFFER" ]; then
     BUFFER="$original_buffer"
   fi

   CURSOR=${#BUFFER}
}

zle -N incremental-select-command-history
bindkey '^[[A' incremental-select-command-history

Image

  • Push up arrow key and start incremental search
  • Keep original input when incremental search canceled ( with Esc key )
  • Select some command to input string to your console and hit Enter one more time to execute command.

image

So comfortable.

Versions

  • zsh 5.5.1 (x86_64-apple-darwin17.5.0)
  • peco version v0.5.1
  • Mac OS X High sierra

Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment