Skip to content

Commit 3dfe0d9

Browse files
committed
Updated rich_utils.prepare_objects_for_rich_print() to only convert styled strings to Rich Text objects.
1 parent c1af802 commit 3dfe0d9

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

cmd2/rich_utils.py

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -306,17 +306,27 @@ def indent(renderable: RenderableType, level: int) -> Padding:
306306
def prepare_objects_for_rich_print(*objects: Any) -> tuple[RenderableType, ...]:
307307
"""Prepare a tuple of objects for printing by Rich's Console.print().
308308
309-
Converts any non-Rich objects (i.e., not ConsoleRenderable or RichCast)
310-
into rich.Text objects by stringifying them and processing them with
311-
from_ansi(). This ensures Rich correctly interprets any embedded ANSI
312-
escape sequences.
309+
This function converts any non-Rich object whose string representation contains
310+
ANSI style codes into a rich.Text object. This ensures correct display width
311+
calculation, as Rich can then properly parse and account for the non-printing
312+
ANSI codes. All other objects are left untouched, allowing Rich's native
313+
renderers to handle them.
313314
314315
:param objects: objects to prepare
315-
:return: a tuple containing the processed objects, where non-Rich objects are
316-
converted to rich.Text.
316+
:return: a tuple containing the processed objects.
317317
"""
318318
object_list = list(objects)
319319
for i, obj in enumerate(object_list):
320-
if not isinstance(obj, (ConsoleRenderable, RichCast)):
321-
object_list[i] = string_to_rich_text(str(obj))
320+
# If the object is a recognized renderable, we don't need to do anything. Rich will handle it.
321+
if isinstance(obj, (ConsoleRenderable, RichCast)):
322+
continue
323+
324+
# Check if the object's string representation contains ANSI styles, and if so,
325+
# replace it with a Rich Text object for correct width calculation.
326+
obj_str = str(obj)
327+
obj_text = string_to_rich_text(obj_str)
328+
329+
if obj_text.plain != obj_str:
330+
object_list[i] = obj_text
331+
322332
return tuple(object_list)

tests/test_argparse.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -425,7 +425,7 @@ def test_subcmd_decorator(subcommand_app) -> None:
425425

426426
# Test subcommand that has no help option
427427
out, err = run_cmd(subcommand_app, 'test_subcmd_decorator helpless_subcmd')
428-
assert "'subcommand': 'helpless_subcmd'" in out[0]
428+
assert "'subcommand': 'helpless_subcmd'" in out[1]
429429

430430
out, err = run_cmd(subcommand_app, 'help test_subcmd_decorator helpless_subcmd')
431431
assert out[0] == 'Usage: test_subcmd_decorator helpless_subcmd'

0 commit comments

Comments
 (0)