Skip to content

# cmd2.rich_utils

## `` cmd2.rich_utils

Provides common utilities to support Rich in cmd2-based applications.

### `` ANSI_STYLE_SEQUENCE_RE `module-attribute`

    ANSI_STYLE_SEQUENCE_RE = compile('\\x1b\\[[0-9;]*m')

### `` HelpContent `module-attribute`

    HelpContent = RenderableType | HelpFormatterRenderable

### `` ALLOW_STYLE `module-attribute`

    ALLOW_STYLE = TERMINAL

### `` HelpFormatterRenderable

Bases: `Protocol`

Protocol for objects that require a Cmd2HelpFormatter to render.

### `` AllowStyle

Bases: `Enum`

Values for `cmd2.rich_utils.ALLOW_STYLE`.

#### `` ALWAYS `class-attribute` `instance-attribute`

    ALWAYS = 'Always'

#### `` NEVER `class-attribute` `instance-attribute`

    NEVER = 'Never'

#### `` TERMINAL `class-attribute` `instance-attribute`

    TERMINAL = 'Terminal'

### `` Cmd2HelpFormatter

    Cmd2HelpFormatter(prog, indent_increment=2, max_help_position=24, width=None, *, file=None, console=None, **kwargs)

Bases: `RichHelpFormatter`

Custom help formatter to configure ordering of help text.

Initialize Cmd2HelpFormatter.

Source code in `cmd2/rich_utils.py`

    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149

    def __init__(
        self,
        prog: str,
        indent_increment: int = 2,
        max_help_position: int = 24,
        width: int | None = None,
        *,
        file: IO[str] | None = None,
        console: "Cmd2RichArgparseConsole | None" = None,
        **kwargs: Any,
    ) -> None:
        """Initialize Cmd2HelpFormatter."""
        if file is not None and console is not None:
            raise TypeError("cannot provide both 'file' and 'console' arguments")

        self._file = file
        super().__init__(prog, indent_increment, max_help_position, width, console=console, **kwargs)

        # Recast to assist type checkers
        self._console: Cmd2RichArgparseConsole | None

#### `` styles `class-attribute`

    styles = copy()

#### `` highlights `class-attribute`

    highlights = []

#### `` usage_markup `class-attribute`

    usage_markup = False

#### `` help_markup `class-attribute`

    help_markup = False

#### `` text_markup `class-attribute`

    text_markup = False

#### `` console `property` `writable`

    console

Return our console instance.

#### `` add_text

    add_text(text)

Override to support HelpFormatterRenderable objects.

Source code in `cmd2/rich_utils.py`

    164
    165
    166
    167
    168

    def add_text(self, text: Any) -> None:
        """Override to support HelpFormatterRenderable objects."""
        if isinstance(text, HelpFormatterRenderable):
            text = text.__cmd2_argparse_help__(self)
        super().add_text(text)

### `` RawDescriptionCmd2HelpFormatter

    RawDescriptionCmd2HelpFormatter(prog, indent_increment=2, max_help_position=24, width=None, *, file=None, console=None, **kwargs)

Bases: `RawDescriptionRichHelpFormatter`, `Cmd2HelpFormatter`

Cmd2 help message formatter which retains any formatting in descriptions and epilogs.

Initialize Cmd2HelpFormatter.

Source code in `cmd2/rich_utils.py`

    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149

    def __init__(
        self,
        prog: str,
        indent_increment: int = 2,
        max_help_position: int = 24,
        width: int | None = None,
        *,
        file: IO[str] | None = None,
        console: "Cmd2RichArgparseConsole | None" = None,
        **kwargs: Any,
    ) -> None:
        """Initialize Cmd2HelpFormatter."""
        if file is not None and console is not None:
            raise TypeError("cannot provide both 'file' and 'console' arguments")

        self._file = file
        super().__init__(prog, indent_increment, max_help_position, width, console=console, **kwargs)

        # Recast to assist type checkers
        self._console: Cmd2RichArgparseConsole | None

#### `` styles `class-attribute`

    styles = copy()

#### `` highlights `class-attribute`

    highlights = []

#### `` usage_markup `class-attribute`

    usage_markup = False

#### `` help_markup `class-attribute`

    help_markup = False

#### `` text_markup `class-attribute`

    text_markup = False

#### `` console `property` `writable`

    console

Return our console instance.

#### `` add_text

    add_text(text)

Override to support HelpFormatterRenderable objects.

Source code in `cmd2/rich_utils.py`

    164
    165
    166
    167
    168

    def add_text(self, text: Any) -> None:
        """Override to support HelpFormatterRenderable objects."""
        if isinstance(text, HelpFormatterRenderable):
            text = text.__cmd2_argparse_help__(self)
        super().add_text(text)

### `` RawTextCmd2HelpFormatter

    RawTextCmd2HelpFormatter(prog, indent_increment=2, max_help_position=24, width=None, *, file=None, console=None, **kwargs)

Bases: `RawTextRichHelpFormatter`, `Cmd2HelpFormatter`

Cmd2 help message formatter which retains formatting of all help text.

Initialize Cmd2HelpFormatter.

