summaryrefslogtreecommitdiffstats
path: root/examples/print-text/print-formatted-text.py
blob: 4b09ae2afd46b10bd084cf8edf49bdff9d4e4dbd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env python
"""
Example of printing colored text to the output.
"""
from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import ANSI, HTML, FormattedText
from prompt_toolkit.styles import Style

print = print_formatted_text


def main():
    style = Style.from_dict(
        {
            "hello": "#ff0066",
            "world": "#44ff44 italic",
        }
    )

    # Print using a a list of text fragments.
    text_fragments = FormattedText(
        [
            ("class:hello", "Hello "),
            ("class:world", "World"),
            ("", "\n"),
        ]
    )
    print(text_fragments, style=style)

    # Print using an HTML object.
    print(HTML("<hello>hello</hello> <world>world</world>\n"), style=style)

    # Print using an HTML object with inline styling.
    print(
        HTML(
            '<style fg="#ff0066">hello</style> '
            '<style fg="#44ff44"><i>world</i></style>\n'
        )
    )

    # Print using ANSI escape sequences.
    print(ANSI("\x1b[31mhello \x1b[32mworld\n"))


if __name__ == "__main__":
    main()