% \iffalse meta-comment % % Copyright (C) 2013-2024 by Geoffrey M. Poore % Copyright (C) 2010-2011 by Konrad Rudolph % -------------------------------------------------------------------------- % This work may be distributed and/or modified under the % conditions of the LaTeX Project Public License, either version 1.3c % of this license or (at your option) any later version. % The latest version of this license is in % https://www.latex-project.org/lppl.txt % and version 1.3c or later is part of all distributions of LaTeX % version 2008/05/04 or later. % % This work has the LPPL maintenance status `maintained'. % % The Current Maintainer of this work is Geoffrey M. Poore. % % This work consists of the files minted.dtx and minted.ins % and the derived file minted.sty. % % \fi % % \iffalse %<*driver> \ProvidesFile{minted.dtx} % %\NeedsTeXFormat{LaTeX2e} %\ProvidesPackage{minted} %<*package> [2024/11/17 v3.4.0 Yet another Pygments shim for LaTeX] % %<*driver> \documentclass{ltxdoc} \DisableCrossrefs ^^A\EnableCrossrefs ^^A\CodelineIndex ^^A\RecordChanges ^^A\OnlyDescription \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{lmodern} \usepackage{fourier} \usepackage{dingbat} \usepackage{microtype} \usepackage[svgnames]{xcolor} \usepackage{graphicx} \usepackage[lexerlinenos, highlightmode=immediate]{minted} \setminted{literatecomment=\%, autogobble} \usepackage{calc} \usepackage{multicol} \usepackage[hyperindex]{hyperref} \usepackage{cleveref} \newcommand{\env}[1]{\texttt{#1}} \makeatletter % The typesetting for macrocode doesn't use \@noligs, which upquote modifies. % So apply the upquote fix to \verbatim@nolig@list as well, which is in macrocode. \begingroup \catcode`'=\active \catcode``=\active \g@addto@macro\verbatim@nolig@list{% \let'\textquotesingle \let`\textasciigrave \ifx\encodingdefault\upquote@OTone \ifx\ttdefault\upquote@cmtt \def'{\char13 }% \def`{\char18 }% \fi\fi} \endgroup % Create a short verbatim pipe that handles quotation marks properly \begingroup \catcode`\|=\active \gdef\pipe@active@verbatim{% \begingroup \let\do\@makeother\dospecials \catcode`\|=\active \catcode`\`=\active \catcode`\'=\active \catcode`\<=\active \catcode`\>=\active \catcode`\-=\active \catcode`\,=\active \catcode`\ =\active \pipe@active@verbatim@i} \gdef\pipe@active@verbatim@i#1|{% \endgroup \begingroup \def\FV@SV@pipe@active@verbatim{% \FV@Gobble \expandafter\FV@ProcessLine\expandafter{#1}}% \BUseVerbatim{pipe@active@verbatim}% \endgroup} \AtBeginDocument{\let|\pipe@active@verbatim} \endgroup \def\MacroFont{% \fontencoding\encodingdefault% \fontfamily\ttdefault% \fontseries\mddefault% \fontshape\updefault% \small} \definecolor{minted@mint}{HTML}{0B610B} \colorlet{minted@linkcolor}{minted@mint} \def\PrintDescribeMacro#1{\strut \MacroFont\textcolor{minted@linkcolor}{\string #1\ }} \let\PrintDescribeEnv\PrintDescribeMacro \let\PrintMacroName\PrintDescribeMacro \let\PrintEnvName\PrintDescribeEnv \renewenvironment{macro}{\macro@custom@arg}{} \def\macro@custom@arg{% \begingroup\makeatletter\macro@custom@arg@i} \def\macro@custom@arg@i#1{% \makeatother \par\noindent \ifstrempty{#1}% {~\par}% {\ttfamily\color{minted@mint}\hspace*{-0.5in}% \macro@custom@arg@split#1,\FV@Sentinel\par}% \endgroup} \def\macro@custom@arg@spacegobble#1{#1} \def\macro@custom@arg@split#1,#2\FV@Sentinel{% \expandafter\string\macro@custom@arg@spacegobble#1% \if\relax\detokenize{#2}\relax \expandafter\@firstoftwo \else \expandafter\@secondoftwo \fi {}{\\\hspace*{-0.5in}\macro@custom@arg@split#2\FV@Sentinel}} \renewenvironment{environment}{\env@custom@arg}{} \def\env@custom@arg{% \begingroup\makeatletter\env@custom@arg@i} \def\env@custom@arg@i#1{% \makeatother \ifstrempty{#1}% {~\par}% {\ttfamily\color{minted@mint}\hspace*{-0.5in}% \env@custom@arg@split#1,\FV@Sentinel\par}% \endgroup} \def\env@custom@arg@spacegobble#1{#1} \def\env@custom@arg@split#1,#2\FV@Sentinel{% \env@custom@arg@spacegobble#1{\textrm{ \textit{(env.)}}}% \if\relax\detokenize{#2}\relax \expandafter\@firstoftwo \else \expandafter\@secondoftwo \fi {}{\\\hspace*{-0.5in}\env@custom@arg@split#2\FV@Sentinel}} \def\theCodelineNo{\textcolor{minted@linkcolor}{\sffamily\footnotesize\oldstylenums{\arabic{CodelineNo}}}} % \hypersetup{ pdftitle=The minted package: Highlighted source code in LaTeX, pdfauthor=Geoffrey M. Poore, pdfsubject={Minted LaTeX package manual}, colorlinks=true, allcolors=minted@linkcolor, } \newenvironment{mintedminted}% {\VerbatimEnvironment \begin{minted}}% {\end{minted}} \newenvironment{example} {\VerbatimEnvironment \begin{VerbatimOut}[gobble=1]{example.out}} {\end{VerbatimOut}% \setlength{\parindent}{0pt}% \vspace{1em}% \fbox{% \vspace{1ex}% \begin{minipage}{0.5\linewidth-2em-\fboxsep}% \inputminted[resetmargins]{latex}{example.out}% \end{minipage}% \hspace{2em}\vrule\hspace{2em}% \begin{minipage}{0.5\linewidth-2em-\fboxsep}% \input{example.out}% \end{minipage}% \vspace{1ex}}% \vspace{1em}} \begingroup \catcode`\^^M=\active% \gdef\longexample@i#1{% \def\longexample@arg{#1}% \begin{VerbatimOut}[gobble=1]{example.out}^^M}% \endgroup \newenvironment{longexample} {\VerbatimEnvironment \FVExtraReadOArgBeforeVEnv{\longexample@i}} {\end{VerbatimOut}% \vspace{1em}% \setlength{\parindent}{0pt}% \fbox{ \vspace{1ex}% \begin{minipage}{\linewidth-2\fboxsep}% \inputminted[resetmargins]{latex}{example.out}% ~\hrulefill~ \expandafter\fvset\expandafter{\longexample@arg}% \input{example.out}% \end{minipage}% \vspace{1ex}}% \vspace{1em}} \def\minted@printopt#1(#2) (#3){% \vspace{0.1in}% \leavevmode% \marginpar{\raggedleft\texttt{\textcolor{minted@linkcolor}{\small #1}}\ }% \kern-\parindent\textsf{(#2)}\hfill(default: \texttt{#3})\\} \newenvironment{optionlist}% {~\par\vspace{-14pt}% \def\pipechar{|} \let\|\pipechar \newcommand*\mintednext{}% \let\item@orig\item \renewcommand*\item[1][]{% \ifdefstring{\@currenvir}{optionlist}% {\mintednext% \renewcommand*\mintednext{\par}% \minted@printopt##1% \ignorespaces}% {\ifstrempty{##1}% {\vspace{-4pt}\item@orig} {\vspace{-4pt}\item@orig[##1]}}}} {\par} \edef\hashchar{\string#} \renewcommand*\l@subsection{\@dottedtocline{2}{1.5em}{3em}} \renewcommand*\l@subsubsection{\@dottedtocline{3}{4.5em}{3.8em}} \makeatother \newenvironment{mintedexample}% {\VerbatimEnvironment \begin{minted}}% {\end{minted}} \begin{document} \DocInput{minted.dtx} % ^^A\PrintIndex \end{document} % % \fi % % % ^^A\DoNotIndex{\newcommand,\newenvironment} % ^^A\DoNotIndex{\#,\$,\%,\&,\@,\\,\{,\},\^,\_,\~,\ } % ^^A\DoNotIndex{\@ne} % ^^A\DoNotIndex{\advance,\begingroup,\catcode,\closein} % ^^A\DoNotIndex{\closeout,\day,\def,\edef,\else,\empty,\endgroup} % ^^A\DoNotIndex{\begin,\end,\bgroup,\egroup} % ^^A\DoNotIndex{\@namedef,\@nameuse,=,\csname,\endcsname} % % % \GetFileInfo{minted.sty} % % \newcommand{\texpkg}[1]{\textsf{\detokenize{#1}}} % \newcommand{\pypkg}[1]{\textsf{\detokenize{#1}}} % \newcommand{\mintedpkg}{\texpkg{minted}} % \newcommand{\app}[1]{\textsf{#1}} % % \title{The \textcolor{minted@mint}{\mintedpkg} package:\\Highlighted source code in \LaTeX} % \author{Geoffrey M.\ Poore \\ \url{gpoore@gmail.com} \\ \href{https://github.com/gpoore/minted}{\texttt{github.com/gpoore/minted}} \\ ~\\ Originally created and maintained (2009--2013) by \\ Konrad Rudolph} % \date{\fileversion~from \filedate} % % \maketitle % % \begin{abstract} % \noindent\mintedpkg\ provides syntax highlighting using the \href{https://pygments.org/}{Pygments} library. It also provides options for customizing the highlighted source code output, including features implemented in Python such as selecting snippets of code with regular expressions. % % \vspace{0.5in} % \noindent The original development of \mintedpkg\ version 3 was funded by a \href{https://tug.org/tc/devfund/grants.html}{\TeX\ Development Fund grant} from the \href{https://tug.org/}{\TeX\ Users Group} in 2023. % \end{abstract} % % \vspace{0.5in} % % \subsection*{License} % \href{https://www.latex-project.org/lppl.txt}{LaTeX Project Public License (LPPL)} version 1.3c. % % \pagebreak % % \tableofcontents % % \fvset{ % codes={\catcode`\%=9}, ^^A Ignore initial |%| % numbersep=5pt, % } % \setlength{\fboxsep}{1ex} % % \mbox{}\newpage % \section{Introduction} % % % % \mintedpkg\ provides syntax highlighting using the \href{https://pygments.org/}{Pygments} library. The general strategy is to wrap code in a command or environment that captures it verbatim, like this: %\begin{mintedexample}[frame=single]{latex} %\begin{minted}{} % %\end{minted} %\end{mintedexample} % % Then the code is passed to Python, highlighted with Pygments, and passed back to \LaTeX\ for inclusion in the document. Here is an example with Ruby code, showing the \LaTeX\ source and then the highlighted output: % % \begin{example} % \begin{minted}{ruby} % class Foo % def init % pi = Math::PI % @var = "Pi = #{pi}..." % end % end % \end{minted} % \end{example} % % Because \mintedpkg\ uses Pygments and other Python software, it can provide more highlighting features than are practical in syntax highlighting packages like \href{ https://ctan.org/pkg/listings}{\texpkg{listings}} that are implemented purely in \LaTeX. In the past, this reliance on external software brought several disadvantages, including a requirement for separately installing Pygments. As of \mintedpkg\ version 3, all Python software including Pygments is bundled with the \LaTeX\ package when it is installed with a \TeX\ package manager, and no dependencies must be installed separately. % % % \section{Installation} % % \subsection{Package manager} % % Installation will typically be simpler and faster using your \TeX\ distribution's package manager. Start your package manager's graphical user interface, or use the relevant command below: % \begin{itemize} % \item TeX Live: |tlmgr install minted| % \item MiKTeX: |mpm --admin --install=minted| % \end{itemize} % When the \mintedpkg\ package is installed, it includes the |latexminted| Python executable and all required Python libraries including Pygments. For these to function correctly, Python 3.8+ must be installed and on |PATH| when the |latexminted| executable runs. % % Note that if you plan to use Pygments plugin packages, you will need to install the \pypkg{latexminted} Python package and dependencies including Pygments within a Python installation. The Python libraries installed by a \TeX\ package manager within a \TeX\ installation are not compatible with plugin packages. After installing \pypkg{latexminted} within a Python installation, make sure that its |latexminted| executable has precedence on |PATH|. % % The \mintedpkg\ package has the \LaTeX\ package dependencies listed below. Depending on your \TeX\ distribution and configuration, these may be installed automatically when \mintedpkg\ is installed. % \begin{multicols}{4} % \begin{itemize} % \setlength{\itemsep}{0pt} % \setlength{\parskip}{0pt} % \setlength{\parsep}{0pt} % \item \texpkg{catchfile} % \item \texpkg{etoolbox} % \item \texpkg{float} % \item \texpkg{fvextra} % \item \texpkg{latex2pydata} % \item \texpkg{newfloat} % \item \texpkg{pdftexcmds} % \item \texpkg{pgfkeys} % \item \texpkg{pgfopts} % \item \texpkg{shellesc} % \item \texpkg{xcolor} % \end{itemize} % \end{multicols} % % % \subsection{Manual installation} % % \mintedpkg\ source files are available at \href{https://github.com/gpoore/minted}{|github.com/gpoore/minted|}. There is also \href{https://ctan.org/pkg/minted}{|ctan.org/pkg/minted|}. % % Install |minted.sty| (and |minted2.sty| and |minted1.sty| if desired) within your \TeX\ installation. For TeX Live, it may be best to put style files under |TEXMFLOCAL|, which can be located by running |kpsewhich --var-value TEXMFLOCAL|. For example, you might put the files in |//texmf-local/tex/latex/local/minted|. For further details, consult your \TeX\ distribution's documentation, or an online guide such as \href{https://en.wikibooks.org/wiki/LaTeX/Installing_Extra_Packages}{\Verb{en.wikibooks.org/wiki/LaTeX/Installing_Extra_Packages}} or \href{https://texfaq.org/}{\Verb|texfaq.org|}. After installing the |.sty| files, make \TeX\ aware of the new files by running |texhash| or |mktexlsr| (TeX Live), or |initexmf --update-fndb| (MiKTeX). % % Next, install the Python side of the package. Python 3.8+ is required. There are two options: Install the \pypkg{latexminted} package and dependencies within a Python installation (typically easier, and required for compatibility with Pygments plugin packages), or install them within your \TeX\ installation. % % Note that if you are only using the \texpkg{minted2} package for backward compatibility with \mintedpkg\ version 2, you do not need \pypkg{latexminted}. \texpkg{minted2} only requires the Pygments package, which can be installed with something like |pip install pygments|, |conda install anaconda::pygments|, or |brew install pygments|, depending on your operating system and Python distribution. You may need to modify the command depending on system versus user installation and depending on virtual environments. % % \subsubsection{Option 1 (recommended): Install \pypkg{latexminted} within Python installation} % % If your Python distribution is compatible with \href{https://pypi.org/}{The Python Package Index (PyPI)}, this can be accomplished by running |pip install latexminted|. This will install \pypkg{latexminted} plus all dependencies including Pygments. You may need to modify the command depending on whether you want a system or user (|--user|) installation, depending on whether you are using virtual environments, and depending on whether something like |pip3| is needed instead of |pip|. % % If you cannot or do not wish to use PyPI via |pip|, install the following packages manually or from other sources. % \begin{itemize} % \setlength{\itemsep}{0pt} % \setlength{\parskip}{0pt} % \setlength{\parsep}{0pt} % \item \pypkg{latexminted}: \url{https://pypi.org/project/latexminted/} % \item \pypkg{latexrestricted}: \url{https://pypi.org/project/latexrestricted/} % \item \pypkg{latex2pydata}: \url{https://pypi.org/project/latex2pydata/} % \item Pygments: \url{https://pypi.org/project/Pygments/} % \end{itemize} % % \subsubsection{Option 2: Install \pypkg{latexminted} within \TeX\ installation} % % This approach is more involved and essentially replicates the process that is performed automatically when using a \TeX\ package manager. % % Install the |latexminted.py| executable within your \TeX\ installation. (It is part of the \mintedpkg\ \LaTeX\ package, separate from the \pypkg{latexminted} Python package.) This should typically be within a |scripts| directory. When TeX Live installs \mintedpkg\ with its package manager, this is something like |//texmf-dist/scripts/minted|. % % Download Python wheels (|*.whl|) for the following Python packages, and place them in the same location as |latexminted.py|. % \begin{itemize} % \setlength{\itemsep}{0pt} % \setlength{\parskip}{0pt} % \setlength{\parsep}{0pt} % \item \pypkg{latexminted}: \url{https://pypi.org/project/latexminted/} % \item \pypkg{latexrestricted}: \url{https://pypi.org/project/latexrestricted/} % \item \pypkg{latex2pydata}: \url{https://pypi.org/project/latex2pydata/} % \item Pygments: \url{https://pypi.org/project/Pygments/} % \end{itemize} % % Under non-Windows operating systems, create a symlink called |latexminted| in the \TeX\ binary directory or another appropriate location that points to |latexminted.py|. When TeX Live installs \mintedpkg\ with its package manager, this is something like |//bin/|. % % Under Windows, a launcher executable for |latexminted.py| needs to be created. When TeX Live installs \mintedpkg\ with its package manager, it creates a copy of |runscript.exe| named |latexminted.exe| within the \TeX\ binary directory, which is something like |//bin/windows|. % % % % \section{Migrating from \mintedpkg\ version 2} % % \mintedpkg\ version 3 is a complete rewrite from version 2.9. A brief summary of changes is provided below. For full details, see |CHANGELOG_MINTED_LATEX_PACKAGE.md|. % % \subsubsection*{Backward compatibility} % % The new \texpkg{minted2} package provides the features of \texpkg{minted} version 2.9, the final release before version 3. No additional version 2 releases are planned; no changes to the \texpkg{minted2} package are expected. % % % \subsubsection*{New features and changes} % % \begin{itemize} % \item Version 3 uses a new \mintedpkg-specific Python executable called |latexminted| to perform syntax highlighting. This executable is specifically designed to meet the security requirements for restricted shell escape programs. Once it has passed a security review and is accepted by \TeX\ distributions, it will be possible to highlight code without |-shell-escape| and its attendant security vulnerabilities. % % Syntax highlighting is still performed with Pygments, but the |pygmentize| executable included with Pygments is no longer used. % % When \mintedpkg\ is installed with a \TeX\ package manager, the new |latexminted| executable and all Python libraries including Pygments are installed within the \TeX\ installation. A separate step to install Pygments is no longer necessary. % % \item Temporary files are no longer created unless code needs to be highlighted. There is a new naming scheme for temporary files and for cache files. % % \item New package options: |debug| (additional debug info during compilation), |highlightmode| (modify when code is highlighted for faster compilation), |placeholder| (insert a placeholder instead of code), and |verbatim| (insert verbatim approximation of code). % % \item Renamed package options |langlinenos| to |lexerlinenos| and |inputlanglinenos| to |inputlexerlinenos|. The old names are still supported. % % \item |bgcolor| now uses the new |bgcolor| option from \texpkg{fvextra} v1.8. Because |bgcolor| now introduces no additional whitespace or padding, existing documents may require some modification. Added new option |bgcolorpadding| for modifying padding in background color regions. Added new option |bgcolorvphantom| for setting height of background color in inline contexts. When more sophisticated background colors are needed, \texpkg{tcolorbox} or a similar package should be used. % % \item The default cache directory name is now |_minted|. All files within a directory now share the same cache, instead of having separate per-document caches. Document-specific caching as in |minted| version 2 can be restored using the package option |cachedir|. % % \item |\newminted| now creates an environment that takes an optional argument consisting of options, instead of taking no argument. % % \item File encoding changes: The new |latexminted| executable assumes that \LaTeX\ output files are UTF-8, and saves highlighted code as UTF-8. That is, LaTeX should be configured so that everything is UTF-8. The |encoding| option now defaults to UTF-8. It is only used in decoding files for |\inputminted| and commands based on it. The |outencoding| option is no longer supported. % % \item Added new options for including ranges of code based on literal string delimiters or regular expressions: |rangestartstring|, |rangestartafterstring|, |rangestopstring|, |rangestopbeforestring|, |rangeregex|. % % \item There is now support for custom lexers in standalone Python files. See the documentation for the new |.latexminted_config| configuration files for details. % % \item Several package options are no longer supported and result in errors or warnings. The package options |finalizecache|, |outputdir|, and |kpsewhich| are no longer needed given new \mintedpkg\ version 3 capabilities. The package options |draft| and |final| no longer have any effect and will soon be removed altogether. The new package options |placeholder| and |verbatim| are available in cases where using highlighted code should be completely avoided. % \end{itemize} % % % % \section{Basic usage} % % \subsection{The \Verb{latexminted} Python executable and shell escape} % % The \mintedpkg\ package operates by passing code to the |latexminted| Python executable, which performs syntax highlighting and then returns the highlighted code in \LaTeX\ format. % % |latexminted| is designed to be compatible with the security requirements for restricted shell escape. For up-to-date installations of TeX Live 2024+, the |-shell-escape| option is no longer required. The |latexminted| Python executable has been added to TeX Live's list of trusted executables. % % For versions of TeX Live before 2024 and for MiKTeX, |latexminted| requires special permission to run. This can be accomplished by running \LaTeX\ with the |-shell-escape| option (TeX Live) or the |-enable-write18| option (MiKTeX). Note that using |-shell-escape| or |-enable-write18| allows \LaTeX\ to run potentially arbitrary commands on your system. These should only be used when necessary, with documents from trusted sources. An alternative is to manually designate |latexminted| as a trusted executable. % \begin{itemize} % \item TeX Live: Copy the variable |shell_escape_commands| from the distribution |texmf.cnf| (something like |//texmf-dist/web2c/texmf.cnf|) into the user |texmf.cnf| (something like |//texmf.cnf|), and then add |latexminted| to the |shell_escape_commands| list. The location of the |texmf.cnf| files can be determined by running |kpsewhich -all texmf.cnf|. Note that under Windows, this only works when |latexminted| is installed within a TeX Live installation; it is not compatible with |latexminted| being installed in a Python installation. % \item MiKTeX: Add a line |AllowedShellCommands[] = latexminted| to the existing list of allowed commands in |miktex.ini|. You may want to modify the user-scoped configuration instead of the system-wide configuration. See the \href{https://docs.miktex.org/manual/miktex.ini.html}{MiKTeX documentation} for more details, particularly |initexmf --edit-config-file| and |initexmf --set-config-value|. % \end{itemize} % % For the |latexminted| Python executable to correctly inherit security settings from \LaTeX, there are requirements for system configuration when multiple \TeX\ installations are present. % \begin{itemize} % \item With MiKTeX on systems with multiple MiKTeX installations, the desired MiKTeX installation must be the first MiKTeX installation on |PATH|. % \item With TeX Live on Windows systems with multiple TeX Live installations, the desired TeX Live installation must be the first TeX Live installation on |PATH|. % \end{itemize} % See the \href{https://github.com/gpoore/latexrestricted}{\pypkg{latexrestricted}} documentation for details. % % % \subsection{A minimal complete example} % % The following file |minimal.tex| shows the basic usage of \mintedpkg. % % \begin{VerbatimOut}[gobble=1]{minted.doc.out} % \documentclass{article} % % \usepackage{minted} % \usepackage[svgnames]{xcolor} % % \begin{document} % \begin{minted}[bgcolor=Beige, bgcolorpadding=0.5em]{c} % int main() { % printf("hello, world"); % return 0; % } % \end{minted} % \end{document} % \end{VerbatimOut} % \inputminted[frame=single]{latex}{minted.doc.out} % % This document can be compiled by running ``|pdflatex -shell-escape minimal|'' % to produce the following output in |minimal.pdf|: % % \begin{center} % \begin{minipage}{0.6\textwidth} % \inputminted[rangeregex=\^\\s*int.+?\\\}, rangeregexdotall=true, rangeregexmultiline=true, bgcolor=Beige, bgcolorpadding=0.5em]{c}{minted.doc.out} % \end{minipage} % \end{center} % % % \subsection{Formatting source code} % % \DescribeEnv{minted} % The |minted| environment highlights a block of code: % % \begin{example} % \begin{minted}{python} % def boring(args = None): % pass % \end{minted} % \end{example} % % The environment accepts a number of optional arguments in |key=value| notation. These are described in \cref{sec:options:macro}. % % To use \mintedpkg\ with a language that is not supported by Pygments, or simply to disable highlighting, set the language to |text|: |\begin{minted}{text}|. % % % \DescribeMacro{\mint} % For a single line of source code, you can use |\mint| as a shorthand for |minted|: % % \begin{example} % \mint{python}/import this/ % \end{example} % % This typesets a single line of code using a command rather than an environment, so it saves a little typing, but its output is equivalent to that of the |minted| environment. % % The code is delimited by a pair of identical characters, similar to how |\verb| works. The complete syntax is \cmd\mint\oarg{options}\marg{language}\meta{delim}\meta{code}\meta{delim}, % where the code delimiter can be almost any punctuation character. % The \meta{code} may also be delimited with paired curly braces |{}|, so long as \meta{code} itself does not contain unpaired curly braces. % % Note that the |\mint| command \textbf{is not for inline use}. Rather, it is a shortcut for |minted| when only a single line of code is present. The |\mintinline| command is provided for inline use. % % % \DescribeMacro{\mintinline} % Code can be typeset inline: % % \begin{example} % \mintinline{py}{print("Hello!")} % \end{example} % % The syntax is \cmd\mintinline\oarg{options}\marg{language}\meta{delim}\meta{code}\meta{delim}. The delimiters can be a single repeated character, just like for \cmd{\verb}. They can also be a pair of curly braces, |{}|. Curly braces are required when \cmd{\mintinline} is used in a movable argument, such as in a \cmd{\section}. % % Unlike \cmd{\verb}, \cmd{\mintinline} can usually be used inside other commands. The main exception is when the code contains the percent \texttt{\%} or hash \texttt{\#} characters, or unpaired curly braces. For example, \cmd{\mintinline} typically works in \cmd{\footnote} and \cmd{\section}! Note that some document classes or packages, such as \texpkg{memoir}, redefine \cmd{\section} or have options that modify it in ways that are incompatible with \cmd{\mintinline}. If you use \cmd{\mintinline} inside \cmd{\section} or otherwise in a movable argument, you should experiment to make sure it is compatible with your document configuration. You may also want to consider \texpkg{fvextra}'s \cmd{\Verb} or \cmd{\EscVerb} as an alternative. % % The code typesetting for \cmd{\mintinline} is based on \texpkg{fvextra}'s \cmd{\Verb}. See the \href{https://github.com/gpoore/fvextra/}{\texpkg{fvextra} documentation on \cmd{\Verb}} for additional details about functionality and limitations. % % \DescribeMacro{\inputminted} % Finally, there's the |\inputminted| command to input external files. % Its syntax is \cmd\inputminted\oarg{options}\marg{language}\marg{filename}. % % % \subsection{Using different styles} % % \DescribeMacro{\usemintedstyle} % % \DescribeMacro{\setminted} % Instead of using the default highlighting style you may choose another style provided by Pygments. There are two equivalent ways to do this: % % \begin{minted}{latex} % \usemintedstyle{name} % \setminted{style=name} % \end{minted} % % The |\setminted| approach has the advantage that other \mintedpkg\ options are accepted as well; |\usemintedstyle| is restricted to style modifications. The full syntax is \cmd\usemintedstyle\oarg{language}\marg{style} and \cmd\setminted\oarg{language}\marg{key=value}. The style may be set for the document as a whole (no language specified), or only for a particular language. Note that the style may also be set via the optional argument for each command and environment. % % Highlighting styles with examples are at \href{https://pygments.org/styles/}{pygments.org/styles}. It is possible to preview your code with different styles using the online demo at \href{https://pygments.org/demo/}{pygments.org/demo}. Available styles can also be listed by running the command |pygmentize -L styles|. % % It is also possible to create your own styles. See the instructions on the % \href{https://pygments.org/docs/styles/#creating-own-styles}{\texpkg{Pygments} website}. % \mintedpkg\ only supports style names that match the regular expression |^[0-9A-Za-z_-]+$|. % % % \subsection{Supported languages} % % Pygments supports hundreds of different programming languages, template languages, and other markup languages. The list of currently supported languages is at \href{https://pygments.org/docs/lexers/}{pygments.org/docs/lexers/}. You can also run |pygmentize -L lexers|. % % % % \section{Floating listings}\label{sec:float} % % \DescribeEnv{listing} % \mintedpkg\ provides a |listing| environment that can be used to wrap code blocks. This puts the code in a floating box similar to a figure or table, with default placement |tbp|. You can also provide a |\caption| and a |\label|: % % \begin{longexample} % \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. % \end{longexample} % % The default |listing| placement can be modified easily. When the package option |newfloat=false| (default), the \texpkg{float} package is used to create the |listing| environment. Placement can be modified by redefining |\fps@listing|. For example, %\begin{verbatim} %\makeatletter %\renewcommand{\fps@listing}{htp} %\makeatother %\end{verbatim} % When |newfloat=true|, the more powerful \texpkg{newfloat} package is used to create the |listing| environment. In that case, \texpkg{newfloat} commands are available to customize |listing|: %\begin{verbatim} %\SetupFloatingEnvironment{listing}{placement=htp} %\end{verbatim} % % % \DescribeMacro{\listoflistings} % The |\listoflistings| macro will insert a list of all (floated) listings in the document: % % \begin{example} % \listoflistings % \end{example} % % \subsection*{Customizing the \texttt{listing} environment} % By default, the |listing| environment is created using the \texpkg{float} package. In that case, the |\listingscaption| and |\listoflistingscaption| macros described below may be used to customize the caption and list of listings. If \mintedpkg\ is loaded with the |newfloat| option, then the |listing| environment will be created with the more powerful \href{https://www.ctan.org/pkg/newfloat}{\texpkg{newfloat}} package instead. \texpkg{newfloat} is part of \href{https://www.ctan.org/pkg/caption}{\texpkg{caption}}, which provides many options for customizing captions. % % When \texpkg{newfloat} is used to create the |listing| environment, customization should be achieved using \texpkg{newfloat}'s |\SetupFloatingEnvironment| command. For example, the string ``Listing'' in the caption could be changed to ``Program code'' using %\begin{verbatim} %\SetupFloatingEnvironment{listing}{name=Program code} %\end{verbatim} % And ``List of Listings'' could be changed to ``List of Program Code'' with %\begin{verbatim} %\SetupFloatingEnvironment{listing}{listname=List of Program Code} %\end{verbatim} % Refer to the \texpkg{newfloat} and \texpkg{caption} documentation for additional information. % % \DescribeMacro{\listingscaption} % This allows the string ``Listing'' in a listing's caption to be customized. It only applies when package option |newfloat=false|. For example: % %\begin{verbatim} %\renewcommand{\listingscaption}{Program code} %\end{verbatim} % % \DescribeMacro{\listoflistingscaption} % This allows the caption of the listings list, ``List of Listings,'' to be customized. It only applies when package option |newfloat=false|. For example: % %\begin{verbatim} %\renewcommand{\listoflistingscaption}{List of Program Code} %\end{verbatim} % % % % \section{Configuration} % % % \subsection{\mintedpkg\ config file \Verb{.latexminted_config}} % % Several \mintedpkg\ settings with security implications can be customized with a config file |.latexminted_config|. This config file is loaded by the |latexminted| Python executable when it runs. % % The |latexminted| Python executable looks for |.latexminted_config| files in the following locations: % \begin{itemize} % \item User home directory, as found by Python's \href{https://docs.python.org/3/library/pathlib.html#pathlib.Path.home}{|pathlib.Path.home()|}. % \item |TEXMFHOME|. With MiKTeX on systems with multiple MiKTeX installations, this will be the |TEXMFHOME| from the first MiKTeX installation on |PATH|. With TeX Live on Windows systems with multiple TeX Live installations, this will be the |TEXMFHOME| from the first TeX Live installation on |PATH|. In all other cases, |TEXMFHOME| will correspond to the currently active \TeX\ installation. See the \href{https://github.com/gpoore/latexrestricted}{\pypkg{latexrestricted}} documentation for details. \pypkg{latexrestricted} is used by the |latexminted| Python executable to retrieve the value of |TEXMFHOME|. % \item The current \TeX\ working directory. Note that |enable_cwd_config| must be set |true| in the |.latexminted_config| in the user home directory or in the |TEXMFHOME| directory to enable this; |.latexminted_config| in the current \TeX\ working directory is not enabled by default for security reasons. Even when a config file in the current \TeX\ working directory is enabled, it cannot be used to modify certain security-related settings. % \end{itemize} % % Overall configuration is derived by merging all config files, with later files in the list above having precedence over earlier files. Boolean and string values are overwritten by later config files. Collection values (currently only sets derived from lists) are merged with earlier values. % % The |.latexminted_config| file may be in Python literal format (dicts and lists of strings and bools), JSON, or TOML (requires Python 3.11+). It must be encoded as UTF-8. % % % \subsubsection*{Config settings} % % \begin{description} % \item[{\Verb/security: dict[str, str | bool]/}] These settings relate to |latexminted| security. They can only be set in |.latexminted_config| in the user home directory or in |TEXMFHOME|. They cannot be set in |.latexminted_config| in the current \TeX\ working directory. % \begin{description} % \item[\Verb|enable_cwd_config: bool = False|] Load a |.latexminted_config| file from the current \TeX\ working directory if it exists. This is disabled by default because the config file can enable |custom_lexers|, which is equivalent to arbitrary code execution. % \item[\Verb/file_path_analysis: "resolve" | "string" = "resolve"/] This specifies how |latexminted| determines whether files are readable and writable. Relative file paths are always treated as being relative to the current \TeX\ working directory. % % With |resolve|, any symlinks in file paths are resolved with the file system before paths are compared with permitted \LaTeX\ read/write locations. Arbitrary relative paths including ``|..|'' are allowed so long as the final location is permitted. % % With |string|, paths are analyzed as strings in comparing them with permitted \LaTeX\ read/write locations. This follows the approach taken in \TeX's file system security. Paths cannot contain ``|..|'' to access a parent directory, even if the parent directory is a valid location. Because symlinks are not resolved with the file system, it is possible to access locations outside permitted \LaTeX\ read/write locations, if the permitted locations contain symlinks to elsewhere. % % \item[{\Verb|permitted_pathext_file_extensions: list[str]|}] As a security measure under Windows, \LaTeX\ cannot write files with file extensions in |PATHEXT|, such as |.bat| and |.exe|. This setting allows |latexminted| to write files with the specified file extensions, overriding \LaTeX\ security. File extensions should be in the form ``|.|'', for example, ``|.bat|''. This setting is used in extracting source code from \LaTeX\ documents and saving it in standalone source files. % % When these file extensions are enabled for writing, as a security measure |latexminted| will only allow them to be created in \textbf{subdirectories} of the current \TeX\ working directory, |TEXMFOUTPUT|, and |TEXMF_OUTPUT_DIRECTORY|. These files cannot be created directly under the \TeX\ working directory, |TEXMFOUTPUT|, and |TEXMF_OUTPUT_DIRECTORY| because those locations are more likely to be used as a working directory in a shell, and thus writing executable files in those locations would increase the risk of accidental code execution. % \end{description} % % \item[{\Verb/custom_lexers: dict[str, str | list[str]]/}] This is a mapping of custom lexer file names to SHA256 hashes. Only custom lexers with these file names and the corresponding hashes are permitted. Lists of hashes are allowed to permit multiple versions of a lexer with a given file name. All other custom lexers are prohibited, because loading custom lexers is equivalent to arbitrary code execution. For example: %\begin{verbatim} %"custom_lexers": { % "mylexer.py": "" %} %\end{verbatim} % % By default, it is assumed that custom lexer files implement a class |CustomLexer|. This can be modified by including the lexer class name with the file name, separated by a colon, when the lexer is used. For example: % %\begin{verbatim} %\inputminted{.//mylexer.py:LexerClass}{} %\end{verbatim} % % Note that |custom_lexers| only applies to custom lexers in standalone Python files. Lexers that are installed within Python as plugin packages work automatically with Pygments and do not need to be enabled separately. However, in that case it is necessary to install \pypkg{latexminted} and Pygments within a Python installation. When \TeX\ package managers install \pypkg{latexminted} and Pygments within a \TeX\ installation, these are not compatible with Pygments plugin packages. % \end{description} % % % \subsection{macOS compatibility} % \label{sec:configuration:macos} % % If you are using \mintedpkg\ with some versions/configurations of macOS, and are using caching with a large number of code blocks ($>256$), you may receive a Python error during syntax highlighting that looks like this: %\begin{Verbatim} %OSError: [Errno 24] Too many open files: %\end{Verbatim} % This is due to the way files are handled by the operating system, combined with the way that caching works. To resolve this, you may use one of the following commands to increase the number of files that may be used: % \begin{itemize} % \item |launchctl limit maxfiles| % \item |ulimit -n| % \end{itemize} % % % \section{Options} % % % % \subsection{Package options} % % \DescribeMacro{chapter} % To control how \LaTeX{} counts the |listing| floats, you can pass either the % |chapter| or |section| option when loading the \mintedpkg\ package. % For example, the following will cause listings to be counted by chapter: % % \begin{minted}{latex} % \usepackage[chapter]{minted} % \end{minted} % % % \DescribeMacro{cache=\meta{boolean} (default:~true)} % \mintedpkg\ works by saving code to a temporary file, highlighting it with Pygments, and then passing the result back to \LaTeX\ for inclusion in the document. This process can become quite slow if there are several chunks of code to highlight. To avoid this, the package provides a |cache| option. This is on by default. % % The |cache| option creates a directory |_minted| in the document's root directory (this may be customized with the |cachedir| option). Files of highlighted code are stored in this directory, so that the code will not have to be highlighted again in the future. Cache files that are no longer used are automatically deleted. In most cases, caching will significantly speed up document compilation. % % % \DescribeMacro{cachedir=\meta{directory} (default:~\_minted)} % This allows the directory in which cache files are stored to be customized. Paths should use forward slashes, even under Windows. Special characters must be escaped with |\string| or |\detokenize|. % % Note that the cache directory is relative to |-output-directory| or equivalently the |TEXMF_OUTPUT_DIRECTORY| environment variable, if that is set. % % % \DescribeMacro{debug=\meta{boolean} (default:~false)} % Provide additional information for aid in debugging. This keeps temp files that are used in generating highlighted code and also writes additional information to the log. % % % \DescribeMacro{frozencache=\meta{boolean} (default:~false)} % Use a frozen (static) cache. When |frozencache=true|, Python and Pygments are not required, and any external files accessed through |\inputminted| are no longer necessary. If a cache file is missing, an error will be reported and there will be no attempt to generate the missing cache file. % % When using |frozencache| with |-output-directory|, the |cachedir| package option should be used to specify a full relative path to the cache (for example, |cachedir=.//_minted|). % % % \DescribeMacro{highlightmode=\meta{string} (default:~fastfirst)} % Determines when code is highlighted. This only has an effect when |cache=true|. % % The default is |fastfirst|. If a cache for the document exists, then code is highlighted immediately. If a cache for the document does not exist, then typeset a placeholder instead of code and highlight all code at the end of the document. This will require a second compile before code is typeset, but because all code is highlighted at once, there is less overhead and the total time required can be significantly less for documents that include many code snippets. % % The alternatives are |fast| (always highlight at end of document, requiring a second compile) and |immediate| (always highlight immediately, so no second compile is needed). % % Temporary files with the following file extensions are automatically detected and processed correctly, regardless of |highlightmode|: |.listing|, |.out|, |.outfile|, |.output|, |.temp|, |.tempfile|, |.tmp|, |.verb|, and |.vrb|. For temp files with other file extensions, |highlightmode=immediate| is needed if the files are overwritten or deleted during compilation. |fastfirst| can work in such cases, but it will give an error message about modified or missing files during the first compile, and then will work correctly during subsequent compiles when it switches to |immediate| mode. % % When code is highlighted at the end of the document with |fast| or |fastfirst|, any error and warning messages will refer to a location at the end of the document rather than the original code location, since highlighting occurred at the end of the document. In this case, messages are supplemented with original \LaTeX\ source file names and line numbers to aid in debugging. % % % \DescribeMacro{inputlexerlinenos=\meta{boolean} (default:~false)} % This enables |lexerlinenos| and causes it to apply to |\inputminted| (and custom commands based on it) in addition to |minted| environments and |\mint| commands (and custom environments/commands based on them). % % The regular |lexerlinenos| option treats all code within a document's |.tex| files as having one set of line numbering per language, and then treats each inputted source file as having its own separate numbering. |inputlexerlinenos| defines a single numbering per lexer, regardless of where code originates. % % % \DescribeMacro{lexerlinenos=\meta{boolean} (default:~false)} % This allows all |minted| environments and |\mint| commands (and custom environments/commands based on them) for a given lexer (language) to share line numbering when |firstnumber=last|, so that each subsequent command/environment has line numbering that continues from the previous one. This does not apply to |\inputminted| (and custom commands based on it); see the package option |inputlexerlinenos| for that. % % \mintedpkg\ uses the \texpkg{fancyvrb} package behind the scenes for the code typesetting. \texpkg{fancyvrb} provides an option |firstnumber| that allows the starting line number of an environment to be specified. For convenience, there is an option |firstnumber=last| that allows line numbering to pick up where it left off. The |lexerlinenos| option makes |firstnumber| work for each lexer (language) individually with all |minted| and |\mint| usages. For example, consider the code and output below. % % \begin{longexample}[xleftmargin=1em] % \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} % \end{longexample} % % Without the |lexerlinenos| option, the line numbering in the second Python environment would not pick up where the first Python environment left off. Rather, it would pick up with the Ruby line numbering. % % % \DescribeMacro{newfloat=\meta{boolean} (default:~false)} % By default, the |listing| environment is created using the \texpkg{float} package. The |newfloat| option creates the environment using \texpkg{newfloat} instead. This provides better integration with the \texpkg{caption} package. % % % \DescribeMacro{placeholder=\meta{boolean} (default:~false)} % Instead of typesetting code, insert a placeholder. This is enabled automatically when working with PGF/TikZ externalization. % % % \DescribeMacro{section} % To control how \LaTeX{} counts the |listing| floats, you can pass either the % |section| or |chapter| option when loading the \mintedpkg\ package. % % % \DescribeMacro{verbatim=\meta{boolean} (default:~false)} % Instead of highlighting code, attempt to typeset it verbatim without using the |latexminted| Python executable. This is not guaranteed to be an accurate representation of the code, since some features such as |autogobble| require Python. % % % \subsection{Setting options for commands and environments} % \label{sec:options:macro} % % All \mintedpkg\ highlighting commands and environment accept the same set of options. % Options are specified as a comma-separated list of |key=value| pairs. % For example, we can specify that the lines should be numbered: % % \begin{example} % \begin{minted}[linenos=true]{c++} % #include % int main() { % std::cout << "Hello " % << "world" % << std::endl; % } % \end{minted} % \end{example} % % An option value of |true| may also be omitted entirely (including the ``|=|''). % % |\mint| accepts the same options: % % \begin{example} % \mint[linenos]{perl}|$x=~/foo/| % \end{example} % % Here's another example: we want to use the \LaTeX{} math mode inside comments: % % \begin{example} % \begin{minted}[mathescape]{py} % # Returns $\sum_{i=1}^{n}i$ % def sum_from_one_to(n): % r = range(1, n + 1) % return sum(r) % \end{minted} % \end{example} % % To make your \LaTeX{} code more readable you might want to indent the code inside a |minted| % environment. % The option |gobble| removes a specified number of characters from the output. There is also an |autogobble| option that automatically removes indentation (dedents code). % % \begingroup % \setminted{autogobble=false} % \begin{example} % \begin{minted}[showspaces]{py} % def boring(args = None): % pass % \end{minted} % % versus % % \begin{minted}[gobble=4, % showspaces]{py} % def boring(args = None): % pass % \end{minted} % \end{example} % \endgroup % % \DescribeMacro{\setminted} % You may wish to set options for the document as a whole, or for an entire lexer (language). This is possible via \cmd\setminted\oarg{lexer}\marg{key=value,...}. Lexer-specific options override document-wide options. Individual command and environment options override lexer-specific options. % % \DescribeMacro{\setmintedinline} % You may wish to set separate options for \cmd\mintinline, either for the document as a whole or for a specific lexer (language). This is possible via \cmd\setmintedinline. The syntax is % \cmd\setmintedinline\oarg{lexer}\marg{key=value,...}. Lexer-specific options override document-wide options. Individual command options override lexer-specific options. All settings specified with \cmd\setmintedinline\ override those set with \cmd\setminted. That is, inline settings always have a higher precedence than general settings. % % \subsection{Command and environment options} % % \newcommand\appliesto[1]{\textsf{[For #1 only]}} % % Following is a full list of available options. Several options are simply passed on to Pygments, \texpkg{fancyvrb}, and \texpkg{fvextra} for processing. In those cases, more details may be in the documentation for those software packages. % % \begin{optionlist} % \item[autogobble (boolean) (false)] % Remove (gobble) all common leading whitespace from code. Essentially a version of |gobble| that automatically determines what should be removed. Good for code that originally is not indented, but is manually indented after being pasted into a \LaTeX\ document. % % \begin{example} % ...text. % \begin{minted}[autogobble]{py} % def f(x): % return x**2 % \end{minted} % \end{example} % % When |autogobble| and |gobble| are used together, the effect is cumulative. First |autogobble| removes all common indentation, and then |gobble| is applied. % % |autogobble| and |gobble| operate on code before the highlighting process begins (before lexing), treating the code purely as text. Meanwhile, |gobblefilter| operates on the token stream generated by a lexer. If the removed characters are simply indentation coming from how the code was entered within \LaTeX, then |autogobble| and |gobble| should typically be preferred. If the removed characters are syntactically significant, then |gobblefilter| may be better. Which approach is preferable may also depend on the implementation details of the lexer. % % \item[baselinestretch (dimension) (\meta{document default})] % Value to use for baselinestretch inside the listing. % % % \item[beameroverlays (boolean) (false)] % Give the |<| and |>| characters their normal text meanings when used with |escapeinside| and |texcomments|, so that \texpkg{beamer} overlays of the form |\only<1>{...}| will work. % % % \item[bgcolor (string) (none)] % Background color behind commands and environments. This is only a basic, lightweight implementation of background colors using |\colorbox|. For more control of background colors, consider \href{https://ctan.org/pkg/tcolorbox}{\pkg{tcolorbox}} or a similar package, or a custom background color implementation. % % |bgcolor| prevents line breaks for |\mintinline|. If you want to use \texttt{\string\setminted} to set background colors, and only want background colors on \texttt{minted} and \texttt{\string\mint}, you may use \texttt{\string\setmintedinline\{bgcolor=none\}} to turn off the coloring for inline commands. % % The value of this option must \emph{not} be a color command. Instead, it must be a color \emph{name}, given as a string, of a previously-defined color: % % \begin{example} % \definecolor{bg}{rgb}{.9, .9, .9} % \begin{minted}[bgcolor=bg]{php} % % \end{minted} % \end{example} % % As an alternative to |bgcolor|, \texpkg{tcolorbox} provides a built-in framing environment with \mintedpkg\ support. Simply use \texttt{\string\tcbuselibrary\{minted\}} in the preamble, and then put code within a \texttt{tcblisting} environment: %\begin{Verbatim} %\begin{tcblisting}{, % minted language=, % minted style=