Skip to content

Instantly share code, notes, and snippets.

@ltratt
Created February 20, 2025 17:54
Show Gist options
  • Save ltratt/eaa5857249c50b2ef736ff58d03e378c to your computer and use it in GitHub Desktop.
Save ltratt/eaa5857249c50b2ef736ff58d03e378c to your computer and use it in GitHub Desktop.
skim-history-widget (Ctrl-R) for zsh
# CTRL-R - Paste the selected command from history into the command line
skim-history-widget() {
local selected num
setopt localoptions noglobsubst noposixbuiltins pipefail no_aliases 2> /dev/null
local awk_filter='{ cmd=$0; sub(/^\s*[0-9]+\**\s+/, "", cmd); if (!seen[cmd]++) print $0 }' # filter out duplicates
local n=1 fc_opts=''
if [[ -o extended_history ]]; then
awk_filter='
{
split($2, sp1, "-")
split($3, sp2, ":")
ts = mktime(sp1[1] " " sp1[2] " " sp1[3] " " sp2[1] " " sp2[2] " 00")
delta = systime() - ts
delta_days = int(delta / 86400)
if (delta < 0) { $2="+" delta_days "d" }
else if (delta_days < 1 && delta < 72000) { $2=sp2[1] ":" sp2[2] }
else if (delta_days == 0) { $2="1d" }
else { $2=delta_days "d" }
$3=""
line=$0; $1=""; $2=""
if (!seen[$0]++) print line
}'
fc_opts='-i'
n=2
fi
selected=( $(fc -rl $fc_opts 1 | sed -E "s/^ *//" | awk "$awk_filter" |
SKIM_DEFAULT_OPTIONS="--height ${SKIM_TMUX_HEIGHT:-40%} $SKIM_DEFAULT_OPTIONS --with-nth $n.. --bind=ctrl-r:toggle-sort $SKIM_CTRL_R_OPTS --query=${(qqq)LBUFFER} --no-multi" $(__skimcmd)) )
local ret=$?
if [ -n "$selected" ]; then
num=$selected[1]
if [ -n "$num" ]; then
zle vi-fetch-history -n $num
fi
fi
zle reset-prompt
return $ret
}
zle -N skim-history-widget
bindkey '^R' skim-history-widget
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment