как вставить код latex в latex
Записки разработчика
Страницы
вторник, 14 января 2014 г.
minted: Оформляем исходный код в LaTeX
Помнится, ещё на студенческой скамье я встречал задачу оформления исходного кода в LaTeX. В ту пору я использовал пакет listings. И я страдал. О, как же я страдал! Русские буквы не хотели дружить с UTF-8, а глаза мои текли кровавыми слезами при взгляде на итоговое форматирование. И вот, вновь я встретился с этой тяжёлой задачей. В поисках решения я наткнулся на замечательный пост в записках дебианщика Как оформить исходный код программ в LaTeX без адских страданий. Название подсказывало мне, что развлечение это не простое. Я аккуратно перепробовал все рецепты из статьи, но ни один меня не устроил. И в самом конце поста я обнаружил ссылку на замечательный пакет minted, который должен был положить конец моим страданиям.
Пакет minted базируется на Python-овской библиотеке Pygments, которая умеет на отличненько раскрашивать код, поддерживается около 300 разных языков и форматов разметки. Для начала нам понадобится её установить (предполагаем, что Python и easy_install уже имеются):
Переходим в любимый LaTeX-редактор и начинаем писать код (опять-таки предполагаем, что версия нашего LaTeX-дистрибутива включает пакет minted и все его зависимости):
Проблемы возникнут, если мы захотим в UTF-8 кодировке использовать русские буквы. Но мне удалось найти другой замечательный пост, в котором приводилось немного магии в преамбуле для поддержки кириллицы. Оттранслируем следующий файл:
И возрадуемся появлению русских букв:
Пакет содержит большое количество опций для стилизации листингов: можно добавить рамку, номера строк и кучу прочих вкусностей.
Больше информации вы найдёте на GitHub-е и в документации
Code listing
Contents
Introduction
L a T e X is widely used in science and programming has become an important aspect in several areas of science, hence the need for a tool that properly displays code. This article explains how to use the standard verbatim environment as well as the package listings, which provide more advanced code-formatting features. This separate article discusses the minted package, which performs syntax-highlighting using Python’s pygmentize library.
The verbatim environment
The code above produces the following output:
Just as in the example at the introduction, all text is printed keeping line breaks and white spaces. There’s a starred version of this command whose output is slightly different.
The code above produces the following output:
Verbatim-like text can also be used in a paragraph by means of the \verb command.
The code above produces the following output:
Using listings to highlight code
To use the lstlisting environment you have to add the following line to the preamble of your document:
Here’s an example of using the lstlisting environment from the listings package:
The code above produces the following output:
In this example, the output ignores all L a T e X commands and the text is printed keeping all the line breaks and white spaces typed. Let’s see a second example:
The code above produces the following output:
The additional parameter inside brackets [language=Python] enables code highlighting for this particular programming language (Python), special words are in boldface font and comments are italicized. See the reference guide for a complete list of supported programming languages.
Importing code from a file
Code is usually stored in a source file, therefore a command that automatically pulls code from a file becomes very handy.
The command \lstinputlisting[language=Octave]
If firstline or lastline is omitted, it’s assumed that the values are the beginning of the file, or the bottom of the file, respectively.
Code styles and colours
Code formatting with the listing package is highly customisable. Let’s see an example
The code above produces the following output:
As you see, the code colouring and styling greatly improves readability.
In this example the package xcolor is imported and then the command \definecolor<><><> is used to define new colours in rgb format that will later be used. For more information see: using colours in L a T e X
There are essentially two commands that generate the style for this example:
\lstdefinestyle