CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-libtmux

Typed library that provides an ORM wrapper for tmux, a terminal multiplexer.

Pending
Overview
Eval results
Files

exceptions.mddocs/

Exception Handling

libtmux provides a comprehensive exception hierarchy for handling tmux-specific errors and edge cases. All exceptions inherit from the base LibTmuxException class and provide detailed error information for proper error handling and debugging.

Capabilities

Base Exception

Root exception class for all libtmux-specific errors.

class LibTmuxException(Exception):
    """Base exception class for all libtmux errors."""

Server and Connection Errors

Exceptions related to tmux server connection and availability.

class TmuxCommandNotFound(LibTmuxException):
    """Raised when tmux binary is not found in PATH."""

class VersionTooLow(LibTmuxException):
    """
    Raised when tmux version is below minimum required version.
    
    Attributes:
    - current_version: Detected tmux version
    - minimum_version: Required minimum version
    """

Session Management Errors

Exceptions related to session operations and lifecycle.

class TmuxSessionExists(LibTmuxException):
    """Session does not exist in the server."""

class BadSessionName(LibTmuxException):
    """
    Disallowed session name for tmux (empty, contains periods or colons).
    
    Parameters:
    - reason: Description of why session name is bad
    - session_name: The invalid session name (optional)
    """

Object Existence Errors

Exceptions for operations on non-existent tmux objects.

class TmuxObjectDoesNotExist(ObjectDoesNotExist):
    """
    The query returned multiple objects when only one was expected.
    
    Parameters:
    - obj_key: Object key to search for
    - obj_id: ID of object that doesn't exist
    - list_cmd: tmux command used for listing
    - list_extra_args: Extra arguments for list command
    """

Option Management Errors

Base and specific exceptions for tmux option operations.

class OptionError(LibTmuxException):
    """Base exception for option-related errors."""

class UnknownOption(OptionError):
    """Option unknown to tmux show-option(s) or show-window-option(s)."""

class UnknownColorOption(UnknownOption):
    """
    Unknown color option.
    
    Automatically provides message: "Server.colors must equal 88 or 256"
    """

class InvalidOption(OptionError):
    """Option invalid to tmux, introduced in tmux v2.4."""

class AmbiguousOption(OptionError):
    """Option that could potentially match more than one."""

Window Management Errors

Exceptions specific to window operations and state.

class WindowError(LibTmuxException):
    """Base exception for window-related errors."""

class MultipleActiveWindows(WindowError):
    """
    Multiple active windows.
    
    Parameters:
    - count: Number of active windows found
    """

class NoActiveWindow(WindowError):
    """No active window found."""

class NoWindowsExist(WindowError):
    """No windows exist for object."""

Pane Management Errors

Exceptions specific to pane operations and state.

class PaneError(LibTmuxException):
    """Base exception for pane-related errors."""

class PaneNotFound(PaneError):
    """
    Pane not found.
    
    Parameters:
    - pane_id: ID of the missing pane (optional)
    """

Resize and Adjustment Errors

Exceptions related to pane and window resizing operations.

class AdjustmentDirectionRequiresAdjustment(LibTmuxException, ValueError):
    """If adjustment_direction is set, adjustment must be set."""

class WindowAdjustmentDirectionRequiresAdjustment(
    WindowError,
    AdjustmentDirectionRequiresAdjustment
):
    """ValueError for libtmux.Window.resize_window."""

class PaneAdjustmentDirectionRequiresAdjustment(
    WindowError,
    AdjustmentDirectionRequiresAdjustment
):
    """ValueError for libtmux.Pane.resize_pane."""

class RequiresDigitOrPercentage(LibTmuxException, ValueError):
    """
    Requires digit (int or str digit) or a percentage.
    
    Automatically provides message: "Requires digit (int or str digit) or a percentage."
    """

Timeout and Synchronization Errors

Exceptions for timing and synchronization operations.

class WaitTimeout(LibTmuxException):
    """Function timed out without meeting condition."""

Data Processing Errors

