Skip to content

ansi_interface

Various functions to interface with the terminal, using ANSI sequences.

Credits:

  • https://wiki.bash-hackers.org/scripting/terminalcodes
  • https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797

MouseAction

Bases: Enum

An enumeration of all the polled mouse actions

Source code in pytermgui/ansi_interface.py
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
class MouseAction(Enum):
    """An enumeration of all the polled mouse actions"""

    LEFT_CLICK = "left_click"
    """Start of a left button action sequence."""

    LEFT_DRAG = "left_drag"
    """Mouse moved while left button was held down."""

    RIGHT_CLICK = "right_click"
    """Start of a right button action sequence."""

    RIGHT_DRAG = "right_drag"
    """Mouse moved while right button was held down."""

    SCROLL_UP = "scroll_up"
    """Mouse wheel or touchpad scroll upwards."""

    SCROLL_DOWN = "scroll_down"
    """Mouse wheel or touchpad scroll downwards."""

    SHIFT_SCROLL_UP = "shift_scroll_up"
    """Mouse wheel or touchpad scroll upwards."""

    SHIFT_SCROLL_DOWN = "shift_scroll_down"
    """Mouse wheel or touchpad scroll downwards."""

    HOVER = "hover"
    """Mouse moved without clicking."""

    # TODO: Support left & right mouse release separately, without breaking
    #       current API.
    RELEASE = "release"
    """Mouse button released; end of any and all mouse action sequences."""

HOVER = 'hover' class-attribute instance-attribute

Mouse moved without clicking.

LEFT_CLICK = 'left_click' class-attribute instance-attribute

Start of a left button action sequence.

LEFT_DRAG = 'left_drag' class-attribute instance-attribute

Mouse moved while left button was held down.

RELEASE = 'release' class-attribute instance-attribute

Mouse button released; end of any and all mouse action sequences.

RIGHT_CLICK = 'right_click' class-attribute instance-attribute

Start of a right button action sequence.

RIGHT_DRAG = 'right_drag' class-attribute instance-attribute

Mouse moved while right button was held down.

SCROLL_DOWN = 'scroll_down' class-attribute instance-attribute

Mouse wheel or touchpad scroll downwards.

SCROLL_UP = 'scroll_up' class-attribute instance-attribute

Mouse wheel or touchpad scroll upwards.

SHIFT_SCROLL_DOWN = 'shift_scroll_down' class-attribute instance-attribute

Mouse wheel or touchpad scroll downwards.

SHIFT_SCROLL_UP = 'shift_scroll_up' class-attribute instance-attribute

Mouse wheel or touchpad scroll upwards.

MouseEvent dataclass

A class to represent events created by mouse actions.

Its first argument is a MouseAction describing what happened, and its second argument is a tuple[int, int] describing where it happened.

This class mostly exists for readability & typing reasons. It also implements the iterable protocol, so you can use the unpacking syntax, such as:

action, position = MouseEvent(...)
Source code in pytermgui/ansi_interface.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
@dataclass
class MouseEvent:
    """A class to represent events created by mouse actions.

    Its first argument is a `MouseAction` describing what happened,
    and its second argument is a `tuple[int, int]` describing where
    it happened.

    This class mostly exists for readability & typing reasons. It also
    implements the iterable protocol, so you can use the unpacking syntax,
    such as:

    ```python3
    action, position = MouseEvent(...)
    ```
    """

    action: MouseAction
    position: tuple[int, int]

    def __post_init__(self) -> None:
        """Initialize iteration counter"""

        self._iter_index = 0

    def __next__(self) -> MouseAction | tuple[int, int]:
        """Get next iteration item"""

        data = fields(self)

        if self._iter_index >= len(data):
            self._iter_index = 0
            raise StopIteration

        self._iter_index += 1
        return getattr(self, data[self._iter_index - 1].name)

    def __iter__(self) -> MouseEvent:
        """Start iteration"""

        return self

    def is_scroll(self) -> bool:
        """Returns True if event.action is one of the scrolling actions."""

        return self.action in {MouseAction.SCROLL_DOWN, MouseAction.SCROLL_UP}

    def is_primary(self) -> bool:
        """Returns True if event.action is one of the primary (left-button) actions."""

        return self.action in {MouseAction.LEFT_CLICK, MouseAction.LEFT_DRAG}

    def is_secondary(self) -> bool:
        """Returns True if event.action is one of the secondary (secondary-button) actions."""

        return self.action in {MouseAction.RIGHT_CLICK, MouseAction.RIGHT_DRAG}

__iter__()

Start iteration

Source code in pytermgui/ansi_interface.py
450
451
452
453
def __iter__(self) -> MouseEvent:
    """Start iteration"""

    return self

__next__()

Get next iteration item

Source code in pytermgui/ansi_interface.py
438
439
440
441
442
443
444
445
446
447
448
def __next__(self) -> MouseAction | tuple[int, int]:
    """Get next iteration item"""

    data = fields(self)

    if self._iter_index >= len(data):
        self._iter_index = 0
        raise StopIteration

    self._iter_index += 1
    return getattr(self, data[self._iter_index - 1].name)

__post_init__()

Initialize iteration counter

Source code in pytermgui/ansi_interface.py
433
434
435
436
def __post_init__(self) -> None:
    """Initialize iteration counter"""

    self._iter_index = 0

is_primary()

Returns True if event.action is one of the primary (left-button) actions.

Source code in pytermgui/ansi_interface.py
460
461
462
463
def is_primary(self) -> bool:
    """Returns True if event.action is one of the primary (left-button) actions."""

    return self.action in {MouseAction.LEFT_CLICK, MouseAction.LEFT_DRAG}

is_scroll()

Returns True if event.action is one of the scrolling actions.

Source code in pytermgui/ansi_interface.py
455
456
457
458
def is_scroll(self) -> bool:
    """Returns True if event.action is one of the scrolling actions."""

    return self.action in {MouseAction.SCROLL_DOWN, MouseAction.SCROLL_UP}

is_secondary()

Returns True if event.action is one of the secondary (secondary-button) actions.

Source code in pytermgui/ansi_interface.py
465
466
467
468
def is_secondary(self) -> bool:
    """Returns True if event.action is one of the secondary (secondary-button) actions."""

    return self.action in {MouseAction.RIGHT_CLICK, MouseAction.RIGHT_DRAG}

Returns text blinking.

Parameters:

Name Type Description Default
reset_style Optional[bool]

Boolean that determines whether a reset character should be appended to the end of the string.

True
Source code in pytermgui/ansi_interface.py
682
683
684
685
686
687
688
689
690
def blink(text: str, reset_style: Optional[bool] = True) -> str:
    """Returns text blinking.

    Args:
        reset_style: Boolean that determines whether a reset character should
            be appended to the end of the string.
    """

    return set_mode("blink", False) + text + (reset() if reset_style else "")

bold(text, reset_style=True)

Returns text in bold.

Parameters:

Name Type Description Default
reset_style Optional[bool]

Boolean that determines whether a reset character should be appended to the end of the string.

True
Source code in pytermgui/ansi_interface.py
638
639
640
641
642
643
644
645
646
def bold(text: str, reset_style: Optional[bool] = True) -> str:
    """Returns text in bold.

    Args:
        reset_style: Boolean that determines whether a reset character should
            be appended to the end of the string.
    """

    return set_mode("bold", False) + text + (reset() if reset_style else "")

clear(what='screen')

Clears the specified screen region.

Parameters:

Name Type Description Default
what str

The specifier defining the screen area.

'screen'

Available options: * screen: clear whole screen and go to origin * bos: clear screen from cursor backwards * eos: clear screen from cursor forwards * line: clear line and go to beginning * bol: clear line from cursor backwards * eol: clear line from cursor forwards

