Skip to content

Commit

Permalink
added markup property
Browse files Browse the repository at this point in the history
  • Loading branch information
willmcgugan committed Dec 11, 2021
1 parent 215597a commit a8e188f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name = "rich"
homepage = "https://github.com/willmcgugan/rich"
documentation = "https://rich.readthedocs.io/en/latest/"
version = "10.15.3"
version = "10.15.3-alpha2"
description = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal"
authors = ["Will McGugan <willmcgugan@gmail.com>"]
license = "MIT"
Expand Down
34 changes: 34 additions & 0 deletions rich/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,36 @@ def cell_len(self) -> int:
"""Get the number of cells required to render this text."""
return cell_len(self.plain)

@property
def markup(self) -> str:
"""Get console markup to render this Text.
Returns:
str: A string potentially creating markup tags.
"""
from .markup import escape

output: List[str] = []

plain = self.plain
markup_spans = [
(0, False, self.style),
*((span.start, False, span.style) for span in self._spans),
*((span.end, True, span.style) for span in self._spans),
(len(plain), True, self.style),
]
markup_spans = sorted(markup_spans, key=itemgetter(0, 1))
position = 0
append = output.append
for offset, closing, style in markup_spans:
if offset > position:
append(escape(plain[position:offset]))
position = offset
if style:
append(f"[/{style}]" if closing else f"[{style}]")
markup = "".join(output)
return markup

@classmethod
def from_markup(
cls,
Expand Down Expand Up @@ -1217,6 +1247,10 @@ def with_indent_guides(
text.highlight_words(["ipsum"], "italic")

console = Console()

print(text.markup)
console.print(text.markup)

console.rule("justify='left'")
console.print(text, style="red")
console.print()
Expand Down

0 comments on commit a8e188f

Please sign in to comment.