0
# Argparse Formatters
1
2
Core rich formatting classes that replace argparse's built-in help formatters with enhanced visual output. These formatters provide customizable colors, syntax highlighting, and rich markup support while maintaining full compatibility with existing argparse code.
3
4
## Capabilities
5
6
### RichHelpFormatter
7
8
The main formatter class that provides rich, colorful help output for argparse. It's the drop-in replacement for argparse.HelpFormatter with extensive customization options.
9
10
```python { .api }
11
class RichHelpFormatter(argparse.HelpFormatter):
12
"""An argparse HelpFormatter class that renders using rich."""
13
14
# Class attributes for customization
15
group_name_formatter: ClassVar[Callable[[str], str]] = str.title
16
"""A function that formats group names. Defaults to str.title."""
17
18
styles: ClassVar[dict[str, StyleType]] = {
19
"argparse.args": "cyan",
20
"argparse.groups": "dark_orange",
21
"argparse.help": "default",
22
"argparse.metavar": "dark_cyan",
23
"argparse.syntax": "bold",
24
"argparse.text": "default",
25
"argparse.prog": "grey50",
26
"argparse.default": "italic",
27
}
28
"""A dict of rich styles to control the formatter styles."""
29
30
highlights: ClassVar[list[str]]
31
"""A list of regex patterns to highlight in the help text."""
32
33
usage_markup: ClassVar[bool] = False
34
"""If True, render the usage string as markup."""
35
36
help_markup: ClassVar[bool] = True
37
"""If True, render argument help messages as console markup."""
38
39
text_markup: ClassVar[bool] = True
40
"""If True, render descriptions and epilog as console markup."""
41
42
def __init__(
43
self,
44
prog: str,
45
indent_increment: int = 2,
46
max_help_position: int = 24,
47
width: int | None = None,
48
*,
49
console: Console | None = None,
50
**kwargs
51
) -> None:
52
"""
53
Initialize the rich help formatter.
54
55
Args:
56
prog: Program name
57
indent_increment: Number of spaces for each indentation level
58
max_help_position: Maximum position for help text alignment
59
width: Maximum width for formatting (None for auto-detect)
60
console: Rich console instance (None for default)
61
**kwargs: Additional arguments passed to parent HelpFormatter
62
"""
63
```
64
65
#### Usage Examples
66
67
Basic usage with custom styles:
68
69
```python
70
import argparse
71
from rich_argparse import RichHelpFormatter
72
73
# Customize colors
74
RichHelpFormatter.styles["argparse.args"] = "bold blue"
75
RichHelpFormatter.styles["argparse.help"] = "dim"
76
77
parser = argparse.ArgumentParser(
78
prog="myapp",
79
description="A sample application with custom colors",
80
formatter_class=RichHelpFormatter
81
)
82
```
83
84
Custom group name formatting:
85
86
```python
87
# Custom group name formatter
88
RichHelpFormatter.group_name_formatter = str.upper
89
90
parser = argparse.ArgumentParser(formatter_class=RichHelpFormatter)
91
group = parser.add_argument_group("advanced options") # Will show as "ADVANCED OPTIONS"
92
```
93
94
Disable highlighting:
95
96
```python
97
# Turn off text highlighting
98
RichHelpFormatter.highlights.clear()
99
100
parser = argparse.ArgumentParser(formatter_class=RichHelpFormatter)
101
```
102
103
### RawDescriptionRichHelpFormatter
104
105
Preserves raw description formatting without processing the description text, similar to argparse.RawDescriptionHelpFormatter but with rich styling.
106
107
```python { .api }
108
class RawDescriptionRichHelpFormatter(RichHelpFormatter):
109
"""Rich help message formatter which retains the raw description."""
110
```
111
112
#### Usage Examples
113
114
```python
115
import argparse
116
from rich_argparse import RawDescriptionRichHelpFormatter
117
118
parser = argparse.ArgumentParser(
119
description="""
120
This description preserves:
121
- Line breaks
122
- Indentation
123
- Spacing
124
""",
125
formatter_class=RawDescriptionRichHelpFormatter
126
)
127
```
128
129
### RawTextRichHelpFormatter
130
131
Preserves raw formatting for all text elements (description, epilog, and argument help), similar to argparse.RawTextHelpFormatter but with rich styling.
132
133
```python { .api }
134
class RawTextRichHelpFormatter(RawDescriptionRichHelpFormatter):
135
"""Rich help message formatter which retains raw formatting of all help text."""
136
```
137
138
#### Usage Examples
139
140
```python
141
import argparse
142
from rich_argparse import RawTextRichHelpFormatter
143
144
parser = argparse.ArgumentParser(
145
description="""Raw description with
146
preserved formatting""",
147
epilog="""Raw epilog with
148
preserved formatting""",
149
formatter_class=RawTextRichHelpFormatter
150
)
151
152
parser.add_argument("--input", help="""Raw help text with
153
preserved formatting""")
154
```
155
156
### ArgumentDefaultsRichHelpFormatter
157
158
Shows default values in argument help text, combining argparse.ArgumentDefaultsHelpFormatter with rich formatting.
159
160
```python { .api }
161
class ArgumentDefaultsRichHelpFormatter(argparse.ArgumentDefaultsHelpFormatter, RichHelpFormatter):
162
"""Rich help message formatter which adds default values to argument help."""
163
```
164
165
#### Usage Examples
166
167
```python
168
import argparse
169
from rich_argparse import ArgumentDefaultsRichHelpFormatter
170
171
parser = argparse.ArgumentParser(formatter_class=ArgumentDefaultsRichHelpFormatter)
172
173
parser.add_argument("--count", type=int, default=10, help="Number of items")
174
parser.add_argument("--format", default="json", help="Output format")
175
# Help will show: "Number of items (default: 10)" and "Output format (default: json)"
176
```
177
178
### MetavarTypeRichHelpFormatter
179
180
Uses type names as metavars instead of dest names, combining argparse.MetavarTypeHelpFormatter with rich formatting.
181
182
```python { .api }
183
class MetavarTypeRichHelpFormatter(argparse.MetavarTypeHelpFormatter, RichHelpFormatter):
184
"""Rich help message formatter which uses type names for metavars."""
185
```
186
187
#### Usage Examples
188
189
```python
190
import argparse
191
from rich_argparse import MetavarTypeRichHelpFormatter
192
193
parser = argparse.ArgumentParser(formatter_class=MetavarTypeRichHelpFormatter)
194
195
parser.add_argument("--count", type=int, help="Number of items")
196
parser.add_argument("--rate", type=float, help="Processing rate")
197
# Help will show: "--count int" instead of "--count COUNT"
198
# and "--rate float" instead of "--rate RATE"
199
```
200
201
### HelpPreviewAction
202
203
Special action class for generating help preview images or SVG files, useful for documentation and testing.
204
205
```python { .api }
206
class HelpPreviewAction(argparse.Action):
207
"""Action to generate help preview images/SVGs."""
208
209
def __init__(
210
self,
211
option_strings,
212
dest,
213
*,
214
path: str,
215
export_kwds: dict | None = None,
216
**kwargs
217
):
218
"""
219
Initialize the help preview action.
220
221
Args:
222
option_strings: Command line option strings
223
dest: Destination attribute name
224
path: Output file path for preview
225
export_kwds: Additional arguments for rich export
226
**kwargs: Additional arguments passed to parent Action
227
"""
228
```
229
230
#### Usage Examples
231
232
```python
233
import argparse
234
from rich_argparse import RichHelpFormatter, HelpPreviewAction
235
from rich.terminal_theme import DIMMED_MONOKAI
236
237
parser = argparse.ArgumentParser(formatter_class=RichHelpFormatter)
238
239
parser.add_argument(
240
"--generate-preview",
241
action=HelpPreviewAction,
242
path="help-preview.svg",
243
export_kwds={"theme": DIMMED_MONOKAI}
244
)
245
246
# Running with --generate-preview will create help-preview.svg
247
```
248
249
## Style Customization
250
251
### Available Style Keys
252
253
```python { .api }
254
# Style keys for argparse formatters
255
ARGPARSE_STYLE_KEYS = {
256
"argparse.args": "Positional arguments and options (e.g., '--help')",
257
"argparse.groups": "Group names (e.g., 'positional arguments')",
258
"argparse.help": "Argument help text (e.g., 'show this help message and exit')",
259
"argparse.metavar": "Meta variables (e.g., 'FILE' in '--file FILE')",
260
"argparse.prog": "Program name in usage (e.g., 'foo' in 'Usage: foo [options]')",
261
"argparse.syntax": "Highlighted back-tick quoted text (e.g., '`some text`')",
262
"argparse.text": "Descriptions and epilog (e.g., 'A foo program')",
263
"argparse.default": "Default values in help (e.g., 'Value' in '(default: Value)')"
264
}
265
```
266
267
### Highlight Patterns
268
269
```python { .api }
270
# Default highlight regex patterns
271
DEFAULT_HIGHLIGHTS = [
272
r"`(?P<syntax>[^`]*)`|(?:^|\s)(?P<args>-{1,2}[\w]+[\w-]*)"
273
]
274
# Highlights:
275
# - Text in backticks with "argparse.syntax" style
276
# - Command-line options (--option, -o) with "argparse.args" style
277
```
278
279
## Configuration Examples
280
281
### Global Style Customization
282
283
```python
284
from rich_argparse import RichHelpFormatter
285
286
# Customize all instances
287
RichHelpFormatter.styles.update({
288
"argparse.args": "bold cyan",
289
"argparse.groups": "bold yellow",
290
"argparse.help": "dim white",
291
"argparse.metavar": "bold green"
292
})
293
```
294
295
### Per-Instance Customization
296
297
```python
298
import argparse
299
from rich_argparse import RichHelpFormatter
300
301
class CustomFormatter(RichHelpFormatter):
302
styles = {
303
**RichHelpFormatter.styles,
304
"argparse.args": "magenta",
305
"argparse.groups": "blue"
306
}
307
308
parser = argparse.ArgumentParser(formatter_class=CustomFormatter)
309
```
310
311
### Rich Console Integration
312
313
```python
314
import argparse
315
from rich.console import Console
316
from rich_argparse import RichHelpFormatter
317
318
# Use custom console
319
console = Console(width=120, theme=my_theme)
320
321
parser = argparse.ArgumentParser(
322
formatter_class=lambda prog: RichHelpFormatter(
323
prog,
324
console=console
325
)
326
)
327
```