Source code in pytermgui/ansi_interface.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def clear(what: str = "screen") -> None:
    """Clears the specified screen region.

    Args:
        what: The specifier defining the screen area.

    Available options:
    * screen: clear whole screen and go to origin
    * bos: clear screen from cursor backwards
    * eos: clear screen from cursor forwards
    * line: clear line and go to beginning
    * bol: clear line from cursor backwards
    * eol: clear line from cursor forwards
    """

    commands = {
        "eos": "\x1b[0J",
        "bos": "\x1b[1J",
        "screen": "\x1b[2J",
        "eol": "\x1b[0K",
        "bol": "\x1b[1K",
        "line": "\x1b[2K",
    }

    get_terminal().write(commands[what])

cursor_column(num=0)

Moves the cursor to the num-th character of the current line.

Parameters:

Name Type Description Default
num int

The new cursor position.

0
Note

This does not flush the terminal for performance reasons. You can do it manually with sys.stdout.flush().

Source code in pytermgui/ansi_interface.py
276
277
278
279
280
281
282
283
284
285
286
287
def cursor_column(num: int = 0) -> None:
    """Moves the cursor to the `num`-th character of the current line.

    Args:
        num: The new cursor position.

    Note:
        This does not flush the terminal for performance reasons. You
        can do it manually with `sys.stdout.flush()`.
    """

    get_terminal().write(f"\x1b[{num}G")

cursor_down(num=1)

Moves the cursor up by num lines.

Parameters:

Name Type Description Default
num int

How many lines the cursor should move by. Must be positive, to move in the opposite direction use cursor_up.

1
Note

This does not flush the terminal for performance reasons. You can do it manually with sys.stdout.flush().

Source code in pytermgui/ansi_interface.py
206
207
208
209
210
211
212
213
214
215
216
217
def cursor_down(num: int = 1) -> None:
    """Moves the cursor up by `num` lines.

    Args:
        num: How many lines the cursor should move by. Must be positive,
            to move in the opposite direction use `cursor_up`.
    Note:
        This does not flush the terminal for performance reasons. You
        can do it manually with `sys.stdout.flush()`.
    """

    get_terminal().write(f"\x1b[{num}B")

cursor_home()

Moves cursor to get_terminal().origin.

Note

This does not flush the terminal for performance reasons. You can do it manually with sys.stdout.flush().

Source code in pytermgui/ansi_interface.py
290
291
292
293
294
295
296
297
298
def cursor_home() -> None:
    """Moves cursor to `get_terminal().origin`.

    Note:
        This does not flush the terminal for performance reasons. You
        can do it manually with `sys.stdout.flush()`.
    """

    get_terminal().write("\x1b[H")

cursor_left(num=1)

Moves the cursor left by num lines.

Parameters:

Name Type Description Default
num int

How many characters the cursor should move by. Must be positive, to move in the opposite direction use cursor_right.

1
Note

This does not flush the terminal for performance reasons. You can do it manually with sys.stdout.flush().

Source code in pytermgui/ansi_interface.py
234
235
236
237
238
239
240
241
242
243
244
245
def cursor_left(num: int = 1) -> None:
    """Moves the cursor left by `num` lines.

    Args:
        num: How many characters the cursor should move by. Must be positive,
            to move in the opposite direction use `cursor_right`.
    Note:
        This does not flush the terminal for performance reasons. You
        can do it manually with `sys.stdout.flush()`.
    """

    get_terminal().write(f"\x1b[{num}D")

cursor_next_line(num=1)

Moves the cursor to the beginning of the num-th line downwards.

Parameters:

Name Type Description Default
num int

The amount the cursor should move by. Must be positive, to move in the opposite direction use cursor_prev_line.

1
Note

This does not flush the terminal for performance reasons. You can do it manually with sys.stdout.flush().

Source code in pytermgui/ansi_interface.py
248
249
250
251
252
253
254
255
256
257
258
259
def cursor_next_line(num: int = 1) -> None:
    """Moves the cursor to the beginning of the `num`-th line downwards.

    Args:
        num: The amount the cursor should move by. Must be positive, to move
            in the opposite direction use `cursor_prev_line`.
    Note:
        This does not flush the terminal for performance reasons. You
        can do it manually with `sys.stdout.flush()`.
    """

    get_terminal().write(f"\x1b[{num}E")

