Skip to content

Instantly share code, notes, and snippets.

@courajs
Last active October 6, 2022 18:21
Show Gist options
  • Save courajs/2ac721bfae14c7ce44019e5804c86c7a to your computer and use it in GitHub Desktop.
Save courajs/2ac721bfae14c7ce44019e5804c86c7a to your computer and use it in GitHub Desktop.
Run a command each time you suspend vim with ctrl+z
# Current unix time in millisecond
function ms() {
echo $(($(date +%s%N)/1000000))
}
# If we suspend vim (ctrl-z), run the on-suspend command and then
# re-foreground vim. If we exit fully, return to the shell.
function post_vim() {
# 148 status code indicate the previous command was suspended
if [ ! $? = 148 ]; then return; fi
if [ 0 = "$#" ]; then
# Not required to set the command initially, it will prompt you
# the first time you suspend
set_command
else
wrap_command $@
post_command $@
fi
}
# Just print some helpful information about the on-suspend command invocation
function wrap_command() {
clear
local before=`ms`
bash -c "$*"
local status="$?"
local after=`ms`
local dt=$(($after - $before))
echo "[Exited with status $status after ${dt}ms]"
}
# After running the on-suspend command, prompt with options:
# - drop to a bash shell (`b` or `s`)
# - change the on-suspend command (`c`)
# - return to vim (any other key)
function post_command() {
read -n 1 -srp "[Press 's' for shell, 'c' to change command, any other key to continue]" key
if [ "$key" = b -o "$key" = s ]; then
bash
fg
post_vim $@
elif [ "$key" = c ]; then
echo
echo "New on-background command:"
read command
wrap_command $command
post_command $command
else
fg
post_vim $@
fi
}
# Prompt for a new on-suspend command, then return to the loop
function set_command() {
echo
echo "New on-background command:"
read command
wrap_command $command
post_command $command
}
function viv() {
nvim
post_vim $@
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment