API Documentation

terminal.py

Module containing Terminal, the primary API entry point.

class Terminal(kind=None, stream=None, force_styling=False)[source]

An abstraction for color, style, positioning, and input in the terminal.

This keeps the endless calls to tigetstr() and tparm() out of your code, acts intelligently when somebody pipes your output to a non-terminal, and abstracts over the complexity of unbuffered keyboard input. It uses the terminfo database to remain portable across terminal types.

Initialize the terminal.

Parameters:
  • kind (str) –

    A terminal string as taken by curses.setupterm(). Defaults to the value of the TERM environment variable.

    Note

    Terminals withing a single process must share a common kind. See _CUR_TERM.

  • stream (file) –

    A file-like object representing the Terminal output. Defaults to the original value of sys.__stdout__, like curses.initscr() does.

    If stream is not a tty, empty Unicode strings are returned for all capability values, so things like piping your program output to a pipe or file does not emit terminal sequences.

  • force_styling (bool) –

    Whether to force the emission of capabilities even if sys.__stdout__ does not seem to be connected to a terminal. If you want to force styling to not happen, use force_styling=None.

    This comes in handy if users are trying to pipe your output through something like less -r or build systems which support decoding of terminal sequences.

__getattr__(attr)[source]

Return a terminal capability as Unicode string.

For example, term.bold is a unicode string that may be prepended to text to set the video attribute for bold, which should also be terminated with the pairing normal. This capability returns a callable, so you can use term.bold("hi") which results in the joining of (term.bold, "hi", term.normal).

Compound formatters may also be used. For example:

>>> term.bold_blink_red_on_green("merry x-mas!")

For a parametrized capability such as move (or cup), pass the parameters as positional arguments:

>>> term.move(line, column)

See the manual page terminfo(5) for a complete list of capabilities and their arguments.

kind

Read-only property: Terminal kind determined on class initialization.

Return type:str
does_styling

Read-only property: Whether this class instance may emit sequences.

Return type:bool
is_a_tty

Read-only property: Whether stream is a terminal.

Return type:bool
height

Read-only property: Height of the terminal (in number of lines).

Return type:int
width

Read-only property: Width of the terminal (in number of columns).

Return type:int
location(x=None, y=None)[source]

Context manager for temporarily moving the cursor.

Move the cursor to a certain position on entry, let you print stuff there, then return the cursor to its original position:

term = Terminal()
with term.location(2, 5):
    for x in xrange(10):
        print('I can do it %i times!' % x)
