Skip to content

Instantly share code, notes, and snippets.

@ericfreese
Last active June 10, 2016 22:46
Show Gist options
  • Save ericfreese/20db47bc62b9df3e28732ea03c1bc811 to your computer and use it in GitHub Desktop.
Save ericfreese/20db47bc62b9df3e28732ea03c1bc811 to your computer and use it in GitHub Desktop.
# A proof of concept implementation of fetching history suggestions
# asynchronously using `coproc`
#
# See https://github.com/zsh-users/zsh-autosuggestions/issues/170
#
# Problems with this approach:
# - Requires MONITOR option not be set
# - Usage of coproc may conflict with end user
# - Usage of SIGUSR1 signal may conflict with end user
# - Spawns a new process for every suggestion, which seems excessive
# Necessary AFAIK to avoid job notifications when using coproc
unsetopt monitor
MASTER_PID=$$
# Runs in the coproc. Notifies the main process when it's ready
fetch_suggestion() {
sleep 1 # Simulated lookup delay
fc -lnrm "$1*" 1 2>/dev/null | head -n 1
kill -USR1 $MASTER_PID 2>/dev/null
}
trap 'suggestion_ready' USR1
# Called when we get a USR1 signal
suggestion_ready() {
read -p -d '' suggestion
zle display-suggestion $suggestion
}
# Widget function to display the suggestion
_display_suggestion() {
POSTDISPLAY="${1#$BUFFER}"
zle -R
}
zle -N display-suggestion _display_suggestion
# Wrap the self-insert widget to fetch a suggestion on every keystroke
_self_insert() {
typeset -g LAST_COPROC_PID
# Kill any currently running coproc
if [ -n "$LAST_COPROC_PID" ]; then
kill -9 $LAST_COPROC_PID 2>/dev/null
fi
unset POSTDISPLAY
zle .self-insert
# Start a coproc and task it with fetching a suggestion
coproc { fetch_suggestion "$BUFFER" }
LAST_COPROC_PID=$!
}
zle -N self-insert _self_insert
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment