0
# Styling and Formatting
1
2
Rich text formatting with HTML-like syntax, ANSI sequences, and CSS-like styling with Pygments integration. The styling system provides comprehensive control over text appearance, colors, and formatting in terminal applications.
3
4
## Capabilities
5
6
### Formatted Text Output
7
8
Core function for printing formatted text to the terminal with support for styles, colors, and formatting.
9
10
```python { .api }
11
def print_formatted_text(
12
*values,
13
sep=" ",
14
end="\n",
15
file=None,
16
flush=False,
17
style=None,
18
output=None,
19
color_depth=None,
20
style_transformation=None,
21
include_default_pygments_style=None
22
):
23
"""
24
Print formatted text with styling support.
25
26
Parameters:
27
- *values: AnyFormattedText values to print
28
- sep: str, separator between values
29
- end: str, string to append at end
30
- file: file-like object to write to
31
- flush: bool, whether to flush output
32
- style: Style instance for formatting
33
- output: Output instance for terminal control
34
- color_depth: ColorDepth for color support level
35
- style_transformation: StyleTransformation to apply
36
- include_default_pygments_style: bool, include Pygments defaults
37
"""
38
```
39
40
### Formatted Text Classes
41
42
Classes for creating formatted text with different markup styles.
43
44
```python { .api }
45
class HTML:
46
def __init__(self, value):
47
"""
48
HTML-like formatted text with tag-based markup.
49
50
Parameters:
51
- value: str, HTML-like markup string
52
53
Supported tags:
54
- <b>bold</b>, <i>italic</i>, <u>underline</u>
55
- <style fg="color" bg="color">styled text</style>
56
- <reverse>reverse video</reverse>
57
- <hidden>hidden text</hidden>
58
- <blink>blinking text</blink>
59
"""
60
61
class ANSI:
62
def __init__(self, value):
63
"""
64
ANSI escape sequence formatted text.
65
66
Parameters:
67
- value: str, text with ANSI escape sequences
68
69
Common sequences:
70
- \\x1b[1m bold \\x1b[0m
71
- \\x1b[31m red \\x1b[0m
72
- \\x1b[42m green background \\x1b[0m
73
"""
74
75
class FormattedText:
76
def __init__(self, value):
77
"""
78
Generic formatted text container.
79
80
Parameters:
81
- value: List of (style, text) tuples or other formatted text
82
"""
83
84
class PygmentsTokens:
85
def __init__(self, tokens):
86
"""
87
Formatted text from Pygments syntax highlighting tokens.
88
89
Parameters:
90
- tokens: Iterator of (token_type, text) tuples from Pygments
91
"""
92
```
93
94
### Formatted Text Utilities
95
96
Functions for working with and manipulating formatted text.
97
98
```python { .api }
99
def to_formatted_text(value, style="", auto_convert=False):
100
"""
101
Convert various inputs to formatted text.
102
103
Parameters:
104
- value: str, FormattedText, HTML, ANSI, or list of tuples
105
- style: str, default style to apply
106
- auto_convert: bool, automatically convert strings
107
108
Returns:
109
FormattedText instance
110
"""
111
112
def is_formatted_text(value):
113
"""
114
Check if value is formatted text.
115
116
Parameters:
117
- value: Object to check
118
119
Returns:
120
bool: True if value is formatted text
121
"""
122
123
def merge_formatted_text(values):
124
"""
125
Merge multiple formatted text objects.
126
127
Parameters:
128
- values: List of formatted text objects
129
130
Returns:
131
Merged FormattedText instance
132
"""
133
134
def fragment_list_len(fragments):
135
"""
136
Get character length of fragment list.
137
138
Parameters:
139
- fragments: List of (style, text) tuples
140
141
Returns:
142
int: Total character count
143
"""
144
145
def fragment_list_width(fragments):
146
"""
147
Get display width of fragment list.
148
149
Parameters:
150
- fragments: List of (style, text) tuples
151
152
Returns:
153
int: Display width accounting for wide characters
154
"""
155
156
def fragment_list_to_text(fragments):
157
"""
158
Convert fragment list to plain text.
159
160
Parameters:
161
- fragments: List of (style, text) tuples
162
163
Returns:
164
str: Plain text without styling
165
"""
166
167
def split_lines(formatted_text):
168
"""
169
Split formatted text into lines.
170
171
Parameters:
172
- formatted_text: AnyFormattedText to split
173
174
Returns:
175
List of formatted text lines
176
"""
177
178
def to_plain_text(formatted_text):
179
"""
180
Extract plain text from formatted text.
181
182
Parameters:
183
- formatted_text: AnyFormattedText to convert
184
185
Returns:
186
str: Plain text without formatting
187
"""
188
189
class Template:
190
def __init__(self, template):
191
"""
192
Template for parameterized formatted text.
193
194
Parameters:
195
- template: str, template string with {variables}
196
"""
197
198
def format(self, **kwargs):
199
"""
200
Format template with values.
201
202
Parameters:
203
- **kwargs: Values to substitute in template
204
205
Returns:
206
FormattedText instance
207
"""
208
```
209
210
### Style Classes
211
212
CSS-like styling system for defining text appearance and colors.
213
214
```python { .api }
215
class Style:
216
@classmethod
217
def from_dict(cls, style_dict):
218
"""
219
Create style from dictionary mapping.
220
221
Parameters:
222
- style_dict: Dict mapping class names to style strings
223
224
Returns:
225
Style instance
226
227
Style string format:
228
- Colors: fg:red bg:blue, #ff0000, ansiblue
229
- Attributes: bold, italic, underline, reverse, blink, hidden
230
- Combined: "bold italic fg:red bg:#ffffff"
231
"""
232
233
class BaseStyle:
234
"""Abstract base class for styles."""
235
236
def get_attrs_for_style_str(self, style_str):
237
"""
238
Get attributes for style string.
239
240
Parameters:
241
- style_str: str, CSS-like style specification
242
243
Returns:
244
Attrs instance
245
"""
246
247
class DummyStyle(BaseStyle):
248
"""Dummy style implementation for testing."""
249
250
def __init__(self):
251
"""Create dummy style with no formatting."""
252
253
class DynamicStyle(BaseStyle):
254
def __init__(self, get_style):
255
"""
256
Dynamic style that changes based on function.
257
258
Parameters:
259
- get_style: Function returning Style instance
260
"""
261
262
def merge_styles(styles):
263
"""
264
Merge multiple style objects.
265
266
Parameters:
267
- styles: List of Style instances
268
269
Returns:
270
Combined Style instance
271
"""
272
273
def default_ui_style():
274
"""
275
Get default UI style for prompt-toolkit interfaces.
276
277
Returns:
278
Style instance with default UI styling
279
"""
280
281
def default_pygments_style():
282
"""
283
Get default Pygments style for syntax highlighting.
284
285
Returns:
286
Style instance with Pygments defaults
287
"""
288
289
class Priority(Enum):
290
"""Style priority levels for override behavior."""
291
LOWEST = 0
292
LOW = 25
293
MEDIUM = 50
294
HIGH = 75
295
HIGHEST = 100
296
```
297
298
### Text Attributes
299
300
Classes for specifying detailed text formatting attributes.
301
302
```python { .api }
303
class Attrs:
304
def __init__(
305
self,
306
color=None,
307
bgcolor=None,
308
bold=None,
309
underline=None,
310
strike=None,
311
italic=None,
312
blink=None,
313
reverse=None,
314
hidden=None
315
):
316
"""
317
Text attribute specification.
318
319
Parameters:
320
- color: str, foreground color
321
- bgcolor: str, background color
322
- bold: bool, bold text
323
- underline: bool, underlined text
324
- strike: bool, strikethrough text
325
- italic: bool, italic text
326
- blink: bool, blinking text
327
- reverse: bool, reverse video
328
- hidden: bool, hidden text
329
"""
330
331
DEFAULT_ATTRS = Attrs() # Default text attributes
332
333
ANSI_COLOR_NAMES = {
334
# Standard ANSI color name mappings
335
'ansiblack': '000000',
336
'ansired': '800000',
337
'ansigreen': '008000',
338
'ansiyellow': '808000',
339
'ansiblue': '000080',
340
'ansimagenta': '800080',
341
'ansicyan': '008080',
342
'ansigray': 'c0c0c0',
343
# Bright colors
344
'ansibrightblack': '808080',
345
'ansibrightred': 'ff0000',
346
'ansibrightgreen': '00ff00',
347
'ansibrightyellow': 'ffff00',
348
'ansibrightblue': '0000ff',
349
'ansibrightmagenta': 'ff00ff',
350
'ansibrightcyan': '00ffff',
351
'ansiwhite': 'ffffff'
352
}
353
354
NAMED_COLORS = {
355
# Extended named color definitions
356
'red': 'ff0000',
357
'green': '00ff00',
358
'blue': '0000ff',
359
'yellow': 'ffff00',
360
'magenta': 'ff00ff',
361
'cyan': '00ffff',
362
'white': 'ffffff',
363
'black': '000000',
364
'gray': '808080',
365
'orange': 'ffa500',
366
'purple': '800080',
367
'brown': 'a52a2a',
368
'pink': 'ffc0cb'
369
}
370
371
def parse_color(color_str):
372
"""
373
Parse color specification string.
374
375
Parameters:
376
- color_str: str, color specification
377
378
Returns:
379
Parsed color value
380
381
Supported formats:
382
- Named colors: red, blue, ansiblue
383
- Hex colors: #ff0000, #f00
384
- RGB colors: rgb(255,0,0)
385
"""
386
```
387
388
### Style Transformations
389
390
System for applying dynamic transformations to existing styles.
391
392
```python { .api }
393
class StyleTransformation:
394
"""Abstract base class for style transformations."""
395
396
def transform_attrs(self, attrs, style_str):
397
"""
398
Transform text attributes.
399
400
Parameters:
401
- attrs: Attrs instance to transform
402
- style_str: str, original style string
403
404
Returns:
405
Transformed Attrs instance
406
"""
407
408
class SwapLightAndDarkStyleTransformation(StyleTransformation):
409
"""Swap light and dark colors in styles."""
410
411
def __init__(self):
412
"""Create light/dark swap transformation."""
413
414
class ReverseStyleTransformation(StyleTransformation):
415
"""Reverse foreground and background colors."""
416
417
def __init__(self):
418
"""Create color reversal transformation."""
419
420
class SetDefaultColorStyleTransformation(StyleTransformation):
421
def __init__(self, fg=None, bg=None):
422
"""
423
Set default foreground/background colors.
424
425
Parameters:
426
- fg: str, default foreground color
427
- bg: str, default background color
428
"""
429
430
class AdjustBrightnessStyleTransformation(StyleTransformation):
431
def __init__(self, min_brightness=0.0, max_brightness=1.0):
432
"""
433
Adjust color brightness levels.
434
435
Parameters:
436
- min_brightness: float, minimum brightness (0.0-1.0)
437
- max_brightness: float, maximum brightness (0.0-1.0)
438
"""
439
440
class DummyStyleTransformation(StyleTransformation):
441
"""Dummy transformation that makes no changes."""
442
443
def __init__(self):
444
"""Create no-op transformation."""
445
446
class ConditionalStyleTransformation(StyleTransformation):
447
def __init__(self, transformation, filter):
448
"""
449
Apply transformation conditionally.
450
451
Parameters:
452
- transformation: StyleTransformation to apply
453
- filter: Filter determining when to apply
454
"""
455
456
class DynamicStyleTransformation(StyleTransformation):
457
def __init__(self, get_transformation):
458
"""
459
Dynamic transformation based on function.
460
461
Parameters:
462
- get_transformation: Function returning StyleTransformation
463
"""
464
465
def merge_style_transformations(transformations):
466
"""
467
Merge multiple style transformations.
468
469
Parameters:
470
- transformations: List of StyleTransformation instances
471
472
Returns:
473
Combined StyleTransformation
474
"""
475
```
476
477
### Pygments Integration
478
479
Functions for integrating with Pygments syntax highlighting library.
480
481
```python { .api }
482
def style_from_pygments_cls(pygments_style_cls):
483
"""
484
Create prompt-toolkit style from Pygments style class.
485
486
Parameters:
487
- pygments_style_cls: Pygments style class
488
489
Returns:
490
Style instance
491
"""
492
493
def style_from_pygments_dict(pygments_style_dict):
494
"""
495
Create prompt-toolkit style from Pygments style dictionary.
496
497
Parameters:
498
- pygments_style_dict: Dict of Pygments style definitions
499
500
Returns:
501
Style instance
502
"""
503
504
def pygments_token_to_classname(token):
505
"""
506
Convert Pygments token to CSS class name.
507
508
Parameters:
509
- token: Pygments token type
510
511
Returns:
512
str: CSS class name
513
"""
514
```
515
516
## Usage Examples
517
518
### Basic Formatted Text
519
520
```python
521
from prompt_toolkit import print_formatted_text
522
from prompt_toolkit.formatted_text import HTML, ANSI
523
524
# HTML-like formatting
525
print_formatted_text(HTML('<b>Bold text</b> and <i>italic text</i>'))
526
print_formatted_text(HTML('<style fg="red">Red text</style>'))
527
print_formatted_text(HTML('<style bg="blue" fg="white">Blue background</style>'))
528
529
# ANSI escape sequences
530
print_formatted_text(ANSI('\x1b[1mBold\x1b[0m \x1b[31mRed\x1b[0m'))
531
print_formatted_text(ANSI('\x1b[42mGreen background\x1b[0m'))
532
533
# Fragment list format
534
from prompt_toolkit.formatted_text import FormattedText
535
fragments = [
536
('class:title', 'Title: '),
537
('class:content', 'This is the content'),
538
('', '\n')
539
]
540
print_formatted_text(FormattedText(fragments))
541
```
542
543
### Custom Styles
544
545
```python
546
from prompt_toolkit import print_formatted_text
547
from prompt_toolkit.formatted_text import HTML
548
from prompt_toolkit.styles import Style
549
550
# Define custom style
551
style = Style.from_dict({
552
'title': 'bold #ff0066',
553
'subtitle': 'italic #44ff44',
554
'content': '#ffffff',
555
'highlight': 'reverse',
556
'error': 'bold bg:red fg:white',
557
'warning': 'bold fg:yellow',
558
'success': 'bold fg:green'
559
})
560
561
# Use custom style
562
print_formatted_text(
563
HTML('<title>Application Title</title>\n'
564
'<subtitle>Version 1.0</subtitle>\n'
565
'<content>Normal content text</content>\n'
566
'<highlight>Highlighted text</highlight>\n'
567
'<error>Error message</error>\n'
568
'<warning>Warning message</warning>\n'
569
'<success>Success message</success>'),
570
style=style
571
)
572
```
573
574
### Pygments Syntax Highlighting
575
576
```python
577
from prompt_toolkit import print_formatted_text
578
from prompt_toolkit.formatted_text import PygmentsTokens
579
from prompt_toolkit.styles import style_from_pygments_cls
580
from pygments import highlight
581
from pygments.lexers import PythonLexer
582
from pygments.styles import get_style_by_name
583
584
# Python code to highlight
585
code = '''
586
def fibonacci(n):
587
if n < 2:
588
return n
589
return fibonacci(n-1) + fibonacci(n-2)
590
591
result = fibonacci(10)
592
print(f"Fibonacci(10) = {result}")
593
'''
594
595
# Create Pygments tokens
596
lexer = PythonLexer()
597
tokens = list(lexer.get_tokens(code))
598
599
# Create style from Pygments
600
pygments_style = get_style_by_name('monokai')
601
style = style_from_pygments_cls(pygments_style)
602
603
# Print with syntax highlighting
604
print_formatted_text(PygmentsTokens(tokens), style=style)
605
```
606
607
### Template Formatting
608
609
```python
610
from prompt_toolkit.formatted_text import Template
611
from prompt_toolkit import print_formatted_text
612
from prompt_toolkit.styles import Style
613
614
# Create template
615
template = Template('''
616
<title>Welcome {username}!</title>
617
618
<info>Status: {status}</info>
619
<details>
620
- Login time: {login_time}
621
- Messages: {message_count}
622
- Last activity: {last_activity}
623
</details>
624
''')
625
626
# Define style for template
627
style = Style.from_dict({
628
'title': 'bold fg:blue',
629
'info': 'fg:green',
630
'details': 'fg:gray'
631
})
632
633
# Format and print template
634
formatted = template.format(
635
username='John Doe',
636
status='Online',
637
login_time='2023-12-01 09:30:00',
638
message_count='5',
639
last_activity='2 minutes ago'
640
)
641
642
print_formatted_text(formatted, style=style)
643
```
644
645
### Dynamic Styling
646
647
```python
648
from prompt_toolkit import print_formatted_text
649
from prompt_toolkit.formatted_text import HTML
650
from prompt_toolkit.styles import DynamicStyle, Style
651
652
# Create dynamic style that changes based on conditions
653
def get_current_style():
654
# Could be based on user preferences, time of day, etc.
655
if some_condition:
656
return Style.from_dict({
657
'title': 'bold fg:blue',
658
'content': 'fg:white'
659
})
660
else:
661
return Style.from_dict({
662
'title': 'bold fg:red',
663
'content': 'fg:yellow'
664
})
665
666
dynamic_style = DynamicStyle(get_current_style)
667
668
# Use dynamic style
669
print_formatted_text(
670
HTML('<title>Dynamic Title</title>\n<content>Dynamic content</content>'),
671
style=dynamic_style
672
)
673
```
674
675
### Style Transformations
676
677
```python
678
from prompt_toolkit import print_formatted_text
679
from prompt_toolkit.formatted_text import HTML
680
from prompt_toolkit.styles import Style
681
from prompt_toolkit.styles import (
682
SwapLightAndDarkStyleTransformation,
683
AdjustBrightnessStyleTransformation
684
)
685
686
# Base style
687
style = Style.from_dict({
688
'light': 'fg:white bg:black',
689
'dark': 'fg:black bg:white',
690
'colored': 'fg:red bg:blue'
691
})
692
693
text = HTML('<light>Light text</light> <dark>Dark text</dark> <colored>Colored</colored>')
694
695
# Original style
696
print_formatted_text('Original:', text, style=style)
697
698
# Swap light and dark
699
print_formatted_text(
700
'Swapped:',
701
text,
702
style=style,
703
style_transformation=SwapLightAndDarkStyleTransformation()
704
)
705
706
# Adjust brightness
707
print_formatted_text(
708
'Dimmed:',
709
text,
710
style=style,
711
style_transformation=AdjustBrightnessStyleTransformation(
712
min_brightness=0.3,
713
max_brightness=0.7
714
)
715
)
716
```