Scott Skiles
Scott Skiles

Reputation: 3857

How to close all windows to the right in tmux

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.

Upvotes: 3

Views: 1040

Answers (2)

pschmitt
pschmitt

Reputation: 103

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

Upvotes: 3

Jean Carlo Machado
Jean Carlo Machado

Reputation: 1616

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

Upvotes: 1

Related Questions