syntax.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. import os.path
  2. import platform
  3. from pip._vendor.rich.containers import Lines
  4. import textwrap
  5. from abc import ABC, abstractmethod
  6. from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Type, Union
  7. from pip._vendor.pygments.lexer import Lexer
  8. from pip._vendor.pygments.lexers import get_lexer_by_name, guess_lexer_for_filename
  9. from pip._vendor.pygments.style import Style as PygmentsStyle
  10. from pip._vendor.pygments.styles import get_style_by_name
  11. from pip._vendor.pygments.token import (
  12. Comment,
  13. Error,
  14. Generic,
  15. Keyword,
  16. Name,
  17. Number,
  18. Operator,
  19. String,
  20. Token,
  21. Whitespace,
  22. )
  23. from pip._vendor.pygments.util import ClassNotFound
  24. from ._loop import loop_first
  25. from .color import Color, blend_rgb
  26. from .console import Console, ConsoleOptions, JustifyMethod, RenderResult
  27. from .jupyter import JupyterMixin
  28. from .measure import Measurement
  29. from .segment import Segment
  30. from .style import Style
  31. from .text import Text
  32. TokenType = Tuple[str, ...]
  33. WINDOWS = platform.system() == "Windows"
  34. DEFAULT_THEME = "monokai"
  35. # The following styles are based on https://github.com/pygments/pygments/blob/master/pygments/formatters/terminal.py
  36. # A few modifications were made
  37. ANSI_LIGHT: Dict[TokenType, Style] = {
  38. Token: Style(),
  39. Whitespace: Style(color="white"),
  40. Comment: Style(dim=True),
  41. Comment.Preproc: Style(color="cyan"),
  42. Keyword: Style(color="blue"),
  43. Keyword.Type: Style(color="cyan"),
  44. Operator.Word: Style(color="magenta"),
  45. Name.Builtin: Style(color="cyan"),
  46. Name.Function: Style(color="green"),
  47. Name.Namespace: Style(color="cyan", underline=True),
  48. Name.Class: Style(color="green", underline=True),
  49. Name.Exception: Style(color="cyan"),
  50. Name.Decorator: Style(color="magenta", bold=True),
  51. Name.Variable: Style(color="red"),
  52. Name.Constant: Style(color="red"),
  53. Name.Attribute: Style(color="cyan"),
  54. Name.Tag: Style(color="bright_blue"),
  55. String: Style(color="yellow"),
  56. Number: Style(color="blue"),
  57. Generic.Deleted: Style(color="bright_red"),
  58. Generic.Inserted: Style(color="green"),
  59. Generic.Heading: Style(bold=True),
  60. Generic.Subheading: Style(color="magenta", bold=True),
  61. Generic.Prompt: Style(bold=True),
  62. Generic.Error: Style(color="bright_red"),
  63. Error: Style(color="red", underline=True),
  64. }
  65. ANSI_DARK: Dict[TokenType, Style] = {
  66. Token: Style(),
  67. Whitespace: Style(color="bright_black"),
  68. Comment: Style(dim=True),
  69. Comment.Preproc: Style(color="bright_cyan"),
  70. Keyword: Style(color="bright_blue"),
  71. Keyword.Type: Style(color="bright_cyan"),
  72. Operator.Word: Style(color="bright_magenta"),
  73. Name.Builtin: Style(color="bright_cyan"),
  74. Name.Function: Style(color="bright_green"),
  75. Name.Namespace: Style(color="bright_cyan", underline=True),
  76. Name.Class: Style(color="bright_green", underline=True),
  77. Name.Exception: Style(color="bright_cyan"),
  78. Name.Decorator: Style(color="bright_magenta", bold=True),
  79. Name.Variable: Style(color="bright_red"),
  80. Name.Constant: Style(color="bright_red"),
  81. Name.Attribute: Style(color="bright_cyan"),
  82. Name.Tag: Style(color="bright_blue"),
  83. String: Style(color="yellow"),
  84. Number: Style(color="bright_blue"),
  85. Generic.Deleted: Style(color="bright_red"),
  86. Generic.Inserted: Style(color="bright_green"),
  87. Generic.Heading: Style(bold=True),
  88. Generic.Subheading: Style(color="bright_magenta", bold=True),
  89. Generic.Prompt: Style(bold=True),
  90. Generic.Error: Style(color="bright_red"),
  91. Error: Style(color="red", underline=True),
  92. }
  93. RICH_SYNTAX_THEMES = {"ansi_light": ANSI_LIGHT, "ansi_dark": ANSI_DARK}
  94. class SyntaxTheme(ABC):
  95. """Base class for a syntax theme."""
  96. @abstractmethod
  97. def get_style_for_token(self, token_type: TokenType) -> Style:
  98. """Get a style for a given Pygments token."""
  99. raise NotImplementedError # pragma: no cover
  100. @abstractmethod
  101. def get_background_style(self) -> Style:
  102. """Get the background color."""
  103. raise NotImplementedError # pragma: no cover
  104. class PygmentsSyntaxTheme(SyntaxTheme):
  105. """Syntax theme that delegates to Pygments theme."""
  106. def __init__(self, theme: Union[str, Type[PygmentsStyle]]) -> None:
  107. self._style_cache: Dict[TokenType, Style] = {}
  108. if isinstance(theme, str):
  109. try:
  110. self._pygments_style_class = get_style_by_name(theme)
  111. except ClassNotFound:
  112. self._pygments_style_class = get_style_by_name("default")
  113. else:
  114. self._pygments_style_class = theme
  115. self._background_color = self._pygments_style_class.background_color
  116. self._background_style = Style(bgcolor=self._background_color)
  117. def get_style_for_token(self, token_type: TokenType) -> Style:
  118. """Get a style from a Pygments class."""
  119. try:
  120. return self._style_cache[token_type]
  121. except KeyError:
  122. try:
  123. pygments_style = self._pygments_style_class.style_for_token(token_type)
  124. except KeyError:
  125. style = Style.null()
  126. else:
  127. color = pygments_style["color"]
  128. bgcolor = pygments_style["bgcolor"]
  129. style = Style(
  130. color="#" + color if color else "#000000",
  131. bgcolor="#" + bgcolor if bgcolor else self._background_color,
  132. bold=pygments_style["bold"],
  133. italic=pygments_style["italic"],
  134. underline=pygments_style["underline"],
  135. )
  136. self._style_cache[token_type] = style
  137. return style
  138. def get_background_style(self) -> Style:
  139. return self._background_style
  140. class ANSISyntaxTheme(SyntaxTheme):
  141. """Syntax theme to use standard colors."""
  142. def __init__(self, style_map: Dict[TokenType, Style]) -> None:
  143. self.style_map = style_map
  144. self._missing_style = Style.null()
  145. self._background_style = Style.null()
  146. self._style_cache: Dict[TokenType, Style] = {}
  147. def get_style_for_token(self, token_type: TokenType) -> Style:
  148. """Look up style in the style map."""
  149. try:
  150. return self._style_cache[token_type]
  151. except KeyError:
  152. # Styles form a hierarchy
  153. # We need to go from most to least specific
  154. # e.g. ("foo", "bar", "baz") to ("foo", "bar") to ("foo",)
  155. get_style = self.style_map.get
  156. token = tuple(token_type)
  157. style = self._missing_style
  158. while token:
  159. _style = get_style(token)
  160. if _style is not None:
  161. style = _style
  162. break
  163. token = token[:-1]
  164. self._style_cache[token_type] = style
  165. return style
  166. def get_background_style(self) -> Style:
  167. return self._background_style
  168. class Syntax(JupyterMixin):
  169. """Construct a Syntax object to render syntax highlighted code.
  170. Args:
  171. code (str): Code to highlight.
  172. lexer (Lexer | str): Lexer to use (see https://pygments.org/docs/lexers/)
  173. theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "monokai".
  174. dedent (bool, optional): Enable stripping of initial whitespace. Defaults to False.
  175. line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.
  176. start_line (int, optional): Starting number for line numbers. Defaults to 1.
  177. line_range (Tuple[int, int], optional): If given should be a tuple of the start and end line to render.
  178. highlight_lines (Set[int]): A set of line numbers to highlight.
  179. code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.
  180. tab_size (int, optional): Size of tabs. Defaults to 4.
  181. word_wrap (bool, optional): Enable word wrapping.
  182. background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.
  183. indent_guides (bool, optional): Show indent guides. Defaults to False.
  184. """
  185. _pygments_style_class: Type[PygmentsStyle]
  186. _theme: SyntaxTheme
  187. @classmethod
  188. def get_theme(cls, name: Union[str, SyntaxTheme]) -> SyntaxTheme:
  189. """Get a syntax theme instance."""
  190. if isinstance(name, SyntaxTheme):
  191. return name
  192. theme: SyntaxTheme
  193. if name in RICH_SYNTAX_THEMES:
  194. theme = ANSISyntaxTheme(RICH_SYNTAX_THEMES[name])
  195. else:
  196. theme = PygmentsSyntaxTheme(name)
  197. return theme
  198. def __init__(
  199. self,
  200. code: str,
  201. lexer: Union[Lexer, str],
  202. *,
  203. theme: Union[str, SyntaxTheme] = DEFAULT_THEME,
  204. dedent: bool = False,
  205. line_numbers: bool = False,
  206. start_line: int = 1,
  207. line_range: Optional[Tuple[int, int]] = None,
  208. highlight_lines: Optional[Set[int]] = None,
  209. code_width: Optional[int] = None,
  210. tab_size: int = 4,
  211. word_wrap: bool = False,
  212. background_color: Optional[str] = None,
  213. indent_guides: bool = False,
  214. ) -> None:
  215. self.code = code
  216. self._lexer = lexer
  217. self.dedent = dedent
  218. self.line_numbers = line_numbers
  219. self.start_line = start_line
  220. self.line_range = line_range
  221. self.highlight_lines = highlight_lines or set()
  222. self.code_width = code_width
  223. self.tab_size = tab_size
  224. self.word_wrap = word_wrap
  225. self.background_color = background_color
  226. self.background_style = (
  227. Style(bgcolor=background_color) if background_color else Style()
  228. )
  229. self.indent_guides = indent_guides
  230. self._theme = self.get_theme(theme)
  231. @classmethod
  232. def from_path(
  233. cls,
  234. path: str,
  235. encoding: str = "utf-8",
  236. theme: Union[str, SyntaxTheme] = DEFAULT_THEME,
  237. dedent: bool = False,
  238. line_numbers: bool = False,
  239. line_range: Optional[Tuple[int, int]] = None,
  240. start_line: int = 1,
  241. highlight_lines: Optional[Set[int]] = None,
  242. code_width: Optional[int] = None,
  243. tab_size: int = 4,
  244. word_wrap: bool = False,
  245. background_color: Optional[str] = None,
  246. indent_guides: bool = False,
  247. ) -> "Syntax":
  248. """Construct a Syntax object from a file.
  249. Args:
  250. path (str): Path to file to highlight.
  251. encoding (str): Encoding of file.
  252. theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "emacs".
  253. dedent (bool, optional): Enable stripping of initial whitespace. Defaults to True.
  254. line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.
  255. start_line (int, optional): Starting number for line numbers. Defaults to 1.
  256. line_range (Tuple[int, int], optional): If given should be a tuple of the start and end line to render.
  257. highlight_lines (Set[int]): A set of line numbers to highlight.
  258. code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.
  259. tab_size (int, optional): Size of tabs. Defaults to 4.
  260. word_wrap (bool, optional): Enable word wrapping of code.
  261. background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.
  262. indent_guides (bool, optional): Show indent guides. Defaults to False.
  263. Returns:
  264. [Syntax]: A Syntax object that may be printed to the console
  265. """
  266. with open(path, "rt", encoding=encoding) as code_file:
  267. code = code_file.read()
  268. lexer = None
  269. lexer_name = "default"
  270. try:
  271. _, ext = os.path.splitext(path)
  272. if ext:
  273. extension = ext.lstrip(".").lower()
  274. lexer = get_lexer_by_name(extension)
  275. lexer_name = lexer.name
  276. except ClassNotFound:
  277. pass
  278. if lexer is None:
  279. try:
  280. lexer_name = guess_lexer_for_filename(path, code).name
  281. except ClassNotFound:
  282. pass
  283. return cls(
  284. code,
  285. lexer_name,
  286. theme=theme,
  287. dedent=dedent,
  288. line_numbers=line_numbers,
  289. line_range=line_range,
  290. start_line=start_line,
  291. highlight_lines=highlight_lines,
  292. code_width=code_width,
  293. tab_size=tab_size,
  294. word_wrap=word_wrap,
  295. background_color=background_color,
  296. indent_guides=indent_guides,
  297. )
  298. def _get_base_style(self) -> Style:
  299. """Get the base style."""
  300. default_style = self._theme.get_background_style() + self.background_style
  301. return default_style
  302. def _get_token_color(self, token_type: TokenType) -> Optional[Color]:
  303. """Get a color (if any) for the given token.
  304. Args:
  305. token_type (TokenType): A token type tuple from Pygments.
  306. Returns:
  307. Optional[Color]: Color from theme, or None for no color.
  308. """
  309. style = self._theme.get_style_for_token(token_type)
  310. return style.color
  311. @property
  312. def lexer(self) -> Optional[Lexer]:
  313. """The lexer for this syntax, or None if no lexer was found.
  314. Tries to find the lexer by name if a string was passed to the constructor.
  315. """
  316. if isinstance(self._lexer, Lexer):
  317. return self._lexer
  318. try:
  319. return get_lexer_by_name(
  320. self._lexer,
  321. stripnl=False,
  322. ensurenl=True,
  323. tabsize=self.tab_size,
  324. )
  325. except ClassNotFound:
  326. return None
  327. def highlight(
  328. self, code: str, line_range: Optional[Tuple[int, int]] = None
  329. ) -> Text:
  330. """Highlight code and return a Text instance.
  331. Args:
  332. code (str): Code to highlight.
  333. line_range(Tuple[int, int], optional): Optional line range to highlight.
  334. Returns:
  335. Text: A text instance containing highlighted syntax.
  336. """
  337. base_style = self._get_base_style()
  338. justify: JustifyMethod = (
  339. "default" if base_style.transparent_background else "left"
  340. )
  341. text = Text(
  342. justify=justify,
  343. style=base_style,
  344. tab_size=self.tab_size,
  345. no_wrap=not self.word_wrap,
  346. )
  347. _get_theme_style = self._theme.get_style_for_token
  348. lexer = self.lexer
  349. if lexer is None:
  350. text.append(code)
  351. else:
  352. if line_range:
  353. # More complicated path to only stylize a portion of the code
  354. # This speeds up further operations as there are less spans to process
  355. line_start, line_end = line_range
  356. def line_tokenize() -> Iterable[Tuple[Any, str]]:
  357. """Split tokens to one per line."""
  358. assert lexer
  359. for token_type, token in lexer.get_tokens(code):
  360. while token:
  361. line_token, new_line, token = token.partition("\n")
  362. yield token_type, line_token + new_line
  363. def tokens_to_spans() -> Iterable[Tuple[str, Optional[Style]]]:
  364. """Convert tokens to spans."""
  365. tokens = iter(line_tokenize())
  366. line_no = 0
  367. _line_start = line_start - 1
  368. # Skip over tokens until line start
  369. while line_no < _line_start:
  370. _token_type, token = next(tokens)
  371. yield (token, None)
  372. if token.endswith("\n"):
  373. line_no += 1
  374. # Generate spans until line end
  375. for token_type, token in tokens:
  376. yield (token, _get_theme_style(token_type))
  377. if token.endswith("\n"):
  378. line_no += 1
  379. if line_no >= line_end:
  380. break
  381. text.append_tokens(tokens_to_spans())
  382. else:
  383. text.append_tokens(
  384. (token, _get_theme_style(token_type))
  385. for token_type, token in lexer.get_tokens(code)
  386. )
  387. if self.background_color is not None:
  388. text.stylize(f"on {self.background_color}")
  389. return text
  390. def _get_line_numbers_color(self, blend: float = 0.3) -> Color:
  391. background_style = self._theme.get_background_style() + self.background_style
  392. background_color = background_style.bgcolor
  393. if background_color is None or background_color.is_system_defined:
  394. return Color.default()
  395. foreground_color = self._get_token_color(Token.Text)
  396. if foreground_color is None or foreground_color.is_system_defined:
  397. return foreground_color or Color.default()
  398. new_color = blend_rgb(
  399. background_color.get_truecolor(),
  400. foreground_color.get_truecolor(),
  401. cross_fade=blend,
  402. )
  403. return Color.from_triplet(new_color)
  404. @property
  405. def _numbers_column_width(self) -> int:
  406. """Get the number of characters used to render the numbers column."""
  407. column_width = 0
  408. if self.line_numbers:
  409. column_width = len(str(self.start_line + self.code.count("\n"))) + 2
  410. return column_width
  411. def _get_number_styles(self, console: Console) -> Tuple[Style, Style, Style]:
  412. """Get background, number, and highlight styles for line numbers."""
  413. background_style = self._get_base_style()
  414. if background_style.transparent_background:
  415. return Style.null(), Style(dim=True), Style.null()
  416. if console.color_system in ("256", "truecolor"):
  417. number_style = Style.chain(
  418. background_style,
  419. self._theme.get_style_for_token(Token.Text),
  420. Style(color=self._get_line_numbers_color()),
  421. self.background_style,
  422. )
  423. highlight_number_style = Style.chain(
  424. background_style,
  425. self._theme.get_style_for_token(Token.Text),
  426. Style(bold=True, color=self._get_line_numbers_color(0.9)),
  427. self.background_style,
  428. )
  429. else:
  430. number_style = background_style + Style(dim=True)
  431. highlight_number_style = background_style + Style(dim=False)
  432. return background_style, number_style, highlight_number_style
  433. def __rich_measure__(
  434. self, console: "Console", options: "ConsoleOptions"
  435. ) -> "Measurement":
  436. if self.code_width is not None:
  437. width = self.code_width + self._numbers_column_width
  438. return Measurement(self._numbers_column_width, width)
  439. return Measurement(self._numbers_column_width, options.max_width)
  440. def __rich_console__(
  441. self, console: Console, options: ConsoleOptions
  442. ) -> RenderResult:
  443. transparent_background = self._get_base_style().transparent_background
  444. code_width = (
  445. (
  446. (options.max_width - self._numbers_column_width - 1)
  447. if self.line_numbers
  448. else options.max_width
  449. )
  450. if self.code_width is None
  451. else self.code_width
  452. )
  453. line_offset = 0
  454. if self.line_range:
  455. start_line, end_line = self.line_range
  456. line_offset = max(0, start_line - 1)
  457. ends_on_nl = self.code.endswith("\n")
  458. code = self.code if ends_on_nl else self.code + "\n"
  459. code = textwrap.dedent(code) if self.dedent else code
  460. code = code.expandtabs(self.tab_size)
  461. text = self.highlight(code, self.line_range)
  462. (
  463. background_style,
  464. number_style,
  465. highlight_number_style,
  466. ) = self._get_number_styles(console)
  467. if not self.line_numbers and not self.word_wrap and not self.line_range:
  468. if not ends_on_nl:
  469. text.remove_suffix("\n")
  470. # Simple case of just rendering text
  471. style = (
  472. self._get_base_style()
  473. + self._theme.get_style_for_token(Comment)
  474. + Style(dim=True)
  475. + self.background_style
  476. )
  477. if self.indent_guides and not options.ascii_only:
  478. text = text.with_indent_guides(self.tab_size, style=style)
  479. text.overflow = "crop"
  480. if style.transparent_background:
  481. yield from console.render(
  482. text, options=options.update(width=code_width)
  483. )
  484. else:
  485. syntax_lines = console.render_lines(
  486. text,
  487. options.update(width=code_width, height=None),
  488. style=self.background_style,
  489. pad=True,
  490. new_lines=True,
  491. )
  492. for syntax_line in syntax_lines:
  493. yield from syntax_line
  494. return
  495. lines: Union[List[Text], Lines] = text.split("\n", allow_blank=ends_on_nl)
  496. if self.line_range:
  497. lines = lines[line_offset:end_line]
  498. if self.indent_guides and not options.ascii_only:
  499. style = (
  500. self._get_base_style()
  501. + self._theme.get_style_for_token(Comment)
  502. + Style(dim=True)
  503. + self.background_style
  504. )
  505. lines = (
  506. Text("\n")
  507. .join(lines)
  508. .with_indent_guides(self.tab_size, style=style)
  509. .split("\n", allow_blank=True)
  510. )
  511. numbers_column_width = self._numbers_column_width
  512. render_options = options.update(width=code_width)
  513. highlight_line = self.highlight_lines.__contains__
  514. _Segment = Segment
  515. padding = _Segment(" " * numbers_column_width + " ", background_style)
  516. new_line = _Segment("\n")
  517. line_pointer = "> " if options.legacy_windows else "❱ "
  518. for line_no, line in enumerate(lines, self.start_line + line_offset):
  519. if self.word_wrap:
  520. wrapped_lines = console.render_lines(
  521. line,
  522. render_options.update(height=None),
  523. style=background_style,
  524. pad=not transparent_background,
  525. )
  526. else:
  527. segments = list(line.render(console, end=""))
  528. if options.no_wrap:
  529. wrapped_lines = [segments]
  530. else:
  531. wrapped_lines = [
  532. _Segment.adjust_line_length(
  533. segments,
  534. render_options.max_width,
  535. style=background_style,
  536. pad=not transparent_background,
  537. )
  538. ]
  539. if self.line_numbers:
  540. for first, wrapped_line in loop_first(wrapped_lines):
  541. if first:
  542. line_column = str(line_no).rjust(numbers_column_width - 2) + " "
  543. if highlight_line(line_no):
  544. yield _Segment(line_pointer, Style(color="red"))
  545. yield _Segment(line_column, highlight_number_style)
  546. else:
  547. yield _Segment(" ", highlight_number_style)
  548. yield _Segment(line_column, number_style)
  549. else:
  550. yield padding
  551. yield from wrapped_line
  552. yield new_line
  553. else:
  554. for wrapped_line in wrapped_lines:
  555. yield from wrapped_line
  556. yield new_line
  557. if __name__ == "__main__": # pragma: no cover
  558. import argparse
  559. import sys
  560. parser = argparse.ArgumentParser(
  561. description="Render syntax to the console with Rich"
  562. )
  563. parser.add_argument(
  564. "path",
  565. metavar="PATH",
  566. help="path to file, or - for stdin",
  567. )
  568. parser.add_argument(
  569. "-c",
  570. "--force-color",
  571. dest="force_color",
  572. action="store_true",
  573. default=None,
  574. help="force color for non-terminals",
  575. )
  576. parser.add_argument(
  577. "-i",
  578. "--indent-guides",
  579. dest="indent_guides",
  580. action="store_true",
  581. default=False,
  582. help="display indent guides",
  583. )
  584. parser.add_argument(
  585. "-l",
  586. "--line-numbers",
  587. dest="line_numbers",
  588. action="store_true",
  589. help="render line numbers",
  590. )
  591. parser.add_argument(
  592. "-w",
  593. "--width",
  594. type=int,
  595. dest="width",
  596. default=None,
  597. help="width of output (default will auto-detect)",
  598. )
  599. parser.add_argument(
  600. "-r",
  601. "--wrap",
  602. dest="word_wrap",
  603. action="store_true",
  604. default=False,
  605. help="word wrap long lines",
  606. )
  607. parser.add_argument(
  608. "-s",
  609. "--soft-wrap",
  610. action="store_true",
  611. dest="soft_wrap",
  612. default=False,
  613. help="enable soft wrapping mode",
  614. )
  615. parser.add_argument(
  616. "-t", "--theme", dest="theme", default="monokai", help="pygments theme"
  617. )
  618. parser.add_argument(
  619. "-b",
  620. "--background-color",
  621. dest="background_color",
  622. default=None,
  623. help="Override background color",
  624. )
  625. parser.add_argument(
  626. "-x",
  627. "--lexer",
  628. default="default",
  629. dest="lexer_name",
  630. help="Lexer name",
  631. )
  632. args = parser.parse_args()
  633. from pip._vendor.rich.console import Console
  634. console = Console(force_terminal=args.force_color, width=args.width)
  635. if args.path == "-":
  636. code = sys.stdin.read()
  637. syntax = Syntax(
  638. code=code,
  639. lexer=args.lexer_name,
  640. line_numbers=args.line_numbers,
  641. word_wrap=args.word_wrap,
  642. theme=args.theme,
  643. background_color=args.background_color,
  644. indent_guides=args.indent_guides,
  645. )
  646. else:
  647. syntax = Syntax.from_path(
  648. args.path,
  649. line_numbers=args.line_numbers,
  650. word_wrap=args.word_wrap,
  651. theme=args.theme,
  652. background_color=args.background_color,
  653. indent_guides=args.indent_guides,
  654. )
  655. console.print(syntax, soft_wrap=args.soft_wrap)