diff --git a/CHANGELOG.md b/CHANGELOG.md index 4052e793..18462cc5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added description parameter to Progress.update - Added rich.prompt - Added detecting 'dumb' terminals +- Added Text.styled alternative constructor ### Fixes diff --git a/rich/text.py b/rich/text.py index d6505830..f17070e4 100644 --- a/rich/text.py +++ b/rich/text.py @@ -208,6 +208,31 @@ class Text(JupyterMixin): rendered_text.overflow = overflow return rendered_text + @classmethod + def styled( + cls, + text: str, + style: StyleType = "", + *, + justify: "JustifyMethod" = None, + overflow: "OverflowMethod" = None, + ) -> "Text": + """Construct a Text instance with a pre-applied styled. A style applied in this way won't be used + to pad the text when it is justified. + + Args: + text (str): A string containing console markup. + style (Union[str, Style]): Style to apply to the text. Defaults to "". + justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. + overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. + + Returns: + Text: A text instance with a style applied to the entire string. + """ + styled_text = cls(text, justify=justify, overflow=overflow) + styled_text.stylize_all(style) + return styled_text + @classmethod def assemble( cls, diff --git a/tests/test_text.py b/tests/test_text.py index 9419b2fb..06b12d7b 100644 --- a/tests/test_text.py +++ b/tests/test_text.py @@ -484,6 +484,13 @@ def test_assemble(): assert text._spans == [Span(3, 6, "bold")] +def test_styled(): + text = Text.styled("foo", "bold red") + assert text.style == "" + assert str(text) == "foo" + assert text._spans == [Span(0, 3, "bold red")] + + def test_strip_control_codes(): text = Text("foo\rbar") assert str(text) == "foobar"