rich/docs/source/syntax.rst

58 lines
1.9 KiB
ReStructuredText
Raw Normal View History

2020-01-12 11:43:23 +00:00
Syntax
======
Rich can syntax highlight various programming languages with line numbers.
To syntax highlight code, construct a :class:`~rich.syntax.Syntax` object and print it to the console. Here's an example::
2020-09-18 15:02:02 +00:00
from rich.console import Console
from rich.syntax import Syntax
console = Console()
2020-12-16 20:36:13 +00:00
with open("syntax.py", "rt") as code_file:
2020-09-18 15:02:02 +00:00
syntax = Syntax(code_file.read(), "python")
console.print(syntax)
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::
2020-01-12 11:43:23 +00:00
from rich.console import Console
2020-01-12 11:43:23 +00:00
from rich.syntax import Syntax
console = Console()
2020-09-18 15:02:02 +00:00
syntax = Syntax.from_path("syntax.py")
2020-01-12 11:43:23 +00:00
console.print(syntax)
2020-05-08 12:36:12 +00:00
2020-09-18 15:02:02 +00:00
Line numbers
------------
If you set ``line_numbers=True``, Rich will render a column for line numbers::
syntax = Syntax.from_path("syntax.py", line_numbers=True)
Theme
-----
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.
Background color
----------------
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.
Syntax CLI
----------
2020-05-08 14:14:18 +00:00
You can use this class from the command line. Here's how you would syntax highlight a file called "syntax.py"::
python -m rich.syntax syntax.py
For the full list of arguments, run the following::
python -m rich.syntax -h