cursor_prev_line(num=1)

Moves the cursor to the beginning of the num-th line upwards.

Parameters:

Name Type Description Default
num int

The amount the cursor should move by. Must be positive, to move in the opposite direction use cursor_next_line.

1
Note

This does not flush the terminal for performance reasons. You can do it manually with sys.stdout.flush().

Source code in pytermgui/ansi_interface.py
262
263
264
265
266
267
268
269
270
271
272
273
def cursor_prev_line(num: int = 1) -> None:
    """Moves the cursor to the beginning of the `num`-th line upwards.

    Args:
        num: The amount the cursor should move by. Must be positive, to move
            in the opposite direction use `cursor_next_line`.
    Note:
        This does not flush the terminal for performance reasons. You
        can do it manually with `sys.stdout.flush()`.
    """

    get_terminal().write(f"\x1b[{num}F")

cursor_right(num=1)

Moves the cursor right by num lines.

Parameters:

Name Type Description Default
num int

How many characters the cursor should move by. Must be positive, to move in the opposite direction use cursor_left.

1
Note

This does not flush the terminal for performance reasons. You can do it manually with sys.stdout.flush().

Source code in pytermgui/ansi_interface.py
220
221
222
223
224
225
226
227
228
229
230
231
def cursor_right(num: int = 1) -> None:
    """Moves the cursor right by `num` lines.

    Args:
        num: How many characters the cursor should move by. Must be positive,
            to move in the opposite direction use `cursor_left`.
    Note:
        This does not flush the terminal for performance reasons. You
        can do it manually with `sys.stdout.flush()`.
    """

    get_terminal().write(f"\x1b[{num}C")

cursor_up(num=1)

Moves the cursor up by num lines.

Parameters:

Name Type Description Default
num int

How many lines the cursor should move by. Must be positive, to move in the opposite direction use cursor_down.

1
Note

This does not flush the terminal for performance reasons. You can do it manually with sys.stdout.flush().

Source code in pytermgui/ansi_interface.py
192
193
194
195
196
197
198
199
200
201
202
203
def cursor_up(num: int = 1) -> None:
    """Moves the cursor up by `num` lines.

    Args:
        num: How many lines the cursor should move by. Must be positive,
            to move in the opposite direction use `cursor_down`.
    Note:
        This does not flush the terminal for performance reasons. You
        can do it manually with `sys.stdout.flush()`.
    """

    get_terminal().write(f"\x1b[{num}A")

dim(text, reset_style=True)

Returns text in dim.

Parameters:

Name Type Description Default
reset_style Optional[bool]

Boolean that determines whether a reset character should be appended to the end of the string.

True
Source code in pytermgui/ansi_interface.py
649
650
651
652
653
654
655
656
657
def dim(text: str, reset_style: Optional[bool] = True) -> str:
    """Returns text in dim.

    Args:
        reset_style: Boolean that determines whether a reset character should
            be appended to the end of the string.
    """

    return set_mode("dim", False) + text + (reset() if reset_style else "")

hide_cursor()

Stops printing the cursor.

Source code in pytermgui/ansi_interface.py
129
130
131
132
def hide_cursor() -> None:
    """Stops printing the cursor."""

    get_terminal().write("\x1b[?25l")

inverse(text, reset_style=True)

Returns text inverse-colored.

Parameters:

Name Type Description Default
reset_style Optional[bool]

Boolean that determines whether a reset character should be appended to the end of the string.

True
Source code in pytermgui/ansi_interface.py
693
694
695
696
697
698
699
700
701
def inverse(text: str, reset_style: Optional[bool] = True) -> str:
    """Returns text inverse-colored.

    Args:
        reset_style: Boolean that determines whether a reset character should
            be appended to the end of the string.
    """

    return set_mode("inverse", False) + text + (reset() if reset_style else "")