Source code in `cmd2/rich_utils.py`

    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149

    def __init__(
        self,
        prog: str,
        indent_increment: int = 2,
        max_help_position: int = 24,
        width: int | None = None,
        *,
        file: IO[str] | None = None,
        console: "Cmd2RichArgparseConsole | None" = None,
        **kwargs: Any,
    ) -> None:
        """Initialize Cmd2HelpFormatter."""
        if file is not None and console is not None:
            raise TypeError("cannot provide both 'file' and 'console' arguments")

        self._file = file
        super().__init__(prog, indent_increment, max_help_position, width, console=console, **kwargs)

        # Recast to assist type checkers
        self._console: Cmd2RichArgparseConsole | None

#### `` styles `class-attribute`

    styles = copy()

#### `` highlights `class-attribute`

    highlights = []

#### `` usage_markup `class-attribute`

    usage_markup = False

#### `` help_markup `class-attribute`

    help_markup = False

#### `` text_markup `class-attribute`

    text_markup = False

#### `` console `property` `writable`

    console

Return our console instance.

#### `` add_text

    add_text(text)

Override to support HelpFormatterRenderable objects.

Source code in `cmd2/rich_utils.py`

    164
    165
    166
    167
    168

    def add_text(self, text: Any) -> None:
        """Override to support HelpFormatterRenderable objects."""
        if isinstance(text, HelpFormatterRenderable):
            text = text.__cmd2_argparse_help__(self)
        super().add_text(text)

### `` ArgumentDefaultsCmd2HelpFormatter

    ArgumentDefaultsCmd2HelpFormatter(prog, indent_increment=2, max_help_position=24, width=None, *, file=None, console=None, **kwargs)

Bases: `ArgumentDefaultsRichHelpFormatter`, `Cmd2HelpFormatter`

Cmd2 help message formatter which adds default values to argument help.

Initialize Cmd2HelpFormatter.

Source code in `cmd2/rich_utils.py`

    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149

    def __init__(
        self,
        prog: str,
        indent_increment: int = 2,
        max_help_position: int = 24,
        width: int | None = None,
        *,
        file: IO[str] | None = None,
        console: "Cmd2RichArgparseConsole | None" = None,
        **kwargs: Any,
    ) -> None:
        """Initialize Cmd2HelpFormatter."""
        if file is not None and console is not None:
            raise TypeError("cannot provide both 'file' and 'console' arguments")

        self._file = file
        super().__init__(prog, indent_increment, max_help_position, width, console=console, **kwargs)

        # Recast to assist type checkers
        self._console: Cmd2RichArgparseConsole | None

#### `` styles `class-attribute`

    styles = copy()

#### `` highlights `class-attribute`

    highlights = []

#### `` usage_markup `class-attribute`

    usage_markup = False

#### `` help_markup `class-attribute`

    help_markup = False

#### `` text_markup `class-attribute`

    text_markup = False

#### `` console `property` `writable`

    console

Return our console instance.

#### `` add_text

    add_text(text)

Override to support HelpFormatterRenderable objects.

Source code in `cmd2/rich_utils.py`

    164
    165
    166
    167
    168

    def add_text(self, text: Any) -> None:
        """Override to support HelpFormatterRenderable objects."""
        if isinstance(text, HelpFormatterRenderable):
            text = text.__cmd2_argparse_help__(self)
        super().add_text(text)

### `` MetavarTypeCmd2HelpFormatter

    MetavarTypeCmd2HelpFormatter(prog, indent_increment=2, max_help_position=24, width=None, *, file=None, console=None, **kwargs)

Bases: `MetavarTypeRichHelpFormatter`, `Cmd2HelpFormatter`

Cmd2 help message formatter which uses the argument 'type' as the default metavar value (instead of the argument 'dest').

Initialize Cmd2HelpFormatter.

Source code in `cmd2/rich_utils.py`

    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149

    def __init__(
        self,
        prog: str,
        indent_increment: int = 2,
        max_help_position: int = 24,
        width: int | None = None,
        *,
        file: IO[str] | None = None,
        console: "Cmd2RichArgparseConsole | None" = None,
        **kwargs: Any,
    ) -> None:
        """Initialize Cmd2HelpFormatter."""
        if file is not None and console is not None:
            raise TypeError("cannot provide both 'file' and 'console' arguments")

        self._file = file
        super().__init__(prog, indent_increment, max_help_position, width, console=console, **kwargs)

        # Recast to assist type checkers
        self._console: Cmd2RichArgparseConsole | None

#### `` styles `class-attribute`

    styles = copy()

#### `` highlights `class-attribute`

    highlights = []

#### `` usage_markup `class-attribute`

    usage_markup = False

#### `` help_markup `class-attribute`

    help_markup = False

#### `` text_markup `class-attribute`

    text_markup = False

#### `` console `property` `writable`

    console

Return our console instance.

#### `` add_text

    add_text(text)

Override to support HelpFormatterRenderable objects.

Source code in `cmd2/rich_utils.py`

    164
    165
    166
    167
    168

    def add_text(self, text: Any) -> None:
        """Override to support HelpFormatterRenderable objects."""
        if isinstance(text, HelpFormatterRenderable):
            text = text.__cmd2_argparse_help__(self)
        super().add_text(text)

