我正在尝试定义一个\NewDocumentEnvironment
叫{代码片段}从而产生{铸造}代码块,包裹在{颜色框}环境进行造型。我的环境需要两个{解析}参数:{ s o }
s
是为了能够显示{铸造}行号(行列选项),当星号存在时;
o
旨在将 Pygments 语法高亮语言传递给{铸造},如有必要。
这是我的环境定义:
\NewDocumentEnvironment{codesnippet}{ s o }
{%
\VerbatimEnvironment%
\begin{tcolorbox}[
enhanced,
left=5mm, arc=0.25mm,
borderline={0.25mm}{0mm}{NavyBlue!15!white},
colback=bgblue!15!white,
colframe=white]%
\begin{minted}[%
numbersep=6pt,fontsize=\small,breaklines,%
\IfBooleanT {#1}
{linenos}]{#2}}
{\end{minted}\end{tcolorbox}
}
我进一步使用这个环境,一旦和明星和曾经没有星。
和星:
\begin{codesnippet}*[docker]
%Numbered code here.
\end{codesnippet}
没有星:
\begin{codesnippet}[tex]
%Code without numbers here.
\end{codesnippet}
现在,每当我尝试编译此文件时,都会出现以下错误:
! Package keyval Error: undefined.
l.19 \begin{codesnippet}[tex]
如果我把星号加到第二个{代码片段}块,一切都编译正常。
我是否没有正确理解 的用法\IfBooleanT
?根据我的代码,它不应该添加行列选项如果星号存在则为真,如果星号不存在则不执行任何操作?
答案1
在minted
评估选项时,不会进行扩展,因此
\begin{minted}[
numbersep=6pt,
fontsize=\small,
breaklines,
\IfBooleanT{#1}{linenos}]{#2}
}
不设置linenos
选项。您可以改用\setminted
:
\documentclass{article}
\usepackage{xparse}
\usepackage[many]{tcolorbox}
\tcbuselibrary{minted}
\NewDocumentEnvironment{codesnippet}{ s m }
{%
\VerbatimEnvironment
\begin{tcolorbox}[
enhanced,
left=5mm,
arc=0.25mm,
borderline={0.25mm}{0mm}{red!15!white},
colback=blue!15!white,
colframe=white
]
\IfBooleanT{#1}{\setminted{linenos}}
\begin{minted}[numbersep=6pt,fontsize=\small,breaklines]{#2}%
}
{\end{minted}\end{tcolorbox}}
\begin{document}
\begin{codesnippet}*{docker}
abc
def
ghi
\end{codesnippet}
\begin{codesnippet}{docker}
abc
def
ghi
\end{codesnippet}
\end{document}
注意。我将o
其改为m
;如果您想使用可选参数,则应将其改为O{<default>}
,其中<default>
代表通常所需的词法分析器。我还更改了颜色(您没有显示它们的定义)。
一个不同的实现\NewTCBListing
:
\documentclass{article}
\usepackage{xparse}
\usepackage[many]{tcolorbox}
\tcbuselibrary{minted}
\NewTCBListing{codesnippet}{ s m }
{
listing engine=minted,
listing only,
enhanced,
left=5mm,
arc=0.25mm,
borderline={0.25mm}{0mm}{red!15!white},
colback=blue!15!white,
colframe=white,
minted language=#2,
minted options/.expanded={
numbersep=6pt,
fontsize=\noexpand\small,
breaklines,
\IfBooleanT{#1}{linenos,}
},
}
\begin{document}
\begin{codesnippet}*{docker}
abc
def
ghi
\end{codesnippet}
\begin{codesnippet}{docker}
abc
def
ghi
\end{codesnippet}
\end{document}
不过,我认为传递linenos
选项更好;以下实现也允许任何其他选项minted
。
\documentclass{article}
\usepackage[many]{tcolorbox}
\tcbuselibrary{minted}
\NewTCBListing{codesnippet}{ O{} m }
{
listing engine=minted,
listing only,
enhanced,
left=5mm,
arc=0.25mm,
borderline={0.25mm}{0mm}{red!15!white},
colback=blue!15!white,
colframe=white,
minted language=#2,
minted options/.expanded={
numbersep=6pt,
fontsize=\noexpand\small,
breaklines,
#1
},
}
\begin{document}
\begin{codesnippet}[linenos]{docker}
abc
def
ghi
\end{codesnippet}
\begin{codesnippet}{docker}
abc
def
ghi
\end{codesnippet}
\end{document}