print('We're back to the original location.')

Specify x to move to a certain column, y to move to a certain row, both, or neither. If you specify neither, only the saving and restoration of cursor position will happen. This can be useful if you simply want to restore your place after doing some manual cursor movement.

Note

The store- and restore-cursor capabilities used internally provide no stack. This means that location() calls cannot be nested: only one should be entered at a time.

get_location(timeout=None)[source]

Return tuple (row, column) of cursor position.

Parameters:timeout (float) – Return after time elapsed in seconds with value (-1, -1) indicating that the remote end did not respond.
Return type:tuple
Returns:cursor position as tuple in form of (row, column).

The location of the cursor is determined by emitting the u7 terminal capability, or VT100 Query Cursor Position when such capability is undefined, which elicits a response from a reply string described by capability u6, or again VT100’s definition of \x1b[%i%d;%dR when undefined.

The (row, col) return value matches the parameter order of the move capability, so that the following sequence should cause the cursor to not move at all:

>>> term = Terminal()
>>> term.move(*term.get_location()))

Warning

You might first test that a terminal is capable of informing you of its location, while using a timeout, before later calling. When a timeout is specified, always ensure the return value is conditionally checked for (-1, -1).

fullscreen()[source]

Context manager that switches to secondary screen, restoring on exit.

Under the hood, this switches between the primary screen buffer and the secondary one. The primary one is saved on entry and restored on exit. Likewise, the secondary contents are also stable and are faithfully restored on the next entry:

with term.fullscreen():
    main()

Note

There is only one primary and one secondary screen buffer. fullscreen() calls cannot be nested, only one should be entered at a time.

hidden_cursor()[source]

Context manager that hides the cursor, setting visibility on exit.

with term.hidden_cursor():
main()

Note

hidden_cursor() calls cannot be nested: only one should be entered at a time.

color

A callable string that sets the foreground color.

Parameters:num (int) – The foreground color index. This should be within the bounds of number_of_colors.
Return type:ParameterizingString

The capability is unparameterized until called and passed a number, 0-15, at which point it returns another string which represents a specific color change. This second string can further be called to color a piece of text and set everything back to normal afterward.

on_color

A callable capability that sets the background color.

Parameters:num (int) – The background color index.
Return type:ParameterizingString
normal

A capability that resets all video attributes.

Return type:str

normal is an alias for sgr0 or exit_attribute_mode. Any styling attributes previously applied, such as foreground or background colors, reverse video, or bold are reset to defaults.

stream

Read-only property: stream the terminal outputs to.

This is a convenience attribute. It is used internally for implied writes performed by context managers hidden_cursor(), fullscreen(), location(), and keypad().

number_of_colors

Read-only property: number of colors supported by terminal.

Common values are 0, 8, 16, 88, and 256.

Most commonly, this may be used to test whether the terminal supports colors. Though the underlying capability returns -1 when there is no color support, we return 0. This lets you test more Pythonically:

if term.number_of_colors:
    ...
ljust(text, width=None, fillchar=' ')[source]

Left-align text, which may contain terminal sequences.

Parameters:
  • text (str) – String to be aligned
  • width (int) – Total width to fill with aligned text. If unspecified, the whole width of the terminal is filled.
  • fillchar (str) – String for padding the right of text
Return type:

str

rjust(text, width=None, fillchar=' ')[source]

Right-align text, which may contain terminal sequences.

Parameters:
  • text (str) – String to be aligned
  • width (int) – Total width to fill with aligned text. If unspecified, the whole width of the terminal is used.
  • fillchar (str) – String for padding the left of text
Return type:

str

center(text, width=None, fillchar=' ')[source]

Center text, which may contain terminal sequences.

Parameters:
  • text (str) – String to be centered
  • width (int) – Total width in which to center text. If unspecified, the whole width of the terminal is used.
  • fillchar (str) – String for padding the left and right of text
Return type:

str

length(text)[source]

Return printable length of a string containing sequences.

Parameters:text (str) – String to measure. May contain terminal sequences.
Return type:int
Returns:The number of terminal character cells the string will occupy when printed

Wide characters that consume 2 character cells are supported:

>>> term = Terminal()
>>> term.length(term.clear + term.red(u'コンニチハ'))
10

Note

Sequences such as ‘clear’, which is considered as a “movement sequence” because it would move the cursor to (y, x)(0, 0), are evaluated as a printable length of 0.

strip(text, chars=None)[source]

Return text without sequences and leading or trailing whitespace.

Return type:str
>>> term.strip(u' \x1b[0;3m xyz ')
u'xyz'
rstrip(text, chars=None)[source]

Return text without terminal sequences or trailing whitespace.

Return type:str
>>> term.rstrip(u' \x1b[0;3m xyz ')
u'  xyz'
lstrip(text, chars=None)[source]

Return text without terminal sequences or leading whitespace.

Return type:str
>>> term.lstrip(u' \x1b[0;3m xyz ')
u'xyz '
strip_seqs(text)[source]

Return text stripped of only its terminal sequences.

Return type:str
>>> term.strip_seqs(u'\x1b[0;3mxyz')
u'xyz'
>>> term.strip_seqs(term.cuf(5) + term.red(u'test'))
u'     test'

Note

Non-destructive sequences that adjust horizontal distance (such as \b or term.cuf(5)) are replaced by destructive space or erasing.

split_seqs(text, **kwds)[source]

Return text split by individual character elements and sequences.

Parameters:kwds – remaining keyword arguments for re.split().
Return type:list[str]
>>> term.split_seqs(term.underline(u'xyz'))
['\x1b[4m', 'x', 'y', 'z', '\x1b(B', '\x1b[m']
wrap(text, width=None, **kwargs)[source]

Text-wrap a string, returning a list of wrapped lines.

Parameters:
  • text (str) – Unlike textwrap.wrap(), text may contain terminal sequences, such as colors, bold, or underline. By default, tabs in text are expanded by string.expandtabs().
  • width (int) – Unlike textwrap.wrap(), width will default to the width of the attached terminal.
Return type:

list

See textwrap.TextWrapper for keyword arguments that can customize wrapping behaviour.

getch()[source]

Read, decode, and return the next byte from the keyboard stream.

Return type:unicode
Returns:a single unicode character, or u'' if a multi-byte sequence has not yet been fully received.

This method name and behavior mimics curses getch(void), and it supports inkey(), reading only one byte from the keyboard string at a time. This method should always return without blocking if called after kbhit() has returned True.

Implementors of alternate input stream methods should override this method.

ungetch(text)[source]

Buffer input data to be discovered by next call to inkey().

Parameters:ucs (str) – String to be buffered as keyboard input.
kbhit(timeout=None, **_kwargs)[source]

Return whether a keypress has been detected on the keyboard.

This method is used by inkey() to determine if a byte may be read using getch() without blocking. The standard implementation simply uses the select.select() call on stdin.

Parameters:timeout (float) – When timeout is 0, this call is non-blocking, otherwise blocking indefinitely until keypress is detected when None (default). When timeout is a positive number, returns after timeout seconds have elapsed (float).
Return type:bool
Returns:True if a keypress is awaiting to be read on the keyboard attached to this terminal. When input is not a terminal, False is always returned.
cbreak()[source]

Allow each keystroke to be read immediately after it is pressed.

This is a context manager for tty.setcbreak().

This context manager activates ‘rare’ mode, the opposite of ‘cooked’ mode: On entry, tty.setcbreak() mode is activated disabling line-buffering of keyboard input and turning off automatic echo of input as output.

Note

You must explicitly print any user input you would like displayed. If you provide any kind of editing, you must handle backspace and other line-editing control functions in this mode as well!

Normally, characters received from the keyboard cannot be read by Python until the Return key is pressed. Also known as cooked or canonical input mode, it allows the tty driver to provide line-editing before shuttling the input to your program and is the (implicit) default terminal mode set by most unix shells before executing programs.

Technically, this context manager sets the termios attributes of the terminal attached to sys.__stdin__.

raw()[source]

A context manager for tty.setraw().

Although both break() and raw() modes allow each keystroke to be read immediately after it is pressed, Raw mode disables processing of input and output.

In cbreak mode, special input characters such as ^C or ^S are interpreted by the terminal driver and excluded from the stdin stream. In raw mode these values are receive by the inkey() method.

Because output processing is not done, the newline '\n' is not enough, you must also print carriage return to ensure that the cursor is returned to the first column:

with term.raw():
    print("printing in raw mode", end="\r\n")
keypad()[source]

Context manager that enables directional keypad input.

On entrying, this puts the terminal into “keyboard_transmit” mode by emitting the keypad_xmit (smkx) capability. On exit, it emits keypad_local (rmkx).

On an IBM-PC keyboard with numeric keypad of terminal-type xterm, with numlock off, the lower-left diagonal key transmits sequence \\x1b[F, translated to Terminal attribute KEY_END.

However, upon entering keypad(), \\x1b[OF is transmitted, translating to KEY_LL (lower-left key), allowing you to determine diagonal direction keys.

inkey(timeout=None, esc_delay=0.35, **_kwargs)[source]

Read and return the next keyboard event within given timeout.

Generally, this should be used inside the raw() context manager.

Parameters:
  • timeout (float) – Number of seconds to wait for a keystroke before returning. When None (default), this method may block indefinitely.
  • esc_delay (float) – To distinguish between the keystroke of KEY_ESCAPE, and sequences beginning with escape, the parameter esc_delay specifies the amount of time after receiving escape (chr(27)) to seek for the completion of an application key before returning a Keystroke instance for KEY_ESCAPE.
Return type:

Keystroke.

Returns:

Keystroke, which may be empty (u'') if timeout is specified and keystroke is not received.

Raises:

RuntimeError – When stream is not a terminal, having no keyboard attached, a timeout value of None would block indefinitely, prevented by by raising an exception.

Note

When used without the context manager cbreak(), or raw(), sys.__stdin__ remains line-buffered, and this function will block until the return key is pressed!

class WINSZ[source]

Structure represents return value of termios.TIOCGWINSZ.

ws_row

rows, in characters

ws_col

columns, in characters

ws_xpixel

horizontal size, pixels

ws_ypixel

vertical size, pixels

Create new instance of WINSZ(ws_row, ws_col, ws_xpixel, ws_ypixel)

_CUR_TERM = None

formatters.py

Sub-module providing sequence-formatting functions.

_make_colors()[source]

Return set of valid colors and their derivatives.

Return type:set
_make_compoundables(colors)[source]

Return given set colors along with all “compoundable” attributes.

Parameters:colors (set) – set of color names as string.
Return type:set
COLORS = {'black', 'blue', 'bright_black', 'bright_blue', 'bright_cyan', 'bright_green', 'bright_magenta', 'bright_red', 'bright_white', 'bright_yellow', 'cyan', 'green', 'magenta', 'on_black', 'on_blue', 'on_bright_black', 'on_bright_blue', 'on_bright_cyan', 'on_bright_green', 'on_bright_magenta', 'on_bright_red', 'on_bright_white', 'on_bright_yellow', 'on_cyan', 'on_green', 'on_magenta', 'on_red', 'on_white', 'on_yellow', 'red', 'white', 'yellow'}

Valid colors and their background (on), bright, and bright-background derivatives.

COMPOUNDABLES = {'black', 'blink', 'blue', 'bold', 'bright_black', 'bright_blue', 'bright_cyan', 'bright_green', 'bright_magenta', 'bright_red', 'bright_white', 'bright_yellow', 'cyan', 'dim', 'green', 'italic', 'magenta', 'on_black', 'on_blue', 'on_bright_black', 'on_bright_blue', 'on_bright_cyan', 'on_bright_green', 'on_bright_magenta', 'on_bright_red', 'on_bright_white', 'on_bright_yellow', 'on_cyan', 'on_green', 'on_magenta', 'on_red', 'on_white', 'on_yellow', 'red', 'reverse', 'shadow', 'standout', 'subscript', 'superscript', 'underline', 'white', 'yellow'}

Attributes and colors which may be compounded by underscore.

class ParameterizingString[source]

A Unicode string which can be called as a parameterizing termcap.

For example:

>>> term = Terminal()
>>> color = ParameterizingString(term.color, term.normal, 'color')
>>> color(9)('color #9')
u'\x1b[91mcolor #9\x1b(B\x1b[m'

Class constructor accepting 3 positional arguments.

Parameters:
  • cap – parameterized string suitable for curses.tparm()
  • normal – terminating sequence for this capability (optional).
  • name – name of this terminal capability (optional).
__call__(*args)[source]

Returning FormattingString instance for given parameters.

Return evaluated terminal capability (self), receiving arguments *args, followed by the terminating sequence (self.normal) into a FormattingString capable of being called.

Return type:FormattingString or NullCallableString
class ParameterizingProxyString[source]

A Unicode string which can be called to proxy missing termcap entries.

This class supports the function get_proxy_string(), and mirrors the behavior of ParameterizingString, except that instead of a capability name, receives a format string, and callable to filter the given positional *args of ParameterizingProxyString.__call__() into a terminal sequence.

For example:

>>> from blessed import Terminal
>>> term = Terminal('screen')
>>> hpa = ParameterizingString(term.hpa, term.normal, 'hpa')
>>> hpa(9)
u''
>>> fmt = u'\x1b[{0}G'
>>> fmt_arg = lambda *arg: (arg[0] + 1,)
>>> hpa = ParameterizingProxyString((fmt, fmt_arg), term.normal, 'hpa')
>>> hpa(9)
u'\x1b[10G'

Class constructor accepting 4 positional arguments.

Parameters:
  • fmt – format string suitable for displaying terminal sequences.
  • callable – receives __call__ arguments for formatting fmt.
  • normal – terminating sequence for this capability (optional).
  • name – name of this terminal capability (optional).
__call__(*args)[source]

Returning FormattingString instance for given parameters.

Arguments are determined by the capability. For example, hpa (move_x) receives only a single integer, whereas cup (move) receives two integers. See documentation in terminfo(5) for the given capability.

Return type:FormattingString
get_proxy_string(term, attr)[source]

Proxy and return callable string for proxied attributes.

Parameters:
  • term (Terminal) – Terminal instance.
  • attr (str) – terminal capability name that may be proxied.
Return type:

None or ParameterizingProxyString.

Returns:

ParameterizingProxyString for some attributes of some terminal types that support it, where the terminfo(5) database would otherwise come up empty, such as move_x attribute for term.kind of screen. Otherwise, None.

class FormattingString[source]

A Unicode string which doubles as a callable.

This is used for terminal attributes, so that it may be used both directly, or as a callable. When used directly, it simply emits the given terminal sequence. When used as a callable, it wraps the given (string) argument with the 2nd argument used by the class constructor:

>>> style = FormattingString(term.bright_blue, term.normal)
>>> print(repr(style))
u'\x1b[94m'
>>> style('Big Blue')
u'\x1b[94mBig Blue\x1b(B\x1b[m'

Class constructor accepting 2 positional arguments.

Parameters:
  • sequence – terminal attribute sequence.
  • normal – terminating sequence for this attribute (optional).
__call__(*args)[source]

Return text joined by sequence and normal.

class NullCallableString[source]

A dummy callable Unicode alternative to FormattingString.

This is used for colors on terminals that do not support colors, it is just a basic form of unicode that may also act as a callable.

Class constructor.

__call__(*args)[source]

Allow empty string to be callable, returning given string, if any.

When called with an int as the first arg, return an empty Unicode. An int is a good hint that I am a ParameterizingString, as there are only about half a dozen string-returning capabilities listed in terminfo(5) which accept non-int arguments, they are seldom used.

When called with a non-int as the first arg (no no args at all), return the first arg, acting in place of FormattingString without any attributes.

split_compound(compound)[source]

Split compound formating string into segments.

>>> split_compound('bold_underline_bright_blue_on_red')
['bold', 'underline', 'bright_blue', 'on_red']
Parameters:compound (str) – a string that may contain compounds, separated by underline (_).
Return type:list
resolve_capability(term, attr)[source]

Resolve a raw terminal capability using tigetstr().

Parameters:
Returns:

string of the given terminal capability named by attr, which may be empty (u’‘) if not found or not supported by the given kind.

Return type:

str

resolve_color(term, color)[source]

Resolve a simple color name to a callable capability.

This function supports resolve_attribute().

Parameters:
Returns:

a string class instance which emits the terminal sequence for the given color, and may be used as a callable to wrap the given string with such sequence.

Returns:

NullCallableString when number_of_colors is 0, otherwise FormattingString.

Return type:

NullCallableString or FormattingString

resolve_attribute(term, attr)[source]

Resolve a terminal attribute name into a capability class.

Parameters:
  • term (Terminal) – Terminal instance.
  • attr (str) – Sugary, ordinary, or compound formatted terminal capability, such as “red_on_white”, “normal”, “red”, or “bold_on_black”, respectively.
Returns:

a string class instance which emits the terminal sequence for the given terminal capability, or may be used as a callable to wrap the given string with such sequence.

Returns:

NullCallableString when number_of_colors is 0, otherwise FormattingString.

Return type:

NullCallableString or FormattingString

COLORS = {'black', 'blue', 'bright_black', 'bright_blue', 'bright_cyan', 'bright_green', 'bright_magenta', 'bright_red', 'bright_white', 'bright_yellow', 'cyan', 'green', 'magenta', 'on_black', 'on_blue', 'on_bright_black', 'on_bright_blue', 'on_bright_cyan', 'on_bright_green', 'on_bright_magenta', 'on_bright_red', 'on_bright_white', 'on_bright_yellow', 'on_cyan', 'on_green', 'on_magenta', 'on_red', 'on_white', 'on_yellow', 'red', 'white', 'yellow'}

Valid colors and their background (on), bright, and bright-background derivatives.

COMPOUNDABLES = {'black', 'blink', 'blue', 'bold', 'bright_black', 'bright_blue', 'bright_cyan', 'bright_green', 'bright_magenta', 'bright_red', 'bright_white', 'bright_yellow', 'cyan', 'dim', 'green', 'italic', 'magenta', 'on_black', 'on_blue', 'on_bright_black', 'on_bright_blue', 'on_bright_cyan', 'on_bright_green', 'on_bright_magenta', 'on_bright_red', 'on_bright_white', 'on_bright_yellow', 'on_cyan', 'on_green', 'on_magenta', 'on_red', 'on_white', 'on_yellow', 'red', 'reverse', 'shadow', 'standout', 'subscript', 'superscript', 'underline', 'white', 'yellow'}

Attributes and colors which may be compounded by underscore.

keyboard.py

Sub-module providing ‘keyboard awareness’.

class Keystroke[source]

A unicode-derived class for describing a single keystroke.

A class instance describes a single keystroke received on input, which may contain multiple characters as a multibyte sequence, which is indicated by properties is_sequence returning True.

When the string is a known sequence, code matches terminal class attributes for comparison, such as term.KEY_LEFT.

The string-name of the sequence, such as u'KEY_LEFT' is accessed by property name, and is used by the __repr__() method to display a human-readable form of the Keystroke this class instance represents. It may otherwise by joined, split, or evaluated just as as any other unicode string.

Class constructor.

static __new__(cls, ucs='', code=None, name=None)[source]

Class constructor.

is_sequence

Whether the value represents a multibyte sequence (bool).

name

String-name of key sequence, such as u'KEY_LEFT' (str).

code

Integer keycode value of multibyte sequence (int).

get_keyboard_codes()[source]

Return mapping of keycode integer values paired by their curses key-name.

Return type:dict

Returns dictionary of (code, name) pairs for curses keyboard constant values and their mnemonic name. Such as key 260, with the value of its identity, u'KEY_LEFT'. These are derived from the attributes by the same of the curses module, with the following exceptions:

  • KEY_DELETE in place of KEY_DC
  • KEY_INSERT in place of KEY_IC
  • KEY_PGUP in place of KEY_PPAGE
  • KEY_PGDOWN in place of KEY_NPAGE
  • KEY_ESCAPE in place of KEY_EXIT
  • KEY_SUP in place of KEY_SR
  • KEY_SDOWN in place of KEY_SF

This function is the inverse of get_curses_keycodes(). With the given override “mixins” listed above, the keycode for the delete key will map to our imaginary KEY_DELETE mnemonic, effectively erasing the phrase KEY_DC from our code vocabulary for anyone that wishes to use the return value to determine the key-name by keycode.

get_keyboard_sequences(term)[source]

Return mapping of keyboard sequences paired by keycodes.

Parameters:term (blessed.Terminal) – Terminal instance.
Returns:mapping of keyboard unicode sequences paired by keycodes as integer. This is used as the argument mapper to the supporting function resolve_sequence().
Return type:OrderedDict

Initialize and return a keyboard map and sequence lookup table, (sequence, keycode) from Terminal instance term, where sequence is a multibyte input sequence of unicode characters, such as u'\x1b[D', and keycode is an integer value, matching curses constant such as term.KEY_LEFT.

The return value is an OrderedDict instance, with their keys sorted longest-first.

_alternative_left_right(term)[source]

Determine and return mapping of left and right arrow keys sequences.

Parameters:term (blessed.Terminal) – Terminal instance.
Return type:dict

This function supports get_terminal_sequences() to discover the preferred input sequence for the left and right application keys.

Return dict of sequences term._cuf1, and term._cub1, valued as KEY_RIGHT, KEY_LEFT (when appropriate). It is necessary to check the value of these sequences to ensure we do not use u' ' and u'\b' for KEY_RIGHT and KEY_LEFT, preferring their true application key sequence, instead.

_inject_curses_keynames()[source]

Inject KEY_NAMES that we think would be useful into the curses module.

This function compliments the global constant DEFAULT_SEQUENCE_MIXIN. It is important to note that this function has the side-effect of injecting new attributes to the curses module, and is called from the global namespace at time of import.

Though we may determine keynames and codes for keyboard input that generate multibyte sequences, it is also especially useful to aliases a few basic ASCII characters such as KEY_TAB instead of u'\t' for uniformity.

Furthermore, many key-names for application keys enabled only by context manager keypad() are surprisingly absent. We inject them here directly into the curses module.

It is not necessary to directly “monkeypatch” the curses module to contain these constants, as they will also be accessible as attributes of the Terminal class instance, they are provided only for convenience when mixed in with other curses code.

DEFAULT_SEQUENCE_MIXIN = (('\n', 343), ('\r', 343), ('\x08', 263), ('\t', 512), ('\x1b', 361), ('\x7f', 330), ('\x1b[A', 259), ('\x1b[B', 258), ('\x1b[C', 261), ('\x1b[D', 260), ('\x1b[F', 360), ('\x1b[H', 262), ('\x1b[K', 360), ('\x1b[U', 338), ('\x1b[V', 339), ('\x1bOM', 343), ('\x1bOj', 513), ('\x1bOk', 514), ('\x1bOl', 515), ('\x1bOm', 516), ('\x1bOn', 517), ('\x1bOo', 518), ('\x1bOX', 519), ('\x1bOp', 520), ('\x1bOq', 521), ('\x1bOr', 522), ('\x1bOs', 523), ('\x1bOt', 524), ('\x1bOu', 525), ('\x1bOv', 526), ('\x1bOw', 527), ('\x1bOx', 528), ('\x1bOy', 529), ('\x1b[1~', 362), ('\x1b[2~', 331), ('\x1b[3~', 330), ('\x1b[4~', 385), ('\x1b[5~', 339), ('\x1b[6~', 338), ('\x1b[7~', 262), ('\x1b[8~', 360), ('\x1b[OA', 259), ('\x1b[OB', 258), ('\x1b[OC', 261), ('\x1b[OD', 260), ('\x1b[OF', 360), ('\x1b[OH', 262), ('\x1bOP', 265), ('\x1bOQ', 266), ('\x1bOR', 267), ('\x1bOS', 268))

In a perfect world, terminal emulators would always send exactly what the terminfo(5) capability database plans for them, accordingly by the value of the TERM name they declare.

But this isn’t a perfect world. Many vt220-derived terminals, such as those declaring ‘xterm’, will continue to send vt220 codes instead of their native-declared codes, for backwards-compatibility.

This goes for many: rxvt, putty, iTerm.

These “mixins” are used for all terminals, regardless of their type.

Furthermore, curses does not provide sequences sent by the keypad, at least, it does not provide a way to distinguish between keypad 0 and numeric 0.

CURSES_KEYCODE_OVERRIDE_MIXIN = (('KEY_DELETE', 330), ('KEY_INSERT', 331), ('KEY_PGUP', 339), ('KEY_PGDOWN', 338), ('KEY_ESCAPE', 361), ('KEY_SUP', 337), ('KEY_SDOWN', 336), ('KEY_UP_LEFT', 348), ('KEY_UP_RIGHT', 349), ('KEY_CENTER', 350), ('KEY_BEGIN', 354))

Override mixins for a few curses constants with easier mnemonics: there may only be a 1:1 mapping when only a keycode (int) is given, where these phrases are preferred.

sequences.py

Module providing ‘sequence awareness’.

class SequenceTextWrapper(width, term, **kwargs)[source]

Object for wrapping/filling text. The public interface consists of the wrap() and fill() methods; the other methods are just there for subclasses to override in order to tweak the default behaviour. If you want to completely replace the main wrapping algorithm, you’ll probably have to override _wrap_chunks().

Several instance attributes control various aspects of wrapping:
width (default: 70)
the maximum width of wrapped lines (unless break_long_words is false)
initial_indent (default: “”)
string that will be prepended to the first line of wrapped output. Counts towards the line’s width.
subsequent_indent (default: “”)
string that will be prepended to all lines save the first of wrapped output; also counts towards each line’s width.
expand_tabs (default: true)
Expand tabs in input text to spaces before further processing. Each tab will become 0 .. ‘tabsize’ spaces, depending on its position in its line. If false, each tab is treated as a single character.
tabsize (default: 8)
Expand tabs in input text to 0 .. ‘tabsize’ spaces, unless ‘expand_tabs’ is false.
replace_whitespace (default: true)
Replace all whitespace characters in the input text by spaces after tab expansion. Note that if expand_tabs is false and replace_whitespace is true, every tab will be converted to a single space!
fix_sentence_endings (default: false)
Ensure that sentence-ending punctuation is always followed by two spaces. Off by default because the algorithm is (unavoidably) imperfect.
break_long_words (default: true)
Break words longer than ‘width’. If false, those words will not be broken, and some lines might be longer than ‘width’.
break_on_hyphens (default: true)
Allow breaking hyphenated words. If true, wrapping will occur preferably on whitespaces and right after hyphens part of compound words.
drop_whitespace (default: true)
Drop leading and trailing whitespace from lines.
max_lines (default: None)
Truncate wrapped lines.
placeholder (default: ‘ […]’)
Append to the last line of truncated text.

Class initializer.

This class supports the wrap() method.

_wrap_chunks(chunks)[source]

Sequence-aware variant of textwrap.TextWrapper._wrap_chunks().

This simply ensures that word boundaries are not broken mid-sequence, as standard python textwrap would incorrectly determine the length of a string containing sequences, and may also break consider sequences part of a “word” that may be broken by hyphen (-), where this implementation corrects both.

_handle_long_word(reversed_chunks, cur_line, cur_len, width)[source]

Sequence-aware textwrap.TextWrapper._handle_long_word().

This simply ensures that word boundaries are not broken mid-sequence, as standard python textwrap would incorrectly determine the length of a string containing sequences, and may also break consider sequences part of a “word” that may be broken by hyphen (-), where this implementation corrects both.

class Sequence[source]

A “sequence-aware” version of the base str class.

This unicode-derived class understands the effect of escape sequences of printable length, allowing a properly implemented rjust(), ljust(), center(), and length().

Class constructor.

Parameters:
  • sequence_text – A string that may contain sequences.
  • term (blessed.Terminal) – Terminal instance.
ljust(width, fillchar=' ')[source]

Return string containing sequences, left-adjusted.

Parameters:
  • width (int) – Total width given to right-adjust text. If unspecified, the width of the attached terminal is used (default).
  • fillchar (str) – String for padding right-of text.
Returns:

String of text, right-aligned by width.

Return type:

str

rjust(width, fillchar=' ')[source]

Return string containing sequences, right-adjusted.

Parameters:
  • width (int) – Total width given to right-adjust text. If unspecified, the width of the attached terminal is used (default).
  • fillchar (str) – String for padding left-of text.
Returns:

String of text, right-aligned by width.

Return type:

str

center(width, fillchar=' ')[source]

Return string containing sequences, centered.

Parameters:
  • width (int) – Total width given to center text. If unspecified, the width of the attached terminal is used (default).
  • fillchar (str) – String for padding left and right-of text.
Returns:

String of text, centered by width.

Return type:

str

length()[source]

Return the printable length of string containing sequences.

Strings containing term.left or \b will cause “overstrike”, but a length less than 0 is not ever returned. So _\b+ is a length of 1 (displays as +), but \b alone is simply a length of 0.

Some characters may consume more than one cell, mainly those CJK Unified Ideographs (Chinese, Japanese, Korean) defined by Unicode as half or full-width characters.

For example:

>>> from blessed import Terminal
>>> from blessed.sequences import Sequence
>>> term = Terminal()
>>> msg = term.clear + term.red(u'コンニチハ'), term
>>> Sequence(msg).length()
10

Note

Although accounted for, strings containing sequences such as term.clear will not give accurate returns, it is not considered lengthy (a length of 0).

strip(chars=None)[source]

Return string of sequences, leading, and trailing whitespace removed.

Parameters:chars (str) – Remove characters in chars instead of whitespace.
Return type:str
lstrip(chars=None)[source]

Return string of all sequences and leading whitespace removed.

Parameters:chars (str) – Remove characters in chars instead of whitespace.
Return type:str
rstrip(chars=None)[source]

Return string of all sequences and trailing whitespace removed.

Parameters:chars (str) – Remove characters in chars instead of whitespace.
Return type:str
strip_seqs()[source]

Return text stripped of only its terminal sequences.

Return type:str
padd()[source]

Return non-destructive horizontal movement as destructive spacing.

Return type:str
iter_parse(term, text)[source]

Generator yields (text, capability) for characters of text.

value for capability may be None, where text is str of length 1. Otherwise, text is a full matching sequence of given capability.

measure_length(text, term)[source]

Deprecated since version 1.12.0..

Return type:int