### `` TextGroup

    TextGroup(title, text)

A block of text which is formatted like an argparse argument group, including a title.

Title: Here is the first row of text. Here is yet another row of text.

TextGroup initializer.

PARAMETER | DESCRIPTION
--- | ---
`title` | the group's title TYPE: `str`
`text` | the group's text (string or object that may be rendered by Rich) TYPE: `RenderableType`

Source code in `cmd2/rich_utils.py`

    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297

    def __init__(
        self,
        title: str,
        text: RenderableType,
    ) -> None:
        """TextGroup initializer.

        :param title: the group's title
        :param text: the group's text (string or object that may be rendered by Rich)
        """
        self.title = title
        self.text = text

#### `` title `instance-attribute`

    title = title

#### `` text `instance-attribute`

    text = text

### `` Cmd2BaseConsole

    Cmd2BaseConsole(*, file=None, **kwargs)

Bases: `Console`

Base class for all cmd2 Rich consoles.

This class handles the core logic for managing Rich behavior based on cmd2's global settings, such as ALLOW_STYLE and the application theme.

Cmd2BaseConsole initializer.

PARAMETER | DESCRIPTION
--- | ---
`file` | optional file object where the console should write to. Defaults to sys.stdout. TYPE: `IO[str] | None` DEFAULT: `None`
`kwargs` | keyword arguments passed to the parent Console class. TYPE: `Any` DEFAULT: `{}`

RAISES | DESCRIPTION
--- | ---
`TypeError` | if disallowed keyword argument is passed in.

Source code in `cmd2/rich_utils.py`

    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380

    def __init__(
        self,
        *,
        file: IO[str] | None = None,
        **kwargs: Any,
    ) -> None:
        """Cmd2BaseConsole initializer.

        :param file: optional file object where the console should write to.
                     Defaults to sys.stdout.
        :param kwargs: keyword arguments passed to the parent Console class.
        :raises TypeError: if disallowed keyword argument is passed in.
        """
        # These settings are controlled by the ALLOW_STYLE setting and cannot be overridden.
        if "color_system" in kwargs:
            raise TypeError("Passing 'color_system' is not allowed. Its behavior is controlled by the 'ALLOW_STYLE' setting.")
        if "force_terminal" in kwargs:
            raise TypeError(
                "Passing 'force_terminal' is not allowed. Its behavior is controlled by the 'ALLOW_STYLE' setting."
            )
        if "force_interactive" in kwargs:
            raise TypeError(
                "Passing 'force_interactive' is not allowed. Its behavior is controlled by the 'ALLOW_STYLE' setting."
            )

        # Don't allow a theme to be passed in. Use update_theme() to modify the global theme
        # or use a temporary theme with console.use_theme().
        if "theme" in kwargs:
            raise TypeError("Passing 'theme' is not allowed. Modify the global theme with update_theme().")

        # Store the configuration key used by cmd2 to cache this console.
        self._config_key = self._build_config_key(file=file, **kwargs)

        force_terminal: bool | None = None
        force_interactive: bool | None = None
        allow_style = False

        if ALLOW_STYLE == AllowStyle.ALWAYS:
            force_terminal = True
            allow_style = True

            # Turn off interactive mode if dest is not a terminal which supports it.
            tmp_console = Console(file=file)
            force_interactive = tmp_console.is_interactive
        elif ALLOW_STYLE == AllowStyle.TERMINAL:
            tmp_console = Console(file=file)
            allow_style = tmp_console.is_terminal
        elif ALLOW_STYLE == AllowStyle.NEVER:
            force_terminal = False

        super().__init__(
            file=file,
            color_system="truecolor" if allow_style else None,
            force_terminal=force_terminal,
            force_interactive=force_interactive,
            theme=_get_theme(),
            **kwargs,
        )

#### `` matches_config

    matches_config(*, file, **kwargs)

Check if this console instance was initialized with the specified settings.

PARAMETER | DESCRIPTION
--- | ---
`file` | file stream being checked TYPE: `IO[str] | None`
`kwargs` | other console settings being checked TYPE: `Any` DEFAULT: `{}`

RETURNS | DESCRIPTION
--- | ---
`bool` | True if the settings match this console's configuration

Source code in `cmd2/rich_utils.py`

    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415

    def matches_config(
        self,
        *,
        file: IO[str] | None,
        **kwargs: Any,
    ) -> bool:
        """Check if this console instance was initialized with the specified settings.

        :param file: file stream being checked
        :param kwargs: other console settings being checked
        :return: True if the settings match this console's configuration
        """
        return self._config_key == self._build_config_key(file=file, **kwargs)

#### `` on_broken_pipe

    on_broken_pipe()

Override which raises BrokenPipeError instead of SystemExit.

Source code in `cmd2/rich_utils.py`

    417
    418
    419
    420

    def on_broken_pipe(self) -> None:
        """Override which raises BrokenPipeError instead of SystemExit."""
        self.quiet = True
        raise BrokenPipeError

