Skip to content

Commit

Permalink
[text] Replace ASCII special characters with their "non-special" read…
Browse files Browse the repository at this point in the history
…able version

With this we allow the following:
- Such characters will be displayed in the data returned by "rich.inspect" when they are used in docstrings
- We fix the crash that can happen in some circumstances in the `Text.divide()` method when some docstrings have such special characters
  • Loading branch information
Olivier Philippon committed May 25, 2022
1 parent b7aab32 commit 49e2b1d
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 30 deletions.
14 changes: 0 additions & 14 deletions rich/_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,6 @@
from .table import Table
from .text import Text, TextType

_SPECIAL_CHARACTERS_TRANSLATION_TABLE = str.maketrans(
# Some special characters (such as "\b", aka "Backspace") are stripped from the docstrings when
# we display them, and also mess up our processing
# --> let's replace them with a readable "non-special" version of them (i.e. "\b" -> "\\b"):
{
"\a": "\\a", # ASCII Bell
"\b": "\\b", # ASCII Backspace
"\f": "\\f", # ASCII Formfeed
"\r": "\\r", # ASCII Carriage Return
"\v": "\\v", # ASCII Vertical Tab
}
)


def _first_paragraph(doc: str) -> str:
"""Get the first paragraph from a docstring."""
Expand Down Expand Up @@ -230,5 +217,4 @@ def _get_formatted_doc(self, object_: Any) -> Optional[str]:
docs = cleandoc(docs).strip()
if not self.help:
docs = _first_paragraph(docs)
docs = docs.translate(_SPECIAL_CHARACTERS_TRANSLATION_TABLE)
return docs
38 changes: 35 additions & 3 deletions rich/control.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,35 @@
import sys
import time
from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Union

if sys.version_info >= (3, 8):
from typing import Final
else:
from typing_extensions import Final # pragma: no cover

from .segment import ControlCode, ControlType, Segment

if TYPE_CHECKING:
from .console import Console, ConsoleOptions, RenderResult

STRIP_CONTROL_CODES = [
STRIP_CONTROL_CODES: Final = [
7, # Bell
8, # Backspace
11, # Vertical tab
12, # Form feed
13, # Carriage return
]
_CONTROL_TRANSLATE = {_codepoint: None for _codepoint in STRIP_CONTROL_CODES}
_CONTROL_STRIP_TRANSLATE: Final = {
_codepoint: None for _codepoint in STRIP_CONTROL_CODES
}

_CONTROL_MAKE_READABLE_TRANSLATE: Final = {
7: "\\a",
8: "\\b",
11: "\\v",
12: "\\f",
13: "\\r",
}

CONTROL_CODES_FORMAT: Dict[int, Callable[..., str]] = {
ControlType.BELL: lambda: "\x07",
Expand Down Expand Up @@ -169,7 +185,7 @@ def __rich_console__(


def strip_control_codes(
text: str, _translate_table: Dict[int, None] = _CONTROL_TRANSLATE
text: str, _translate_table: Dict[int, None] = _CONTROL_STRIP_TRANSLATE
) -> str:
"""Remove control codes from text.
Expand All @@ -182,6 +198,22 @@ def strip_control_codes(
return text.translate(_translate_table)


def make_control_codes_readable(
text: str,
_translate_table: Dict[int, str] = _CONTROL_MAKE_READABLE_TRANSLATE,
) -> str:
"""Replace control codes with their "readable" equivalent in the given text.
(e.g. "\b" becomes "\\b")
Args:
text (str): A string possibly contain control codes.
Returns:
str: String with control codes replaced with a readable version.
"""
return text.translate(_translate_table)


if __name__ == "__main__": # pragma: no cover
from rich.console import Console

Expand Down
19 changes: 10 additions & 9 deletions rich/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from functools import partial, reduce
from math import gcd
from operator import itemgetter
from rich.emoji import EmojiVariant
from typing import (
TYPE_CHECKING,
Any,
Expand All @@ -22,7 +21,7 @@
from .align import AlignMethod
from .cells import cell_len, set_cell_size
from .containers import Lines
from .control import strip_control_codes
from .control import make_control_codes_readable
from .emoji import EmojiVariant
from .jupyter import JupyterMixin
from .measure import Measurement
Expand Down Expand Up @@ -141,15 +140,16 @@ def __init__(
tab_size: Optional[int] = 8,
spans: Optional[List[Span]] = None,
) -> None:
self._text = [strip_control_codes(text)]
sanitized_text = make_control_codes_readable(text)
self._text = [sanitized_text]
self.style = style
self.justify: Optional["JustifyMethod"] = justify
self.overflow: Optional["OverflowMethod"] = overflow
self.no_wrap = no_wrap
self.end = end
self.tab_size = tab_size
self._spans: List[Span] = spans or []
self._length: int = len(text)
self._length: int = len(sanitized_text)

def __len__(self) -> int:
return self._length
Expand Down Expand Up @@ -394,9 +394,10 @@ def plain(self) -> str:
def plain(self, new_text: str) -> None:
"""Set the text to a new value."""
if new_text != self.plain:
self._text[:] = [new_text]
sanitized_text = make_control_codes_readable(new_text)
self._text[:] = [sanitized_text]
old_length = self._length
self._length = len(new_text)
self._length = len(sanitized_text)
if old_length > self._length:
self._trim_spans()

Expand Down Expand Up @@ -906,10 +907,10 @@ def append(

if len(text):
if isinstance(text, str):
text = strip_control_codes(text)
self._text.append(text)
sanitized_text = make_control_codes_readable(text)
self._text.append(sanitized_text)
offset = len(self)
text_length = len(text)
text_length = len(sanitized_text)
if style is not None:
self._spans.append(Span(offset, offset + text_length, style))
self._length += text_length
Expand Down
11 changes: 10 additions & 1 deletion tests/test_control.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from rich.control import Control, strip_control_codes
from rich.control import Control, make_control_codes_readable, strip_control_codes
from rich.segment import ControlType, Segment


Expand All @@ -13,6 +13,15 @@ def test_strip_control_codes():
assert strip_control_codes("Fear is the mind killer") == "Fear is the mind killer"


def test_make_control_codes_readable():
assert make_control_codes_readable("") == ""
assert make_control_codes_readable("foo\rbar") == "foo\\rbar"
assert (
make_control_codes_readable("Fear is the mind killer")
== "Fear is the mind killer"
)


def test_control_move_to():
control = Control.move_to(5, 10)
print(control.segment)
Expand Down
6 changes: 3 additions & 3 deletions tests/test_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,11 +583,11 @@ def test_styled():
assert text._spans == [Span(0, 3, "bold red")]


def test_strip_control_codes():
def test_make_control_codes_readable():
text = Text("foo\rbar")
assert str(text) == "foobar"
assert str(text) == "foo\\rbar"
text.append("\x08")
assert str(text) == "foobar"
assert str(text) == "foo\\rbar\\b"


def test_get_style_at_offset():
Expand Down

0 comments on commit 49e2b1d

Please sign in to comment.