Skip to content

context_managers

Ease-of-use context-manager classes & functions.

There isn't much (or any) additional functionality provided in this module, most things are nicer-packaged combinations to already available methods from pytermgui.ansi_interface.

alt_buffer(echo=False, cursor=True)

Creates non-scrollable alt-buffer.

This is useful for retrieving original terminal state after program end.

Parameters:

Name Type Description Default
echo bool

Whether unset_echo should be called on startup.

False
cursor bool

Whether hide_cursor should be called on startup.

True
Source code in pytermgui/context_managers.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@contextmanager
def alt_buffer(echo: bool = False, cursor: bool = True) -> Generator[None, None, None]:
    """Creates non-scrollable alt-buffer.

    This is useful for retrieving original terminal state after program end.

    Args:
        echo: Whether `unset_echo` should be called on startup.
        cursor: Whether `hide_cursor` should be called on startup.
    """

    terminal = get_terminal()

    try:
        set_alt_buffer()

        if not echo and name == "posix" and not terminal.is_interactive():
            unset_echo()

        if not cursor:
            hide_cursor()

        yield

    finally:
        unset_alt_buffer()

        if not echo and name == "posix" and not terminal.is_interactive():
            set_echo()
            cursor_up()

        if not cursor:
            show_cursor()
            cursor_up()

cursor_at(pos)

Gets callable to print at pos, incrementing y on every print.

Parameters:

Name Type Description Default
pos tuple[int, int]

The position to start printing at. Follows the order (columns, rows).

required

Yields:

Type Description
Callable[..., None]

A callable printing function. This function forwards all arguments to print,

Callable[..., None]

but positions the cursor before doing so. After every call, the y position is

Callable[..., None]

incremented.

Source code in pytermgui/context_managers.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
@contextmanager
def cursor_at(pos: tuple[int, int]) -> Generator[Callable[..., None], None, None]:
    """Gets callable to print at `pos`, incrementing `y` on every print.

    Args:
        pos: The position to start printing at. Follows the order (columns, rows).

    Yields:
        A callable printing function. This function forwards all arguments to `print`,
        but positions the cursor before doing so. After every call, the y position is
        incremented.
    """

    offset = 0
    posx, posy = pos

    def printer(*args: Any, **kwargs: Any) -> None:
        """Print to posx, current y"""

        nonlocal offset

        print_to((posx, posy + offset), *args, **kwargs)
        offset += 1

    try:
        save_cursor()
        yield printer

    finally:
        restore_cursor()

mouse_handler(events, method='decimal_xterm')

Return a mouse handler function

See help(report_mouse) for help about all of the methods.

Parameters:

Name Type Description Default
events list[str]

A list of pytermgui.ansi_interface.report_mouse events.

required
method str

The method to use for reporting. Only decimal_urxvt and decimal_xterm are currently supported.

'decimal_xterm'

Example use:

import pytermgui as ptg

with ptg.mouse_handler(["press", "hover"]) as mouse:
    while True:
      event = mouse(ptg.getch())
      print(type(event))
      print(event.action)
      print(event.position)

'pytermgui.ansi_interface.MouseEvent'
'pytermgui.ansi_interface.MouseAction.LEFT_CLICK'
(33, 55)
Source code in pytermgui/context_managers.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
@contextmanager
def mouse_handler(
    events: list[str], method: str = "decimal_xterm"
) -> Generator[MouseTranslator, None, None]:
    """Return a mouse handler function

    See `help(report_mouse)` for help about all of the methods.

    Args:
        events: A list of `pytermgui.ansi_interface.report_mouse` events.
        method: The method to use for reporting. Only `decimal_urxvt` and
            `decimal_xterm` are currently supported.

    Example use:

    ```python3
    import pytermgui as ptg

    with ptg.mouse_handler(["press", "hover"]) as mouse:
        while True:
          event = mouse(ptg.getch())
          print(type(event))
          print(event.action)
          print(event.position)

    'pytermgui.ansi_interface.MouseEvent'
    'pytermgui.ansi_interface.MouseAction.LEFT_CLICK'
    (33, 55)
    ```

    """

    try:
        for event in events:
            report_mouse(event, method=method)

        yield lambda code: translate_mouse(code, method=method)

    finally:
        for event in events:
            report_mouse(event, method=method, stop=True)