Syntax Highlighting – Hamel’s Blog - Hamel Husain
Заметка Hamel Husain объясняет, как работает подсветка синтаксиса в Quarto, которая опирается на механизм подсветки pandoc. Разбираются две ключевые концепции: цветовые темы синтаксиса (настраиваются через параметр highlight-style, с возможностью задать отдельные темы для светлого и тёмного режимов) и определения синтаксиса (правила подсветки в XML-файлах по схеме KDE/Kate). По умолчанию Quarto использует тему arrow-light, а любимая тема автора — dracula. Чтобы задокументировать язык, не поддерживаемый из коробки, можно добавить собственное определение синтаксиса через параметр syntax-definitions. В качестве примера показано, как создать вымышленный язык Fomo — почти идентичный Python, но с ключевым словом fomo для определения функций — скопировав python.xml, изменив поля name, style и extension и добавив fomo в список defs.
Background
Предыстория
Syntax highlighting in Quarto follows the way pandoc handles syntax highlighting. There are two important concepts concerning syntax highlighting:
Подсветка синтаксиса в Quarto работает так же, как pandoc обрабатывает подсветку синтаксиса. Есть две важные концепции, касающиеся подсветки синтаксиса:
1. Syntax Color Themes
1. Цветовые темы синтаксиса
Syntax color themes allow you to customize the colors shown in syntax highlighting. These are expressed with the highlight-style setting. You can change the syntax color theme in either your front matter or site-wide in _quarto.yml like this:
Цветовые темы синтаксиса позволяют настроить цвета, отображаемые при подсветке синтаксиса. Они задаются с помощью настройки highlight-style. Цветовую тему синтаксиса можно изменить либо во front matter, либо для всего сайта в _quarto.yml, вот так:
--- highlight-style: custom.theme ---
--- highlight-style: custom.theme ---
If you have both light and dark themes, you will likely want to set those separately like this:
Если у вас есть и светлая, и тёмная темы, скорее всего вы захотите задать их по отдельности, вот так:
--- highlight-style: light: custom-light.theme dark: custom-dark.theme ---
--- highlight-style: light: custom-light.theme dark: custom-dark.theme ---
_quarto.yml
_quarto.yml
format: html: theme: light: assets/ek-theme-light.scss dark: assets/ek-theme-dark.scss highlight-style: light: assets/ek-light.theme dark: assets/ek-dark.theme
format: html: theme: light: assets/ek-theme-light.scss dark: assets/ek-theme-dark.scss highlight-style: light: assets/ek-light.theme dark: assets/ek-dark.theme
These color themes are defined by json files with the schema defined here. However, it is recommended that you choose one of the themes that quarto already provides and edit that. By default, Quarto uses the arrow-light theme. This means if you are happy with the way Quarto is highlighting syntax, you can just tweak this theme. Personally, my favorite theme is dracula. It is useful to look through these different themes to get a sense of the types of things you can change.
Эти цветовые темы задаются файлами json по схеме, описанной здесь. Однако рекомендуется выбрать одну из тем, которые Quarto уже предоставляет, и отредактировать её. По умолчанию Quarto использует тему arrow-light. Это означает, что если вас устраивает то, как Quarto подсвечивает синтаксис, вы можете просто немного подправить эту тему. Лично моя любимая тема — dracula. Полезно просмотреть эти разные темы, чтобы получить представление о том, что именно можно менять.
2. Syntax Definitions
2. Определения синтаксиса
Syntax definitions define the rules by which syntax is highlighted. A rule is a string, character or regular expression against which to match the text being analyzed. This is helpful if you need to document a language that isn’t supported by Quarto out of the box. You can see the list of supported languages with this command:
Определения синтаксиса задают правила, по которым подсвечивается синтаксис. Правило — это строка, символ или регулярное выражение, с которым сопоставляется анализируемый текст. Это полезно, если вам нужно задокументировать язык, который не поддерживается Quarto из коробки. Посмотреть список поддерживаемых языков можно этой командой:
quarto pandoc --list-highlight-languages
quarto pandoc --list-highlight-languages
Syntax definitions are defined in xml files that follow this schema. Examples of syntax definitions for various languages can be found here.
Определения синтаксиса задаются в файлах xml, которые следуют этой схеме. Примеры определений синтаксиса для различных языков можно найти здесь.
Quarto has additional example syntax definitions here which are useful to look at. Note how the name of the language and its file extensions are defined in the XML file.
У Quarto есть дополнительные примеры определений синтаксиса здесь, на которые полезно взглянуть. Обратите внимание, как в XML-файле задаются название языка и его расширения файлов.
In order to supply an additional syntax definition or override an existing one, set the syntax-definitions in your _quarto.yml file like this:
Чтобы добавить дополнительное определение синтаксиса или переопределить существующее, задайте параметр syntax-definitions в вашем файле _quarto.yml, вот так:
_quarto.yml
_quarto.yml
format: html: syntax-definitions: - new_language.xml
format: html: syntax-definitions: - new_language.xml
An example of defining a new language is illustrated below.
Пример определения нового языка показан ниже.
Example
Пример
Suppose you have a new programming language called Fomo that is just like Python, except you can define functions with fomo in addition to def. For example, consider this Python code:
Предположим, у вас есть новый язык программирования под названием Fomo, который точно такой же, как Python, за исключением того, что функции можно определять с помощью fomo в дополнение к def. Например, рассмотрим этот код на Python:
def hello_world(): "An example" pass
def hello_world(): "An example" pass
Unfortunately, If you try to use the Python code fence for Fomo it looks like this:
К сожалению, если попытаться использовать ограждение кода Python для Fomo, это выглядит так:
fomo hello_world(): "An example" pass
fomo hello_world(): "An example" pass
Since Fomo is almost identical to Python, you can start by copying the python syntax definition into a file named fomo.xml and edit the language name, style and extension fields like so:
Поскольку Fomo почти идентичен Python, можно начать с копирования определения синтаксиса python в файл с именем fomo.xml и редактирования полей языка name, style и extension, вот так:
fomo.xml
fomo.xml
- <language name="Python" version="26" style="python" indenter="python" kateversion="5.0" section="Scripts" extensions="*.py;*.pyw;*.pyi;SConstruct;SConscript;*.FCMacro" ... + <language name="Fomo" version="26" style="fomo" indenter="python" kateversion="5.0" section="Scripts" extensions="*.fomo" ...
-
You also have to add fomo to the list of defs like this:
Также нужно добавить fomo в список defs, вот так:
fomo.xml
fomo.xml
<list name="defs"> <item>class</item> <item>def</item> + <item>fomo</item> <item>del</item> <item>global</item> <item>lambda</item> <item>nonlocal</item> </list>
After that, you can add the Fomo syntax definition to your Quarto project with the syntax-definitions option like so:
После этого можно добавить определение синтаксиса Fomo в ваш проект Quarto с помощью параметра syntax-definitions, вот так:
_quarto.yml
_quarto.yml
format: html: syntax-definitions: - fomo.xml
format: html: syntax-definitions: - fomo.xml
In this case, fomo.xml is in the root of the Quarto project, but you can put it in a sub-folder as well.
В данном случае fomo.xml находится в корне проекта Quarto, но вы можете поместить его и в подпапку.
After doing this, you can use the ```fomo code fence, and your code will be highlighted correctly!
После этого вы можете использовать ограждение кода ```fomo, и ваш код будет подсвечен правильно!
fomo hello_world(): "An example" pass
fomo hello_world(): "An example" pass