I had presented in a previous post how I can easily rerun a previous command on the command line. I used this approach to speed the edit-run cycle for scripting. A better way yet is to use a custom Vim binding to execute the previous command using tmux’s send-keys mechanism. Furthermore, one can directly switch to the tmux window where that command is running.

The necessary tmux commands are the following:

# Send the keys "Up" (arrow up) and "Enter" to the pane <pane> in window <window>.
tmux send-keys -t :<window>.<pane> Up Enter
# Switch to the last (previously active) window.
tmux select-window -t :{last}

If we switch to the last window and then send the keys, we do not even have to give tmux send-keys the target window/pane because by default the currently active pane is used. This results in the following Vim mapping:

" Save current file and rerun previous command in previous tmux window.
map <leader>t :up<CR>:execute 'silent !tmux select-window -t :{last} && tmux send-keys Up Enter'<CR>

This works right after one has executed the command in question once in the other (i.e. non-Vim) tmux window. From that point on, pressing <leader>t results in “instant” script execution.

You can see the desired behavior in the following video. In tmux window 1, a shell script is executed once. In window 0, Vim is used to modify the script. After pressing <leader>t, the script is saved, tmux jumps to back to window 1 and executes the previous command (i.e. the script) again. All in one go.