0
# Rich Classes
1
2
Enhanced Click classes with rich formatting capabilities. These classes extend Click's core functionality to provide rich text formatting, enhanced help output, and improved visual presentation for command-line applications.
3
4
## Capabilities
5
6
### RichCommand
7
8
Enhanced Click command class with Rich formatting capabilities for help output and error messages.
9
10
```python { .api }
11
class RichCommand(click.Command):
12
"""
13
Richly formatted click Command.
14
15
Inherits click.Command and overrides help and error methods
16
to print richly formatted output.
17
18
Attributes:
19
- context_class: Type[RichContext] = RichContext
20
- _formatter: Optional[RichHelpFormatter] = None
21
"""
22
23
def __init__(self, *args, **kwargs):
24
"""Create Rich Command instance."""
25
26
@property
27
def console(self) -> Optional["Console"]:
28
"""
29
Rich Console instance.
30
31
This is a separate instance from the help formatter that allows
32
full control of the console configuration.
33
"""
34
35
@property
36
def help_config(self) -> Optional[RichHelpConfiguration]:
37
"""Rich Help Configuration (deprecated)."""
38
```
39
40
Usage example:
41
42
```python
43
import rich_click as click
44
45
# Using RichCommand directly
46
cmd = click.RichCommand(
47
name="hello",
48
callback=lambda: click.echo("Hello!"),
49
help="A hello command"
50
)
51
52
# Using via decorator (recommended)
53
@click.command(cls=click.RichCommand)
54
def hello():
55
"""A hello command."""
56
click.echo("Hello!")
57
```
58
59
### RichGroup
60
61
Enhanced Click group class with Rich formatting capabilities for multi-command applications.
62
63
```python { .api }
64
class RichGroup(click.Group):
65
"""
66
Richly formatted click Group.
67
68
Inherits click.Group and provides rich formatting for
69
command groups and subcommands.
70
"""
71
```
72
73
Usage example:
74
75
```python
76
import rich_click as click
77
78
# Using RichGroup directly
79
@click.group(cls=click.RichGroup)
80
def cli():
81
"""My CLI application."""
82
pass
83
84
@cli.command()
85
def hello():
86
"""Say hello."""
87
click.echo("Hello!")
88
89
# Using via decorator (recommended)
90
@click.group() # Uses RichGroup by default
91
def cli():
92
"""My CLI application."""
93
pass
94
```
95
96
### RichCommandCollection
97
98
Enhanced Click command collection with Rich formatting capabilities.
99
100
```python { .api }
101
class RichCommandCollection(click.CommandCollection):
102
"""
103
Richly formatted click CommandCollection.
104
105
Inherits click.CommandCollection and provides rich formatting
106
for collections of commands.
107
"""
108
```
109
110
### RichContext
111
112
Enhanced Click context class with Rich capabilities including console access and export functionality.
113
114
```python { .api }
115
class RichContext(click.Context):
116
"""
117
Click Context class endowed with Rich superpowers.
118
119
Attributes:
120
- formatter_class: Type[RichHelpFormatter] = RichHelpFormatter
121
- console: Optional["Console"] = None
122
- export_console_as: Literal[None, "html", "svg"] = None
123
- errors_in_output_format: bool = False
124
"""
125
126
def __init__(self, *args, rich_console=None, rich_help_config=None, **kwargs):
127
"""
128
Create Rich Context instance.
129
130
Parameters:
131
- *args: Args passed to click.Context
132
- rich_console (Console, optional): Rich Console instance
133
- rich_help_config (Union[Mapping, RichHelpConfiguration], optional):
134
Rich help configuration
135
- **kwargs: Kwargs passed to click.Context
136
"""
137
138
def make_formatter(self, error=False) -> RichHelpFormatter:
139
"""
140
Create the Rich Help Formatter.
141
142
Parameters:
143
- error (bool): Whether this is for error formatting
144
145
Returns:
146
RichHelpFormatter: Configured formatter instance
147
"""
148
149
def exit(self, code=0):
150
"""
151
Enhanced exit with export capabilities.
152
153
Parameters:
154
- code (int): Exit code, defaults to 0
155
156
If export_console_as is set, exports console output as HTML or SVG
157
before exiting.
158
"""
159
```
160
161
Usage example:
162
163
```python
164
import rich_click as click
165
from rich.console import Console
166
167
# Context is automatically created with rich capabilities
168
@click.command()
169
@click.pass_context
170
def hello(ctx):
171
"""Command using rich context."""
172
# ctx is automatically a RichContext
173
console = ctx.console or Console()
174
console.print("Hello from Rich!", style="bold blue")
175
176
# Manual context creation
177
console = Console(width=120)
178
ctx = click.RichContext(
179
command=hello,
180
rich_console=console,
181
rich_help_config={"style_option": "bold red"}
182
)
183
```
184
185
### RichHelpConfiguration
186
187
Comprehensive configuration class for customizing Rich-Click help formatting and behavior.
188
189
```python { .api }
190
class RichHelpConfiguration:
191
"""
192
Rich Help Configuration class.
193
194
When merging multiple RichHelpConfigurations together, user-defined values
195
always take precedence over the class's defaults.
196
"""
197
198
# Style configuration fields (selection of key ones)
199
style_option: str = "bold cyan"
200
style_argument: str = "bold cyan"
201
style_command: str = "bold cyan"
202
style_switch: str = "bold green"
203
style_metavar: str = "bold yellow"
204
style_usage: str = "yellow"
205
style_deprecated: str = "red"
206
style_helptext: str = "dim"
207
208
# Panel and table styling
209
style_options_panel_border: str = "dim"
210
style_options_panel_box: Optional[str] = "ROUNDED"
211
style_commands_panel_border: str = "dim"
212
style_errors_panel_border: str = "red"
213
214
# Terminal configuration
215
width: Optional[int] = None
216
max_width: Optional[int] = None
217
color_system: Optional[str] = "auto"
218
force_terminal: Optional[bool] = None
219
220
# Text configuration
221
header_text: Optional[str] = None
222
footer_text: Optional[str] = None
223
deprecated_string: str = "(Deprecated) "
224
default_string: str = "[default: {}]"
225
arguments_panel_title: str = "Arguments"
226
options_panel_title: str = "Options"
227
commands_panel_title: str = "Commands"
228
229
# Behavior configuration
230
show_arguments: bool = False
231
show_metavars_column: bool = True
232
append_metavars_help: bool = False
233
group_arguments_options: bool = False
234
text_markup: str = "ansi"
235
use_markdown: bool = False
236
use_rich_markup: bool = False
237
command_groups: Dict[str, List[CommandGroupDict]] = field(default_factory=dict)
238
option_groups: Dict[str, List[OptionGroupDict]] = field(default_factory=dict)
239
240
@classmethod
241
def load_from_globals(cls, module=None, **extra):
242
"""
243
Build a RichHelpConfiguration from globals in rich_click.rich_click.
244
245
Parameters:
246
- module (ModuleType, optional): Module to load from
247
- **extra: Additional configuration overrides
248
249
Returns:
250
RichHelpConfiguration: Configuration instance
251
"""
252
253
def dump_to_globals(self, module=None):
254
"""
255
Dump configuration to module globals.
256
257
Parameters:
258
- module (ModuleType, optional): Module to dump to
259
"""
260
```
261
262
Usage example:
263
264
```python
265
import rich_click as click
266
267
# Create configuration
268
config = click.RichHelpConfiguration(
269
style_option="bold red",
270
style_command="bold blue",
271
show_arguments=True,
272
options_panel_title="Available Options",
273
commands_panel_title="Available Commands"
274
)
275
276
# Use with decorator
277
@click.command()
278
@click.rich_config(config)
279
def hello():
280
"""Configured command."""
281
click.echo("Hello!")
282
283
# Load from globals
284
config = click.RichHelpConfiguration.load_from_globals()
285
286
# Modify and dump back
287
config.style_option = "bold yellow"
288
config.dump_to_globals()
289
```
290
291
## Deprecated Classes
292
293
### RichMultiCommand
294
295
Deprecated class, use RichGroup instead.
296
297
```python { .api }
298
class RichMultiCommand:
299
"""
300
Deprecated class. Use RichGroup instead.
301
302
This class is deprecated and will be removed in Click 9.0.
303
Use RichGroup for multi-command functionality.
304
"""
305
```
306
307
## Type Information
308
309
```python { .api }
310
# Type definitions for configuration
311
CommandGroupDict = TypedDict('CommandGroupDict', {
312
'name': NotRequired[str],
313
'commands': List[str],
314
'table_styles': NotRequired[Dict[str, Any]],
315
'panel_styles': NotRequired[Dict[str, Any]],
316
'deduplicate': NotRequired[bool]
317
})
318
319
OptionGroupDict = TypedDict('OptionGroupDict', {
320
'name': NotRequired[str],
321
'options': NotRequired[List[str]],
322
'table_styles': NotRequired[Dict[str, Any]],
323
'panel_styles': NotRequired[Dict[str, Any]],
324
'deduplicate': NotRequired[bool]
325
})
326
```