invisible(text, reset_style=True)

Returns text as invisible.

Parameters:

Name Type Description Default
reset_style Optional[bool]

Boolean that determines whether a reset character should be appended to the end of the string.

True
Note

This isn't very widely supported.

Source code in pytermgui/ansi_interface.py
704
705
706
707
708
709
710
711
712
713
714
715
def invisible(text: str, reset_style: Optional[bool] = True) -> str:
    """Returns text as invisible.

    Args:
        reset_style: Boolean that determines whether a reset character should
            be appended to the end of the string.

    Note:
        This isn't very widely supported.
    """

    return set_mode("invisible", False) + text + (reset() if reset_style else "")

italic(text, reset_style=True)

Returns text in italic.

Parameters:

Name Type Description Default
reset_style Optional[bool]

Boolean that determines whether a reset character should be appended to the end of the string.

True
Source code in pytermgui/ansi_interface.py
660
661
662
663
664
665
666
667
668
def italic(text: str, reset_style: Optional[bool] = True) -> str:
    """Returns text in italic.

    Args:
        reset_style: Boolean that determines whether a reset character should
            be appended to the end of the string.
    """

    return set_mode("italic", False) + text + (reset() if reset_style else "")

move_cursor(pos)

Moves the cursor.

Parameters:

Name Type Description Default
pos tuple[int, int]

Tuple of that the cursor will be moved to.

required

This does not flush the terminal for performance reasons. You can do it manually with sys.stdout.flush().

Source code in pytermgui/ansi_interface.py
178
179
180
181
182
183
184
185
186
187
188
189
def move_cursor(pos: tuple[int, int]) -> None:
    """Moves the cursor.

    Args:
        pos: Tuple of that the cursor will be moved to.

    This does not flush the terminal for performance reasons. You
    can do it manually with `sys.stdout.flush()`.
    """

    posx, posy = pos
    get_terminal().write(f"\x1b[{posy};{posx}H")

overline(text, reset_style=True)

Return text overlined.

Parameters:

Name Type Description Default
reset_style Optional[bool]

Boolean that determines whether a reset character should be appended to the end of the string.

True
Note

This isnt' very widely supported.

Source code in pytermgui/ansi_interface.py
729
730
731
732
733
734
735
736
737
738
739
740
def overline(text: str, reset_style: Optional[bool] = True) -> str:
    """Return text overlined.

    Args:
        reset_style: Boolean that determines whether a reset character should
            be appended to the end of the string.

    Note:
        This isnt' very widely supported.
    """

    return set_mode("overline", False) + text + (reset() if reset_style else "")

print_to(pos, *args, **kwargs)

Prints text to given pos.

Note

This method passes through all arguments (except for pos) to the print method.

Source code in pytermgui/ansi_interface.py
620
621
622
623
624
625
626
627
628
629
def print_to(pos: tuple[int, int], *args: Any, **kwargs: Any) -> None:
    """Prints text to given `pos`.

    Note:
        This method passes through all arguments (except for `pos`) to the `print`
        method.
    """

    move_cursor(pos)
    print(*args, **kwargs)

report_cursor()

Gets position of cursor.

Returns:

Type Description
'Optional[tuple[int, int]]'

A tuple of integers, (columns, rows), describing the

'Optional[tuple[int, int]]'

current (printing) cursor's position. Returns None if

'Optional[tuple[int, int]]'

this could not be determined.

'Optional[tuple[int, int]]'

Note that this position is not the mouse position. See

'Optional[tuple[int, int]]'

report_mouse if that is what you are interested in.

Source code in pytermgui/ansi_interface.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def report_cursor() -> "Optional[tuple[int, int]]":
    """Gets position of cursor.

    Returns:
        A tuple of integers, (columns, rows), describing the
        current (printing) cursor's position. Returns None if
        this could not be determined.

        Note that this position is **not** the mouse position. See
        `report_mouse` if that is what you are interested in.
    """

    get_terminal().write("\x1b[6n", flush=True)
    chars = getch()
    posy, posx = chars[2:-1].split(";")

    if not posx.isdigit() or not posy.isdigit():
        return None

    return int(posx), int(posy)

