Debian Codegraph @

docs/source/syntax.rst

raw
1 Syntax
2 ======
3
4 Rich can syntax highlight various programming languages with line numbers.
5
6 To syntax highlight code, construct a :class:`~rich.syntax.Syntax` object and print it to the console. Here's an example::
7
8 from rich.console import Console
9 from rich.syntax import Syntax
10
11 console = Console()
12 with open("syntax.py", "rt") as code_file:
13 syntax = Syntax(code_file.read(), "python")
14 console.print(syntax)
15
16 You may also use the :meth:`~rich.syntax.Syntax.from_path` alternative constructor which will load the code from disk and auto-detect the file type. The example above could be re-written as follows::
17
18
19 from rich.console import Console
20 from rich.syntax import Syntax
21
22 console = Console()
23 syntax = Syntax.from_path("syntax.py")
24 console.print(syntax)
25
26
27 Line numbers
28 ------------
29
30 If you set ``line_numbers=True``, Rich will render a column for line numbers::
31
32 syntax = Syntax.from_path("syntax.py", line_numbers=True)
33
34
35 Theme
36 -----
37
38 The Syntax constructor (and :meth:`~rich.syntax.Syntax.from_path`) accept a ``theme`` attribute which should be the name of a `Pygments theme <https://pygments.org/demo/>`_. It may also be one of the special case theme names "ansi_dark" or "ansi_light" which will use the color theme configured by the terminal.
39
40
41 Background color
42 ----------------
43
44 You can override the background color from the theme by supplying a ``background_color`` argument to the constructor. This should be a string in the same format a style definition accepts, e.g. "red", "#ff0000", "rgb(255,0,0)" etc. You may also set the special value "default" which will use the default background color set in the terminal.
45
46
47 Syntax CLI
48 ----------
49
50 You can use this class from the command line. Here's how you would syntax highlight a file called "syntax.py"::
51
52 python -m rich.syntax syntax.py
53
54 For the full list of arguments, run the following::
55
56 python -m rich.syntax -h
57