MCPcopy
hub / github.com/Textualize/textual / highlight

Function highlight

src/textual/highlight.py:184–238  ·  view source on GitHub ↗

Apply syntax highlighting to a string. Args: code: A string to highlight. language: The language to highlight. theme: A HighlightTheme class (type not instance). tab_size: Number of spaces in a tab. Returns: A Content instance which may be used in a

(
    code: str,
    *,
    language: str | None = None,
    path: str | None = None,
    theme: type[HighlightTheme] = HighlightTheme,
    tab_size: int = 8,
)

Source from the content-addressed store, hash-verified

182
183
184def highlight(
185 code: str,
186 *,
187 language: str | None = None,
188 path: str | None = None,
189 theme: type[HighlightTheme] = HighlightTheme,
190 tab_size: int = 8,
191) -> Content:
192 """Apply syntax highlighting to a string.
193
194 Args:
195 code: A string to highlight.
196 language: The language to highlight.
197 theme: A HighlightTheme class (type not instance).
198 tab_size: Number of spaces in a tab.
199
200 Returns:
201 A Content instance which may be used in a widget.
202 """
203 if not language:
204 language = guess_language(code, path)
205
206 assert language is not None
207 code = "\n".join(code.splitlines())
208 try:
209 lexer = get_lexer_by_name(
210 language,
211 stripnl=False,
212 ensurenl=True,
213 tabsize=tab_size,
214 )
215 except ClassNotFound:
216 lexer = get_lexer_by_name(
217 "text",
218 stripnl=False,
219 ensurenl=True,
220 tabsize=tab_size,
221 )
222
223 token_start = 0
224 spans: list[Span] = []
225 styles = theme.STYLES
226
227 for token_type, token in lexer.get_tokens(code):
228 token_end = token_start + len(token)
229 while True:
230 if style := styles.get(token_type):
231 spans.append(Span(token_start, token_end, style))
232 break
233 if (token_type := token_type.parent) is None:
234 break
235 token_start = token_end
236
237 highlighted_code = Content(code, spans=spans).stylize_before("$text")
238 return highlighted_code

Callers 3

highlightMethod · 0.90
test_highlightFunction · 0.90
watch_pathMethod · 0.90

Calls 7

SpanClass · 0.90
ContentClass · 0.90
guess_languageFunction · 0.85
stylize_beforeMethod · 0.80
joinMethod · 0.45
getMethod · 0.45
appendMethod · 0.45

Tested by 1

test_highlightFunction · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…