report_mouse(event, method='decimal_xterm', stop=False)

Starts reporting of mouse events.

You can specify multiple events to report on.

Parameters:

Name Type Description Default
event str

The type of event to report on. See below for options.

required
method Optional[str]

The method of reporting to use. See below for options.

'decimal_xterm'
stop bool

If set to True, the stopping code is written to stdout.

False

Raises:

Type Description
NotImplementedError

The given event is not supported.

Note

If you need this functionality, you're probably better off using the wrapper pytermgui.context_managers.mouse_handler, which allows listening on multiple events, gives a translator method and handles exceptions.

Possible events
  • press: Report when the mouse is clicked, left or right button.
  • highlight: Report highlighting.
  • press_hold: Report with a left or right click, as well as both left & right drag and release.
  • all: Report every event, even hover.
Methods
  • None: Non-decimal xterm method. Limited in coordinates.
  • decimal_xterm: The default setting. Most universally supported.
  • decimal_urxvt: Older, less compatible, but useful on some systems.
  • decimal_utf8: Apparently not too stable.

More information here.

Source code in pytermgui/ansi_interface.py
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def report_mouse(
    event: str, method: Optional[str] = "decimal_xterm", stop: bool = False
) -> None:
    """Starts reporting of mouse events.

    You can specify multiple events to report on.

    Args:
        event: The type of event to report on. See below for options.
        method: The method of reporting to use. See below for options.
        stop: If set to True, the stopping code is written to stdout.

    Raises:
        NotImplementedError: The given event is not supported.

    Note:
        If you need this functionality, you're probably better off using the wrapper
        `pytermgui.context_managers.mouse_handler`, which allows listening on multiple
        events, gives a translator method and handles exceptions.

    Possible events:
        - **press**: Report when the mouse is clicked, left or right button.
        - **highlight**: Report highlighting.
        - **press_hold**: Report with a left or right click, as well as both
            left & right drag and release.
        - **all**: Report every event, even hover.

    Methods:
        - **None**: Non-decimal xterm method. Limited in coordinates.
        - **decimal_xterm**: The default setting. Most universally supported.
        - **decimal_urxvt**: Older, less compatible, but useful on some systems.
        - **decimal_utf8**:  Apparently not too stable.

    More information <a href='https://stackoverflow.com/a/5970472'>here</a>.
    """

    terminal = get_terminal()

    if event == "press":
        terminal.write("\x1b[?1000")

    elif event == "highlight":
        terminal.write("\x1b[?1001")

    elif event == "press_hold":
        terminal.write("\x1b[?1002")

    elif event == "all":
        terminal.write("\x1b[?1003")

    else:
        raise NotImplementedError(f"Mouse report event {event!r} is not supported!")

    terminal.write("l" if stop else "h")

    if method == "decimal_utf8":
        terminal.write("\x1b[?1005")

    elif method == "decimal_xterm":
        terminal.write("\x1b[?1006")

    elif method == "decimal_urxvt":
        terminal.write("\x1b[?1015")

    elif method is None:
        return

    else:
        raise NotImplementedError(f"Mouse report method {method} is not supported!")

    terminal.write("l" if stop else "h", flush=True)

reset()

Resets printing mode.

Source code in pytermgui/ansi_interface.py
632
633
634
635
def reset() -> str:
    """Resets printing mode."""

    return set_mode("reset", False)

restore_cursor()

Restore cursor position as saved by save_cursor.

Source code in pytermgui/ansi_interface.py
150
151
152
153
def restore_cursor() -> None:
    """Restore cursor position as saved by `save_cursor`."""

    get_terminal().write("\x1b[u")

restore_screen()

Restores the contents of the screen saved by save_screen().

Source code in pytermgui/ansi_interface.py
83
84
85
86
def restore_screen() -> None:
    """Restores the contents of the screen saved by `save_screen()`."""

    print("\x1b[?47l")

