diff --git a/en/syntax/code.md b/en/syntax/code.md index 85aacdbf..1d1181cf 100644 --- a/en/syntax/code.md +++ b/en/syntax/code.md @@ -80,6 +80,38 @@ For syntax highlighting, specify the language in which the code is written in th You can find the full list of available languages in [GitHub](https://github.com/highlightjs/highlight.js/tree/master/src/languages). +### Including code from a file {#include-code} + +Use the `{% code %}` directive to include a local file as a code block: + +````markdown +{% code "./examples/main.ts" lang="typescript" %} +```` + +A path without a leading `/` is resolved relative to the Markdown file containing the directive. A path with a leading `/` is resolved relative to the documentation input root. The `lang` parameter sets the code block language for syntax highlighting. Without this parameter, the block language is empty. + +By default, the common indentation is removed from all non-empty lines. Add `keep-indents` to preserve the original indentation: + +````markdown +{% code "./examples/main.ts" keep-indents %} +```` + +Use the `lines` parameter to include part of a file. Numeric ranges are one-based and include both boundaries: + +````markdown +{% code "./examples/main.ts" lines="10-25" %} +```` + +You can also provide two substring markers separated by `-`. The lines containing the markers are excluded: + +````markdown +{% code "./examples/main.ts" lines="[BEGIN example]-[END example]" %} +```` + +If the start or end marker is missing, the CLI emits a warning and uses the beginning or end of the file, respectively. If the end marker occurs before the start marker, the CLI emits a warning and creates an empty code block. + +The directive reads only local files inside the documentation input directory. External HTTP and Git sources, automatic named-region selection, and `jsonpath` are not processed by the OSS CLI. A missing file, a path outside the input directory, or an invalid numeric range causes a build error. + ### Displaying line numbers {#line-numbers} If you need to enable line numbers in a code block, use the keyword `showLineNumbers`. @@ -146,4 +178,4 @@ $ npm run build This feature is especially useful for **snippets**. If a code block contains only commands, without their output, the user can copy the entire content with one button and paste it into the terminal — without selecting lines individually. -{% endnote %} \ No newline at end of file +{% endnote %} diff --git a/ru/syntax/code.md b/ru/syntax/code.md index c2310ac8..8e99ce52 100644 --- a/ru/syntax/code.md +++ b/ru/syntax/code.md @@ -80,6 +80,38 @@ Ознакомиться с полным перечнем доступных языков можно в [GitHub](https://github.com/highlightjs/highlight.js/tree/master/src/languages). +### Включение кода из файла {#include-code} + +Чтобы включить содержимое локального файла как блок кода, используйте директиву `{% code %}`: + +````markdown +{% code "./examples/main.ts" lang="typescript" %} +```` + +Путь без начального `/` разрешается относительно Markdown-файла с директивой. Путь с начальным `/` разрешается относительно корня входной директории документации. Параметр `lang` задаёт язык блока для подсветки синтаксиса. Если параметр не указан, язык блока остаётся пустым. + +По умолчанию из всех непустых строк удаляется общий отступ. Чтобы сохранить исходные отступы, добавьте параметр `keep-indents`: + +````markdown +{% code "./examples/main.ts" keep-indents %} +```` + +Параметр `lines` позволяет включить часть файла. Числовой диапазон задаётся с нумерацией от 1, обе границы включаются: + +````markdown +{% code "./examples/main.ts" lines="10-25" %} +```` + +Также можно указать две подстроки-маркера через `-`. Строки с маркерами в результат не включаются: + +````markdown +{% code "./examples/main.ts" lines="[BEGIN example]-[END example]" %} +```` + +Если начальный или конечный маркер не найден, CLI выводит предупреждение и использует соответственно начало или конец файла. Если конечный маркер расположен раньше начального, CLI выводит предупреждение и создаёт пустой блок кода. + +Директива читает только локальные файлы внутри входной директории. Внешние HTTP- и Git-источники, автоматический выбор именованных регионов и `jsonpath` не обрабатываются OSS CLI. Отсутствующий файл, выход пути за пределы входной директории и некорректный числовой диапазон приводят к ошибке сборки. + ### Отображение номеров строк {#line-numbers} Если необходимо включить отображение номеров строк в блоке кода, используйте ключевое слово `showLineNumbers`. @@ -146,4 +178,4 @@ $ npm run build Эта возможность особенно полезна для **сниппетов**. Если блок кода содержит только команды, без их вывода, то пользователь может скопировать всё содержимое одной кнопкой и вставить в терминал — не выделяя строки по отдельности. -{% endnote %} \ No newline at end of file +{% endnote %}