#### `` print

    print(*objects, sep=' ', end='\n', style=None, justify=None, overflow=None, no_wrap=None, emoji=None, markup=None, highlight=None, width=None, height=None, crop=True, soft_wrap=None, new_line_start=False)

Override to support ANSI sequences.

This method calls cmd2.rich_utils.prepare_objects_for_rendering on the objects being printed. This ensures that strings containing ANSI style sequences are converted to Rich Text objects, so that Rich can correctly calculate their display width.

Source code in `cmd2/rich_utils.py`

    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465

    def print(
        self,
        *objects: Any,
        sep: str = " ",
        end: str = "\n",
        style: StyleType | None = None,
        justify: JustifyMethod | None = None,
        overflow: OverflowMethod | None = None,
        no_wrap: bool | None = None,
        emoji: bool | None = None,
        markup: bool | None = None,
        highlight: bool | None = None,
        width: int | None = None,
        height: int | None = None,
        crop: bool = True,
        soft_wrap: bool | None = None,
        new_line_start: bool = False,
    ) -> None:
        """Override to support ANSI sequences.

        This method calls [cmd2.rich_utils.prepare_objects_for_rendering][] on the
        objects being printed. This ensures that strings containing ANSI style
        sequences are converted to Rich Text objects, so that Rich can correctly
        calculate their display width.
        """
        prepared_objects = prepare_objects_for_rendering(*objects)

        super().print(
            *prepared_objects,
            sep=sep,
            end=end,
            style=style,
            justify=justify,
            overflow=overflow,
            no_wrap=no_wrap,
            emoji=emoji,
            markup=markup,
            highlight=highlight,
            width=width,
            height=height,
            crop=crop,
            soft_wrap=soft_wrap,
            new_line_start=new_line_start,
        )

#### `` log

    log(*objects, sep=' ', end='\n', style=None, justify=None, emoji=None, markup=None, highlight=None, log_locals=False, _stack_offset=1)

Override to support ANSI sequences.

This method calls cmd2.rich_utils.prepare_objects_for_rendering on the objects being logged. This ensures that strings containing ANSI style sequences are converted to Rich Text objects, so that Rich can correctly calculate their display width.

Source code in `cmd2/rich_utils.py`

    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501

    def log(
        self,
        *objects: Any,
        sep: str = " ",
        end: str = "\n",
        style: StyleType | None = None,
        justify: JustifyMethod | None = None,
        emoji: bool | None = None,
        markup: bool | None = None,
        highlight: bool | None = None,
        log_locals: bool = False,
        _stack_offset: int = 1,
    ) -> None:
        """Override to support ANSI sequences.

        This method calls [cmd2.rich_utils.prepare_objects_for_rendering][] on the
        objects being logged. This ensures that strings containing ANSI style
        sequences are converted to Rich Text objects, so that Rich can correctly
        calculate their display width.
        """
        prepared_objects = prepare_objects_for_rendering(*objects)

        # Increment _stack_offset because we added this wrapper frame
        super().log(
            *prepared_objects,
            sep=sep,
            end=end,
            style=style,
            justify=justify,
            emoji=emoji,
            markup=markup,
            highlight=highlight,
            log_locals=log_locals,
            _stack_offset=_stack_offset + 1,
        )

### `` Cmd2GeneralConsole

    Cmd2GeneralConsole(*, file=None)

Bases: `Cmd2BaseConsole`

Rich console for general-purpose printing.

It enables soft wrap and disables Rich's automatic detection for markup, emoji, and highlighting.

Cmd2GeneralConsole initializer.

PARAMETER | DESCRIPTION
--- | ---
`file` | optional file object where the console should write to. Defaults to sys.stdout. TYPE: `IO[str] | None` DEFAULT: `None`

Source code in `cmd2/rich_utils.py`

    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523

    def __init__(self, *, file: IO[str] | None = None) -> None:
        """Cmd2GeneralConsole initializer.

        :param file: optional file object where the console should write to.
                     Defaults to sys.stdout.
        """
        super().__init__(
            file=file,
            soft_wrap=True,
            markup=False,
            emoji=False,
            highlight=False,
        )

#### `` matches_config

    matches_config(*, file, **kwargs)

Check if this console instance was initialized with the specified settings.

PARAMETER | DESCRIPTION
--- | ---
`file` | file stream being checked TYPE: `IO[str] | None`
`kwargs` | other console settings being checked TYPE: `Any` DEFAULT: `{}`

RETURNS | DESCRIPTION
--- | ---
`bool` | True if the settings match this console's configuration

Source code in `cmd2/rich_utils.py`

    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415

    def matches_config(
        self,
        *,
        file: IO[str] | None,
        **kwargs: Any,
    ) -> bool:
        """Check if this console instance was initialized with the specified settings.

        :param file: file stream being checked
        :param kwargs: other console settings being checked
        :return: True if the settings match this console's configuration
        """
        return self._config_key == self._build_config_key(file=file, **kwargs)

#### `` on_broken_pipe

    on_broken_pipe()

Override which raises BrokenPipeError instead of SystemExit.

