Skip to content

Instantly share code, notes, and snippets.

@psprint
Last active September 18, 2019 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psprint/f2a0db07cc80351e19e30378c6eaa779 to your computer and use it in GitHub Desktop.
Save psprint/f2a0db07cc80351e19e30378c6eaa779 to your computer and use it in GitHub Desktop.
deploy-code – a Zsh function to deploy code execution for later, in Zle context
# This Zshell function will execute the given code from a Zle context.
# It has an optional delay first argument: "@sleep:<secnods with fractions>".
# If given, then the code will wait in background before being executed, for
# the specified amount of time.
# The limit of the code length is 25 lines and can be easily extended by
# changing the "repeat 25" line
#
# Usage:
# deploy-code "echo Hello world"
# deploy-code "BUFFER[-1]=''"
# deploy-code @sleep:5.5 "BUFFER='The time has passed, sorry for replacing your command line ;)'"
deploy-code() {
[[ "$1" = <-> && ( ${#} = 1 || ( "$2" = (hup|nval|err) && ${#} = 2 ) ) ]] && {
local alltext text IFS=$'\n' nl=$'\n'
repeat 25; do read -r -u"$1" text; alltext+="${text:+$text$nl}"; done
zle -F "$1"; exec {1}<&-
eval "$alltext"
return 0
}
local THEFD
exec {THEFD} < <(
# The expansion is: if there is @sleep: pfx, then use what is after
# it, otherwise substitute 0
LANG=C sleep $(( 0.005 + ${${${(M)1#@sleep:}:+${1#@sleep:}}:-0} ))
print -r -- ${1:#(@code|@sleep:*)} "${@[2,-1]}"
)
zle -N deploy-code # idempotent
zle -w -F "$THEFD" deploy-code
}
# vim;ft=zsh:sts=4:sw=4:et
@psprint
Copy link
Author

psprint commented Sep 18, 2019

An important update on 18.09.2019 – it was possible for the the function to not work, especially on Linux (OS X seems resistant, I've never occurred the described situation under it), due to the arguments passed to the zle -F callback by Zsh to be possible to be of count 2, not only 1.

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