Skip to content

Instantly share code, notes, and snippets.

@andreypopp
Last active July 27, 2020 09:53
Show Gist options
  • Save andreypopp/482c78a992acd3de70793bde62584392 to your computer and use it in GitHub Desktop.
Save andreypopp/482c78a992acd3de70793bde62584392 to your computer and use it in GitHub Desktop.
#
# vimr provides per-tmux-window nvim instances
#
# First invocation will start a brand new nvim instance and will remember its
# pane, next invocations will forward commands to this pane and will switch to
# this pane.
#
# Based on https://github.com/joshdick/dntw
#
function vimr () {
local NVIM_CMD
local NVIM_SESSION
local NVIM_PANE_ID_KEY
local NVIM_PANE_ID
local NVIM_LISTEN_ADDRESS
NVIM_CMD="${NVIM_CMD:-nvim}"
if [[ -n "$TMUX" ]]; then
# We are in tmux, construct stable id for nvim session.
NVIM_SESSION=$(tmux display-message -p '#{session_id}_#{window_id}')
NVIM_PANE_ID_KEY="NVIM_PANE_ID_${NVIM_SESSION}"
NVIM_LISTEN_ADDRESS="${TMPDIR}nvim_session__${NVIM_SESSION}"
if [ "$(nvr --serverlist | grep -ic "$NVIM_LISTEN_ADDRESS")" -eq 1 ]; then
# Found nvim session, send nvim commands there and switch the pane.
nvr --nostart --servername "$NVIM_LISTEN_ADDRESS" "$@"
NVIM_PANE_ID="${$(tmux showenv "${NVIM_PANE_ID_KEY}")##${NVIM_PANE_ID_KEY}=}"
tmux select-pane -t "${NVIM_PANE_ID}"
else
# No nvim session found, start one and remember pane id.
NVIM_PANE_ID=$(tmux display-message -p '#{pane_id}')
tmux setenv "${NVIM_PANE_ID_KEY}" "${NVIM_PANE_ID}"
"$NVIM_CMD" --listen "$NVIM_LISTEN_ADDRESS" "$@"
tmux setenv -u "${NVIM_PANE_ID_KEY}"
fi
else
# Not in tmux, just run nvim
"$NVIM_CMD" "$@"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment