我正在写一份报告,其中有一些代码片段。使用以下代码,我可以创建一个美观的minted
环境并将其置于中心:
\documentclass{article}
% Required for minted
\usepackage{keyval}
\usepackage{kvoptions}
\usepackage{fancyvrb}
\usepackage{float}
\usepackage{ifthen}
\usepackage{calc}
\usepackage{ifplatform}
\usepackage{pdftexcmds}
\usepackage{etoolbox}
\usepackage{xstring}
\usepackage{xcolor}
\usepackage{lineno}
\usepackage{minted}
\setminted[c++]{ %
linenos=true, % Line numbers
autogobble=true, % Automatically remove common whitespace
%bgcolor=dark-bg,
frame=lines,
framesep=2mm,
fontsize=\footnotesize
}
\newenvironment{code}{%
\VerbatimEnvironment
\begin{figure}[thp]%
\centering
\begin{minipage}{0.8\textwidth}%
\begin{minted}{c++}}
{%
\end{minted}
\end{minipage}
\end{figure}}
\begin{document}
\begin{code}
struct config {
/* Default values. */
std::string
address = "",
port = "6667",
nick = "Temeraire",
user = nick,
/* Optional */
/* NickServ identification */
nick_pw = "",
server_pw = "";
bool ssl = true;
};
\end{code}
\end{document}
但是当在相同的环境中使用更长的代码时,结果如下:
如图所示,minted
的框线远远不够长,并且整个代码不再居中。
虽然0.4\textwidth
可以根据具体使用的代码进行修改,但需要我为想要包含的每个代码片段创建一个新环境。环境的宽度怎么可能与最长的代码行相同呢?
答案1
您可以使用BVerbatim
而不是Verbatim
,但必须手动添加行号和框架。
\documentclass{article}
\usepackage{minted}
\usepackage{lipsum}
\setminted[c++]{ %
linenos=true, % Line numbers
autogobble=true, % Automatically remove common white space
frame=lines,
framesep=2mm,
fontsize=\footnotesize
}
\makeatletter
\newenvironment{code}
{\RecustomVerbatimEnvironment{Verbatim}{BVerbatim}{}%
\def\FV@BProcessLine##1{%
\hbox{%
\hbox to\z@{\hss\theFancyVerbLine\kern\FV@NumberSep}%
\FancyVerbFormatLine{##1}%
}%
}%
\VerbatimEnvironment
\setbox\z@=\hbox\bgroup
\begin{minted}{c++}}
{\end{minted}\egroup
\leavevmode\vbox{\hrule\kern2mm\box\z@\kern2mm\hrule}}
\makeatother
\begin{document}
\begin{minted}{c++}
struct config {
/* Default values. */
std::string
address = "",
port = "6667",
nick = "Temeraire",
user = nick,
/* Optional */
/* NickServ identification */
nick_pw = "",
server_pw = "";
bool ssl = true;
};
\end{minted}
\lipsum[2]
\begin{figure}[htp]
\centering
\begin{code}
struct config {
/* Default values. */
std::string
address = "",
port = "6667",
nick = "Temeraire",
user = nick,
/* Optional */
/* NickServ identification */
nick_pw = "",
server_pw = "";
bool ssl = true;
};
\end{code}
\caption{Some centered code}
\end{figure}
\end{document}