Skip to content

Commit 7ba58d9

Browse files
committed
Added way to update rich-argparse colors using a Rich Theme.
1 parent 55099eb commit 7ba58d9

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

cmd2/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@
5858
)
5959
from .parsing import Statement
6060
from .py_bridge import CommandResult
61-
from .rich_utils import set_default_theme
61+
from .rich_utils import set_theme
6262
from .utils import (
6363
CompletionMode,
6464
CustomCompletionSettings,
@@ -107,7 +107,7 @@
107107
'plugin',
108108
'rich_utils',
109109
# Rich Utils Exports
110-
'set_default_theme',
110+
'set_theme',
111111
# Utilities
112112
'categorize',
113113
'CompletionMode',

cmd2/rich_utils.py

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from rich.console import Console
1212
from rich.style import Style
1313
from rich.theme import Theme
14+
from rich_argparse import RichHelpFormatter
1415

1516
# Default styles for printing strings of various types.
1617
# These can be altered to suit an application's needs and only need to be a
@@ -44,19 +45,29 @@ def __repr__(self) -> str:
4445
# Controls when ANSI style sequences are allowed in output
4546
allow_style = AllowStyle.TERMINAL
4647

48+
# Rich theme used by Cmd2Console
49+
THEME: Optional[Theme] = None
4750

48-
# Default Rich theme used by Cmd2Console
49-
DEFAULT_THEME: Optional[Theme] = None
51+
# Backup of default rich-argparse styles
52+
DEFAULT_RICH_ARGPARSE_STYLES = RichHelpFormatter.styles.copy()
5053

5154

52-
def set_default_theme(theme: Optional[Theme]) -> None:
55+
def set_theme(theme: Optional[Theme]) -> None:
5356
"""
54-
Set the default Rich theme used by Cmd2Console.
57+
Set the Rich theme used by Cmd2Console and rich-argparse.
5558
56-
:param theme: new default theme or None if you want to use Rich's default
59+
:param theme: new theme or None if you want to use Rich and rich-argparse defaults.
5760
"""
58-
global DEFAULT_THEME
59-
DEFAULT_THEME = theme
61+
global THEME
62+
THEME = theme
63+
64+
# Update rich-argparse styles
65+
if theme is None:
66+
RichHelpFormatter.styles = DEFAULT_RICH_ARGPARSE_STYLES.copy()
67+
else:
68+
for name, style in theme.styles.items():
69+
if name in RichHelpFormatter.styles:
70+
RichHelpFormatter.styles[name] = style
6071

6172

6273
class Cmd2Console(Console):
@@ -86,7 +97,7 @@ def __init__(self, file: IO[str]) -> None:
8697
markup=False,
8798
emoji=False,
8899
highlight=False,
89-
theme=DEFAULT_THEME,
100+
theme=THEME,
90101
**kwargs,
91102
)
92103

0 commit comments

Comments
 (0)