Skip to content

Commit

Permalink
Added way to update rich-argparse colors using a Rich Theme.
Browse files Browse the repository at this point in the history
  • Loading branch information
kmvanbrunt committed Dec 31, 2024
1 parent 55099eb commit 7ba58d9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
4 changes: 2 additions & 2 deletions cmd2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
)
from .parsing import Statement
from .py_bridge import CommandResult
from .rich_utils import set_default_theme
from .rich_utils import set_theme
from .utils import (
CompletionMode,
CustomCompletionSettings,
Expand Down Expand Up @@ -107,7 +107,7 @@
'plugin',
'rich_utils',
# Rich Utils Exports
'set_default_theme',
'set_theme',
# Utilities
'categorize',
'CompletionMode',
Expand Down
27 changes: 19 additions & 8 deletions cmd2/rich_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from rich.console import Console
from rich.style import Style
from rich.theme import Theme
from rich_argparse import RichHelpFormatter

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

# Rich theme used by Cmd2Console
THEME: Optional[Theme] = None

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


def set_default_theme(theme: Optional[Theme]) -> None:
def set_theme(theme: Optional[Theme]) -> None:
"""
Set the default Rich theme used by Cmd2Console.
Set the Rich theme used by Cmd2Console and rich-argparse.
:param theme: new default theme or None if you want to use Rich's default
:param theme: new theme or None if you want to use Rich and rich-argparse defaults.
"""
global DEFAULT_THEME
DEFAULT_THEME = theme
global THEME
THEME = theme

# Update rich-argparse styles
if theme is None:
RichHelpFormatter.styles = DEFAULT_RICH_ARGPARSE_STYLES.copy()
else:
for name, style in theme.styles.items():
if name in RichHelpFormatter.styles:
RichHelpFormatter.styles[name] = style


class Cmd2Console(Console):
Expand Down Expand Up @@ -86,7 +97,7 @@ def __init__(self, file: IO[str]) -> None:
markup=False,
emoji=False,
highlight=False,
theme=DEFAULT_THEME,
theme=THEME,
**kwargs,
)

Expand Down

0 comments on commit 7ba58d9

Please sign in to comment.