minted (1)

38
The minted package: Highlighted source code in L A T E X Geoffrey M. Poore [email protected] github.com/gpoore/minted Originally created and maintained (2009-2013) by Konrad Rudolph v2.0-alpha2 from 2013/08/21 Abstract minted is a package that facilitates expressive syntax highlighting using the powerful Pygments library. The package also provides options to customize the highlighted source code output. Current status minted was created in 2009 by Konrad Rudolph. Geoffrey Poore agreed to take over minted maintenance in March of 2013, since his PythonTeX package also provides an interface to Pygments. minted is currently in an alpha release for v2.0. The goal is to close all current issues, including those on the old Google Code site, before the full v2.0 release. During this time of transition, users who need maximum stability are encouraged to use minted 1.7 or PythonTeX. The release on CTAN will only be updated once v2.0 stabilizes. License LaTeX Project Public License (LPPL) version 1.3. Additionally, the project may be distributed under the terms of the 3-Clause (“New”) BSD license: http://opensource.org/licenses/BSD-3-Clause. 1

description

Minted Documentation

Transcript of minted (1)

  • The minted package:Highlighted source code in LATEX

    Geoffrey M. [email protected]

    github.com/gpoore/minted

    Originally created and maintained (2009-2013) byKonrad Rudolph

    v2.0-alpha2 from 2013/08/21

    Abstract

    minted is a package that facilitates expressive syntax highlighting using thepowerful Pygments library. The package also provides options to customizethe highlighted source code output.

    Current status

    minted was created in 2009 by Konrad Rudolph. Geoffrey Poore agreed to take overminted maintenance in March of 2013, since his PythonTeX package also providesan interface to Pygments.

    minted is currently in an alpha release for v2.0. The goal is to close all currentissues, including those on the old Google Code site, before the full v2.0 release.During this time of transition, users who need maximum stability are encouragedto use minted 1.7 or PythonTeX. The release on CTAN will only be updated oncev2.0 stabilizes.

    License

    LaTeX Project Public License (LPPL) version 1.3.

    Additionally, the project may be distributed under the terms of the 3-Clause(New) BSD license: http://opensource.org/licenses/BSD-3-Clause.

    1

  • Contents

    1 Introduction 4

    2 Installation 4

    2.1 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

    2.2 Required packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

    2.3 Installing minted . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

    3 Basic usage 6

    3.1 Preliminary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

    3.2 A minimal complete example . . . . . . . . . . . . . . . . . . . . . . . 6

    3.3 Formatting source code . . . . . . . . . . . . . . . . . . . . . . . . . . 7

    3.4 Using different styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

    3.5 Supported languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

    4 Floating listings 9

    5 Options 10

    5.1 Package options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

    5.2 Macro option usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

    5.3 Available options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

    6 Defining shortcuts 15

    7 FAQ and Troubleshooting 16

    Version History 17

    8 Implementation 18

    8.1 Required packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

    8.2 Package options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

    8.3 Caching and temp files . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

    8.4 OS interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

    8.5 Option processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    8.6 Internal helpers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

    8.7 Public API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

    8.8 Command shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

    2

  • 8.9 Float support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

    8.10 Epilogue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

    8.11 Final cleanup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

    3

  • 1 Introduction

    minted is a package that allows formatting source code in LATEX. For example:

    \begin{minted}{language}code

    \end{minted}

    will highlight a piece of code in a chosen language. The display can be customizedby a number of arguments and colour schemes.

    Unlike some other packages, most notably listings, minted requires the installationof additional software, Pygments. This may seem like a disadvantage, but thereare also significant advantages.

    Pygments provides superior syntax highlighting compared to conventional packages.For example, listings basically only highlights strings, comments and keywords.Pygments, on the other hand, can be completely customized to highlight any kindof token the source language might support. This might include special formattingsequences inside strings, numbers, different kinds of identifiers and exotic constructssuch as HTML tags.

    Some languages make this especially desirable. Consider the following Ruby codeas an extreme, but at the same time typical, example:

    for compatibility with earlier versions

    class Foodef initpi = Math::PI@var = "Pi is approx. #{pi}"

    endend

    Here we have four different colors for identifiers (five, if you count keywords) andescapes from inside strings, none of which pose a problem for Pygments.Additionally, installing Pygments is actually incredibly easy (see the next section).

    2 Installation

    2.1 Prerequisites

    Pygments is written in Python, so make sure that you have at Python 2.6 or laterinstalled on your system. This may be easily checked from the command line:

    $ python --versionPython 2.7.5

    4

  • If you dont have Python installed, you can download it from the Python websiteor use your operating systems package manager.

    Some Python distributions include Pygments (see some of the options underAlternative Implementations on the Python site). Otherwise, you will need toinstall Pygments manually.

    This may be done by installing setuptools, which facilitates the distribution ofPython applications. You can then install Pygments using the following command:

    $ sudo easy_install Pygments

    Under Windows, you will not need the sudo, but may need to run the commandprompt as administrator.

    If you already have Pygments installed, be aware that a current version is recom-mended (at least 1.4 or later). minted may work with versions as early as 1.2, butthere are no guarantees.

    2.2 Required packages

    minted requires that the following packages be available and reasonably up to dateon your system. All of these ship with recent TEX distributions.

    keyval

    fancyvrb

    float

    ifthen

    calc

    ifplatform

    pdftexcmds

    etoolbox

    xstring

    xcolor

    2.3 Installing minted

    You can probably install minted with your TEX distributions package manager.Otherwise, you can install it manually by following the directions below.

    If the file minted.sty doesnt exist yet, we first have to create it. If youre using asystem that supports the make command, then you can simply type the followingcommand in the folder where youve extracted the minted package code:

    5

  • $ make

    Alternatively, you may download this file separately from the projects homepage,or create it manually by executing the command

    $ tex minted.ins

    on the command line.

    Finally, we have to install the file so that TEX is able to find it. In order to dothat, please refer to the TEX FAQ. If you just want to experiment with the latestversion, you could locate your current minted.sty in your TEX installation andreplace it with the latest version. Or you could just put the latest minted.sty inthe same directory as the file you wish to use it with.

    3 Basic usage

    3.1 Preliminary

    Since minted makes calls to the outside world (that is, Pygments), you need totell the LATEX processor about this by passing it the -shell-escape option or itwont allow such calls. In effect, instead of calling the processor like this:

    $ latex input

    you need to call it like this:

    $ latex -shell-escape input

    The same holds for other processors, such as pdflatex or xelatex.

    You should be aware that using -shell-escape allows LATEX to run potentiallyarbitrary commands on your system. It is probably best to use -shell-escapeonly when you need it, and to use only it with documents from trusted sources.

    3.2 A minimal complete example

    The following file minimal.tex shows the basic usage of minted.

    \documentclass{article}

    \usepackage{minted}

    \begin{document}

    6

  • \begin{minted}{c}int main() {

    printf("hello, world");return 0;

    }\end{minted}\end{document}

    By compiling the source file like this:

    $ pdflatex -shell-escape minimal

    we end up with the following output in minimal.pdf:

    int main() {printf("hello, world");return 0;

    }

    3.3 Formatting source code

    Using minted is straightforward. For example, to highlight some Python sourcemintedcode we might use the following code snippet (result on the right):

    \begin{minted}{python}def boring(args = None):

    pass\end{minted}

    def boring(args = None):pass

    Optionally, the environment accepts a number of options in key=value notation,which are described in more detail below.

    For a single line of source code, you can alternatively use a shorthand notation:\mint

    \mint{python}|import this| import this

    The code is delimited by a pair of identical characters, similar to how \verb works.The complete syntax is \mint[options]{language}delimcodedelim, wherethe code delimiter can be almost any punctuation character. Again, this commandsupports a number of options described below.

    Note that the \mint command is not for inline use. Rather, it is a shortcut forminted when only a single line of code is present. The \mintinline command isprovided for inline use.

    Code can be typeset inline:\mintinline

    X\mintinline{python}{print(x**2)}X Xprint(x**2)X

    7

  • The syntax is \mintinline[options]{language}delimcodedelim. Thedelimiters can be a pair of characters, as for \mint. They can also be a matchedpair of curly braces, {}.

    The command has been carefully crafted so that in most cases it will functioncorrectly when used inside other commands.1

    Finally, theres the \inputminted command to read and format whole files. Its\inputmintedsyntax is \inputminted[options]{language}{filename}.

    3.4 Using different styles

    Instead of using the default style you may choose another stylesheet provided by\usemintedstylePygments. This may be done via the following:

    \usemintedstyle{name}

    The full syntax is \usemintedstyle[language]{style}. The style may be setfor the document as a whole (no language specified), or only for a particularlanguage. Note that the style may also be set via \setminted and via the optionalargument for each command and environment.2

    To get a list of all available stylesheets, see the online demo at the Pygmentswebsite or execute the following command on the command line:

    $ pygmentize -L styles

    Creating your own styles is also easy. Just follow the instructions provided on thewebsite.

    3.5 Supported languages

    Pygments supports over 150 different programming languages, template languages,and other markup languages. To see an exhaustive list of the currently supportedlanguages, use the command

    $ pygmentize -L lexers

    1For example, \mintinline works in footnotes! The main exception is when the codecontains the percent % and hash # characters.

    2Version 2.0 added the optional language argument and removed the restriction that thecommand be used in the preamble.

    8

  • 4 Floating listings

    minted provides the listing environment to wrap around a source code block.listingThis puts the code into a floating box. You can also provide a \caption and a\label for such a listing in the usual way (that is, as for the table and figureenvironments):

    \begin{listing}[H]\mint{cl}/(car (cons 1 (2)))/\caption{Example of a listing.}\label{lst:example}

    \end{listing}

    Listing \ref{lst:example} contains an example of a listing.

    will yield:

    (car (cons 1 (2)))

    Listing 1: Example of a listing.

    Listing 1 contains an example of a listing.

    The \listoflistings macro will insert a list of all (floated) listings in the\listoflistingsdocument:

    \listoflistingsList of listings

    1 Example of a listing. 9

    The string Listing in a listings caption can be changed. To do this, simply\listingscaptionredefine the macro \listingscaption, for example:

    \renewcommand{\listingscaption}{Program code}

    Likewise, the caption of the listings list, List of listings, can be changed by\listoflistingscaptionredefining \listoflistingscaption:

    \renewcommand{\listoflistingscaption}{List of program codes}

    9

  • 5 Options

    5.1 Package options

    To control how LATEX counts the listing floats, you can pass either the sectionsectionchapter or chapter option when loading the minted package. For example, the following

    will cause listings to be counted by section:

    \usepackage[section]{minted}

    minted works by saving code to a temporary file, highlighting the code via Pygmentscacheand saving the output to another temporary file, and inputting the output into theLATEX document. This process can become quite slow if there are many chunks ofcode to highlight. To avoid this, the package provides a cache option.

    The cache option creates a directory .minted-jobname in the documents rootdirectory. Files of highlighted code are stored in this directory, so that the codewill not have to be highlighted again in the future. In most cases, caching willsignificantly speed up document compilation.

    Cached files that are no longer in use are automatically deleted.3

    minted uses the fancyvrb package behind the scenes for the code typesetting.langlinenosfancyvrb provides an option firstnumber that allows the starting line number of anenvironment to be specified. For convenience, there is an option firstnumber=lastthat allows line numbering to pick up where it left off. The langlinenos optionmakes firstnumber work for each language individually with all minted and\mint usages. For example, consider the code and output below.

    \begin{minted}[linenos]{python}def f(x):

    return x**2\end{minted}

    \begin{minted}[linenos]{ruby}def func

    puts "message"end\end{minted}

    \begin{minted}[linenos, firstnumber=last]{python}def g(x):

    return 2*x\end{minted}

    3This depends on the main auxiliary file not being deleted or becoming corrupted. If thathappens, you could simply delete the cache directory and start over.

    10

  • 1 def f(x):2 return x**2

    1 def func2 puts "message"3 end

    3 def g(x):4 return 2*x

    Without the langlinenos option, the line numbering in the second Python envi-ronment would not pick up where the first Python environment left off.

    5.2 Macro option usage

    All minted highlighting commands accept the same set of options. Options arespecified as a comma-separated list of key=value pairs. For example, we canspecify that the lines should be numbered:

    \begin{minted}[linenos=true]{c++}#include int main() {

    std::cout

  • \begin{minted}[gobble=2,showspaces]{python}def boring(args = None):

    pass\end{minted}

    versus

    \begin{minted}[showspaces]{python}def boring(args = None):

    pass\end{minted}

    def boring(args = None):pass

    versus

    def boring(args = None):pass

    You may wish to set options for the document as a whole, or for an entire language.\setmintedThis is possible via \setminted. The syntax is \setminted[language]{key=value,...}.Language-specific options override document-wide options, which in turn are over-ridden by individual command and environment options.

    5.3 Available options

    Following is a full list of available options. For more detailed option descriptionsplease refer to the fancyvrb and Pygments documentation.(auto|dimension) (default: auto)baselinestretchValue to use as for baselinestretch inside the listing.

    (string) (default: none)bgcolorBackground color of the listing. Notice that the value of this option must notbe a color command. Instead, it must be a color name, given as a string, of apreviously-defined color:

    \definecolor{bg}{rgb}{0.95,0.95,0.95}\begin{minted}[bgcolor=bg]{php}

    \end{minted}

    Unlike the other options, this option is currently only supported for individualcommands and environments; there is not support at the language and document-wide levels.

    (list of strings) (default: highlight XXX, TODO, BUG, and NOTE)codetagifyHighlight special code tags in comments and docstrings.

    (string) (default: system-specific)encodingSets the file encoding that Pygments expects.(string) (default: system-specific)outencodingSets the file encoding that Pygments uses for highlighted output. Overrides anyencoding previously set via encoding.

    12

  • (integer) (default: 1)firstlineThe first line to be shown. All lines before that line are ignored and do not appearin the output.

    (auto|integer) (default: auto = 1)firstnumberLine number of the first line.

    (family name) (default: tt)fontfamilyThe font family to use. tt, courier and helvetica are pre-defined.

    (series name) (default: auto the same as the current font)fontseriesThe font series to use.

    (font size) (default: auto the same as the current font)fontsizeThe size of the font to use, as a size command, e.g. \footnotesize.

    (font shape) (default: auto the same as the current font)fontshapeThe font shape to use.

    (command) (default: none)formatcomA format to execute before printing verbatim text.

    (none|leftline|topline|bottomline|lines|single) (default: none)frameThe type of frame to put around the source code listing.

    (dimension) (default: 0.4pt)frameruleWidth of the frame.

    (dimension) (default: \fboxsep)framesepDistance between frame and content.

    (boolean) (default: true)funcnamehighlighting[For PHP only] If true, highlights built-in function names.(integer) (default: 0)gobbleRemove the first n characters from each input line.

    (string) (default: lower)keywordcaseChanges capitalization of keywords. Takes lower, upper, or capitalize.

    ([string]string) (default: empty)labelAdd a label to the top, the bottom or both of the frames around the code. See thefancyvrb documentation for more information and examples. Note: This does notadd a \label to the current listing. To achieve that, use a floating environment(section 4) instead.

    (none|topline|bottomline|all) (default: topline, all or none)labelpositionPosition where to print the label (see above; default: topline if one label isdefined, all if two are defined, none else). See the fancyvrb documentation formore information.

    (integer) (default: last line of input)lastlineThe last line to be shown.

    13

  • (boolean) (default: false)linenosEnables line numbers. In order to customize the display style of line numbers, youneed to redefine the \theFancyVerbLine macro:

    \renewcommand{\theFancyVerbLine}{\sffamily\textcolor[rgb]{0.5,0.5,1.0}{\scriptsize\oldstylenums{\arabic{FancyVerbLine}}}}

    \begin{minted}[linenos,firstnumber=11]{python}

    def all(iterable):for i in iterable:

    if not i:return False

    return True\end{minted}

    11 def all(iterable):12 for i in iterable:13 if not i:14 return False15 return True

    (left|right) (default: none)numbersEssentially the same as linenos, except the side on which the numbers appearmay be specified.

    (boolean) (default: false)mathescapeEnable LATEX math mode inside comments. Do not use spaces inside math modethey will be rendered like other full-width verbatim spaces. Usage as in packagelistings.(boolean) (default: true)numberblanklinesEnables or disables numbering of blank lines.

    (dimension) (default: 12pt)numbersepGap between numbers and start of line.

    (boolean) (default: false)obeytabsTreat tabs as tabs instead of converting them to spaces.

    (boolean) (default: false)python3[For PythonConsoleLexer only] Specifies whether Python 3 highlighting is applied.(boolean) (default: false)resetmarginsResets the left margin inside other environments.

    (color command) (default: black)rulecolorThe color of the frame.

    (boolean) (default: false)samepageForces the whole listing to appear on the same page, even if it doesnt fit.

    (boolean) (default: false)showspacesEnables visible spaces: visible spaces.

    (boolean) (default: false)showtabsEnables visible tabsonly works in combination with obeytabs.

    (boolean) (default: false)startinline

    14

  • [For PHP only] Specifies that the code starts in PHP mode, i.e. leading
  • \newminted{cpp}{gobble=2,linenos}

    \begin{cppcode*}{linenos=false,frame=single}

    int const answer = 42;\end{cppcode*}

    int const answer = 42;

    Notice the star * behind the environment namedue to restrictions in fancyvrbshandling of options, it is necessary to provide a separate environment that acceptsoptions, and the options are not optional on the starred version of the environment.

    The default name of the environment is languagecode. If this name clashes withanother environment or if you want to choose an own name for another reason,you may do so by specifying it as the first argument: \newminted[environmentname]{language}{options}.The above macro only defines shortcuts for the minted environment. The main\newmintreason is that the short command form \mint often needs different optionsatthe very least, it will generally not use the gobble option. A shortcut for \mint isdefined using \newmint[macro name]{language}{options}. The argumentsand usage are identical to \newminted. If no macro name is specified, languageis used.

    \newmint{perl}{showspaces}

    \perl/my $foo = $bar;/my $foo = $bar;

    This creates custom versions of \mintinline. The syntax is the same as that\newmintinlinefor \newmint: \newmintinline[macro name]{language}{options}. If amacro name is not specified, then the created macro is called \languageinline.

    \newmintinline{perl}{showspaces}

    X\perlinline/my $foo = $bar;/XXmy $foo = $bar;X

    This creates custom versions of \inputminted. The syntax is\newmintedfile

    \newmintedfile[macro name]{language}{options}

    If no macro name is given, then the macro is called \languagefile.

    7 FAQ and Troubleshooting

    In some cases, minted may not give the desired result due to other document settingsthat it cannot control. Common issues are described below, with workarounds orsolutions. You may also wish to search tex.stackexchange.com or ask a questionthere, if you are working with minted in a non-typical context.

    16

  • Tilde characters ~ are raised, almost like superscripts. This is a fontissue. You need a different font encoding, possibly with a different font. Try\usepackage[T1]{fontenc} plus \usepackage{lmodern}, or somethingsimilar.

    Extended characters do not work inside minted commands andenvironments, even when the inputenc package is used. Version 2.0adds support for extended characters under the pdfTeX engine. But if youneed characters that are not supported by inputenc, you should use the XeTeXor LuaTeX engines instead.

    The caption package produces an error when \captionof and othercommands are used in combination with minted. Load the captionpackage with the option compatibility=false.

    Tabs are eaten by Beamer. This is due to how Beamer works withverbatim content. You are probably using the frame option fragile. Tryfragile=singleslide if you dont need overlays. Otherwise, consider using\inputminted or converting the tabs into spaces.

    I need a listing environment that supports page breaks. See http://tex.stackexchange.com/a/53540/10742.

    I want to use a custom script/executable to access Pygments,rather than pygmentize. Redefine \MintedPygmentize:

    \renewcommand{\MintedPygmentize}{...}

    Acknowledgements

    Konrad Rudolph: Special thanks to Philipp Stephani and the rest of the guys fromcomp.text.tex and tex.stackexchange.com.

    Version History

    v2.0-alpha2 (2013/08/21)

    \DeleteFile now only deletes files if they do indeed exist. This elimi-nates warning messages due to missing files.

    Fixed a bug in the definition of \DeleteFile for non-Windows systems. Added support for Pygments option stripnl. Settings macros that were previously defined globally are now defined lo-

    cally, so that \setmintedmay be confined by \begingroup...\endgroupas expected.

    17

  • Macro definitions for a given style are now loaded only once per docu-ment, rather than once per command/environment. This works evenwithout caching.

    A custom script/executable may now be substituted for pygmentizeby redefining \MintedPygmentize.

    v2.0alpha (2013/07/30)

    Added the package option cache. This significantly increases com-pilation speed by caching old output. For example, compiling thedocumentation is around 5x faster.

    New inline command \mintinline. Custom versions can be createdvia \newmintinline. The command works inside other commands (forexample, footnotes) in most situations, so long as the percent and hashcharacters are avoided.

    The new \setminted command allows options to be specified at thedocument and language levels.

    All extended characters (Unicode, etc.) supported by inputenc nowwork under the pdfTeX engine. This involved using \detokenize oneverything prior to saving.

    New package option langlinenos allows line numbering to pick upwhere it left off for a given language when firstnumber=last.

    New options, including style, encoding, outencoding, codetagify,keywordcase, texcomments (same as texcl), python3 (for thePythonConsoleLexer), and numbers.

    \usemintedstyle now takes an optional argument to specify the stylefor a particular language, and works anywhere in the document.

    xcolor is only loaded if color isnt, preventing potential packageclashes.

    8 Implementation

    8.1 Required packages

    Load required packages. For compatibility reasons, most old functionality shouldbe supported with the original set of packages. More recently added packages, suchas etoolbox and xstring, should only be used for new features when possible.

    1 \RequirePackage{keyval}2 \RequirePackage{fancyvrb}3 \RequirePackage{float}4 \RequirePackage{ifthen}5 \RequirePackage{calc}

    18

  • 6 \RequirePackage{ifplatform}7 \RequirePackage{pdftexcmds}8 \RequirePackage{etoolbox}9 \RequirePackage{xstring}

    Make sure that either color or xcolor is loaded.

    10 \AtBeginDocument{\@ifpackageloaded{color}{}{\RequirePackage{xcolor}}}

    8.2 Package options

    \minted@float@within Define an option that controls the section numbering of the listing float.

    11 \DeclareOption{chapter}{\def\minted@float@within{chapter}}12 \DeclareOption{section}{\def\minted@float@within{section}}

    minted@cache Define an option that determines whether highlighted content is cached. We use aboolean to keep track of its state.

    13 \newboolean{minted@cache}14 \DeclareOption{cache}{%15 \minted@cachetrue16 \AtEndOfPackage{\ProvideDirectory{\minted@cachedir}}%17 }

    langlinenos Define an option that makes all minted environments and \mint commands for agiven language share cumulative line numbering (if firstnumber=last).

    18 \newboolean{minted@langlinenos}19 \DeclareOption{langlinenos}{\minted@langlinenostrue}

    Process package options.

    20 \ProcessOptions\relax

    8.3 Caching and temp files

    \minted@infile Define a default name for files of highlighted content that are brought it. Cachingwill redefine this. We start out with the default, non-caching value.

    21 \newcommand{\minted@infile}{\jobname.out.pyg}

    \minted@cachedir Define a macro with the name of the cache directory. This uses a .minted- prefixfollowed by a sanitized \jobname (spaces and asterisks replaced).

    22 \StrSubstitute{\jobname}{ }{_}[\minted@jobname]

    19

  • 23 \StrSubstitute{\minted@jobname}{"}{}[\minted@jobname]24 \StrSubstitute{\minted@jobname}{*}{-}[\minted@jobname]25 \newcommand{\minted@cachedir}{.minted-\minted@jobname}

    minted-xetex-hasher.py XeTeX doesnt have built-in hashing capabilities, so we create a temporary script tohandle that. (pdfTeX has \pdfmdfivesum, and LuaTeX has equivalent capabilitiesthrough Lua; a common hashing interface for both engines is provided by thepdftexcmds package.)

    26 \expandafter\ifx\csname XeTeXinterchartoks\endcsname\relax27 \else28 \begin{VerbatimOut}[commandchars=!\[\]]{minted-xetex-hasher.py}29 import sys30 import hashlib31 hasher = hashlib.sha1()32 f = open(!jobname.mintedcmd, rb)33 hasher.update(f.read())34 f.close()35 f = open(sys.argv[1], rb)36 hasher.update(f.read())37 f.close()38 f = open(!jobname.mintedmd5, w)39 macro = r\edef\minted@hash{ + hasher.hexdigest() + }%\n40 f.write(\\makeatletter\n)41 f.write(macro)42 f.write(\\makeatother\n)43 f.close()44 \end{VerbatimOut}45 \fi

    We need a way to track the cache files that are created, and delete those that arenot in use.

    \minted@cachefiles This is a list of the current cache files.

    46 \newcommand{\minted@cachefiles}{}

    \minted@addcachefile This adds a file to the list of cache files. It also creates a macro involving the hash,so that the current usage of the hash can be easily checked.

    47 \newcommand{\minted@addcachefile}[1]{%48 \expandafter\gdef\expandafter\minted@cachefiles\expandafter{%49 \minted@cachefiles,#1}%50 \expandafter\gdef\csname minted@current@#1\endcsname{}%51 }

    \minted@savecachefiles We need to be able to save the list of cache files to the .aux file, so that we canreload it on the next run.

    20

  • 52 \newcommand{\minted@savecachefiles}{%53 \immediate\write\@mainaux{%54 \string\gdef\string\minted@oldcachefiles\string{%55 \minted@cachefiles\string}}%56 }

    \minted@cleancache Clean up old cache files that are no longer in use.

    57 \newcommand{\minted@cleancache}{%58 \ifthenelse{\boolean{minted@cache}}{%59 \ifcsname minted@oldcachefiles\endcsname60 \renewcommand{\do}[1]{%61 \ifthenelse{\equal{##1}{}}{}{%62 \ifcsname minted@current@##1\endcsname\else63 \DeleteFile[\minted@cachedir]{##1.pygtex}%64 \fi65 }%66 }%67 \expandafter\docsvlist\expandafter{\minted@oldcachefiles}%68 \else69 \fi70 }{}%71 }

    At the end of the document, save the list of cache files and clean the cache.

    72 \ifthenelse{\boolean{minted@cache}}%73 {\AtEndDocument{%74 \minted@savecachefiles75 \minted@cleancache}}%76 {}%

    8.4 OS interaction

    We need system-dependent macros for communicating with the outside world.

    \DeleteFile Delete a file. Define conditionally in case an equivalent macro has already beendefined.

    77 \ifwindows78 \providecommand{\DeleteFile}[2][]{%79 \ifthenelse{\equal{#1}{}}%80 {\IfFileExists{#2}{\immediate\write18{del "#2"}}{}}%81 {\IfFileExists{#1/#2}{\immediate\write18{del "#1\@backslashchar #2"}}{}}}82 \else83 \providecommand{\DeleteFile}[2][]{%84 \ifthenelse{\equal{#1}{}}%85 {\IfFileExists{#2}{\immediate\write18{rm "#2"}}{}}%

    21

  • 86 {\IfFileExists{#1/#2}{\immediate\write18{rm "#1/#2"}}{}}}87 \fi

    \ProvideDirectory We need to be able to create a directory, if it doesnt already exist. This is primarilyfor storing cached highlighted content.

    88 \ifwindows89 \newcommand{\ProvideDirectory}[1]{%90 \immediate\write18{if not exist "#1" mkdir "#1"}}91 \else92 \newcommand{\ProvideDirectory}[1]{%93 \immediate\write18{mkdir -p "#1"}}94 \fi

    \TestAppExists Determine whether a given application exists.

    Usage is a bit roundabout, but has been retained for backward compatibility. Totest whether an application exists, use the following code:

    \TestAppExists{appname}\ifthenelse{\boolean{AppExists}}{app exists}{app doesnt exist}

    95 \newboolean{AppExists}96 \newread\minted@appexistsfile97 \newcommand{\TestAppExists}[1]{98 \ifwindows

    On Windows, we need to use path expansion and write the result to a file. If theapplication doesnt exist, the file will be empty (except for a newline); otherwise,it will contain the full path of the application.

    99 \DeleteFile{\jobname.aex}100 \immediate\write18{for \string^\@percentchar i in (#1.exe #1.bat #1.cmd)101 do set >\jobname.aex >\jobname.aex}103 %$

  • On Unix-like systems, we do a straightforward which test and create a file uponsuccess, whose existence we can then check.

    116 \immediate\write18{which #1 && touch \jobname.aex}117 \IfFileExists{\jobname.aex}118 {\AppExiststrue119 \DeleteFile{\jobname.aex}}120 {\AppExistsfalse}121 \fi122 }

    8.5 Option processing

    We need macros for storing options that will later be passed to the command line.These are defined at the global (g), language (lang), and command or environment(cmd) levels, so that settings can be specified at various levels of hierarchy. Thelanguage macro is actually a placeholder. Each individual language will create a\minted@optlanglanguage macro. The current language will be tracked using\minted@lang.

    \minted@optg

    123 \newcommand{\minted@optg}{}

    \minted@lang

    124 \let\minted@lang\@empty

    \minted@optlang

    125 \newcommand{\minted@optlang}{}

    \minted@optcmd

    126 \newcommand{\minted@optcmd}{}

    \minted@checklang We need a way to check whether a language has had all its option macros created.

    127 \newcommand{\minted@checklang}{%128 \ifcsname minted@optlang\minted@lang\endcsname\else129 \expandafter\def\csname minted@optlang\minted@lang\endcsname{}%130 \fi131 \ifcsname minted@optlang\minted@lang @extra\endcsname\else132 \expandafter\def\csname minted@optlang\minted@lang @extra\endcsname{}%133 \fi134 }

    23

  • \minted@resetoptcmd We need a macro that will reset command-level options to null values. This macrowill be redefined as command-level options are specified, in such a way that thenext time it is used it will reset all options to null values. An equivalent at theglobal and command levels is not provided, since those options should persist.

    It is convenient always to reset the extra options, given the number of extraoptions and the proportional inconvenience of always having to check whether theyhave been added to the reset list.

    135 \newcommand{\minted@resetoptcmd}{\@namedef{minted@optcmd@extra}{}}

    We need a macro that will retrieve detokenized option values suitable for \write18.We create three versions, one for each level of options.

    \minted@getoptg

    136 \newcommand{\minted@getoptg}[1]{%137 \expandafter\detokenize%138 \expandafter\expandafter\expandafter{\csname minted@optg@#1\endcsname}}

    \minted@getoptlang

    139 \newcommand{\minted@getoptlang}[1]{%140 \expandafter\detokenize\expandafter\expandafter\expandafter{%141 \csname minted@optlang\minted@lang @#1\endcsname}}

    \minted@getoptcmd

    142 \newcommand{\minted@getoptcmd}[1]{%143 \expandafter\detokenize%144 \expandafter\expandafter\expandafter{\csname minted@optcmd@#1\endcsname}}

    We need a macro that will register options as having been used (add the optionsthat are in use to the list macro). As before, we create three versions, one per level.

    \minted@regoptg

    145 \newcommand{\minted@regoptg}[1]{%146 \ifcsname minted@optg@#1@reg\endcsname\else147 \expandafter\let\csname minted@optg@#1@reg\endcsname\@empty148 \expandafter\def\expandafter\minted@optg\expandafter{%149 \minted@optg\space\minted@getoptg{#1}}%150 \fi151 }

    \minted@regoptlang

    152 \newcommand{\minted@regoptlang}[1]{%

    24

  • 153 \ifcsname minted@optlang\minted@lang @#1@reg\endcsname\else154 \ifcsname minted@optlang\minted@lang\endcsname\else155 \expandafter\def\csname minted@optlang\minted@lang\endcsname{}%156 \fi157 \expandafter\let\csname minted@optlang\minted@lang @#1@reg\endcsname\@empty158 \expandafter\let\expandafter\minted@optlang%159 \csname minted@optlang\minted@lang\endcsname160 \expandafter\def\expandafter\minted@optlang\expandafter{%161 \minted@optlang\space\minted@getoptlang{#1}}%162 \expandafter\let\csname minted@optlang\minted@lang\endcsname\minted@optlang163 \let\minted@optlang\@empty164 \fi165 }

    \minted@regoptcmd

    166 \newcommand{\minted@regoptcmd}[1]{%167 \ifcsname minted@optcmd@#1@reg\endcsname\else168 \expandafter\let\csname minted@optcmd@#1@reg\endcsname\@empty169 \expandafter\def\expandafter\minted@optcmd\expandafter{%170 \minted@optcmd\space\minted@getoptcmd{#1}}%171 \expandafter\def\expandafter\minted@resetoptcmd\expandafter{%172 \minted@resetoptcmd173 \@namedef{minted@optcmd@#1}{}}174 \fi175 }

    \minted@define@opt Define a generic option with an optional default argument. If a key option isspecified without =value, the default is assumed. Options are automaticallycreated at all levels.

    176 \newcommand{\minted@define@opt}[3][]{%177 \ifthenelse{\equal{#1}{}}%178 {\define@key{minted@optg}{#2}{\@namedef{minted@optg@#2}{#3}%179 \minted@regoptg{#2}}%180 \define@key{minted@optlang}{#2}{%181 \@namedef{minted@optlang\minted@lang @#2}{#3}%182 \minted@regoptlang{#2}}%183 \define@key{minted@optcmd}{#2}{\@namedef{minted@optcmd@#2}{#3}%184 \minted@regoptcmd{#2}}}%185 {\define@key{minted@optg}{#2}[#1]{\@namedef{minted@optg@#2}{#3}%186 \minted@regoptg{#2}}%187 \define@key{minted@optlang}{#2}[#1]{%188 \@namedef{minted@optlang\minted@lang @#2}{#3}%189 \minted@regoptlang{#2}}%190 \define@key{minted@optcmd}{#2}[#1]{\@namedef{minted@optcmd@#2}{#3}%191 \minted@regoptcmd{#2}}}%192 }

    25

  • \minted@define@optstyle Define an option for styles. These are defined independently, because styles needto be registered, so that the macros for a given style are only created and inputtedonce.

    193 \newcommand{\minted@define@optstyle}{%194 \define@key{minted@optg}{style}{%195 \@namedef{minted@optg@style}{-P style=##1 -P commandprefix=PYG##1}%196 \minted@regoptg{style}\minted@regstyle{##1}}%197 \define@key{minted@optlang}{style}{%198 \@namedef{minted@optlang\minted@lang @style}%199 {-P style=##1 -P commandprefix=PYG##1}%200 \minted@regoptlang{style}\minted@regstyle{##1}}%201 \define@key{minted@optcmd}{style}{%202 \@namedef{minted@optcmd@style}{-P style=##1 -P commandprefix=PYG##1}%203 \minted@regoptcmd{style}\minted@regstyle{##1}}%204 }

    \minted@regstyle Register any used styles, and make sure that the definitions are available.

    Its important that registration be done with \def. The style macros are defed,so they will be local if included within a group. We need to make sure that wedont make the mistake of registering a style globally that is actually only availablein a group.

    We have to do some tricks with \endlinechar to prevent \input from insertingunwanted whitespace. That is primarily for inline commands, where it wouldintroduce a line break.

    205 \newcommand{\minted@regstyle}[1]{%206 \ifcsname minted@stylereg@#1\endcsname\else207 \expandafter\global\expandafter%208 \let\csname minted@stylereg@#1\endcsname\@empty209 \ifthenelse{\boolean{minted@cache}}%210 {\IfFileExists{\minted@cachedir/#1.pygstyle}{}{%211 \ifwindows212 \immediate\write18{\MintedPygmentize\space -S #1 -f latex213 -P commandprefix=PYG#1214 > \minted@cachedir\@backslashchar#1.pygstyle}%215 \else216 \immediate\write18{\MintedPygmentize\space -S #1 -f latex217 -P commandprefix=PYG#1218 > \minted@cachedir/#1.pygstyle}%219 \fi220 }%221 \begingroup222 \let\def\gdef223 \endlinechar=-1\relax224 \input{\minted@cachedir/#1.pygstyle}%225 \endgroup}%226 {\immediate\write18{\MintedPygmentize\space -S #1 -f latex

    26

  • 227 -P commandprefix=PYG#1 > \jobname.pyg}%228 \begingroup229 \let\def\gdef230 \endlinechar=-1\relax231 \input{\jobname.pyg}%232 \endgroup}%233 \fi234 }

    \minted@define@switch Define a switch or boolean option, which is true when no value is specified.

    235 \newcommand{\minted@define@switch}[3][]{236 \define@booleankey{minted@optg}{#2}237 {\@namedef{minted@optg@#2}{#3}\minted@regoptg{#2}}238 {\@namedef{minted@optg@#2}{#1}\minted@regoptg{#2}}239 \define@booleankey{minted@optlang}{#2}240 {\@namedef{minted@optlang\minted@lang @#2}{#3}\minted@regoptlang{#2}}241 {\@namedef{minted@optlang\minted@lang @#2}{#1}\minted@regoptlang{#2}}242 \define@booleankey{minted@optcmd}{#2}243 {\@namedef{minted@optcmd@#2}{#3}\minted@regoptcmd{#2}}244 {\@namedef{minted@optcmd@#2}{#1}\minted@regoptcmd{#2}}245 }

    \minted@define@extra Extra options are passed on to fancyvrb via Pygments.

    246 \newcommand{\minted@define@extra}[1]{247 \define@key{minted@optg}{#1}{%248 \expandafter\def\expandafter\minted@optg@extra\expandafter{%249 \minted@optg@extra,#1=##1}}250 \@namedef{minted@optg@extra}{}251 \define@key{minted@optlang}{#1}{%252 \ifcsname minted@optlang\minted@lang @extra\endcsname\else253 \expandafter\def\csname minted@optlang\minted@lang @extra\endcsname{}%254 \fi255 \expandafter\let\expandafter\minted@optlang@extra%256 \csname minted@optlang\minted@lang @extra \endcsname257 \expandafter\def\expandafter\minted@optlang@extra\expandafter{%258 \minted@optlang@extra,#1=##1}%259 \expandafter\let\csname minted@optlang\minted@lang @extra\endcsname%260 \minted@optlang@extra261 \let\minted@optlang@extra\@empty}%262 \@namedef{minted@optlang@extra}{}263 \define@key{minted@optcmd}{#1}{%264 \expandafter\def\expandafter\minted@optcmd@extra\expandafter{%265 \minted@optcmd@extra,#1=##1}}266 \@namedef{minted@optcmd@extra}{}267 }

    \minted@define@extra@switch Extra switch options are also passed on to fancyvrb.

    27

  • 268 \newcommand{\minted@define@extra@switch}[1]{269 \define@booleankey{minted@optg}{#1}270 {\expandafter\def\expandafter\minted@optg@extra\expandafter{%271 \minted@optg@extra,#1}}272 {\expandafter\def\expandafter\minted@optg@extra\expandafter{%273 \minted@optg@extra,#1=false}}274 \define@booleankey{minted@optlang}{#1}275 {%276 \ifcsname minted@optlang\minted@lang @extra\endcsname\else277 \expandafter\def\csname minted@optlang\minted@lang @extra\endcsname{}%278 \fi279 \expandafter\let\expandafter\minted@optlang@extra%280 \csname minted@optlang\minted@lang @extra\endcsname281 \expandafter\def\expandafter\minted@optlang@extra\expandafter{%282 \minted@optlang@extra,#1}%283 \expandafter\let\csname minted@optlang\minted@lang @extra\endcsname%284 \minted@optlang@extra285 \let\minted@optlang@extra\@empty}286 {%287 \ifcsname minted@optlang\minted@lang @extra\endcsname\else288 \expandafter\def\csname minted@optlang\minted@lang @extra\endcsname{}%289 \fi290 \expandafter\let\expandafter\minted@optlang@extra%291 \csname minted@optlang\minted@lang @extra\endcsname292 \expandafter\def\expandafter\minted@optlang@extra\expandafter{%293 \minted@optlang@extra,#1=false}%294 \expandafter\let\csname minted@optlang\minted@lang @extra\endcsname%295 \minted@optlang@extra296 \let\minted@optlang@extra\@empty}297 \define@booleankey{minted@optcmd}{#1}298 {\expandafter\def\expandafter\minted@optcmd@extra\expandafter{%299 \minted@optcmd@extra,#1}}300 {\expandafter\def\expandafter\minted@optcmd@extra\expandafter{%301 \minted@optcmd@extra,#1=false}}302 }

    Actual option definitions.

    Lexers.

    303 % The following duplicates the extra version; any difference?304 %\minted@define@opt{tabsize}{-P tabsize=#1}305 \minted@define@opt{encoding}{-P encoding=#1}306 \minted@define@opt{outencoding}{-P outencoding=#1}307 \minted@define@opt{stripnl}{-P stripnl=#1}308 % Python console309 \minted@define@switch{python3}{-P python3=True}310 % PHP311 \minted@define@switch[-P funcnamehighlighting=False]%312 {funcnamehighlighting}{-P funcnamehighlighting}

    28

  • 313 \minted@define@switch{startinline}{-P startinline}

    Filters.

    314 \minted@define@opt{gobble}{-F gobble:n=#1}315 \minted@define@opt{codetagify}{-F codetagify:codetags=#1}316 \minted@define@opt{keywordcase}{-F keywordcase:case=#1}

    LATEX formatter.

    317 \minted@define@switch{texcl}{-P texcomments}318 \minted@define@switch{texcomments}{-P texcomments}319 \minted@define@switch{mathescape}{-P mathescape}320 \minted@define@switch{linenos}{-P linenos}321 \minted@define@optstyle

    fancyvrb (via LATEXformatter).

    322 \minted@define@extra{frame}323 \minted@define@extra{framesep}324 \minted@define@extra{framerule}325 \minted@define@extra{rulecolor}326 \minted@define@extra{numbersep}327 \minted@define@extra{numbers}328 \minted@define@extra{firstnumber}329 \minted@define@extra{stepnumber}330 \minted@define@extra{firstline}331 \minted@define@extra{lastline}332 \minted@define@extra{baselinestretch}333 \minted@define@extra{xleftmargin}334 \minted@define@extra{xrightmargin}335 \minted@define@extra{fillcolor}336 \minted@define@extra{tabsize}337 \minted@define@extra{fontfamily}338 \minted@define@extra{fontsize}339 \minted@define@extra{fontshape}340 \minted@define@extra{fontseries}341 \minted@define@extra{formatcom}342 \minted@define@extra{label}343 \minted@define@extra@switch{numberblanklines}344 \minted@define@extra@switch{showspaces}345 \minted@define@extra@switch{resetmargins}346 \minted@define@extra@switch{samepage}347 \minted@define@extra@switch{showtabs}348 \minted@define@extra@switch{obeytabs}

    Other options.

    The old bgcolor is retained for compatibility, but in many cases a dedicatedframing package may be preferable.

    29

  • 349 \let\minted@optcmd@bgcolor\@empty350 \define@key{minted@optcmd}{bgcolor}{\@namedef{minted@optcmd@bgcolor}{#1}}

    8.6 Internal helpers

    \minted@bgbox Define an environment that may be wrapped around a minted environment toassign a background color. This is retained as a holdover from version 1.0. In mostcases, it is probably better to use a dedicated framing package, such as mdframedor tcolorbox.First, we need to define a new save box.

    351 \newsavebox{\minted@bgbox}

    Now we can define the environment that captures a code fragment inside a minipageand applies a background color.

    352 \newenvironment{minted@colorbg}[1]{353 %\setlength{\fboxsep}{-\fboxrule}354 \def\minted@bgcol{#1}355 \noindent356 \begin{lrbox}{\minted@bgbox}357 \begin{minipage}{\linewidth-2\fboxsep}}358 {\end{minipage}359 \end{lrbox}%360 \colorbox{\minted@bgcol}{\usebox{\minted@bgbox}}}

    \minted@code Create a file handle for saving code (and anything else that must be written totemp files).

    361 \newwrite\minted@code

    \minted@savecode Save code to be pygmentized to a file.

    362 \newcommand{\minted@savecode}[1]{363 \immediate\openout\minted@code\jobname.pyg364 \immediate\write\minted@code{\expandafter\detokenize\expandafter{#1}}%365 \immediate\closeout\minted@code}

    \minted@FVB@VerbatimOut We need a custom version of fancyvrbs \FVB@VerbatimOut that supports Unicode(everything written to file is \detokenized).

    366 \newcommand{\minted@write@detok}[1]{%367 \immediate\write\FV@OutFile{\detokenize{#1}}}368 \newcommand{\minted@FVB@VerbatimOut}[1]{%369 \@bsphack370 \begingroup371 \FV@UseKeyValues

    30

  • 372 \FV@DefineWhiteSpace373 \def\FV@Space{\space}%374 \FV@DefineTabOut375 \let\FV@ProcessLine\minted@write@detok376 \immediate\openout\FV@OutFile #1\relax377 \let\FV@FontScanPrep\relax378 \let\@noligs\relax379 \FV@Scan}

    \MintedPygmentize We need a way to customize the executable/script that is called to performhighlighting. Typically, we will want pygmentize. But advanced users might wishto use a custom Python script instead.

    380 \newcommand{\MintedPygmentize}{pygmentize}

    \minted@pygmentize Pygmentize a file (default: \jobname.pyg) using the options provided.

    Unfortunately, the logic for caching is a little complex due to operations that areOS- and engine-dependent.

    The name of cached files is the result of concatenating the md5 of the code andthe md5 of the command. This results in a filename that is longer than ideal(64 characters plus path and extension). Unfortunately, this is the only robustapproach that is possible using the built-in pdfTeX hashing capabilities.4 LuaTeXcould do better, by hashing the command and code together. The Python scriptthat provides XeTeX capabilities simply runs both the command and the codethrough a single sha1 hasher, but has the additional overhead of the \write18 calland Python execution.

    One potential concern is that caching should also keep track of the command fromwhich code originates. What if identical code is highlighted with identical settingsin both the minted environment and \mintinline command? In both cases, whatis actually saved by Pygments is identical. The difference in final appearance isdue to how the environment and command treat the Pygments output.

    Notice that the verboptions macros dont need separating commas, since theyreassembled in such a way that they will always have a leading comma.

    381 \newcommand{\minted@pygmentize}[2][\jobname.pyg]{%382 \minted@checklang383 \def\minted@cmd{\MintedPygmentize\space -l #2 -f latex -F tokenmerge384 \minted@optg \space \csname minted@optlang\minted@lang\endcsname385 \space \minted@optcmd \space -P "verboptions=\minted@getoptg{extra}%386 \minted@getoptlang{extra}\minted@getoptcmd{extra}"387 -o \minted@infile \space #1}%388 % For debugging, uncomment:

    4It would be possible to use only the cache of the code, but that approach breaks down assoon as the code is used multiple times with different options. While that may seem unlikely inpractice, it occurs in this documentation and may be expected to occur in other docs.

    31

  • 389 % \immediate\typeout{\minted@cmd}%390 \ifthenelse{\boolean{minted@cache}}%391 {%392 \expandafter\ifx\csname XeTeXinterchartoks\endcsname\relax393 \edef\minted@hash{\pdf@filemdfivesum{#1}\pdf@mdfivesum{\minted@cmd}}%394 \else395 \immediate\openout\minted@code\jobname.mintedcmd396 \immediate\write\minted@code{\minted@cmd}%397 \immediate\closeout\minted@code398 \immediate\write18{python minted-xetex-hasher.py "#1"}399 \input{\jobname.mintedmd5}400 \fi401 \ifwindows402 \edef\minted@infile{%403 \minted@cachedir\@backslashchar\[email protected]}%404 \else405 \edef\minted@infile{%406 \minted@cachedir/\[email protected]}%407 \fi408 \IfFileExists{\minted@cachedir/\[email protected]}{}{%409 \immediate\write18{\minted@cmd}}%410 \expandafter\minted@addcachefile\expandafter{\minted@hash}%411 \minted@inputpyg}%412 {\immediate\write18{\minted@cmd}%413 \minted@inputpyg}%414 }415 \newcommand{\minted@inputpyg}{%416 \ifthenelse{\equal{\minted@optcmd@bgcolor}{}}%417 {}%418 {\begin{minted@colorbg}{\minted@optcmd@bgcolor}}%419 \input{\minted@infile}%420 \ifthenelse{\equal{\minted@optcmd@bgcolor}{}}%421 {}%422 {\end{minted@colorbg}}%423 }

    We need a way to have line counters on a per-language basis.

    \minted@langlinenoson

    424 \newcounter{minted@FancyVerbLineTemp}425 \newcommand{\minted@langlinenoson}{%426 \ifcsname c@minted@lang\minted@lang\endcsname\else427 \newcounter{minted@lang\minted@lang}%428 \fi429 \setcounter{minted@FancyVerbLineTemp}{\value{FancyVerbLine}}%430 \setcounter{FancyVerbLine}{\value{minted@lang\minted@lang}}%431 }

    32

  • \minted@langlinenosoff

    432 \newcommand{\minted@langlinenosoff}{%433 \setcounter{minted@lang\minted@lang}{\value{FancyVerbLine}}%434 \setcounter{FancyVerbLine}{\value{minted@FancyVerbLineTemp}}%435 }

    Disable the language-specific settings if the package option isnt used.

    436 \ifthenelse{\boolean{minted@langlinenos}}{}{%437 \let\minted@langlinenoson\relax438 \let\minted@langlinenosoff\relax439 }

    8.7 Public API

    \setminted Set global or language-level options.

    440 \newcommand{\setminted}[2][]{%441 \ifthenelse{\equal{#1}{}}%442 {\setkeys{minted@optg}{#2}}%443 {\def\minted@lang{#1}\setkeys{minted@optlang}{#2}}%444 }

    \usemintedstyle Set style. This is a holdover from version 1, since \setminted can now accomplishthis, and a hierarchy of style settings are now possible.

    445 \newcommand{\usemintedstyle}[2][]{\setminted[#1]{style=#2}}

    \mintinline Define an inline command. This requires some catcode acrobatics. The typicalverbatim methods are not used. Rather, a different approach is taken that isgenerally more robust when used within other commands (for example, when usedin footnotes).

    Pygments saves code wrapped in a Verbatim environment. Getting the inline com-mand to work correctly require redefining Verbatim to be BVerbatim temporarily.This approach would break if BVerbatim were ever redefined elsewhere.

    446 \newcommand{\mintinline}[2][]{%447 \minted@resetoptcmd448 \setkeys{minted@optcmd}{#1}%449 \def\minted@lang{#2}%450 \begingroup451 \let\do\@makeother\dospecials452 \catcode\{=1453 \catcode\}=2454 \catcode\^^I=\active455 \@ifnextchar\bgroup

    33

  • 456 {\minted@inline@iii}%457 {\catcode\{=12\catcode\}=12458 \minted@inline@i}}459 \def\minted@inline@i#1{%460 \endgroup461 \def\minted@inline@ii##1#1{%462 \minted@inline@iii{##1}}%463 \begingroup464 \let\do\@makeother\dospecials465 \minted@inline@ii}466 \newcommand{\minted@inline@iii}[1]{%467 \endgroup468 \immediate\openout\minted@code\jobname.pyg469 \immediate\write\minted@code{\detokenize{#1}}%470 \immediate\closeout\minted@code471 \begingroup472 \RecustomVerbatimEnvironment{Verbatim}{BVerbatim}{}%473 \minted@pygmentize{\minted@lang}%474 \endgroup}

    \mint Highlight a small piece of verbatim code.

    475 \newcommand{\mint}[3][]{%476 \def\minted@lang{#2}%477 \DefineShortVerb{#3}%478 \minted@resetoptcmd479 \setkeys{minted@optcmd}{#1}%480 \SaveVerb[aftersave={%481 \UndefineShortVerb{#3}%482 \minted@savecode{\FV@SV@minted@verb}%483 \minted@langlinenoson484 \minted@pygmentize{#2}485 \minted@langlinenosoff}]{minted@verb}#3}

    minted Highlight a longer piece of code inside a verbatim environment.

    486 \newenvironment{minted}[2][]487 {\VerbatimEnvironment488 \let\FVB@VerbatimOut\minted@FVB@VerbatimOut489 \def\minted@lang{#2}%490 \minted@resetoptcmd491 \setkeys{minted@optcmd}{#1}%492 \begin{VerbatimOut}[codes={\catcode\^^I=12}]{\jobname.pyg}}%493 {\end{VerbatimOut}%494 \minted@langlinenoson495 \minted@pygmentize{\minted@lang}%496 \minted@langlinenosoff}

    \inputminted Highlight an external source file.

    34

  • 497 \newcommand{\inputminted}[3][]{%498 \def\minted@lang{#2}%499 \minted@resetoptcmd500 \setkeys{minted@optcmd}{#1}%501 \minted@pygmentize[#3]{#2}}

    8.8 Command shortcuts

    We allow the user to define shortcuts for the highlighting commands.

    \newminted Define a new language-specific alias for the minted environment.

    502 \newcommand{\newminted}[3][]{

    First, we look whether a custom environment name was given as the first optionalargument. If thats not the case, construct it from the language name (appendcode).

    503 \ifthenelse{\equal{#1}{}}504 {\def\minted@envname{#2code}}505 {\def\minted@envname{#1}}

    Now, we define two environments. The first takes no further arguments. Thesecond, starred version, takes an extra argument that specifies option overrides.

    506 \newenvironment{\minted@envname}507 {\VerbatimEnvironment508 \begin{minted}[#3]{#2}}509 {\end{minted}}510 \newenvironment{\minted@envname *}[1]511 {\VerbatimEnvironment\begin{minted}[#3,##1]{#2}}512 {\end{minted}}}

    \newmint Define a new language-specific alias for the \mint short form.

    513 \newcommand{\newmint}[3][]{

    Same as with \newminted, look whether an explicit name is provided. If not, takethe language name as command name.

    514 \ifthenelse{\equal{#1}{}}515 {\def\minted@shortname{#2}}516 {\def\minted@shortname{#1}}

    And define the macro.

    517 \expandafter\newcommand\csname\minted@shortname\endcsname[2][]{518 \mint[#3,##1]{#2}##2}}

    35

  • \newmintedfile Define a new language-specific alias for \inputminted.

    519 \newcommand{\newmintedfile}[3][]{

    Here, the default macro name (if none is provided) appends file to the languagename.

    520 \ifthenelse{\equal{#1}{}}521 {\def\minted@shortname{#2file}}522 {\def\minted@shortname{#1}}

    . . . and define the macro.

    523 \expandafter\newcommand\csname\minted@shortname\endcsname[2][]{524 \inputminted[#3,##1]{#2}{##2}}}

    \newmintinline Define an alias for \mintinline.

    As is usual with inline commands, a little catcode trickery must be employed.

    525 \newcommand{\newmintinline}[3][]{%526 \ifthenelse{\equal{#1}{}}%527 {\def\minted@shortname{#2inline}}%528 {\def\minted@shortname{#1}}%529 \expandafter\newcommand\csname\minted@shortname\endcsname{%530 \begingroup531 \let\do\@makeother\dospecials532 \catcode\{=1533 \catcode\}=2534 \@ifnextchar[{\endgroup\minted@inliner[#3][#2]}%535 {\endgroup\minted@inliner[#3][#2][]}}%536 \def\minted@inliner[##1][##2][##3]{\mintinline[##1,##3]{##2}}%537 }

    8.9 Float support

    listing Define a new floating environment to use for floated listings.

    538 \@ifundefined{minted@float@within}539 {\newfloat{listing}{h}{lol}}540 {\newfloat{listing}{h}{lol}[\minted@float@within]}

    \listingcaption The name that is displayed before each individual listings caption and its number.The macro \listingscaption can be redefined by the user.

    541 \newcommand{\listingscaption}{Listing}

    The following definition should not be changed by the user.

    542 \floatname{listing}{\listingscaption}

    36

  • \listoflistingscaption The caption that is displayed for the list of listings.

    543 \newcommand{\listoflistingscaption}{List of listings}

    \listoflistings Used to produce a list of listings (like \listoffigures etc.). This may well clashwith other packages (for example, listings) but we choose to ignore this since thesetwo packages shouldnt be used together in the first place.

    544 \providecommand{\listoflistings}{\listof{listing}{\listoflistingscaption}}

    8.10 Epilogue

    Check whether LaTeX was invoked with -shell-escape option, make surepygmentize exists, and set the default style.

    545 \AtEndOfPackage{546 \ifnum\pdf@shellescape=1\relax\else547 \PackageError{minted}548 {You must invoke LaTeX with the549 -shell-escape flag}550 {Pass the -shell-escape flag to LaTeX. Refer to the minted.sty551 documentation for more information.}%552 \fi553 \TestAppExists{pygmentize}554 \ifAppExists\else555 \PackageError{minted}556 {You must have pygmentize installed557 to use this package}558 {Refer to the installation instructions in the minted559 documentation for more information.}560 \fi561 \setminted{style=default}%562 }

    8.11 Final cleanup

    Clean up temp files. What actually needs to be done depends on caching andengine.

    563 \AtEndDocument{564 \expandafter\ifx\csname XeTeXinterchartoks\endcsname\relax565 \else566 \DeleteFile{minted-xetex-hasher.py}567 \DeleteFile{\jobname.mintedcmd}568 \DeleteFile{\jobname.mintedmd5}569 \fi570 \DeleteFile{\jobname.pyg}%

    37

  • 571 \DeleteFile{\jobname.out.pyg}%572 }

    38

    IntroductionInstallationPrerequisitesRequired packagesInstalling minted

    Basic usagePreliminaryA minimal complete exampleFormatting source codeUsing different stylesSupported languages

    Floating listingsOptionsPackage optionsMacro option usageAvailable options

    Defining shortcutsFAQ and TroubleshootingVersion HistoryImplementationRequired packagesPackage optionsCaching and temp filesOS interactionOption processingInternal helpersPublic APICommand shortcutsFloat supportEpilogueFinal cleanup