Source code in `cmd2/rich_utils.py`

    417
    418
    419
    420

    def on_broken_pipe(self) -> None:
        """Override which raises BrokenPipeError instead of SystemExit."""
        self.quiet = True
        raise BrokenPipeError

#### `` print

    print(*objects, sep=' ', end='\n', style=None, justify=None, overflow=None, no_wrap=None, emoji=None, markup=None, highlight=None, width=None, height=None, crop=True, soft_wrap=None, new_line_start=False)

Override to support ANSI sequences.

This method calls cmd2.rich_utils.prepare_objects_for_rendering on the objects being printed. This ensures that strings containing ANSI style sequences are converted to Rich Text objects, so that Rich can correctly calculate their display width.

Source code in `cmd2/rich_utils.py`

    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465

    def print(
        self,
        *objects: Any,
        sep: str = " ",
        end: str = "\n",
        style: StyleType | None = None,
        justify: JustifyMethod | None = None,
        overflow: OverflowMethod | None = None,
        no_wrap: bool | None = None,
        emoji: bool | None = None,
        markup: bool | None = None,
        highlight: bool | None = None,
        width: int | None = None,
        height: int | None = None,
        crop: bool = True,
        soft_wrap: bool | None = None,
        new_line_start: bool = False,
    ) -> None:
        """Override to support ANSI sequences.

        This method calls [cmd2.rich_utils.prepare_objects_for_rendering][] on the
        objects being printed. This ensures that strings containing ANSI style
        sequences are converted to Rich Text objects, so that Rich can correctly
        calculate their display width.
        """
        prepared_objects = prepare_objects_for_rendering(*objects)

        super().print(
            *prepared_objects,
            sep=sep,
            end=end,
            style=style,
            justify=justify,
            overflow=overflow,
            no_wrap=no_wrap,
            emoji=emoji,
            markup=markup,
            highlight=highlight,
            width=width,
            height=height,
            crop=crop,
            soft_wrap=soft_wrap,
            new_line_start=new_line_start,
        )

#### `` log

    log(*objects, sep=' ', end='\n', style=None, justify=None, emoji=None, markup=None, highlight=None, log_locals=False, _stack_offset=1)

Override to support ANSI sequences.

This method calls cmd2.rich_utils.prepare_objects_for_rendering on the objects being logged. This ensures that strings containing ANSI style sequences are converted to Rich Text objects, so that Rich can correctly calculate their display width.

Source code in `cmd2/rich_utils.py`

    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501

    def log(
        self,
        *objects: Any,
        sep: str = " ",
        end: str = "\n",
        style: StyleType | None = None,
        justify: JustifyMethod | None = None,
        emoji: bool | None = None,
        markup: bool | None = None,
        highlight: bool | None = None,
        log_locals: bool = False,
        _stack_offset: int = 1,
    ) -> None:
        """Override to support ANSI sequences.

        This method calls [cmd2.rich_utils.prepare_objects_for_rendering][] on the
        objects being logged. This ensures that strings containing ANSI style
        sequences are converted to Rich Text objects, so that Rich can correctly
        calculate their display width.
        """
        prepared_objects = prepare_objects_for_rendering(*objects)

        # Increment _stack_offset because we added this wrapper frame
        super().log(
            *prepared_objects,
            sep=sep,
            end=end,
            style=style,
            justify=justify,
            emoji=emoji,
            markup=markup,
            highlight=highlight,
            log_locals=log_locals,
            _stack_offset=_stack_offset + 1,
        )

### `` Cmd2RichArgparseConsole

    Cmd2RichArgparseConsole(*, file=None)

Bases: `Cmd2BaseConsole`

Rich console for rich-argparse output.

Ensures long lines in help text are not truncated by disabling soft_wrap, which conflicts with rich-argparse's explicit no_wrap and overflow settings.

Since this console is used to print error messages which may not be intended for Rich formatting, it disables Rich's automatic detection for markup, emoji, and highlighting. Because rich-argparse does markup and highlighting without involving the console, disabling these settings does not affect the library's internal functionality.

Cmd2RichArgparseConsole initializer.

PARAMETER | DESCRIPTION
--- | ---
`file` | optional file object where the console should write to. Defaults to sys.stdout. TYPE: `IO[str] | None` DEFAULT: `None`

Source code in `cmd2/rich_utils.py`

    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551

    def __init__(self, *, file: IO[str] | None = None) -> None:
        """Cmd2RichArgparseConsole initializer.

        :param file: optional file object where the console should write to.
                     Defaults to sys.stdout.
        """
        super().__init__(
            file=file,
            soft_wrap=False,
            markup=False,
            emoji=False,
            highlight=False,
        )

#### `` matches_config

    matches_config(*, file, **kwargs)

Check if this console instance was initialized with the specified settings.

PARAMETER | DESCRIPTION
--- | ---
`file` | file stream being checked TYPE: `IO[str] | None`
`kwargs` | other console settings being checked TYPE: `Any` DEFAULT: `{}`

RETURNS | DESCRIPTION
--- | ---
`bool` | True if the settings match this console's configuration

