Skip to content

Text

Bases: Text

A drop-in rich.text.Text with gradient colors baked into its spans.

Unlike Gradient, which recolors a renderable at render time, Text stores one color span per character, so it can be measured, sliced, and appended like any other Rich Text.

Parameters:

Name Type Description Default
text TextType

The text: a string (parsed as console markup when markup is True) or a Rich Text, e.g. "[bold]Hello[/bold], world". Defaults to "".

''
colors Optional[Sequence[ColorType]]

Foreground color stops. Each stop may be a color name (Rich/ANSI names such as "red" keep Rich's meaning; CSS names such as "tomato" also work), a hex string ("#f00", "#ff0000"), an "rgb(255, 0, 0)" string, an (r, g, b) tuple, or a rich.color.Color, e.g. ["#f00", "orange", (0, 128, 255)]. If omitted and rainbow is False, hues colors are taken from the spectrum palette. Defaults to None.

None
hues int

Number of colors to take from the spectrum palette when colors is omitted (a run of consecutive hues with a random starting point). Valid values are 2 to 17. Defaults to 5.

5
rainbow bool

Use the full 17-color spectrum palette, ignoring colors and hues. Defaults to False.

False
style StyleType

Base style applied under the gradient. A style string or rich.style.Style, e.g. "dim italic". Any color in this style is replaced by the gradient. Defaults to "".

''
justify JustifyMethod

Text justification: "default", "left", "center", "right", or "full". Defaults to "default".

'default'
overflow OverflowMethod

How to handle words too long for a line: "fold", "crop", "ellipsis", or "ignore". Defaults to "fold".

'fold'
no_wrap bool

Disable wrapping. Defaults to False.

False
end str

String appended after the text when printed. Defaults to a newline.

'\n'
tab_size int

Spaces per tab character. Defaults to 4.

4
bg_colors Optional[Sequence[ColorType]]

Background color stops, in the same formats as colors, e.g. ["#000033", "#330033"]. If omitted, no background gradient is applied. Defaults to None.

None
markup bool

Parse Rich console markup in string input. Defaults to True.

True
spans Optional[Sequence[Span]]

Extra rich.text.Span objects applied on top of the gradient, e.g. [Span(0, 5, "underline")]. Defaults to None.

None

Examples:

>>> from rich.console import Console
>>> Console().print(Text("Hello, gradient!", colors=["#f00", "#00f"]))
>>> Console().print(Text("[bold]Rainbow[/bold]", rainbow=True))
Source code in src/rich_gradient/text.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
class Text(RichText):
    """A drop-in ``rich.text.Text`` with gradient colors baked into its spans.

    Unlike ``Gradient``, which recolors a renderable at render time, ``Text``
    stores one color span per character, so it can be measured, sliced, and
    appended like any other Rich ``Text``.

    Args:
        text (TextType): The text: a string (parsed as console markup when ``markup`` is
            True) or a Rich ``Text``, e.g. ``"[bold]Hello[/bold], world"``. Defaults to
            ``""``.
        colors (Optional[Sequence[ColorType]]): Foreground color stops. Each stop may be
            a color name (Rich/ANSI names such as ``"red"`` keep Rich's meaning; CSS
            names such as ``"tomato"`` also work), a hex string (``"#f00"``,
            ``"#ff0000"``), an ``"rgb(255, 0, 0)"`` string, an ``(r, g, b)`` tuple, or a
            ``rich.color.Color``, e.g. ``["#f00", "orange", (0, 128, 255)]``. If omitted
            and ``rainbow`` is False, ``hues`` colors are taken from the spectrum
            palette. Defaults to None.
        hues (int): Number of colors to take from the spectrum palette when ``colors``
            is omitted (a run of consecutive hues with a random starting point). Valid
            values are 2 to 17. Defaults to 5.
        rainbow (bool): Use the full 17-color spectrum palette, ignoring ``colors`` and
            ``hues``. Defaults to False.
        style (StyleType): Base style applied under the gradient. A style string or
            ``rich.style.Style``, e.g. ``"dim italic"``. Any color in this style is
            replaced by the gradient. Defaults to ``""``.
        justify (JustifyMethod): Text justification: ``"default"``, ``"left"``,
            ``"center"``, ``"right"``, or ``"full"``. Defaults to ``"default"``.
        overflow (OverflowMethod): How to handle words too long for a line: ``"fold"``,
            ``"crop"``, ``"ellipsis"``, or ``"ignore"``. Defaults to ``"fold"``.
        no_wrap (bool): Disable wrapping. Defaults to False.
        end (str): String appended after the text when printed. Defaults to a newline.
        tab_size (int): Spaces per tab character. Defaults to 4.
        bg_colors (Optional[Sequence[ColorType]]): Background color stops, in the same
            formats as ``colors``, e.g. ``["#000033", "#330033"]``. If omitted, no
            background gradient is applied. Defaults to None.
        markup (bool): Parse Rich console markup in string input. Defaults to True.
        spans (Optional[Sequence[Span]]): Extra ``rich.text.Span`` objects applied on
            top of the gradient, e.g. ``[Span(0, 5, "underline")]``. Defaults to None.

    Examples:
        >>> from rich.console import Console
        >>> Console().print(Text("Hello, gradient!", colors=["#f00", "#00f"]))
        >>> Console().print(Text("[bold]Rainbow[/bold]", rainbow=True))
    """

    def __init__(
        self,
        text: TextType = "",
        colors: Sequence[ColorType] | None = None,
        hues: int = 5,
        rainbow: bool = False,
        style: StyleType = "",
        justify: JustifyMethod = "default",
        overflow: OverflowMethod = "fold",
        no_wrap: bool = False,
        end: str = "\n",
        tab_size: int = 4,
        bg_colors: Sequence[ColorType] | None = None,
        markup: bool = True,
        spans: Sequence[Span] | None = None,
    ):
        """Initialize the gradient text; see the class docstring for arguments.

        Raises:
            ValueError: If ``hues`` is out of range.
            ColorParseError: If a color string cannot be parsed.
        """
        # Parse the input text with or without markup
        if markup:
            parsed_text = RichText.from_markup(
                text=str(text), style=style, justify=justify, overflow=overflow
            )
        else:
            parsed_text = RichText(
                strip_control_codes(str(text)),
                style=style,
                justify=justify,
                overflow=overflow,
            )

        # Extract parsed attributes
        plain = parsed_text.plain
        parsed_justify = parsed_text.justify
        parsed_overflow = parsed_text.overflow
        parsed_spans = parsed_text._spans

        # Initialize the parent class
        super().__init__(
            plain,
            style=style,
            justify=parsed_justify,
            overflow=parsed_overflow,
            no_wrap=no_wrap,
            end=end,
            tab_size=tab_size,
            spans=parsed_spans,
        )
        validate_hues(hues)
        self._interpolate_bg_colors = False  # Ensure flag is always initialized
        # Normalize color inputs into rich.color.Color instances
        self.colors = self.parse_colors(colors, hues, rainbow)
        self.bg_colors = self.parse_bg_colors(bg_colors)

        # Handle the single-color and single-background case: apply style directly and return early
        if len(self.colors) == 1 and len(self.bg_colors) == 1:
            # Apply the single color style directly, honoring a missing style definition.
            if isinstance(style, Style):
                base_style = style
            elif isinstance(style, str) and style:
                base_style = Style.parse(style)
            else:
                base_style = Style.null()
            color_layer = Style(color=self.colors[0], bgcolor=self.bg_colors[0])
            style_with_color = color_layer + base_style
            for index in range(len(self.plain)):
                self.stylize(style_with_color, index, index + 1)
            return

        # Apply the gradient coloring
        self.apply_gradient()

    @property
    def colors(self) -> list[Color]:
        """The foreground color stops of the gradient."""
        return list(self._colors) if self._colors else []

    @colors.setter
    def colors(self, value: Sequence[Color] | None) -> None:
        """Set the foreground color stops.

        Args:
            value: Parsed ``rich.color.Color`` stops, or ``None`` to clear them.
        """
        self._colors = list(value) if value else []

    @property
    def bg_colors(self) -> list[Color]:
        """The background colors, one per character after interpolation."""
        return list(self._bg_colors) if self._bg_colors else []

    @bg_colors.setter
    def bg_colors(self, value: Sequence[Color] | None) -> None:
        """Set the background colors.

        Args:
            value: Parsed ``rich.color.Color`` values, or ``None`` to clear them.
        """
        self._bg_colors = list(value) if value else []

    @staticmethod
    def _normalize_color(value: ColorType) -> Color:
        """Normalize a single color-like value to a rich.color.Color.

        Accepts: Color, ColorTriplet, 3-tuple of ints, or string parsable
        by Rich's color parser, falling back to rich-color-ext (CSS names and
        3-digit hex) when Rich rejects it.

        Args:
            value (ColorType): The color-like value to normalize.

        Returns:
            Color: The normalized Color instance.

        Raises:
            ColorParseError: If the color value cannot be parsed.
            TypeError: If ``value`` has an unsupported type.
        """
        try:
            if isinstance(value, Color):
                return value
            elif isinstance(value, ColorTriplet):
                return Color.from_rgb(value.red, value.green, value.blue)
            elif isinstance(value, tuple) and len(value) == 3:
                r, g, b = value
                return Color.from_rgb(int(r), int(g), int(b))
            elif isinstance(value, str):
                return parse_color(value)
            else:
                # Reject unsupported types explicitly (e.g., int, None)
                raise TypeError(f"Unsupported color type: {type(value)!r}")
        except ColorParseError as cpe:
            raise ColorParseError(
                f"Failed to parse and normalize color: {value}"
            ) from cpe

    @staticmethod
    def parse_colors(
        colors: Sequence[ColorType] | None = None,
        hues: int = 5,
        rainbow: bool = False,
    ) -> list[Color]:
        """Parse and return a list of colors for the gradient.

        Supports:

        - rgb strings (e.g. ``'rgb(255, 0, 0)'``)
        - rgb tuples (e.g. ``(255, 0, 0)``)
        - 3-digit hex colors (e.g. ``'#f00'``, ``'#F90'``)
        - 6-digit hex colors (e.g. ``'#ff0000'``, ``'#00FF00'``)
        - color names (e.g. ``'tomato'``, ``'aliceblue'``; Rich/ANSI names keep Rich's meaning)
        - ``rich.color.Color`` objects (e.g. ``Color.parse('#FF0000')``)

        Args:
            colors (Optional[Sequence[ColorType]]): Color stops in any of the formats
                above, e.g. ``["#f00", "orange", (0, 128, 255)]``. Defaults to None,
                which takes ``hues`` colors from the spectrum palette.
            hues (int): Number of spectrum colors to use when ``colors`` is omitted.
                Valid values are 2 to 17. Defaults to 5.
            rainbow (bool): Use the full 17-color spectrum, overriding ``colors`` and
                ``hues``. Defaults to False.

        Returns:
            list[rich.color.Color]: The parsed color stops.

        Raises:
            ColorParseError: If any color value cannot be parsed.
            ValueError: If ``hues`` is out of range.
        """
        # When rainbow is True, we use a full 17-color spectrum
        if rainbow:
            return Spectrum(hues=17).colors

        # If no colors are provided, fall back to Spectrum with the specified hues
        if colors is None or len(colors) == 0:
            return Spectrum(validate_hues(hues)).colors

        # If we have colors, parse and normalize them
        parsed: list[Color] = []
        for c in colors:
            try:
                parsed.append(Text._normalize_color(c))
            except Exception as exc:  # pragma: no cover - defensive
                raise ColorParseError(f"Unsupported color value: {c}") from exc
        return parsed

    def parse_bg_colors(
        self, bg_colors: Sequence[ColorType] | None = None
    ) -> list[Color]:
        """Parse and return a list of background colors for the gradient.

        Accepts the same color formats as ``parse_colors``.

        Args:
            bg_colors (Optional[Sequence[ColorType]]): Background colors, e.g.
                ``["#000033", "#330033"]``. A single color is applied as a solid
                fill; multiple colors are interpolated across the text. Defaults to
                None, which uses the terminal's default background.

        Returns:
            list[Color]: One background color per character.

        Raises:
            ColorParseError: If a color value cannot be parsed.
        """
        if not bg_colors:
            self._interpolate_bg_colors = False
            # Default to transparent/default background per character count
            fallback = Color.parse("default")
            color_count = max(1, len(self.colors))
            return [fallback] * color_count

        if len(bg_colors) == 1:
            # If only one background color is provided, do not interpolate
            self._interpolate_bg_colors = False
            c = bg_colors[0]
            try:
                normalized = Text._normalize_color(c)
            except Exception as exc:  # pragma: no cover - defensive
                raise ColorParseError(f"Unsupported background color: {c}") from exc
            return [normalized] * max(1, len(self.colors))

        # Multiple bg_colors: interpolate across provided stops
        self._interpolate_bg_colors = True
        parsed_bg: list[Color] = []
        for c in bg_colors:
            try:
                parsed_bg.append(Text._normalize_color(c))
            except Exception as exc:  # pragma: no cover - defensive
                raise ColorParseError(f"Unsupported background color: {c}") from exc
        return parsed_bg

    def interpolate_colors(
        self, colors: Sequence[Color] | None = None
    ) -> list[Color]:
        """Interpolate colors across the text using gamma-correct blending.

        Args:
            colors: Color stops to blend. Defaults to None, which uses
                ``self.colors``.

        Returns:
            One color per character of the plain text (empty for empty text).

        Raises:
            ValueError: If there are no color stops.
        """
        colors = list(colors) if colors is not None else self.colors
        if not colors:
            raise ValueError("No colors to interpolate")

        text = self.plain
        length = len(text)
        if length == 0:
            return []
        num_colors = len(colors)
        if num_colors == 1:
            return [colors[0]] * length

        segments = num_colors - 1
        result: list[Color] = []

        GAMMA = 2.2

        def to_linear(v: int) -> float:
            """Convert an sRGB channel to linear light.

            Args:
                v: Channel value, 0-255.

            Returns:
                Linear-light value, 0-1.
            """
            return (v / 255.0) ** GAMMA

        def to_srgb(x: float) -> int:
            """Convert a linear-light value back to an sRGB channel.

            Args:
                x: Linear-light value, 0-1.

            Returns:
                Channel value, 0-255.
            """
            return int((x ** (1.0 / GAMMA)) * 255.0)

        for i in range(length):
            pos = i / (length - 1) if length > 1 else 0.0
            fidx = pos * segments
            idx = int(fidx)
            if idx >= segments:
                idx = segments - 1
                t = 1.0
            else:
                t = fidx - idx

            c0 = colors[idx].get_truecolor()
            c1 = colors[idx + 1].get_truecolor()

            lr = to_linear(c0.red) + (to_linear(c1.red) - to_linear(c0.red)) * t
            lg = to_linear(c0.green) + (to_linear(c1.green) - to_linear(c0.green)) * t
            lb = to_linear(c0.blue) + (to_linear(c1.blue) - to_linear(c0.blue)) * t

            r, g, b = to_srgb(lr), to_srgb(lg), to_srgb(lb)
            result.append(Color.from_rgb(r, g, b))

        return result

    def apply_gradient(self) -> None:
        """Apply interpolated colors as spans to each character in the text."""
        # Generate a color for each character
        colors = self.interpolate_colors(self.colors)
        if self._interpolate_bg_colors:
            # Generate a background color for each character if bg_colors are interpolated
            bg_colors = self.interpolate_colors(self.bg_colors)
        else:
            # If not interpolating background colors, use the first bg_color for all characters
            bg_colors = [self.bg_colors[0]] * len(colors)
        # Apply a style span for each character with its corresponding color
        for index, (color, bg_color) in enumerate(zip(colors, bg_colors)):
            # Build a style with the interpolated color
            span_style = Style(color=color, bgcolor=bg_color)
            # Stylize the single character range
            self.stylize(span_style, index, index + 1)

    def as_rich(self) -> RichText:
        """Return a plain ``rich.text.Text`` with styles and spans applied.

        This converts the current gradient-aware ``Text`` into a base
        ``rich.text.Text`` carrying the same plain content and span/style
        information. Useful when a consumer specifically needs the base type.
        """
        # Create a plain RichText that mirrors the source content and layout
        rich_text = RichText(
            self.plain,
            style=self.style,
            justify=self.justify,
            overflow=self.overflow,
            no_wrap=self.no_wrap,
            end=self.end,
            tab_size=self.tab_size,
        )

        # Copy internal spans from the source into the returned RichText.
        # Using the internal _spans attribute is acceptable here since both
        # classes share the same underlying implementation in rich.
        for span in getattr(self, "_spans", []):
            rich_text._spans.append(span)

        return rich_text

    @property
    def rich(self) -> RichText:
        """A plain ``rich.text.Text`` copy of this text (same as ``as_rich()``)."""
        return self.as_rich()

    def __rich_console__(self, console: Console, options: ConsoleOptions) -> Iterable[Segment]:
        """Render Text while suppressing any output for empty content.

        For empty plain text, yield no segments at all (no stray newlines).
        Otherwise, delegate to the parent implementation and filter a final
        trailing `end` segment as required.

        Args:
            console: The console being rendered to.
            options: The console options for the current render.

        Yields:
            The rendered segments; none for empty text.
        """
        if self.plain == "":
            return
        for render_output in super().__rich_console__(console, options):
            if isinstance(render_output, Segment):
                # For empty Text,
                # filter out both the empty text Segment and the trailing end Segment.
                if self.plain == "" and render_output.text in ("", self.end):
                    continue
                yield render_output
            else:
                # Render nested renderable to segments, filter as needed
                for seg in console.render(render_output, options):
                    if self.plain == "" and seg.text in ("", self.end):
                        continue
                    yield seg

bg_colors property writable

The background colors, one per character after interpolation.

colors property writable

The foreground color stops of the gradient.

rich property

A plain rich.text.Text copy of this text (same as as_rich()).

__init__(text='', colors=None, hues=5, rainbow=False, style='', justify='default', overflow='fold', no_wrap=False, end='\n', tab_size=4, bg_colors=None, markup=True, spans=None)

Initialize the gradient text; see the class docstring for arguments.

Raises:

Type Description
ValueError

If hues is out of range.

ColorParseError

If a color string cannot be parsed.

Source code in src/rich_gradient/text.py
def __init__(
    self,
    text: TextType = "",
    colors: Sequence[ColorType] | None = None,
    hues: int = 5,
    rainbow: bool = False,
    style: StyleType = "",
    justify: JustifyMethod = "default",
    overflow: OverflowMethod = "fold",
    no_wrap: bool = False,
    end: str = "\n",
    tab_size: int = 4,
    bg_colors: Sequence[ColorType] | None = None,
    markup: bool = True,
    spans: Sequence[Span] | None = None,
):
    """Initialize the gradient text; see the class docstring for arguments.

    Raises:
        ValueError: If ``hues`` is out of range.
        ColorParseError: If a color string cannot be parsed.
    """
    # Parse the input text with or without markup
    if markup:
        parsed_text = RichText.from_markup(
            text=str(text), style=style, justify=justify, overflow=overflow
        )
    else:
        parsed_text = RichText(
            strip_control_codes(str(text)),
            style=style,
            justify=justify,
            overflow=overflow,
        )

    # Extract parsed attributes
    plain = parsed_text.plain
    parsed_justify = parsed_text.justify
    parsed_overflow = parsed_text.overflow
    parsed_spans = parsed_text._spans

    # Initialize the parent class
    super().__init__(
        plain,
        style=style,
        justify=parsed_justify,
        overflow=parsed_overflow,
        no_wrap=no_wrap,
        end=end,
        tab_size=tab_size,
        spans=parsed_spans,
    )
    validate_hues(hues)
    self._interpolate_bg_colors = False  # Ensure flag is always initialized
    # Normalize color inputs into rich.color.Color instances
    self.colors = self.parse_colors(colors, hues, rainbow)
    self.bg_colors = self.parse_bg_colors(bg_colors)

    # Handle the single-color and single-background case: apply style directly and return early
    if len(self.colors) == 1 and len(self.bg_colors) == 1:
        # Apply the single color style directly, honoring a missing style definition.
        if isinstance(style, Style):
            base_style = style
        elif isinstance(style, str) and style:
            base_style = Style.parse(style)
        else:
            base_style = Style.null()
        color_layer = Style(color=self.colors[0], bgcolor=self.bg_colors[0])
        style_with_color = color_layer + base_style
        for index in range(len(self.plain)):
            self.stylize(style_with_color, index, index + 1)
        return

    # Apply the gradient coloring
    self.apply_gradient()

__rich_console__(console, options)

Render Text while suppressing any output for empty content.

For empty plain text, yield no segments at all (no stray newlines). Otherwise, delegate to the parent implementation and filter a final trailing end segment as required.

Parameters:

Name Type Description Default
console Console

The console being rendered to.

required
options ConsoleOptions

The console options for the current render.

required

Yields:

Type Description
Iterable[Segment]

The rendered segments; none for empty text.

Source code in src/rich_gradient/text.py
def __rich_console__(self, console: Console, options: ConsoleOptions) -> Iterable[Segment]:
    """Render Text while suppressing any output for empty content.

    For empty plain text, yield no segments at all (no stray newlines).
    Otherwise, delegate to the parent implementation and filter a final
    trailing `end` segment as required.

    Args:
        console: The console being rendered to.
        options: The console options for the current render.

    Yields:
        The rendered segments; none for empty text.
    """
    if self.plain == "":
        return
    for render_output in super().__rich_console__(console, options):
        if isinstance(render_output, Segment):
            # For empty Text,
            # filter out both the empty text Segment and the trailing end Segment.
            if self.plain == "" and render_output.text in ("", self.end):
                continue
            yield render_output
        else:
            # Render nested renderable to segments, filter as needed
            for seg in console.render(render_output, options):
                if self.plain == "" and seg.text in ("", self.end):
                    continue
                yield seg

apply_gradient()

Apply interpolated colors as spans to each character in the text.

Source code in src/rich_gradient/text.py
def apply_gradient(self) -> None:
    """Apply interpolated colors as spans to each character in the text."""
    # Generate a color for each character
    colors = self.interpolate_colors(self.colors)
    if self._interpolate_bg_colors:
        # Generate a background color for each character if bg_colors are interpolated
        bg_colors = self.interpolate_colors(self.bg_colors)
    else:
        # If not interpolating background colors, use the first bg_color for all characters
        bg_colors = [self.bg_colors[0]] * len(colors)
    # Apply a style span for each character with its corresponding color
    for index, (color, bg_color) in enumerate(zip(colors, bg_colors)):
        # Build a style with the interpolated color
        span_style = Style(color=color, bgcolor=bg_color)
        # Stylize the single character range
        self.stylize(span_style, index, index + 1)

as_rich()

Return a plain rich.text.Text with styles and spans applied.

This converts the current gradient-aware Text into a base rich.text.Text carrying the same plain content and span/style information. Useful when a consumer specifically needs the base type.

Source code in src/rich_gradient/text.py
def as_rich(self) -> RichText:
    """Return a plain ``rich.text.Text`` with styles and spans applied.

    This converts the current gradient-aware ``Text`` into a base
    ``rich.text.Text`` carrying the same plain content and span/style
    information. Useful when a consumer specifically needs the base type.
    """
    # Create a plain RichText that mirrors the source content and layout
    rich_text = RichText(
        self.plain,
        style=self.style,
        justify=self.justify,
        overflow=self.overflow,
        no_wrap=self.no_wrap,
        end=self.end,
        tab_size=self.tab_size,
    )

    # Copy internal spans from the source into the returned RichText.
    # Using the internal _spans attribute is acceptable here since both
    # classes share the same underlying implementation in rich.
    for span in getattr(self, "_spans", []):
        rich_text._spans.append(span)

    return rich_text

interpolate_colors(colors=None)

Interpolate colors across the text using gamma-correct blending.

Parameters:

Name Type Description Default
colors Sequence[Color] | None

Color stops to blend. Defaults to None, which uses self.colors.

None

Returns:

Type Description
list[Color]

One color per character of the plain text (empty for empty text).

Raises:

Type Description
ValueError

If there are no color stops.

Source code in src/rich_gradient/text.py
def interpolate_colors(
    self, colors: Sequence[Color] | None = None
) -> list[Color]:
    """Interpolate colors across the text using gamma-correct blending.

    Args:
        colors: Color stops to blend. Defaults to None, which uses
            ``self.colors``.

    Returns:
        One color per character of the plain text (empty for empty text).

    Raises:
        ValueError: If there are no color stops.
    """
    colors = list(colors) if colors is not None else self.colors
    if not colors:
        raise ValueError("No colors to interpolate")

    text = self.plain
    length = len(text)
    if length == 0:
        return []
    num_colors = len(colors)
    if num_colors == 1:
        return [colors[0]] * length

    segments = num_colors - 1
    result: list[Color] = []

    GAMMA = 2.2

    def to_linear(v: int) -> float:
        """Convert an sRGB channel to linear light.

        Args:
            v: Channel value, 0-255.

        Returns:
            Linear-light value, 0-1.
        """
        return (v / 255.0) ** GAMMA

    def to_srgb(x: float) -> int:
        """Convert a linear-light value back to an sRGB channel.

        Args:
            x: Linear-light value, 0-1.

        Returns:
            Channel value, 0-255.
        """
        return int((x ** (1.0 / GAMMA)) * 255.0)

    for i in range(length):
        pos = i / (length - 1) if length > 1 else 0.0
        fidx = pos * segments
        idx = int(fidx)
        if idx >= segments:
            idx = segments - 1
            t = 1.0
        else:
            t = fidx - idx

        c0 = colors[idx].get_truecolor()
        c1 = colors[idx + 1].get_truecolor()

        lr = to_linear(c0.red) + (to_linear(c1.red) - to_linear(c0.red)) * t
        lg = to_linear(c0.green) + (to_linear(c1.green) - to_linear(c0.green)) * t
        lb = to_linear(c0.blue) + (to_linear(c1.blue) - to_linear(c0.blue)) * t

        r, g, b = to_srgb(lr), to_srgb(lg), to_srgb(lb)
        result.append(Color.from_rgb(r, g, b))

    return result

parse_bg_colors(bg_colors=None)

Parse and return a list of background colors for the gradient.

Accepts the same color formats as parse_colors.

Parameters:

Name Type Description Default
bg_colors Optional[Sequence[ColorType]]

Background colors, e.g. ["#000033", "#330033"]. A single color is applied as a solid fill; multiple colors are interpolated across the text. Defaults to None, which uses the terminal's default background.

None

Returns:

Type Description
list[Color]

list[Color]: One background color per character.

Raises:

Type Description
ColorParseError

If a color value cannot be parsed.

Source code in src/rich_gradient/text.py
def parse_bg_colors(
    self, bg_colors: Sequence[ColorType] | None = None
) -> list[Color]:
    """Parse and return a list of background colors for the gradient.

    Accepts the same color formats as ``parse_colors``.

    Args:
        bg_colors (Optional[Sequence[ColorType]]): Background colors, e.g.
            ``["#000033", "#330033"]``. A single color is applied as a solid
            fill; multiple colors are interpolated across the text. Defaults to
            None, which uses the terminal's default background.

    Returns:
        list[Color]: One background color per character.

    Raises:
        ColorParseError: If a color value cannot be parsed.
    """
    if not bg_colors:
        self._interpolate_bg_colors = False
        # Default to transparent/default background per character count
        fallback = Color.parse("default")
        color_count = max(1, len(self.colors))
        return [fallback] * color_count

    if len(bg_colors) == 1:
        # If only one background color is provided, do not interpolate
        self._interpolate_bg_colors = False
        c = bg_colors[0]
        try:
            normalized = Text._normalize_color(c)
        except Exception as exc:  # pragma: no cover - defensive
            raise ColorParseError(f"Unsupported background color: {c}") from exc
        return [normalized] * max(1, len(self.colors))

    # Multiple bg_colors: interpolate across provided stops
    self._interpolate_bg_colors = True
    parsed_bg: list[Color] = []
    for c in bg_colors:
        try:
            parsed_bg.append(Text._normalize_color(c))
        except Exception as exc:  # pragma: no cover - defensive
            raise ColorParseError(f"Unsupported background color: {c}") from exc
    return parsed_bg

parse_colors(colors=None, hues=5, rainbow=False) staticmethod

Parse and return a list of colors for the gradient.

Supports:

  • rgb strings (e.g. 'rgb(255, 0, 0)')
  • rgb tuples (e.g. (255, 0, 0))
  • 3-digit hex colors (e.g. '#f00', '#F90')
  • 6-digit hex colors (e.g. '#ff0000', '#00FF00')
  • color names (e.g. 'tomato', 'aliceblue'; Rich/ANSI names keep Rich's meaning)
  • rich.color.Color objects (e.g. Color.parse('#FF0000'))

Parameters:

Name Type Description Default
colors Optional[Sequence[ColorType]]

Color stops in any of the formats above, e.g. ["#f00", "orange", (0, 128, 255)]. Defaults to None, which takes hues colors from the spectrum palette.

None
hues int

Number of spectrum colors to use when colors is omitted. Valid values are 2 to 17. Defaults to 5.

5
rainbow bool

Use the full 17-color spectrum, overriding colors and hues. Defaults to False.

False

Returns:

Type Description
list[Color]

list[rich.color.Color]: The parsed color stops.

Raises:

Type Description
ColorParseError

If any color value cannot be parsed.

ValueError

If hues is out of range.

Source code in src/rich_gradient/text.py
@staticmethod
def parse_colors(
    colors: Sequence[ColorType] | None = None,
    hues: int = 5,
    rainbow: bool = False,
) -> list[Color]:
    """Parse and return a list of colors for the gradient.

    Supports:

    - rgb strings (e.g. ``'rgb(255, 0, 0)'``)
    - rgb tuples (e.g. ``(255, 0, 0)``)
    - 3-digit hex colors (e.g. ``'#f00'``, ``'#F90'``)
    - 6-digit hex colors (e.g. ``'#ff0000'``, ``'#00FF00'``)
    - color names (e.g. ``'tomato'``, ``'aliceblue'``; Rich/ANSI names keep Rich's meaning)
    - ``rich.color.Color`` objects (e.g. ``Color.parse('#FF0000')``)

    Args:
        colors (Optional[Sequence[ColorType]]): Color stops in any of the formats
            above, e.g. ``["#f00", "orange", (0, 128, 255)]``. Defaults to None,
            which takes ``hues`` colors from the spectrum palette.
        hues (int): Number of spectrum colors to use when ``colors`` is omitted.
            Valid values are 2 to 17. Defaults to 5.
        rainbow (bool): Use the full 17-color spectrum, overriding ``colors`` and
            ``hues``. Defaults to False.

    Returns:
        list[rich.color.Color]: The parsed color stops.

    Raises:
        ColorParseError: If any color value cannot be parsed.
        ValueError: If ``hues`` is out of range.
    """
    # When rainbow is True, we use a full 17-color spectrum
    if rainbow:
        return Spectrum(hues=17).colors

    # If no colors are provided, fall back to Spectrum with the specified hues
    if colors is None or len(colors) == 0:
        return Spectrum(validate_hues(hues)).colors

    # If we have colors, parse and normalize them
    parsed: list[Color] = []
    for c in colors:
        try:
            parsed.append(Text._normalize_color(c))
        except Exception as exc:  # pragma: no cover - defensive
            raise ColorParseError(f"Unsupported color value: {c}") from exc
    return parsed