save_cursor()

Saves the current cursor position.

Use restore_cursor to restore it.

Source code in pytermgui/ansi_interface.py
141
142
143
144
145
146
147
def save_cursor() -> None:
    """Saves the current cursor position.

    Use `restore_cursor` to restore it.
    """

    get_terminal().write("\x1b[s")

save_screen()

Saves the contents of the screen, and wipes it.

Use restore_screen() to get them back.

Source code in pytermgui/ansi_interface.py
74
75
76
77
78
79
80
def save_screen() -> None:
    """Saves the contents of the screen, and wipes it.

    Use `restore_screen()` to get them back.
    """

    print("\x1b[?47h")

set_alt_buffer()

Starts an alternate buffer.

Source code in pytermgui/ansi_interface.py
89
90
91
92
def set_alt_buffer() -> None:
    """Starts an alternate buffer."""

    print("\x1b[?1049h")

set_echo()

Starts echoing of user input.

Note

This is currently only available on POSIX.

Source code in pytermgui/ansi_interface.py
351
352
353
354
355
356
357
358
359
360
361
def set_echo() -> None:
    """Starts echoing of user input.

    Note:
        This is currently only available on POSIX.
    """

    if not _name == "posix":
        return

    system("stty echo")

set_mode(mode, write=True)

Sets terminal display mode.

This is better left internal. To use these modes, you can call their specific functions, such as bold("text") or italic("text").

Parameters:

Name Type Description Default
mode Union[str, int]

One of the available modes. Strings and integers both work.

required
write bool

Boolean that determines whether the output should be written to stdout.

True

Returns:

Type Description
str

A string that sets the given mode.

Available modes
  • 0: reset
  • 1: bold
  • 2: dim
  • 3: italic
  • 4: underline
  • 5: blink
  • 7: inverse
  • 8: invisible
  • 9: strikethrough
  • 53: overline
Source code in pytermgui/ansi_interface.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
def set_mode(mode: Union[str, int], write: bool = True) -> str:
    """Sets terminal display mode.

    This is better left internal. To use these modes, you can call their
    specific functions, such as `bold("text")` or `italic("text")`.

    Args:
        mode: One of the available modes. Strings and integers both work.
        write: Boolean that determines whether the output should be written
            to stdout.

    Returns:
        A string that sets the given mode.

    Available modes:
        - 0: reset
        - 1: bold
        - 2: dim
        - 3: italic
        - 4: underline
        - 5: blink
        - 7: inverse
        - 8: invisible
        - 9: strikethrough
        - 53: overline
    """

    options = {
        "reset": 0,
        "bold": 1,
        "dim": 2,
        "italic": 3,
        "underline": 4,
        "blink": 5,
        "inverse": 7,
        "invisible": 8,
        "strikethrough": 9,
        "overline": 53,
    }

    if not str(mode).isdigit():
        mode = options[str(mode)]

    code = f"\x1b[{mode}m"
    if write:
        get_terminal().write(code)

    return code

show_cursor()

Starts printing the cursor.

Source code in pytermgui/ansi_interface.py
135
136
137
138
def show_cursor() -> None:
    """Starts printing the cursor."""

    get_terminal().write("\x1b[?25h")

strikethrough(text, reset_style=True)

Return text as strikethrough.

Parameters:

Name Type Description Default
reset_style Optional[bool]

Boolean that determines whether a reset character should be appended to the end of the string.

True
Source code in pytermgui/ansi_interface.py
718
719
720
721
722
723
724
725
726
def strikethrough(text: str, reset_style: Optional[bool] = True) -> str:
    """Return text as strikethrough.

    Args:
        reset_style: Boolean that determines whether a reset character should
            be appended to the end of the string.
    """

    return set_mode("strikethrough", False) + text + (reset() if reset_style else "")

translate_mouse(code, method)

Translates the output of produced by setting report_mouse into MouseEvents.

This method currently only supports decimal_xterm and decimal_urxvt.

