patch2vimedit/patch2vimedit/tmux.py

60 lines
1.9 KiB
Python

import subprocess
import multiprocessing
import sys
import random
import libtmux
class TmuxSession:
""" A tmux session """
tmux_server = libtmux.Server()
def __init__(self, session):
self.session = session
self.session_id = session.id
@classmethod
def create_detached(cls, name=None):
""" Create a new detached tmux session, returning the TmuxSession """
if not name:
name = "patch2vimsession-{:04x}".format(random.randint(0, 1 << 16 - 1))
session = cls.tmux_server.new_session(session_name=name, attach=False)
return cls(session)
def attach(self):
""" Attach the tmux session to the current terminal. Does NOT return until the
tmux session ends or is detached. """
self.session.attach_session()
def attach_ro(self):
""" Same as `attach`, but attaches a tmux session in a read-only fashion (see
`tmux attach -r`). """
# libtmux is not expressive enough to avoid `subprocess` here...
subprocess.run(["tmux", "attach", "-r", "-t", self.session.id], check=True)
def session_exists(self):
""" Checks that the session exists """
return self.tmux_server.has_session(self.session_id)
def process_attach(self, read_only=True):
""" Runs `self.attach` in a `multiprocessing.Process` and returns the process.
"""
target = self.attach_ro if read_only else self.attach
process = multiprocessing.Process(target=target)
process.start()
return process
def send_keys(self, *args):
""" Send keys to the tmux process. See `man tmux` and `tmux send-keys` for
documentation """
for arg in args:
self.session.attached_pane.send_keys(
arg, suppress_history=False, enter=False
)
# subprocess.run(
# ["tmux", "send-keys", "-t", self.session.id] + list(args), check=True
# )