Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/rich/syntax.py: 57%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from __future__ import annotations
3import os.path
4import re
5import sys
6import textwrap
7from abc import ABC, abstractmethod
8from pathlib import Path
9from typing import TYPE_CHECKING, Any, Iterable, NamedTuple, Sequence
11from pygments.lexer import Lexer
12from pygments.lexers import get_lexer_by_name, guess_lexer_for_filename
13from pygments.style import Style as PygmentsStyle
14from pygments.styles import get_style_by_name
15from pygments.token import (
16 Comment,
17 Error,
18 Generic,
19 Keyword,
20 Name,
21 Number,
22 Operator,
23 String,
24 Token,
25 Whitespace,
26)
27from pygments.util import ClassNotFound
29if TYPE_CHECKING:
30 from .console import Console, ConsoleOptions, JustifyMethod, RenderResult
32from rich.containers import Lines
33from rich.padding import Padding, PaddingDimensions
35from ._loop import loop_first
36from .cells import cell_len
37from .color import Color, blend_rgb
38from .jupyter import JupyterMixin
39from .measure import Measurement
40from .segment import Segment, Segments
41from .style import Style, StyleType
42from .text import Text
44TokenType = tuple[str, ...]
46WINDOWS = sys.platform == "win32"
47DEFAULT_THEME = "monokai"
49# The following styles are based on https://github.com/pygments/pygments/blob/master/pygments/formatters/terminal.py
50# A few modifications were made
52ANSI_LIGHT: dict[TokenType, Style] = {
53 Token: Style(),
54 Whitespace: Style(color="white"),
55 Comment: Style(dim=True),
56 Comment.Preproc: Style(color="cyan"),
57 Keyword: Style(color="blue"),
58 Keyword.Type: Style(color="cyan"),
59 Operator.Word: Style(color="magenta"),
60 Name.Builtin: Style(color="cyan"),
61 Name.Function: Style(color="green"),
62 Name.Namespace: Style(color="cyan", underline=True),
63 Name.Class: Style(color="green", underline=True),
64 Name.Exception: Style(color="cyan"),
65 Name.Decorator: Style(color="magenta", bold=True),
66 Name.Variable: Style(color="red"),
67 Name.Constant: Style(color="red"),
68 Name.Attribute: Style(color="cyan"),
69 Name.Tag: Style(color="bright_blue"),
70 String: Style(color="yellow"),
71 Number: Style(color="blue"),
72 Generic.Deleted: Style(color="bright_red"),
73 Generic.Inserted: Style(color="green"),
74 Generic.Heading: Style(bold=True),
75 Generic.Subheading: Style(color="magenta", bold=True),
76 Generic.Prompt: Style(bold=True),
77 Generic.Error: Style(color="bright_red"),
78 Error: Style(color="red", underline=True),
79}
81ANSI_DARK: dict[TokenType, Style] = {
82 Token: Style(),
83 Whitespace: Style(color="bright_black"),
84 Comment: Style(dim=True),
85 Comment.Preproc: Style(color="bright_cyan"),
86 Keyword: Style(color="bright_blue"),
87 Keyword.Type: Style(color="bright_cyan"),
88 Operator.Word: Style(color="bright_magenta"),
89 Name.Builtin: Style(color="bright_cyan"),
90 Name.Function: Style(color="bright_green"),
91 Name.Namespace: Style(color="bright_cyan", underline=True),
92 Name.Class: Style(color="bright_green", underline=True),
93 Name.Exception: Style(color="bright_cyan"),
94 Name.Decorator: Style(color="bright_magenta", bold=True),
95 Name.Variable: Style(color="bright_red"),
96 Name.Constant: Style(color="bright_red"),
97 Name.Attribute: Style(color="bright_cyan"),
98 Name.Tag: Style(color="bright_blue"),
99 String: Style(color="yellow"),
100 Number: Style(color="bright_blue"),
101 Generic.Deleted: Style(color="bright_red"),
102 Generic.Inserted: Style(color="bright_green"),
103 Generic.Heading: Style(bold=True),
104 Generic.Subheading: Style(color="bright_magenta", bold=True),
105 Generic.Prompt: Style(bold=True),
106 Generic.Error: Style(color="bright_red"),
107 Error: Style(color="red", underline=True),
108}
110RICH_SYNTAX_THEMES = {"ansi_light": ANSI_LIGHT, "ansi_dark": ANSI_DARK}
111NUMBERS_COLUMN_DEFAULT_PADDING = 2
114class SyntaxTheme(ABC):
115 """Base class for a syntax theme."""
117 @abstractmethod
118 def get_style_for_token(self, token_type: TokenType) -> Style:
119 """Get a style for a given Pygments token."""
120 raise NotImplementedError # pragma: no cover
122 @abstractmethod
123 def get_background_style(self) -> Style:
124 """Get the background color."""
125 raise NotImplementedError # pragma: no cover
128class PygmentsSyntaxTheme(SyntaxTheme):
129 """Syntax theme that delegates to Pygments theme."""
131 def __init__(self, theme: str | type[PygmentsStyle]) -> None:
132 self._style_cache: dict[TokenType, Style] = {}
133 if isinstance(theme, str):
134 try:
135 self._pygments_style_class = get_style_by_name(theme)
136 except ClassNotFound:
137 self._pygments_style_class = get_style_by_name("default")
138 else:
139 self._pygments_style_class = theme
141 self._background_color = self._pygments_style_class.background_color
142 self._background_style = Style(bgcolor=self._background_color)
144 def get_style_for_token(self, token_type: TokenType) -> Style:
145 """Get a style from a Pygments class."""
146 try:
147 return self._style_cache[token_type]
148 except KeyError:
149 try:
150 pygments_style = self._pygments_style_class.style_for_token(token_type)
151 except KeyError:
152 style = Style.null()
153 else:
154 color = pygments_style["color"]
155 bgcolor = pygments_style["bgcolor"]
156 style = Style(
157 color="#" + color if color else "#000000",
158 bgcolor="#" + bgcolor if bgcolor else self._background_color,
159 bold=pygments_style["bold"],
160 italic=pygments_style["italic"],
161 underline=pygments_style["underline"],
162 )
163 self._style_cache[token_type] = style
164 return style
166 def get_background_style(self) -> Style:
167 return self._background_style
170class ANSISyntaxTheme(SyntaxTheme):
171 """Syntax theme to use standard colors."""
173 def __init__(self, style_map: dict[TokenType, Style]) -> None:
174 self.style_map = style_map
175 self._missing_style = Style.null()
176 self._background_style = Style.null()
177 self._style_cache: dict[TokenType, Style] = {}
179 def get_style_for_token(self, token_type: TokenType) -> Style:
180 """Look up style in the style map."""
181 try:
182 return self._style_cache[token_type]
183 except KeyError:
184 # Styles form a hierarchy
185 # We need to go from most to least specific
186 # e.g. ("foo", "bar", "baz") to ("foo", "bar") to ("foo",)
187 get_style = self.style_map.get
188 token = tuple(token_type)
189 style = self._missing_style
190 while token:
191 _style = get_style(token)
192 if _style is not None:
193 style = _style
194 break
195 token = token[:-1]
196 self._style_cache[token_type] = style
197 return style
199 def get_background_style(self) -> Style:
200 return self._background_style
203SyntaxPosition = tuple[int, int]
206class _SyntaxHighlightRange(NamedTuple):
207 """
208 A range to highlight in a Syntax object.
209 `start` and `end` are 2-integers tuples, where the first integer is the line number
210 (starting from 1) and the second integer is the column index (starting from 0).
211 """
213 style: StyleType
214 start: SyntaxPosition
215 end: SyntaxPosition
216 style_before: bool = False
219class PaddingProperty:
220 """Descriptor to get and set padding."""
222 def __get__(self, obj: Syntax, objtype: type[Syntax]) -> tuple[int, int, int, int]:
223 """Space around the Syntax."""
224 return obj._padding
226 def __set__(self, obj: Syntax, padding: PaddingDimensions) -> None:
227 obj._padding = Padding.unpack(padding)
230class Syntax(JupyterMixin):
231 """Construct a Syntax object to render syntax highlighted code.
233 Args:
234 code (str): Code to highlight.
235 lexer (Lexer | str): Lexer to use (see https://pygments.org/docs/lexers/)
236 theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "monokai".
237 dedent (bool, optional): Enable stripping of initial whitespace. Defaults to False.
238 line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.
239 start_line (int, optional): Starting number for line numbers. Defaults to 1.
240 line_range (tuple[int | None, int | None], optional): If given should be a tuple of the start and end line to render.
241 A value of None in the tuple indicates the range is open in that direction.
242 highlight_lines (set[int]): A set of line numbers to highlight.
243 code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.
244 tab_size (int, optional): Size of tabs. Defaults to 4.
245 word_wrap (bool, optional): Enable word wrapping.
246 background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.
247 indent_guides (bool, optional): Show indent guides. Defaults to False.
248 padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding).
249 """
251 _pygments_style_class: type[PygmentsStyle]
252 _theme: SyntaxTheme
254 @classmethod
255 def get_theme(cls, name: str | SyntaxTheme) -> SyntaxTheme:
256 """Get a syntax theme instance."""
257 if isinstance(name, SyntaxTheme):
258 return name
259 theme: SyntaxTheme
260 if name in RICH_SYNTAX_THEMES:
261 theme = ANSISyntaxTheme(RICH_SYNTAX_THEMES[name])
262 else:
263 theme = PygmentsSyntaxTheme(name)
264 return theme
266 def __init__(
267 self,
268 code: str,
269 lexer: Lexer | str,
270 *,
271 theme: str | SyntaxTheme = DEFAULT_THEME,
272 dedent: bool = False,
273 line_numbers: bool = False,
274 start_line: int = 1,
275 line_range: tuple[int | None, int | None] | None = None,
276 highlight_lines: set[int] | None = None,
277 code_width: int | None = None,
278 tab_size: int = 4,
279 word_wrap: bool = False,
280 background_color: str | None = None,
281 indent_guides: bool = False,
282 padding: PaddingDimensions = 0,
283 ) -> None:
284 self.code = code
285 self._lexer = lexer
286 self.dedent = dedent
287 self.line_numbers = line_numbers
288 self.start_line = start_line
289 self.line_range = line_range
290 self.highlight_lines = highlight_lines or set()
291 self.code_width = code_width
292 self.tab_size = tab_size
293 self.word_wrap = word_wrap
294 self.background_color = background_color
295 self.background_style = (
296 Style(bgcolor=background_color) if background_color else Style()
297 )
298 self.indent_guides = indent_guides
299 self._padding = Padding.unpack(padding)
301 self._theme = self.get_theme(theme)
302 self._stylized_ranges: list[_SyntaxHighlightRange] = []
304 padding = PaddingProperty()
306 @classmethod
307 def from_path(
308 cls,
309 path: str,
310 encoding: str = "utf-8",
311 lexer: Lexer | str | None = None,
312 theme: str | SyntaxTheme = DEFAULT_THEME,
313 dedent: bool = False,
314 line_numbers: bool = False,
315 line_range: tuple[int, int] | None = None,
316 start_line: int = 1,
317 highlight_lines: set[int] | None = None,
318 code_width: int | None = None,
319 tab_size: int = 4,
320 word_wrap: bool = False,
321 background_color: str | None = None,
322 indent_guides: bool = False,
323 padding: PaddingDimensions = 0,
324 ) -> "Syntax":
325 """Construct a Syntax object from a file.
327 Args:
328 path (str): Path to file to highlight.
329 encoding (str): Encoding of file.
330 lexer (str | Lexer, optional): Lexer to use. If None, lexer will be auto-detected from path/file content.
331 theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "emacs".
332 dedent (bool, optional): Enable stripping of initial whitespace. Defaults to True.
333 line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.
334 start_line (int, optional): Starting number for line numbers. Defaults to 1.
335 line_range (tuple[int, int], optional): If given should be a tuple of the start and end line to render.
336 highlight_lines (set[int]): A set of line numbers to highlight.
337 code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.
338 tab_size (int, optional): Size of tabs. Defaults to 4.
339 word_wrap (bool, optional): Enable word wrapping of code.
340 background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.
341 indent_guides (bool, optional): Show indent guides. Defaults to False.
342 padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding).
344 Returns:
345 [Syntax]: A Syntax object that may be printed to the console
346 """
347 code = Path(path).read_text(encoding=encoding)
349 if not lexer:
350 lexer = cls.guess_lexer(path, code=code)
352 return cls(
353 code,
354 lexer,
355 theme=theme,
356 dedent=dedent,
357 line_numbers=line_numbers,
358 line_range=line_range,
359 start_line=start_line,
360 highlight_lines=highlight_lines,
361 code_width=code_width,
362 tab_size=tab_size,
363 word_wrap=word_wrap,
364 background_color=background_color,
365 indent_guides=indent_guides,
366 padding=padding,
367 )
369 @classmethod
370 def guess_lexer(cls, path: str, code: str | None = None) -> str:
371 """Guess the alias of the Pygments lexer to use based on a path and an optional string of code.
372 If code is supplied, it will use a combination of the code and the filename to determine the
373 best lexer to use. For example, if the file is ``index.html`` and the file contains Django
374 templating syntax, then "html+django" will be returned. If the file is ``index.html``, and no
375 templating language is used, the "html" lexer will be used. If no string of code
376 is supplied, the lexer will be chosen based on the file extension..
378 Args:
379 path (AnyStr): The path to the file containing the code you wish to know the lexer for.
380 code (str, optional): Optional string of code that will be used as a fallback if no lexer
381 is found for the supplied path.
383 Returns:
384 str: The name of the Pygments lexer that best matches the supplied path/code.
385 """
386 lexer: Lexer | None = None
387 lexer_name = "default"
388 if code:
389 try:
390 lexer = guess_lexer_for_filename(path, code)
391 except ClassNotFound:
392 pass
394 if not lexer:
395 try:
396 _, ext = os.path.splitext(path)
397 if ext:
398 extension = ext.lstrip(".").lower()
399 lexer = get_lexer_by_name(extension)
400 except ClassNotFound:
401 pass
403 if lexer:
404 if lexer.aliases:
405 lexer_name = lexer.aliases[0]
406 else:
407 lexer_name = lexer.name
409 return lexer_name
411 def _get_base_style(self) -> Style:
412 """Get the base style."""
413 default_style = self._theme.get_background_style() + self.background_style
414 return default_style
416 def _get_token_color(self, token_type: TokenType) -> Color | None:
417 """Get a color (if any) for the given token.
419 Args:
420 token_type (TokenType): A token type tuple from Pygments.
422 Returns:
423 Color | None: Color from theme, or None for no color.
424 """
425 style = self._theme.get_style_for_token(token_type)
426 return style.color
428 @property
429 def lexer(self) -> Lexer | None:
430 """The lexer for this syntax, or None if no lexer was found.
432 Tries to find the lexer by name if a string was passed to the constructor.
433 """
435 if isinstance(self._lexer, Lexer):
436 return self._lexer
437 try:
438 return get_lexer_by_name(
439 self._lexer,
440 stripnl=False,
441 ensurenl=True,
442 tabsize=self.tab_size,
443 )
444 except ClassNotFound:
445 return None
447 @property
448 def default_lexer(self) -> Lexer:
449 """A Pygments Lexer to use if one is not specified or invalid."""
450 return get_lexer_by_name(
451 "text",
452 stripnl=False,
453 ensurenl=True,
454 tabsize=self.tab_size,
455 )
457 def highlight(
458 self,
459 code: str,
460 line_range: tuple[int | None, int | None] | None = None,
461 ) -> Text:
462 """Highlight code and return a Text instance.
464 Args:
465 code (str): Code to highlight.
466 line_range(tuple[int, int], optional): Optional line range to highlight.
468 Returns:
469 Text: A text instance containing highlighted syntax.
470 """
472 base_style = self._get_base_style()
473 justify: JustifyMethod = (
474 "default" if base_style.transparent_background else "left"
475 )
477 text = Text(
478 justify=justify,
479 style=base_style,
480 tab_size=self.tab_size,
481 no_wrap=not self.word_wrap,
482 )
483 _get_theme_style = self._theme.get_style_for_token
485 lexer = self.lexer or self.default_lexer
487 if lexer is None:
488 text.append(code)
489 else:
490 if line_range:
491 # More complicated path to only stylize a portion of the code
492 # This speeds up further operations as there are less spans to process
493 line_start, line_end = line_range
495 def line_tokenize() -> Iterable[tuple[Any, str]]:
496 """Split tokens to one per line."""
497 assert lexer # required to make MyPy happy - we know lexer is not None at this point
499 for token_type, token in lexer.get_tokens(code):
500 while token:
501 line_token, new_line, token = token.partition("\n")
502 yield token_type, line_token + new_line
504 def tokens_to_spans() -> Iterable[tuple[str, Style | None]]:
505 """Convert tokens to spans."""
506 tokens = iter(line_tokenize())
507 line_no = 0
508 _line_start = line_start - 1 if line_start else 0
510 # Skip over tokens until line start
511 while line_no < _line_start:
512 try:
513 _token_type, token = next(tokens)
514 except StopIteration:
515 break
516 yield (token, None)
517 if token.endswith("\n"):
518 line_no += 1
519 # Generate spans until line end
520 for token_type, token in tokens:
521 yield (token, _get_theme_style(token_type))
522 if token.endswith("\n"):
523 line_no += 1
524 if line_end and line_no >= line_end:
525 break
527 text.append_tokens(tokens_to_spans())
529 else:
530 text.append_tokens(
531 (token, _get_theme_style(token_type))
532 for token_type, token in lexer.get_tokens(code)
533 )
534 if self.background_color is not None:
535 text.stylize(f"on {self.background_color}")
537 if self._stylized_ranges:
538 self._apply_stylized_ranges(text)
540 return text
542 def stylize_range(
543 self,
544 style: StyleType,
545 start: SyntaxPosition,
546 end: SyntaxPosition,
547 style_before: bool = False,
548 ) -> None:
549 """
550 Adds a custom style on a part of the code, that will be applied to the syntax display when it's rendered.
551 Line numbers are 1-based, while column indexes are 0-based.
553 Args:
554 style (StyleType): The style to apply.
555 start (tuple[int, int]): The start of the range, in the form `[line number, column index]`.
556 end (tuple[int, int]): The end of the range, in the form `[line number, column index]`.
557 style_before (bool): Apply the style before any existing styles.
558 """
559 self._stylized_ranges.append(
560 _SyntaxHighlightRange(style, start, end, style_before)
561 )
563 def _get_line_numbers_color(self, blend: float = 0.3) -> Color:
564 background_style = self._theme.get_background_style() + self.background_style
565 background_color = background_style.bgcolor
566 if background_color is None or background_color.is_system_defined:
567 return Color.default()
568 foreground_color = self._get_token_color(Token.Text)
569 if foreground_color is None or foreground_color.is_system_defined:
570 return foreground_color or Color.default()
571 new_color = blend_rgb(
572 background_color.get_truecolor(),
573 foreground_color.get_truecolor(),
574 cross_fade=blend,
575 )
576 return Color.from_triplet(new_color)
578 @property
579 def _numbers_column_width(self) -> int:
580 """Get the number of characters used to render the numbers column."""
581 column_width = 0
582 if self.line_numbers:
583 column_width = (
584 len(str(self.start_line + self.code.count("\n")))
585 + NUMBERS_COLUMN_DEFAULT_PADDING
586 )
587 return column_width
589 def _get_number_styles(self, console: Console) -> tuple[Style, Style, Style]:
590 """Get background, number, and highlight styles for line numbers."""
591 background_style = self._get_base_style()
592 if background_style.transparent_background:
593 return Style.null(), Style(dim=True), Style.null()
594 if console.color_system in ("256", "truecolor"):
595 number_style = Style.chain(
596 background_style,
597 self._theme.get_style_for_token(Token.Text),
598 Style(color=self._get_line_numbers_color()),
599 self.background_style,
600 )
601 highlight_number_style = Style.chain(
602 background_style,
603 self._theme.get_style_for_token(Token.Text),
604 Style(bold=True, color=self._get_line_numbers_color(0.9)),
605 self.background_style,
606 )
607 else:
608 number_style = background_style + Style(dim=True)
609 highlight_number_style = background_style + Style(dim=False)
610 return background_style, number_style, highlight_number_style
612 def __rich_measure__(
613 self, console: "Console", options: "ConsoleOptions"
614 ) -> "Measurement":
615 _, right, _, left = self.padding
616 padding = left + right
617 if self.code_width is not None:
618 width = self.code_width + self._numbers_column_width + padding + 1
619 return Measurement(self._numbers_column_width, width)
620 lines = self.code.splitlines()
621 width = (
622 self._numbers_column_width
623 + padding
624 + (max(cell_len(line) for line in lines) if lines else 0)
625 )
626 if self.line_numbers:
627 width += 1
628 return Measurement(self._numbers_column_width, width)
630 def __rich_console__(
631 self, console: Console, options: ConsoleOptions
632 ) -> RenderResult:
633 segments = Segments(self._get_syntax(console, options))
634 if any(self.padding):
635 yield Padding(segments, style=self._get_base_style(), pad=self.padding)
636 else:
637 yield segments
639 def _get_syntax(
640 self,
641 console: Console,
642 options: ConsoleOptions,
643 ) -> Iterable[Segment]:
644 """
645 Get the Segments for the Syntax object, excluding any vertical/horizontal padding
646 """
647 transparent_background = self._get_base_style().transparent_background
648 _pad_top, pad_right, _pad_bottom, pad_left = self.padding
649 horizontal_padding = pad_left + pad_right
650 code_width = (
651 (
652 (options.max_width - self._numbers_column_width - 1)
653 if self.line_numbers
654 else options.max_width
655 )
656 - horizontal_padding
657 if self.code_width is None
658 else self.code_width
659 )
660 code_width = max(0, code_width)
662 ends_on_nl, processed_code = self._process_code(self.code)
663 text = self.highlight(processed_code, self.line_range)
665 if not self.line_numbers and not self.word_wrap and not self.line_range:
666 if not ends_on_nl:
667 text.remove_suffix("\n")
668 # Simple case of just rendering text
669 style = (
670 self._get_base_style()
671 + self._theme.get_style_for_token(Comment)
672 + Style(dim=True)
673 + self.background_style
674 )
675 if self.indent_guides and not options.ascii_only:
676 text = text.with_indent_guides(self.tab_size, style=style)
677 text.overflow = "crop"
678 if style.transparent_background:
679 yield from console.render(
680 text, options=options.update(width=code_width)
681 )
682 else:
683 syntax_lines = console.render_lines(
684 text,
685 options.update(width=code_width, height=None, justify="left"),
686 style=self.background_style,
687 pad=True,
688 new_lines=True,
689 )
690 for syntax_line in syntax_lines:
691 yield from syntax_line
692 return
694 start_line, end_line = self.line_range or (None, None)
695 line_offset = 0
696 if start_line:
697 line_offset = max(0, start_line - 1)
698 lines: list[Text] | Lines = text.split("\n", allow_blank=ends_on_nl)
699 if self.line_range:
700 if line_offset > len(lines):
701 return
702 lines = lines[line_offset:end_line]
704 if self.indent_guides and not options.ascii_only:
705 style = (
706 self._get_base_style()
707 + self._theme.get_style_for_token(Comment)
708 + Style(dim=True)
709 + self.background_style
710 )
711 lines = (
712 Text("\n")
713 .join(lines)
714 .with_indent_guides(self.tab_size, style=style + Style(italic=False))
715 .split("\n", allow_blank=True)
716 )
718 numbers_column_width = self._numbers_column_width
719 render_options = options.update(width=code_width)
721 highlight_line = self.highlight_lines.__contains__
722 _Segment = Segment
723 new_line = _Segment("\n")
725 line_pointer = "> " if options.legacy_windows else "❱ "
727 (
728 background_style,
729 number_style,
730 highlight_number_style,
731 ) = self._get_number_styles(console)
733 for line_no, line in enumerate(lines, self.start_line + line_offset):
734 if self.word_wrap:
735 wrapped_lines = console.render_lines(
736 line,
737 render_options.update(height=None, justify="left"),
738 style=background_style,
739 pad=not transparent_background,
740 )
741 else:
742 segments = list(line.render(console, end=""))
743 if options.no_wrap:
744 wrapped_lines = [segments]
745 else:
746 wrapped_lines = [
747 _Segment.adjust_line_length(
748 segments,
749 render_options.max_width,
750 style=background_style,
751 pad=not transparent_background,
752 )
753 ]
755 if self.line_numbers:
756 wrapped_line_left_pad = _Segment(
757 " " * numbers_column_width + " ", background_style
758 )
759 for first, wrapped_line in loop_first(wrapped_lines):
760 if first:
761 line_column = str(line_no).rjust(numbers_column_width - 2) + " "
762 if highlight_line(line_no):
763 yield _Segment(line_pointer, Style(color="red"))
764 yield _Segment(line_column, highlight_number_style)
765 else:
766 yield _Segment(" ", highlight_number_style)
767 yield _Segment(line_column, number_style)
768 else:
769 yield wrapped_line_left_pad
770 yield from wrapped_line
771 yield new_line
772 else:
773 for wrapped_line in wrapped_lines:
774 yield from wrapped_line
775 yield new_line
777 def _apply_stylized_ranges(self, text: Text) -> None:
778 """
779 Apply stylized ranges to a text instance,
780 using the given code to determine the right portion to apply the style to.
782 Args:
783 text (Text): Text instance to apply the style to.
784 """
785 code = text.plain
786 newlines_offsets = [
787 # Let's add outer boundaries at each side of the list:
788 0,
789 # N.B. using "\n" here is much faster than using metacharacters such as "^" or "\Z":
790 *[
791 match.start() + 1
792 for match in re.finditer("\n", code, flags=re.MULTILINE)
793 ],
794 len(code) + 1,
795 ]
797 for stylized_range in self._stylized_ranges:
798 start = _get_code_index_for_syntax_position(
799 newlines_offsets, stylized_range.start
800 )
801 end = _get_code_index_for_syntax_position(
802 newlines_offsets, stylized_range.end
803 )
804 if start is not None and end is not None:
805 if stylized_range.style_before:
806 text.stylize_before(stylized_range.style, start, end)
807 else:
808 text.stylize(stylized_range.style, start, end)
810 def _process_code(self, code: str) -> tuple[bool, str]:
811 """
812 Applies various processing to a raw code string
813 (normalises it so it always ends with a line return, dedents it if necessary, etc.)
815 Args:
816 code (str): The raw code string to process
818 Returns:
819 tuple[bool, str]: the boolean indicates whether the raw code ends with a line return,
820 while the string is the processed code.
821 """
822 ends_on_nl = code.endswith("\n")
823 processed_code = code if ends_on_nl else code + "\n"
824 processed_code = (
825 textwrap.dedent(processed_code) if self.dedent else processed_code
826 )
827 processed_code = processed_code.expandtabs(self.tab_size)
828 return ends_on_nl, processed_code
831def _get_code_index_for_syntax_position(
832 newlines_offsets: Sequence[int], position: SyntaxPosition
833) -> int | None:
834 """
835 Returns the index of the code string for the given positions.
837 Args:
838 newlines_offsets (Sequence[int]): The offset of each newline character found in the code snippet.
839 position (SyntaxPosition): The position to search for.
841 Returns:
842 int | None: The index of the code string for this position, or `None`
843 if the given position's line number is out of range (if it's the column that is out of range
844 we silently clamp its value so that it reaches the end of the line)
845 """
846 lines_count = len(newlines_offsets)
848 line_number, column_index = position
849 if line_number > lines_count or len(newlines_offsets) < (line_number + 1):
850 return None # `line_number` is out of range
851 line_index = line_number - 1
852 line_length = newlines_offsets[line_index + 1] - newlines_offsets[line_index] - 1
853 # If `column_index` is out of range: let's silently clamp it:
854 column_index = min(line_length, column_index)
855 return newlines_offsets[line_index] + column_index
858if __name__ == "__main__": # pragma: no cover
859 import argparse
860 import sys
862 parser = argparse.ArgumentParser(
863 description="Render syntax to the console with Rich"
864 )
865 parser.add_argument(
866 "path",
867 metavar="PATH",
868 help="path to file, or - for stdin",
869 )
870 parser.add_argument(
871 "-c",
872 "--force-color",
873 dest="force_color",
874 action="store_true",
875 default=None,
876 help="force color for non-terminals",
877 )
878 parser.add_argument(
879 "-i",
880 "--indent-guides",
881 dest="indent_guides",
882 action="store_true",
883 default=False,
884 help="display indent guides",
885 )
886 parser.add_argument(
887 "-l",
888 "--line-numbers",
889 dest="line_numbers",
890 action="store_true",
891 help="render line numbers",
892 )
893 parser.add_argument(
894 "-w",
895 "--width",
896 type=int,
897 dest="width",
898 default=None,
899 help="width of output (default will auto-detect)",
900 )
901 parser.add_argument(
902 "-r",
903 "--wrap",
904 dest="word_wrap",
905 action="store_true",
906 default=False,
907 help="word wrap long lines",
908 )
909 parser.add_argument(
910 "-s",
911 "--soft-wrap",
912 action="store_true",
913 dest="soft_wrap",
914 default=False,
915 help="enable soft wrapping mode",
916 )
917 parser.add_argument(
918 "-t", "--theme", dest="theme", default="monokai", help="pygments theme"
919 )
920 parser.add_argument(
921 "-b",
922 "--background-color",
923 dest="background_color",
924 default=None,
925 help="Override background color",
926 )
927 parser.add_argument(
928 "-x",
929 "--lexer",
930 default=None,
931 dest="lexer_name",
932 help="Lexer name",
933 )
934 parser.add_argument(
935 "-p", "--padding", type=int, default=0, dest="padding", help="Padding"
936 )
937 parser.add_argument(
938 "--highlight-line",
939 type=int,
940 default=None,
941 dest="highlight_line",
942 help="The line number (not index!) to highlight",
943 )
944 args = parser.parse_args()
946 from rich.console import Console
948 console = Console(force_terminal=args.force_color, width=args.width)
950 if args.path == "-":
951 code = sys.stdin.read()
952 syntax = Syntax(
953 code=code,
954 lexer=args.lexer_name,
955 line_numbers=args.line_numbers,
956 word_wrap=args.word_wrap,
957 theme=args.theme,
958 background_color=args.background_color,
959 indent_guides=args.indent_guides,
960 padding=args.padding,
961 highlight_lines={args.highlight_line},
962 )
963 else:
964 syntax = Syntax.from_path(
965 args.path,
966 lexer=args.lexer_name,
967 line_numbers=args.line_numbers,
968 word_wrap=args.word_wrap,
969 theme=args.theme,
970 background_color=args.background_color,
971 indent_guides=args.indent_guides,
972 padding=args.padding,
973 highlight_lines={args.highlight_line},
974 )
975 console.print(syntax, soft_wrap=args.soft_wrap)