Introduction¶
The core of this library is the CS
class. Its attributes are templates
for ANSI control sequences. The use of this class is very low level. To make it
a little easier to work with CS.SGR
sequences for coloring and styling
characters on the screen there are the SGR
class and the fg()
and
bg()
functions.
There are higher level functions, e.g. for moving
the cursor,
erasing
characters on the screen, building
,
and printing
strings with SGR sequences.
For more details see the API Reference.
Another feature of this library is the possibilty to specify strings with a special markup for colors and styles.
See also
- ANSI escape code at Wikipedia
CSI (Control Sequence Introducer) sequences
SGR (Select Graphic Rendition) parameters
- XTerm Control Sequences
Functions using CSI
Colors¶
The original eight ANSI colors
are attributes in the SGR
class, e.g. SGR.FgBlack
(black foreground) or
SGR.BgWhite
(white background). The bright colors will be used if the attribute
is prefixed with the ~
unary operator. To reset to the default colors of the terminal
use SGR.FgDefault
and SGR.BgDefault
.
>>> CS.SGR % 31
'\x1b[31m'
>>> CS.SGR % SGR.FgRed
'\x1b[31m'
>>> CS.SGR % 91
'\x1b[91m'
>>> CS.SGR % ~SGR.FgRed
'\x1b[91m'
8-bit colors
are supported by using their index in the interval [0..255]. It is easier to
use them with the fg()
and bg()
functions.
>>> CS.SGR % (38, 5, 124)
'\x1b[38;5;124m'
>>> CS.SGR % fg(124)
'\x1b[38;5;124m'
24-bit colors
are supported with RGB tuples, each of the three values in the interval [0..255].
It is easier to use them with the fg()
and bg()
functions which can also use
HTML-style colors, e.g. #FF0000 or #F00.
>>> CS.SGR % (48, 2, 255, 0, 0)
'\x1b[48;2;255;0;0m'
>>> CS.SGR % bg(255, 0, 0)
'\x1b[48;2;255;0;0m'
>>> CS.SGR % bg('#FF0000')
'\x1b[48;2;255;0;0m'
Specification strings¶
In a specification string the attributes are separated by ;
and enclosed in the
delimiters #[
and ]
. The delimiters can be changed with
set_attributes_delimiters()
. The following attributes are supported (they can
be disabled by prefixing them with not
):
bd |
bold |
ft |
faint |
it |
italic |
ul |
underlined |
bk |
blink |
iv |
inverse |
co |
crossed-out |
ol |
overlined |
Colors start with fg
(foreground color) or
bg
(background color) followed by a COLOR. COLOR can be given as:
name |
|
|
for using the default foreground or background colors of the terminal |
integer |
the index of a 8-bit color in the interval [0..255] |
3 integers |
RGB values each in the interval [0..255], separated by |
HTML-style |
RGB values in hexdecimal, e.g. #FF0000 or #F00 |
To reset all attributes to normal use reset
or an empty string.
>>> s = '#[bd;fg red;bg 0,255,0]Hello, #[not bd;fg bright blue]World!#[]'
>>> parse(s)
'\x1b[1;31;48;2;0;255;0mHello, \x1b[22;94mWorld!\x1b[0m'
>>> print(_)
Hello, World!