Metavariable Separator Formatting
To customize the appearance of brackets ([], <>), pipes (|), and ellipsis (...) in command usage strings, you can modify the STYLE_METAVAR_SEPARATOR configuration in the typer.rich_utils module.
Customizing Separator Styles
You can change the style of metavariable separators globally by updating the STYLE_METAVAR_SEPARATOR variable. This style is applied by the MetavarHighlighter class whenever Typer renders help panels.
from typer import rich_utils
# Change separators to be bold and red instead of the default 'dim'
rich_utils.STYLE_METAVAR_SEPARATOR = "bold red"
rich_utils.STYLE_METAVAR = "green"
How Metavariable Highlighting Works
The MetavarHighlighter class (found in typer/rich_utils.py) uses regular expressions to identify and style specific characters within a metavariable string. It targets the metavar_sep group, which is mapped to the STYLE_METAVAR_SEPARATOR in the Rich theme.
The highlighter specifically looks for:
- Opening brackets or angle brackets at the start of the string:
^(\[|<) - Pipe characters used for alternatives:
\| - Closing brackets or angle brackets at the end of the string, optionally followed by an ellipsis:
(\]|>)(\.\.\.)?$
# From typer/rich_utils.py
class MetavarHighlighter(RegexHighlighter):
highlights = [
r"^(?P<metavar_sep>(\[|<))",
r"(?P<metavar_sep>\|)",
r"(?P<metavar_sep>(\]|>))(\.\.\.)?$",
]
Testing Highlighting Behavior
You can verify how the highlighter processes specific strings by using the metavar_highlighter instance directly. This is useful for debugging custom metavariables.
from rich.text import Text
from typer.rich_utils import metavar_highlighter, STYLE_METAVAR_SEPARATOR, _get_rich_console
def check_highlighting(input_text: str):
console = _get_rich_console()
text = Text(input_text)
highlighted = metavar_highlighter(text)
# Check if the first character (e.g., '[') received the separator style
style = highlighted.get_style_at_offset(console, 0)
print(f"Text: {input_text} | Start Style: {style}")
check_highlighting("[OPTIONS]")
check_highlighting("<name>")
check_highlighting("[ARGS]...")
Troubleshooting Regex Constraints
The MetavarHighlighter is designed with strict anchor constraints to avoid mis-highlighting content inside the metavariable.
- Ellipsis Positioning: The ellipsis (
...) is only highlighted if it immediately follows a closing bracket at the very end of the string. A string like[ARGS...]will not have the ellipsis styled as a separator because the...is inside the bracket. - Nested Brackets: The regex expects the separators at the boundaries. If you use complex nested metavariables like
[[VAL]], only the outermost brackets are guaranteed to be styled as separators by the default patterns. - Pipes: Unlike brackets, pipes (
|) are highlighted anywhere they appear in the string, making them ideal for separating choices (e.g.,[RED|GREEN|BLUE]).