Source code in `cmd2/rich_utils.py`

    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415

    def matches_config(
        self,
        *,
        file: IO[str] | None,
        **kwargs: Any,
    ) -> bool:
        """Check if this console instance was initialized with the specified settings.

        :param file: file stream being checked
        :param kwargs: other console settings being checked
        :return: True if the settings match this console's configuration
        """
        return self._config_key == self._build_config_key(file=file, **kwargs)

#### `` on_broken_pipe

    on_broken_pipe()

Override which raises BrokenPipeError instead of SystemExit.

Source code in `cmd2/rich_utils.py`

    417
    418
    419
    420

    def on_broken_pipe(self) -> None:
        """Override which raises BrokenPipeError instead of SystemExit."""
        self.quiet = True
        raise BrokenPipeError

#### `` print

    print(*objects, sep=' ', end='\n', style=None, justify=None, overflow=None, no_wrap=None, emoji=None, markup=None, highlight=None, width=None, height=None, crop=True, soft_wrap=None, new_line_start=False)

Override to support ANSI sequences.

This method calls cmd2.rich_utils.prepare_objects_for_rendering on the objects being printed. This ensures that strings containing ANSI style sequences are converted to Rich Text objects, so that Rich can correctly calculate their display width.

Source code in `cmd2/rich_utils.py`

    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465

    def print(
        self,
        *objects: Any,
        sep: str = " ",
        end: str = "\n",
        style: StyleType | None = None,
        justify: JustifyMethod | None = None,
        overflow: OverflowMethod | None = None,
        no_wrap: bool | None = None,
        emoji: bool | None = None,
        markup: bool | None = None,
        highlight: bool | None = None,
        width: int | None = None,
        height: int | None = None,
        crop: bool = True,
        soft_wrap: bool | None = None,
        new_line_start: bool = False,
    ) -> None:
        """Override to support ANSI sequences.

        This method calls [cmd2.rich_utils.prepare_objects_for_rendering][] on the
        objects being printed. This ensures that strings containing ANSI style
        sequences are converted to Rich Text objects, so that Rich can correctly
        calculate their display width.
        """
        prepared_objects = prepare_objects_for_rendering(*objects)

        super().print(
            *prepared_objects,
            sep=sep,
            end=end,
            style=style,
            justify=justify,
            overflow=overflow,
            no_wrap=no_wrap,
            emoji=emoji,
            markup=markup,
            highlight=highlight,
            width=width,
            height=height,
            crop=crop,
            soft_wrap=soft_wrap,
            new_line_start=new_line_start,
        )

#### `` log

    log(*objects, sep=' ', end='\n', style=None, justify=None, emoji=None, markup=None, highlight=None, log_locals=False, _stack_offset=1)

Override to support ANSI sequences.

This method calls cmd2.rich_utils.prepare_objects_for_rendering on the objects being logged. This ensures that strings containing ANSI style sequences are converted to Rich Text objects, so that Rich can correctly calculate their display width.

Source code in `cmd2/rich_utils.py`

    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501

    def log(
        self,
        *objects: Any,
        sep: str = " ",
        end: str = "\n",
        style: StyleType | None = None,
        justify: JustifyMethod | None = None,
        emoji: bool | None = None,
        markup: bool | None = None,
        highlight: bool | None = None,
        log_locals: bool = False,
        _stack_offset: int = 1,
    ) -> None:
        """Override to support ANSI sequences.

        This method calls [cmd2.rich_utils.prepare_objects_for_rendering][] on the
        objects being logged. This ensures that strings containing ANSI style
        sequences are converted to Rich Text objects, so that Rich can correctly
        calculate their display width.
        """
        prepared_objects = prepare_objects_for_rendering(*objects)

        # Increment _stack_offset because we added this wrapper frame
        super().log(
            *prepared_objects,
            sep=sep,
            end=end,
            style=style,
            justify=justify,
            emoji=emoji,
            markup=markup,
            highlight=highlight,
            log_locals=log_locals,
            _stack_offset=_stack_offset + 1,
        )

### `` Cmd2ExceptionConsole

    Cmd2ExceptionConsole(*, file=None)

Bases: `Cmd2BaseConsole`

Rich console for printing exceptions and Rich Tracebacks.

Ensures that output is always word-wrapped for readability and disables Rich's automatic detection for markup, emoji, and highlighting to prevent interference with raw error data.

Cmd2ExceptionConsole initializer.

PARAMETER | DESCRIPTION
--- | ---
`file` | optional file object where the console should write to. Defaults to sys.stdout. TYPE: `IO[str] | None` DEFAULT: `None`

Source code in `cmd2/rich_utils.py`

    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574

    def __init__(self, *, file: IO[str] | None = None) -> None:
        """Cmd2ExceptionConsole initializer.

        :param file: optional file object where the console should write to.
                     Defaults to sys.stdout.
        """
        super().__init__(
            file=file,
            soft_wrap=False,
            markup=False,
            emoji=False,
            highlight=False,
        )

#### `` matches_config

    matches_config(*, file, **kwargs)

Check if this console instance was initialized with the specified settings.

