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

Method highlight

rich/syntax.py:470–553  ·  view source on GitHub ↗

Highlight code and return a Text instance. Args: code (str): Code to highlight. line_range(Tuple[int, int], optional): Optional line range to highlight. Returns: Text: A text instance containing highlighted syntax.

(
        self,
        code: str,
        line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,
    )

Source from the content-addressed store, hash-verified

468 )
469
470 def highlight(
471 self,
472 code: str,
473 line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,
474 ) -> Text:
475 """Highlight code and return a Text instance.
476
477 Args:
478 code (str): Code to highlight.
479 line_range(Tuple[int, int], optional): Optional line range to highlight.
480
481 Returns:
482 Text: A text instance containing highlighted syntax.
483 """
484
485 base_style = self._get_base_style()
486 justify: JustifyMethod = (
487 "default" if base_style.transparent_background else "left"
488 )
489
490 text = Text(
491 justify=justify,
492 style=base_style,
493 tab_size=self.tab_size,
494 no_wrap=not self.word_wrap,
495 )
496 _get_theme_style = self._theme.get_style_for_token
497
498 lexer = self.lexer or self.default_lexer
499
500 if lexer is None:
501 text.append(code)
502 else:
503 if line_range:
504 # More complicated path to only stylize a portion of the code
505 # This speeds up further operations as there are less spans to process
506 line_start, line_end = line_range
507
508 def line_tokenize() -> Iterable[Tuple[Any, str]]:
509 """Split tokens to one per line."""
510 assert lexer # required to make MyPy happy - we know lexer is not None at this point
511
512 for token_type, token in lexer.get_tokens(code):
513 while token:
514 line_token, new_line, token = token.partition("\n")
515 yield token_type, line_token + new_line
516
517 def tokens_to_spans() -> Iterable[Tuple[str, Optional[Style]]]:
518 """Convert tokens to spans."""
519 tokens = iter(line_tokenize())
520 line_no = 0
521 _line_start = line_start - 1 if line_start else 0
522
523 # Skip over tokens until line start
524 while line_no < _line_start:
525 try:
526 _token_type, token = next(tokens)
527 except StopIteration:

Callers 7

_get_syntaxMethod · 0.95
test_highlight_regexFunction · 0.45
renderMethod · 0.45
renderMethod · 0.45
on_textMethod · 0.45

Calls 6

_get_base_styleMethod · 0.95
appendMethod · 0.95
append_tokensMethod · 0.95
stylizeMethod · 0.95
TextClass · 0.85

Tested by 3

test_highlight_regexFunction · 0.36