Exceptions for internal data processing and parsing.

class VariableUnpackingError(LibTmuxException):
    """
    Error unpacking variable.
    
    Parameters:
    - variable: The unexpected variable that caused the error
    """

Usage Examples

Basic Exception Handling

import libtmux
from libtmux.exc import TmuxSessionExists, TmuxCommandNotFound

try:
    server = libtmux.Server()
    session = server.new_session('my_session')
except TmuxCommandNotFound:
    print("tmux is not installed or not in PATH")
except TmuxSessionExists as e:
    print(f"Session '{e.session_name}' already exists")
    # Attach to existing session instead
    session = server.sessions.get(session_name='my_session')

Version Checking

import libtmux
from libtmux.exc import VersionTooLow

try:
    server = libtmux.Server()
    # Some operation requiring newer tmux version
except VersionTooLow as e:
    print(f"tmux version {e.current_version} is too old")
    print(f"Minimum required version: {e.minimum_version}")

Option Management Error Handling

import libtmux
from libtmux.exc import UnknownOption, InvalidOption, AmbiguousOption

server = libtmux.Server()
session = server.new_session('test')

try:
    session.set_option('invalid-option', 'value')
except UnknownOption as e:
    print(f"Unknown option: {e.option}")
except InvalidOption as e:
    print(f"Invalid value '{e.value}' for option '{e.option}': {e.reason}")
except AmbiguousOption as e:
    print(f"Ambiguous option '{e.option}' matches: {e.matches}")

Object Existence Checking

import libtmux
from libtmux.exc import TmuxObjectDoesNotExist

server = libtmux.Server()

try:
    # Try to get non-existent session
    session = server.sessions.get(session_name='nonexistent')
except TmuxObjectDoesNotExist as e:
    print(f"Object {e.object_type} '{e.object_id}' does not exist")
    # Create session instead
    session = server.new_session('nonexistent')

Window and Pane Error Handling

import libtmux
from libtmux.exc import NoActiveWindow, PaneNotFound, MultipleActiveWindows

server = libtmux.Server()
session = server.new_session('window_test')

try:
    active_window = session.active_window
except NoActiveWindow:
    print("No active window in session")
    # Create a window
    window = session.new_window('main')
except MultipleActiveWindows as e:
    print(f"Multiple active windows found: {e.windows}")
    # Select first one
    window = session.windows[0]
    window.select()

try:
    pane = window.panes.get(pane_id='%999')
except PaneNotFound as e:
    print(f"Pane {e.pane_id} not found")

Resize Error Handling

import libtmux
from libtmux.exc import (
    PaneAdjustmentDirectionRequiresAdjustment,
    RequiresDigitOrPercentage
)

server = libtmux.Server()
session = server.new_session('resize_test')
window = session.new_window('main')
pane = window.active_pane

try:
    pane.resize('right')  # Missing adjustment amount
except PaneAdjustmentDirectionRequiresAdjustment:
    print("Resize direction requires adjustment amount")
    pane.resize('right', 10)

try:
    pane.set_width('invalid')  # Invalid size format
except RequiresDigitOrPercentage as e:
    print(f"Invalid size value: {e.value}")
    pane.set_width(80)  # Use valid number

Comprehensive Error Handling

import libtmux
from libtmux.exc import LibTmuxException

def safe_tmux_operation():
    try:
        server = libtmux.Server()
        session = server.new_session('safe_session')
        window = session.new_window('main')
        pane = window.split_window()
        
        pane.send_keys('echo "Success"')
        output = pane.capture_pane()
        return output
        
    except LibTmuxException as e:
        print(f"tmux operation failed: {e}")
        return None
    except Exception as e:
        print(f"Unexpected error: {e}")
        return None

result = safe_tmux_operation()
if result:
    print("Operation succeeded:", result)
else:
    print("Operation failed")

Install with Tessl CLI

npx tessl i tessl/pypi-libtmux

docs

exceptions.md

index.md

pane.md

server.md

session.md

utilities.md

window.md

tile.json