PARAMETER | DESCRIPTION
--- | ---
`file` | file stream being checked TYPE: `IO[str] | None`
`kwargs` | other console settings being checked TYPE: `Any` DEFAULT: `{}`

RETURNS | DESCRIPTION
--- | ---
`bool` | True if the settings match this console's configuration

Source code in `cmd2/rich_utils.py`

    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415

    def matches_config(
        self,
        *,
        file: IO[str] | None,
        **kwargs: Any,
    ) -> bool:
        """Check if this console instance was initialized with the specified settings.

        :param file: file stream being checked
        :param kwargs: other console settings being checked
        :return: True if the settings match this console's configuration
        """
        return self._config_key == self._build_config_key(file=file, **kwargs)

#### `` on_broken_pipe

    on_broken_pipe()

Override which raises BrokenPipeError instead of SystemExit.

Source code in `cmd2/rich_utils.py`

    417
    418
    419
    420

    def on_broken_pipe(self) -> None:
        """Override which raises BrokenPipeError instead of SystemExit."""
        self.quiet = True
        raise BrokenPipeError

#### `` print

    print(*objects, sep=' ', end='\n', style=None, justify=None, overflow=None, no_wrap=None, emoji=None, markup=None, highlight=None, width=None, height=None, crop=True, soft_wrap=None, new_line_start=False)

Override to support ANSI sequences.

This method calls cmd2.rich_utils.prepare_objects_for_rendering on the objects being printed. This ensures that strings containing ANSI style sequences are converted to Rich Text objects, so that Rich can correctly calculate their display width.

Source code in `cmd2/rich_utils.py`

    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465

    def print(
        self,
        *objects: Any,
        sep: str = " ",
        end: str = "\n",
        style: StyleType | None = None,
        justify: JustifyMethod | None = None,
        overflow: OverflowMethod | None = None,
        no_wrap: bool | None = None,
        emoji: bool | None = None,
        markup: bool | None = None,
        highlight: bool | None = None,
        width: int | None = None,
        height: int | None = None,
        crop: bool = True,
        soft_wrap: bool | None = None,
        new_line_start: bool = False,
    ) -> None:
        """Override to support ANSI sequences.

        This method calls [cmd2.rich_utils.prepare_objects_for_rendering][] on the
        objects being printed. This ensures that strings containing ANSI style
        sequences are converted to Rich Text objects, so that Rich can correctly
        calculate their display width.
        """
        prepared_objects = prepare_objects_for_rendering(*objects)

        super().print(
            *prepared_objects,
            sep=sep,
            end=end,
            style=style,
            justify=justify,
            overflow=overflow,
            no_wrap=no_wrap,
            emoji=emoji,
            markup=markup,
            highlight=highlight,
            width=width,
            height=height,
            crop=crop,
            soft_wrap=soft_wrap,
            new_line_start=new_line_start,
        )

#### `` log

    log(*objects, sep=' ', end='\n', style=None, justify=None, emoji=None, markup=None, highlight=None, log_locals=False, _stack_offset=1)

Override to support ANSI sequences.

This method calls cmd2.rich_utils.prepare_objects_for_rendering on the objects being logged. This ensures that strings containing ANSI style sequences are converted to Rich Text objects, so that Rich can correctly calculate their display width.

Source code in `cmd2/rich_utils.py`

    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501

    def log(
        self,
        *objects: Any,
        sep: str = " ",
        end: str = "\n",
        style: StyleType | None = None,
        justify: JustifyMethod | None = None,
        emoji: bool | None = None,
        markup: bool | None = None,
        highlight: bool | None = None,
        log_locals: bool = False,
        _stack_offset: int = 1,
    ) -> None:
        """Override to support ANSI sequences.

        This method calls [cmd2.rich_utils.prepare_objects_for_rendering][] on the
        objects being logged. This ensures that strings containing ANSI style
        sequences are converted to Rich Text objects, so that Rich can correctly
        calculate their display width.
        """
        prepared_objects = prepare_objects_for_rendering(*objects)

        # Increment _stack_offset because we added this wrapper frame
        super().log(
            *prepared_objects,
            sep=sep,
            end=end,
            style=style,
            justify=justify,
            emoji=emoji,
            markup=markup,
            highlight=highlight,
            log_locals=log_locals,
            _stack_offset=_stack_offset + 1,
        )

### `` Cmd2SimpleTable

    Cmd2SimpleTable(*headers)

Bases: `Table`

A clean, lightweight Rich Table tailored for cmd2's internal use.

Cmd2SimpleTable initializer.

Source code in `cmd2/rich_utils.py`

    580
    581
    582
    583
    584
    585
    586
    587

    def __init__(self, *headers: Column | str) -> None:
        """Cmd2SimpleTable initializer."""
        super().__init__(
            *headers,
            box=SIMPLE_HEAD,
            show_edge=False,
            border_style=Cmd2Style.TABLE_BORDER,
        )

### `` console_width

    console_width()

Return the width of the console.

Source code in `cmd2/rich_utils.py`

    590
    591
    592

    def console_width() -> int:
        """Return the width of the console."""
        return Console().width

### `` rich_text_to_string

    rich_text_to_string(text)

Convert a Rich Text object to a string.

