How to close all windows to the right in tmux

915 views Asked by At

Is there a way to issue a command to close all tmux windows unless something is open in that window? For example, an open file, a running process, etc.?

I am hoping for something that functions as a web browser where you can right click and select close all other tabs to the right. I'd like to issue this in tmux, and similar to the web browser example, have "busy" windows or panes prompt me to close them or silently fail to close.

I have seen this question, but I don't necessarily want to issue the command to all windows.

2

There are 2 answers

0
Jean Carlo Machado On BEST ANSWER

I just built a script to do so, here it is:

#!/usr/bin/env python3
import subprocess
import os
import re

result = subprocess.run(['tmux', 'list-windows'], stdout=subprocess.PIPE)

result = result.stdout.decode('utf-8')

lines = result.splitlines()
should_close_next = False
for line in lines:

    if should_close_next:
        window = line.split(':')[0]
        os.system(f'tmux kill-window -t {window}')
        continue

    match = re.search("active", line)
    if match:
        should_close_next = True

And to integrate it with your tmux add to your tmux.conf

bind-key "k" run-shell "kill_panes_to_right.py\n"

Best

0
pschmitt On

Here's a shell alternative:

for win_id in $(tmux list-windows -F '#{window_active} #{window_id}' | awk '/^1/ { active=1; next } active { print $2 }'); do tmux kill-window -t "$win_id"; done

And here's the same (readable version):

for win_id in $(tmux list-windows -F '#{window_active} #{window_id}' | \
                awk '/^1/ { active=1; next } active { print $2 }')
do 
  tmux kill-window -t "$win_id"
done

Edit: I made a plugin with this! https://github.com/pschmitt/tmux-forsaken