Can I programmatically style text in a TextArea widget #5336
Replies: 2 comments 3 replies
-
Okay, for anyone with my problem, here is a solution. textarea = TextArea()
textarea._highlights[line_number].append((start_collumn, end_collumn, highlight_name)) Format of highlight_name you can customize the color of the highlights by making a custom theme. BTW: This is a big value of open source. I was able to dig through the source code and see how highlighting is implemented under the hood. Thank you textualize. Also BTW: This is not a supported feature, so it may change without notice. |
Beta Was this translation helpful? Give feedback.
-
Okay here is a custom TextArea widget allowing you to highlight arbitrary selections of text with any color from the rich library import sys
from rich._palettes import EIGHT_BIT_PALETTE, STANDARD_PALETTE, WINDOWS_PALETTE
from rich.color import ANSI_COLOR_NAMES, Color
from rich.style import Style
from textual.widgets import TextArea
IS_WINDOWS = sys.platform == "win32"
class TextAreaWithHighlights(TextArea):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
rich_colors = sorted((v, k) for k, v in ANSI_COLOR_NAMES.items())
for color_number, name in rich_colors:
palette = (
WINDOWS_PALETTE
if IS_WINDOWS and color_number < 16
else STANDARD_PALETTE
if color_number < 16
else EIGHT_BIT_PALETTE
)
color = palette[color_number]
self._theme.syntax_styles[name] = Style(color=Color.from_rgb(*color))
def highlight(
self, row: int, start_column: int, end_column: int, color: str
) -> None:
self._highlights[row].append((start_column, end_column, color)) to highlight a color: the color can be any color in this list. here is an example: class MyApp(App):
def compose(self) -> ComposeResult:
some_text = """here is some text
green blue red yellow
here is more text
here is more text green blah blah
red yellow blue gree orange purple bright_red magenta
"""
yield TextAreaWithHighlights(some_text)
def on_mount(self) -> None:
colors = [
"red",
"green",
"blue",
"yellow",
"orange",
"purple",
"magenta",
"bright_red",
]
textarea: TextAreaWithHighlights = self.query_one(TextAreaWithHighlights)
text = textarea.text
for row, line in enumerate(text.splitlines()):
for col in colors:
if col in line:
index = line.find(col)
textarea.highlight(row, index, index + len(col), col)
if __name__ == "__main__":
app = MyApp()
app.run() |
Beta Was this translation helpful? Give feedback.
-
is it possible for me to programmatically color certain characters inside a textarea, not syntax highlighting.
Beta Was this translation helpful? Give feedback.
All reactions