From dfedeba916d517ad735ab889bd5569d6d765ad72 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt Date: Fri, 24 Apr 2026 19:17:41 -0400 Subject: [PATCH 1/3] Add styles to theme for completion item and meta foreground and background color This is an attempt to provide higher-contrast color options and to make them configurable as part of a theme. --- CHANGELOG.md | 2 ++ cmd2/cmd2.py | 45 +++++++++++++++++++++++++++++++++++++ cmd2/styles.py | 4 ++++ docs/features/completion.md | 7 ++++++ docs/features/theme.md | 14 ++++++++++++ docs/upgrades.md | 10 +++++++++ 6 files changed, 82 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b5e563151..f4f52e6f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -135,6 +135,8 @@ prompt is displayed. full type hints and IDE autocompletion for `self._cmd` without needing to override and cast the property. - Added `traceback_kwargs` attribute to allow customization of Rich-based tracebacks. + - Added ability to customize `prompt-toolkit` completion menu colors by overriding + `Cmd2Style.COMPLETION_MENU_ITEM` and `Cmd2Style.COMPLETION_MENU_META` in the `cmd2` theme. ## 3.5.1 (April 24, 2026) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index f2ab98944..dba825041 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -78,6 +78,8 @@ from prompt_toolkit.output import DummyOutput, create_output from prompt_toolkit.patch_stdout import patch_stdout from prompt_toolkit.shortcuts import CompleteStyle, PromptSession, choice, set_title +from prompt_toolkit.styles import DynamicStyle +from prompt_toolkit.styles import Style as PtStyle from rich.console import ( Group, JustifyMethod, @@ -714,6 +716,46 @@ def _should_continue_multiline(self) -> bool: # No macro found or already processed. The statement is complete. return False + def _get_pt_style(self) -> "PtStyle": + """Return the prompt_toolkit style for the completion menu.""" + + def to_pt_style(rich_style: Style | None) -> str: + """Convert a rich Style object to a prompt_toolkit style string.""" + if not rich_style: + return "" + parts = ["noreverse"] + if rich_style.color: + c = rich_style.color.get_truecolor() + parts.append(f"fg:#{c.red:02x}{c.green:02x}{c.blue:02x}") + else: + parts.append("fg:default") + + if rich_style.bgcolor: + c = rich_style.bgcolor.get_truecolor() + parts.append(f"bg:#{c.red:02x}{c.green:02x}{c.blue:02x}") + else: + parts.append("bg:default") + + if rich_style.bold is not None: + parts.append("bold" if rich_style.bold else "nobold") + if rich_style.italic is not None: + parts.append("italic" if rich_style.italic else "noitalic") + if rich_style.underline is not None: + parts.append("underline" if rich_style.underline else "nounderline") + return " ".join(parts) + + theme = ru.get_theme() + item_style = to_pt_style(theme.styles.get(Cmd2Style.COMPLETION_MENU_ITEM)) + meta_style = to_pt_style(theme.styles.get(Cmd2Style.COMPLETION_MENU_META)) + + return PtStyle.from_dict( + { + "completion-menu.completion.current": item_style, + "completion-menu.meta.completion.current": meta_style, + "completion-menu.multi-column-meta": meta_style, + } + ) + def _create_main_session(self, auto_suggest: bool, completekey: str) -> PromptSession[str]: """Create and return the main PromptSession for the application. @@ -755,6 +797,7 @@ def _(event: Any) -> None: # pragma: no cover "multiline": filters.Condition(self._should_continue_multiline), "prompt_continuation": self.continuation_prompt, "rprompt": self.get_rprompt, + "style": DynamicStyle(self._get_pt_style), } if self.stdin.isatty() and self.stdout.isatty(): @@ -3578,6 +3621,7 @@ def read_input( key_bindings=self.main_session.key_bindings, input=self.main_session.input, output=self.main_session.output, + style=DynamicStyle(self._get_pt_style), ) return self._read_raw_input(prompt, temp_session) @@ -3596,6 +3640,7 @@ def read_secret( temp_session: PromptSession[str] = PromptSession( input=self.main_session.input, output=self.main_session.output, + style=DynamicStyle(self._get_pt_style), ) return self._read_raw_input(prompt, temp_session, is_password=True) diff --git a/cmd2/styles.py b/cmd2/styles.py index 15489d46e..4d015d30b 100644 --- a/cmd2/styles.py +++ b/cmd2/styles.py @@ -51,6 +51,8 @@ class Cmd2Style(StrEnum): """ COMMAND_LINE = "cmd2.example" # Command line examples in help text + COMPLETION_MENU_ITEM = "cmd2.completion_menu.item" # Selected completion item + COMPLETION_MENU_META = "cmd2.completion_menu.meta" # Selected completion help/meta text ERROR = "cmd2.error" # Error text (used by perror()) HELP_HEADER = "cmd2.help.header" # Help table header text HELP_LEADER = "cmd2.help.leader" # Text right before the help tables are listed @@ -63,6 +65,8 @@ class Cmd2Style(StrEnum): # Tightly coupled with the Cmd2Style enum. DEFAULT_CMD2_STYLES: dict[str, StyleType] = { Cmd2Style.COMMAND_LINE: Style(color=Color.CYAN, bold=True), + Cmd2Style.COMPLETION_MENU_ITEM: Style(color=Color.BLACK, bgcolor=Color.GREEN), + Cmd2Style.COMPLETION_MENU_META: Style(color=Color.BLACK, bgcolor=Color.LIGHT_GREEN), Cmd2Style.ERROR: Style(color=Color.BRIGHT_RED), Cmd2Style.HELP_HEADER: Style(color=Color.BRIGHT_GREEN), Cmd2Style.HELP_LEADER: Style(color=Color.CYAN), diff --git a/docs/features/completion.md b/docs/features/completion.md index 85143650b..1def16f23 100644 --- a/docs/features/completion.md +++ b/docs/features/completion.md @@ -116,6 +116,13 @@ demonstration of how this is used. [read_input](https://github.com/python-cmd2/cmd2/blob/main/examples/read_input.py) example for a demonstration. +## Custom Completion Menu Colors + +`cmd2` provides the ability to customize the foreground and background colors of the completion menu +items and their associated help text. See +[Customizing Completion Menu Colors](./theme.md#customizing-completion-menu-colors) in the Theme +documentation for more details. + ## For More Information See [cmd2's argparse_utils API](../api/argparse_utils.md) for a more detailed discussion of argparse diff --git a/docs/features/theme.md b/docs/features/theme.md index 064178fa7..cd348f061 100644 --- a/docs/features/theme.md +++ b/docs/features/theme.md @@ -6,5 +6,19 @@ information. You can use this to brand your application and set an overall consistent look and feel that is appealing to your user base. +## Customizing Completion Menu Colors + +`cmd2` leverages `prompt-toolkit` for its tab completion menu. You can customize the colors of the +completion menu by overriding the following styles in your `cmd2` theme: + +- `Cmd2Style.COMPLETION_MENU_ITEM`: The background and foreground color of the selected completion + item. +- `Cmd2Style.COMPLETION_MENU_META`: The background and foreground color of the selected completion + item's help/meta text. + +By default, these are styled with black text on a green background to provide contrast. + +## Example + See [rich_theme.py](https://github.com/python-cmd2/cmd2/blob/main/examples/rich_theme.py) for a simple example of configuring a custom theme for your `cmd2` application. diff --git a/docs/upgrades.md b/docs/upgrades.md index a89e248f2..2d10a7a44 100644 --- a/docs/upgrades.md +++ b/docs/upgrades.md @@ -46,6 +46,16 @@ See the example for a demonstration of how to implement a background thread that refreshes the toolbar periodically. +### Custom Completion Menu Colors + +`cmd2` now leverages `prompt-toolkit` for its tab completion menu and provides the ability to +customize its appearance using the `cmd2` theme. + +- **Customization**: Override the `Cmd2Style.COMPLETION_MENU_ITEM` and + `Cmd2Style.COMPLETION_MENU_META` styles using `cmd2.rich_utils.set_theme()`. See + [Customizing Completion Menu Colors](features/theme.md#customizing-completion-menu-colors) for + more details. + ### Deleted Modules Removed `rl_utils.py` and `terminal_utils.py` since `prompt-toolkit` provides this functionality. From 1a73c22b29c454c55924ff2830b02d014e7d2657 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt Date: Sat, 25 Apr 2026 14:54:20 -0400 Subject: [PATCH 2/3] Moved to_pt_style function to pt_utils.py and added unit tests for it Also: - Cache prompt-toolkit completion menu styles for efficiency - Fixed color check bug related to default terminal style --- cmd2/cmd2.py | 45 ++++++++++---------------- cmd2/pt_utils.py | 27 ++++++++++++++++ tests/test_pt_utils.py | 73 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 117 insertions(+), 28 deletions(-) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index dba825041..0ab5ad430 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -192,6 +192,7 @@ def __init__(self, msg: str = "") -> None: Cmd2History, Cmd2Lexer, pt_filter_style, + to_pt_style, ) from .utils import ( Settable, @@ -523,6 +524,10 @@ def __init__( self._persistent_history_length = persistent_history_length self._initialize_history(persistent_history_file) + # Cache for prompt_toolkit completion menu styles + self._cached_pt_style: PtStyle | None = None + self._cached_pt_style_params: tuple[Style | None, Style | None] | None = None + # Create the main PromptSession self.bottom_toolbar = bottom_toolbar self.main_session = self._create_main_session(auto_suggest, completekey) @@ -718,37 +723,19 @@ def _should_continue_multiline(self) -> bool: def _get_pt_style(self) -> "PtStyle": """Return the prompt_toolkit style for the completion menu.""" + theme = ru.get_theme() + rich_item_style = theme.styles.get(Cmd2Style.COMPLETION_MENU_ITEM) + rich_meta_style = theme.styles.get(Cmd2Style.COMPLETION_MENU_META) - def to_pt_style(rich_style: Style | None) -> str: - """Convert a rich Style object to a prompt_toolkit style string.""" - if not rich_style: - return "" - parts = ["noreverse"] - if rich_style.color: - c = rich_style.color.get_truecolor() - parts.append(f"fg:#{c.red:02x}{c.green:02x}{c.blue:02x}") - else: - parts.append("fg:default") - - if rich_style.bgcolor: - c = rich_style.bgcolor.get_truecolor() - parts.append(f"bg:#{c.red:02x}{c.green:02x}{c.blue:02x}") - else: - parts.append("bg:default") - - if rich_style.bold is not None: - parts.append("bold" if rich_style.bold else "nobold") - if rich_style.italic is not None: - parts.append("italic" if rich_style.italic else "noitalic") - if rich_style.underline is not None: - parts.append("underline" if rich_style.underline else "nounderline") - return " ".join(parts) + current_params = (rich_item_style, rich_meta_style) + if self._cached_pt_style is not None and self._cached_pt_style_params == current_params: + return self._cached_pt_style - theme = ru.get_theme() - item_style = to_pt_style(theme.styles.get(Cmd2Style.COMPLETION_MENU_ITEM)) - meta_style = to_pt_style(theme.styles.get(Cmd2Style.COMPLETION_MENU_META)) + item_style = to_pt_style(rich_item_style) + meta_style = to_pt_style(rich_meta_style) - return PtStyle.from_dict( + self._cached_pt_style_params = current_params + self._cached_pt_style = PtStyle.from_dict( { "completion-menu.completion.current": item_style, "completion-menu.meta.completion.current": meta_style, @@ -756,6 +743,8 @@ def to_pt_style(rich_style: Style | None) -> str: } ) + return self._cached_pt_style + def _create_main_session(self, auto_suggest: bool, completekey: str) -> PromptSession[str]: """Create and return the main PromptSession for the application. diff --git a/cmd2/pt_utils.py b/cmd2/pt_utils.py index 8ebdb9f3e..62ffe7f72 100644 --- a/cmd2/pt_utils.py +++ b/cmd2/pt_utils.py @@ -20,6 +20,7 @@ from prompt_toolkit.formatted_text import ANSI from prompt_toolkit.history import History from prompt_toolkit.lexers import Lexer +from rich.style import Style from . import ( constants, @@ -50,6 +51,32 @@ def pt_filter_style(text: str | ANSI) -> str | ANSI: return text if isinstance(text, ANSI) else ANSI(text) +def to_pt_style(rich_style: Style | None) -> str: + """Convert a rich Style object to a prompt_toolkit style string.""" + if not rich_style: + return "" + parts = ["noreverse"] + if rich_style.color and not rich_style.color.is_default: + c = rich_style.color.get_truecolor() + parts.append(f"fg:#{c.red:02x}{c.green:02x}{c.blue:02x}") + else: + parts.append("fg:default") + + if rich_style.bgcolor and not rich_style.bgcolor.is_default: + c = rich_style.bgcolor.get_truecolor() + parts.append(f"bg:#{c.red:02x}{c.green:02x}{c.blue:02x}") + else: + parts.append("bg:default") + + if rich_style.bold is not None: + parts.append("bold" if rich_style.bold else "nobold") + if rich_style.italic is not None: + parts.append("italic" if rich_style.italic else "noitalic") + if rich_style.underline is not None: + parts.append("underline" if rich_style.underline else "nounderline") + return " ".join(parts) + + class Cmd2Completer(Completer): """Completer that delegates to cmd2's completion logic.""" diff --git a/tests/test_pt_utils.py b/tests/test_pt_utils.py index 146ab81c8..54ffe5957 100644 --- a/tests/test_pt_utils.py +++ b/tests/test_pt_utils.py @@ -624,3 +624,76 @@ def test_clear(self): history.clear() assert not history.get_strings() + + +class TestToPtStyle: + def test_to_pt_style_none(self): + assert pt_utils.to_pt_style(None) == "" + + def test_to_pt_style_color(self): + from rich.style import Style + + style = Style(color="#123456") + pt_style = pt_utils.to_pt_style(style) + assert "fg:#123456" in pt_style + assert "bg:default" in pt_style + assert "noreverse" in pt_style + + def test_to_pt_style_bgcolor(self): + from rich.style import Style + + style = Style(bgcolor="#654321") + pt_style = pt_utils.to_pt_style(style) + assert "fg:default" in pt_style + assert "bg:#654321" in pt_style + + def test_to_pt_style_default_color(self): + from rich.style import Style + + style = Style(color="default", bgcolor="default") + pt_style = pt_utils.to_pt_style(style) + assert "fg:default" in pt_style + assert "bg:default" in pt_style + + def test_to_pt_style_bold(self): + from rich.style import Style + + style = Style(bold=True) + pt_style = pt_utils.to_pt_style(style) + assert "bold" in pt_style + assert "nobold" not in pt_style + + def test_to_pt_style_nobold(self): + from rich.style import Style + + style = Style(bold=False) + pt_style = pt_utils.to_pt_style(style) + assert "nobold" in pt_style + + def test_to_pt_style_italic(self): + from rich.style import Style + + style = Style(italic=True) + pt_style = pt_utils.to_pt_style(style) + assert "italic" in pt_style + + def test_to_pt_style_noitalic(self): + from rich.style import Style + + style = Style(italic=False) + pt_style = pt_utils.to_pt_style(style) + assert "noitalic" in pt_style + + def test_to_pt_style_underline(self): + from rich.style import Style + + style = Style(underline=True) + pt_style = pt_utils.to_pt_style(style) + assert "underline" in pt_style + + def test_to_pt_style_nounderline(self): + from rich.style import Style + + style = Style(underline=False) + pt_style = pt_utils.to_pt_style(style) + assert "nounderline" in pt_style From 0b5e443ee2cf4cefc53ef039c348cffd6d83d137 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt Date: Sat, 25 Apr 2026 15:07:21 -0400 Subject: [PATCH 3/3] Add a unit test for _get_pt_style method --- tests/test_cmd2.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py index d8093eed1..7ff54ec27 100644 --- a/tests/test_cmd2.py +++ b/tests/test_cmd2.py @@ -1889,6 +1889,48 @@ def do_orate(self, opts, arg) -> None: self.stdout.write(arg + "\n") +def test_get_pt_style_caching(base_app) -> None: + # Get the initial style (populates the cache) + style1 = base_app._get_pt_style() + + # Getting it again should return the exact same object from the cache + style2 = base_app._get_pt_style() + assert style1 is style2 + + # Change the theme which should invalidate the cache + from rich.style import Style + + import cmd2.rich_utils as ru + from cmd2.styles import Cmd2Style + + # Save the original theme to restore later + orig_theme = ru.get_theme() + + try: + ru.set_theme({Cmd2Style.COMPLETION_MENU_ITEM: Style(color="red")}) + + # Getting the style now should return a new object + style3 = base_app._get_pt_style() + assert style3 is not style1 + + # Getting it again should return the new cached object + style4 = base_app._get_pt_style() + assert style4 is style3 + + # Verify the style reflects the change + # In prompt_toolkit 3, styles are accessed differently + attrs = style3.class_names_and_attrs + found = False + for classes, attr in attrs: + if "completion-menu.completion.current" in classes and attr.color in ("800000", "darkred", "ff0000", "#800000"): + found = True + break + assert found, "Color change not found in cached style" + + finally: + ru._APP_THEME = orig_theme + + @pytest.fixture def multiline_app(): return MultilineApp()