This function's purpose is to render a Rich Text object, including any styles (e.g., color, bold), to a plain Python string with ANSI style sequences. It differs from `text.plain`, which strips all formatting.

PARAMETER | DESCRIPTION
--- | ---
`text` | the text object to convert TYPE: `Text`

RETURNS | DESCRIPTION
--- | ---
`str` | the resulting string with ANSI styles preserved.

RAISES | DESCRIPTION
--- | ---
`TypeError` | if text is not a rich.text.Text object

Source code in `cmd2/rich_utils.py`

    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620

    def rich_text_to_string(text: Text) -> str:
        """Convert a Rich Text object to a string.

        This function's purpose is to render a Rich Text object, including any styles (e.g., color, bold),
        to a plain Python string with ANSI style sequences. It differs from `text.plain`, which strips
        all formatting.

        :param text: the text object to convert
        :return: the resulting string with ANSI styles preserved.
        :raises TypeError: if text is not a rich.text.Text object
        """
        # Strictly enforce Text type. While console.print() can render any object,
        # this function is specifically tailored to convert Text instances to strings.
        if not isinstance(text, Text):
            raise TypeError(f"rich_text_to_string() expected a rich.text.Text object, but got {type(text).__name__}")

        console = Console(
            force_terminal=True,
            color_system="truecolor",
            soft_wrap=True,
            no_color=False,
            theme=_get_theme(),
        )
        with console.capture() as capture:
            console.print(text, end="")
        return capture.get()

### `` indent

    indent(renderable, level)

Indent a Rich renderable.

When soft-wrapping is enabled, a Rich console is unable to properly print a Padding object of indented text, as it truncates long strings instead of wrapping them. This function provides a workaround for this issue, ensuring that indented text is printed correctly regardless of the soft-wrap setting.

For non-text objects, this function merely serves as a convenience wrapper around Padding.indent().

PARAMETER | DESCRIPTION
--- | ---
`renderable` | a Rich renderable to indent. TYPE: `RenderableType`
`level` | number of characters to indent. TYPE: `int`

RETURNS | DESCRIPTION
--- | ---
`Padding` | a Padding object containing the indented content.

Source code in `cmd2/rich_utils.py`

    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644

    def indent(renderable: RenderableType, level: int) -> Padding:
        """Indent a Rich renderable.

        When soft-wrapping is enabled, a Rich console is unable to properly print a
        Padding object of indented text, as it truncates long strings instead of wrapping
        them. This function provides a workaround for this issue, ensuring that indented
        text is printed correctly regardless of the soft-wrap setting.

        For non-text objects, this function merely serves as a convenience
        wrapper around Padding.indent().

        :param renderable: a Rich renderable to indent.
        :param level: number of characters to indent.
        :return: a Padding object containing the indented content.
        """
        if isinstance(renderable, (str, Text)):
            # Wrap text in a grid to handle the wrapping.
            text_grid = Table.grid(Column(overflow="fold"))
            text_grid.add_row(renderable)
            renderable = text_grid

        return Padding.indent(renderable, level)

### `` prepare_objects_for_rendering

    prepare_objects_for_rendering(*objects)

Prepare a tuple of objects for printing by Rich's Console.print().

This function processes objects to ensure they are rendered correctly by Rich. It inspects each object and, if its string representation contains ANSI style sequences, it converts the object to a Rich Text object. This ensures Rich can properly parse the non-printing codes for accurate display width calculation.

Objects that already implement the Rich console protocol or are expandable by its pretty printer are left untouched, as they can be handled directly by Rich's native renderers.

PARAMETER | DESCRIPTION
--- | ---
`objects` | objects to prepare TYPE: `Any` DEFAULT: `()`

RETURNS | DESCRIPTION
--- | ---
`tuple[Any, ...]` | a tuple containing the processed objects.

Source code in `cmd2/rich_utils.py`

    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678

    def prepare_objects_for_rendering(*objects: Any) -> tuple[Any, ...]:
        """Prepare a tuple of objects for printing by Rich's Console.print().

        This function processes objects to ensure they are rendered correctly by Rich.
        It inspects each object and, if its string representation contains ANSI style
        sequences, it converts the object to a Rich Text object. This ensures Rich can
        properly parse the non-printing codes for accurate display width calculation.

        Objects that already implement the Rich console protocol or are expandable
        by its pretty printer are left untouched, as they can be handled directly by
        Rich's native renderers.

        :param objects: objects to prepare
        :return: a tuple containing the processed objects.
        """
        object_list = list(objects)

        for i, obj in enumerate(object_list):
            # Resolve the object's final renderable form, including those
            # with a __rich__ method that might return a string.
            renderable = rich_cast(obj)

            # No preprocessing is needed for Rich-compatible or expandable objects.
            if isinstance(renderable, ConsoleRenderable) or is_expandable(renderable):
                continue

            # Check for ANSI style sequences in its string representation.
            renderable_as_str = str(renderable)
            if ANSI_STYLE_SEQUENCE_RE.search(renderable_as_str):
                object_list[i] = Text.from_ansi(renderable_as_str)

        return tuple(object_list)