Last active
March 27, 2025 02:19
-
-
Save philocalyst/b2d764d694e63bc4c5143735f6ddaee2 to your computer and use it in GitHub Desktop.
Fuzzy finder integrated history search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function history_search | |
set -l fuzzy_cmd | |
if type -q sk | |
set fuzzy_cmd sk | |
else if type -q fzf | |
set fuzzy_cmd fzf | |
else | |
echo "Error: Neither skim nor fzf is installed" | |
return 1 | |
end | |
# Height of the found results in relative percentage -- using 50 as a default | |
set -l results_height 50 | |
# Get current time for clever delta calculations | |
set -l now (date +%s) | |
set -l fish_history_file $XDG_DATA_HOME/fish/fish_history | |
# Create a temporary array to hold formatted history entries (Thanks fish!) | |
set -l formatted_history | |
# Declaring here | |
set -l cmd "" | |
set -l timestamp "" | |
for line in (cat $fish_history_file) | |
if string match -r '^- cmd: ' -- "$line" >/dev/null | |
set cmd (string sub -s 8 -- "$line") | |
else if string match -r '^ when: ' -- "$line" >/dev/null | |
# Timestamp for the current command | |
set timestamp (string sub -s 9 -- "$line") | |
if test -n "$cmd" -a -n "$timestamp" | |
set -l delta (math "$now - $timestamp") | |
set -l delta_days (math "floor($delta / 86400)") | |
set -l time_display | |
if test $delta -lt 0 | |
set time_display "+".(-1 \* $delta_days)"d" | |
else if test $delta_days -lt 1 -a $delta -lt 72000 | |
set time_display (date -r $timestamp "+%H:%M") | |
else if test $delta_days -eq 0 | |
set time_display 1d | |
else | |
set time_display "$delta_days"d | |
end | |
set -a formatted_history " $time_display | $cmd" | |
# Reset for next entry | |
set cmd "" | |
set timestamp "" | |
end | |
end | |
end | |
set -l selected (printf "%s\n" $formatted_history | $fuzzy_cmd --height $results_height% --reverse --with-nth 2.. --query=(commandline)) | |
if test -n "$selected" | |
# Extract just the command part (remove the time prefix) | |
set -l cmd_parts (string split --max 1 "|" $selected) | |
if test (count $cmd_parts) -gt 1 | |
commandline $cmd_parts[2] | |
else | |
commandline $selected | |
end | |
end | |
commandline $selected | |
commandline -f repaint | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment