您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

986 行
35 KiB

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