Skip to content

Instantly share code, notes, and snippets.

@florianschmidt1994
Last active July 23, 2019 17:24
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save florianschmidt1994/64d6f5b58a84c77802cce5e415d7e3dc to your computer and use it in GitHub Desktop.
Save florianschmidt1994/64d6f5b58a84c77802cce5e415d7e3dc to your computer and use it in GitHub Desktop.
Using custom fzf history with ctrl-r in zsh
function fh() {
   command=$(fc -ln 0|               # show history without line numbers
     tail -r         |               # reverse the order
     awk '!x[$0]++'  |               # drop duplicates (https://unix.stackexchange.com/a/193331)
     fzf -e +s \
         --color=light \
         --height=20 \
         --inline-info \
         --border \
         --prompt="Search history "  # fuzzy find with exact match, no sorting and custom style
   )

   if [[ !  -z  $param  ]]; then
     BUFFER=$BUFFER
     zle redisplay     # redisplay the current command prompt line
   else
     # See http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#Zle-Widgets
     # for more details on this
     BUFFER=$command   # replace the buffer of the command prompt with our command
     zle redisplay     # redisplay the current command prompt line
     zle accept-line   # accept the current line in buffer a.k.a "press enter"
   fi
 }

 zle -N fh           # Run my as a zsh widget / line editor thing
 bindkey "\C-r" fh   # Bind our function to ctrl-r

https://asciinema.org/a/xe7XnzEqQP06IpWt0OcRmE28J

@pibebtol
Copy link

Instead of using tail to reverse the order, fzf has the option --tac to show results in reversed.

To edit the line before submitting the command, comment out the line zle accept-line # accept the current line in buffer a.k.a "press enter".

@Dreomite
Copy link

Instead of using tail to reverse the order, fzf has the option --tac to show results in reversed.

Executing tail -r before awk ensures older duplicates removal leaving the latest command entry intact and not the other way around. However, I would replace tail -r (which is not POSIX-compliant) with regular tac (reverse cat) from coreutils. Otherwise, this script will work only on OS X/BSD, but not on Linux.

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