tmux - Insert a window at a specified position

The script below will allow you to do what you want. You can run it from a shell prompt or you can do:

:run "ins-move 2 5"

That example moves window two to the position before window five.

#!/bin/bash
for ((i=$1; i<$2-1; i++))
do
    tmux swap-window -s :$i -t :$((i+1))
done

Try: new-window -a

using -a option when create new window can insert the new one just at the next index, while all other subsequent windows' index will increase automatically.


I have got a solution without the need of external scripts. Put the following in your .tmux.conf:

bind i command-prompt -p 'Insert window at:' 'run-shell "if tmux select-window -t %1; then tmux new-window -a; tmux swap-window -s %1 -t \$((%1+1)); else tmux new-window; tmux move-window -t %1; fi; tmux select-window -t #I; tmux select-window -t %1;"'

Press [PREFIX]-i and provide wanted insert location. The last 2 select-window commands make sure the 'previous' window is set as expected and you go to the inserted window.

EDIT: ok, I spoke too soon. I had to change #I to #{window_id} because the window index changes for some windows on insertion. The new function (with added newlines for readability):

bind i command-prompt -p 'Insert window at:' '      \
    run-shell "                                     \
        if tmux select-window -t %1; then           \
            tmux new-window -a;                     \
            tmux swap-window -s %1 -t \$((%1+1));   \
        else                                        \
            tmux new-window;                        \
            tmux move-window -t %1;                 \
        fi;                                         \
        tmux select-window -t #{window_id};         \
        tmux select-window -t %1;                   \
    "'                                               

I started using a simplified version, through the following 2 commands in .tmux.conf:

 bind i command-prompt -p 'Insert window at:' 'new-window -a -t %1; swap-window -t -1'
 bind I command-prompt -p 'New window at:'    'new-window -t %1'

Prefix-i inserts a new window at position x when window x exists, and moves windows above that one up. Prefix-I creates a new window at position x when window x doesn't exist.