Skip to content

Commit

Permalink
Merge pull request #3063 from Textualize/escape-end
Browse files Browse the repository at this point in the history
Fix escaping trailing backslash
  • Loading branch information
willmcgugan committed Jul 29, 2023
2 parents 368e8ad + 58f54ca commit 01b85ac
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Fixed Text.expand_tabs not expanding spans.
- Fixed TimeElapsedColumn from showing negative.
- Fix for escaping strings with a trailing backslash https://github.com/Textualize/rich/issues/2987

### Added

Expand Down
4 changes: 3 additions & 1 deletion rich/markup.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ def escape_backslashes(match: Match[str]) -> str:
return f"{backslashes}{backslashes}\\{text}"

markup = _escape(escape_backslashes, markup)
if markup.endswith("\\") and not markup.endswith("\\\\"):
return markup + "\\"

return markup


Expand Down Expand Up @@ -226,7 +229,6 @@ def pop_style(style_name: str) -> Tuple[int, Tag]:


if __name__ == "__main__": # pragma: no cover

MARKUP = [
"[red]Hello World[/red]",
"[magenta]Hello [b]World[/b]",
Expand Down
14 changes: 13 additions & 1 deletion tests/test_markup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from rich.console import Console
from rich.errors import MarkupError
from rich.markup import RE_TAGS, Tag, _parse, escape, render
from rich.text import Span
from rich.text import Span, Text


def test_re_no_match():
Expand Down Expand Up @@ -44,6 +44,18 @@ def test_escape():
assert escape("[nil, [nil]]") == r"[nil, \[nil]]"


def test_escape_backslash_end():
# https://github.com/Textualize/rich/issues/2987
value = "C:\\"
assert escape(value) == "C:\\\\"

escaped_tags = f"[red]{escape(value)}[/red]"
assert escaped_tags == "[red]C:\\\\[/red]"
escaped_text = Text.from_markup(escaped_tags)
assert escaped_text.plain == "C:\\"
assert escaped_text.spans == [Span(0, 3, "red")]


def test_render_escape():
console = Console(width=80, color_system=None)
console.begin_capture()
Expand Down

0 comments on commit 01b85ac

Please sign in to comment.