Parameters:

Name Type Description Default
code str

The string of mouse code(s) to translate.

required
method str

The reporting method to translate. One of decimal_xterm, decimal_urxvt.

required

Returns:

Type Description
list[MouseEvent | None] | None

A list of optional mouse events obtained from the code argument. If the code was malformed,

list[MouseEvent | None] | None

and no codes could be determined None is returned.

Source code in pytermgui/ansi_interface.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
def translate_mouse(code: str, method: str) -> list[MouseEvent | None] | None:
    """Translates the output of produced by setting `report_mouse` into MouseEvents.

    This method currently only supports `decimal_xterm` and `decimal_urxvt`.

    Args:
        code: The string of mouse code(s) to translate.
        method: The reporting method to translate. One of `decimal_xterm`, `decimal_urxvt`.

    Returns:
        A list of optional mouse events obtained from the code argument. If the code was malformed,
        and no codes could be determined None is returned.
    """

    if code == "\x1b":
        return None

    mouse_codes = {
        "decimal_xterm": {
            "0M": MouseAction.LEFT_CLICK,
            "0m": MouseAction.RELEASE,
            "2M": MouseAction.RIGHT_CLICK,
            "2m": MouseAction.RELEASE,
            "32": MouseAction.LEFT_DRAG,
            "34": MouseAction.RIGHT_DRAG,
            "35": MouseAction.HOVER,
            "64": MouseAction.SCROLL_UP,
            "65": MouseAction.SCROLL_DOWN,
            "68": MouseAction.SHIFT_SCROLL_UP,
            "69": MouseAction.SHIFT_SCROLL_DOWN,
        },
        "decimal_urxvt": {
            "32": MouseAction.LEFT_CLICK,
            "34": MouseAction.RIGHT_CLICK,
            "35": MouseAction.RELEASE,
            "64": MouseAction.LEFT_DRAG,
            "66": MouseAction.RIGHT_DRAG,
            "96": MouseAction.SCROLL_UP,
            "97": MouseAction.SCROLL_DOWN,
        },
    }

    mapping = mouse_codes[method]
    pattern: Pattern = RE_MOUSE[method]

    events: list[MouseEvent | None] = []

    for sequence in code.split("\x1b"):
        if len(sequence) == 0:
            continue

        matches = list(pattern.finditer(sequence))
        if len(matches) == 0:
            return None

        for match in matches:
            identifier, *pos, release_code = match.groups()

            # decimal_xterm uses the last character's
            # capitalization to signify press/release state
            if len(release_code) > 0 and identifier in ["0", "2"]:
                identifier += release_code

            if identifier in mapping:
                action = mapping[identifier]
                assert isinstance(action, MouseAction)

                events.append(MouseEvent(action, (int(pos[0]), int(pos[1]))))
                continue

            events.append(None)

    return events

underline(text, reset_style=True)

Returns text underlined.

Parameters:

Name Type Description Default
reset_style Optional[bool]

Boolean that determines whether a reset character should be appended to the end of the string.

True
Source code in pytermgui/ansi_interface.py
671
672
673
674
675
676
677
678
679
def underline(text: str, reset_style: Optional[bool] = True) -> str:
    """Returns text underlined.

    Args:
        reset_style: Boolean that determines whether a reset character should
            be appended to the end of the string.
    """

    return set_mode("underline", False) + text + (reset() if reset_style else "")

unset_alt_buffer()

Returns to main buffer, restoring its original state.

Source code in pytermgui/ansi_interface.py
95
96
97
98
def unset_alt_buffer() -> None:
    """Returns to main buffer, restoring its original state."""

    print("\x1b[?1049l")

unset_echo()

Stops echoing of user input.

Note

This is currently only available on POSIX.

Source code in pytermgui/ansi_interface.py
364
365
366
367
368
369
370
371
372
373
374
def unset_echo() -> None:
    """Stops echoing of user input.

    Note:
        This is currently only available on POSIX.
    """

    if not _name == "posix":
        return

    system("stty -echo")