该listing
包允许轻松定义相互派生的样式和环境,这非常实用,可以避免复制和粘贴大量代码。我正在尝试了解如何使用 做同样的事情tcolorbox
。
以下面的代码为例:
% Document class
\documentclass[letterpaper, 10pt, onecolumn]{article}
% Packages
\usepackage{calc}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{lipsum}
\usepackage[most]{tcolorbox}
% Style
\newtcblisting{codebox}[4][\small]{
before upper = {\topskip0pt \maxdepth=0pt},
enhanced,
listing only,
breakable = unlimited,
top = 0em,
bottom = 0em,
left = 0pt,
right = 0pt,
arc = 0em,
outer arc = 0em,
boxsep = 0em,
boxrule = 0.5mm,
titlerule = 0em,
colback = white,
colframe = blue,
title = \centering#2,
listing options = {
language = C++,
basicstyle = \fontfamily{cmtt}\selectfont#1,
#3,
},
#4,
}
\newtcblisting{codebox*}[4][\normalsize]{
before upper = {\topskip0pt \maxdepth=0pt},
enhanced,
listing only,
breakable = unlimited,
top = 0em,
bottom = 0em,
left = 0pt,
right = 0pt,
arc = 0em,
outer arc = 0em,
boxsep = 0em,
boxrule = 0.5mm,
titlerule = 0em,
colback = white,
colframe = black,
title = \centering#2,
listing options = {
language = Python,
basicstyle = \fontfamily{cmtt}\selectfont#1,
#3,
},
#4,
}
% Document
\begin{document}
\lipsum[1]
\begin{codebox}{C++ listing example}{}{}
int main(int argc, char* argv[])
{
return 0;
}
\end{codebox}
\begin{codebox*}{Python listing example}{}{}
def f(x):
return x * x
\end{codebox*}
\lipsum[1]
\end{document}
定义了两个环境,codebox
两者codebox*
之间几乎没有什么区别(包括不同的默认参数)。是否可以有一种从另一种派生的方式,以避免复制和粘贴彼此接近的环境的所有选项。一个限制是,我希望用户端的界面保持不变(\begin{codebox}{}{}{}
或\begin{codebox}[]{}{}{}
)。
答案1
这就是样式的用途。此示例将公共键放入样式中common
,两个框均使用该样式。
\documentclass[letterpaper, 10pt, onecolumn]{article}
% Packages
\usepackage{calc}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{lipsum}
\usepackage[most]{tcolorbox}
\tcbset{common/.style={before upper = {\topskip0pt \maxdepth=0pt},
enhanced,
listing only,
breakable = unlimited,
top = 0em,
bottom = 0em,
left = 0pt,
right = 0pt,
arc = 0em,
outer arc = 0em,
boxsep = 0em,
boxrule = 0.5mm,
titlerule = 0em,
colback = white,
}}
% Style
\newtcblisting{codebox}[4][\small]{common,colframe = blue,title = \centering#2,
listing options = {
language = C++,
basicstyle = \fontfamily{cmtt}\selectfont#1,
#3,
},
#4,
}
\newtcblisting{codebox*}[4][\normalsize]{common,
colframe = black,
title = \centering#2,
listing options = {
language = Python,
basicstyle = \fontfamily{cmtt}\selectfont#1,
#3,
},
#4,
}
% Document
\begin{document}
\lipsum[1]
\begin{codebox}{C++ listing example}{}{}
int main(int argc, char* argv[])
{
return 0;
}
\end{codebox}
\begin{codebox*}{Python listing example}{}{}
def f(x):
return x * x
\end{codebox*}
\lipsum[1]
\end{document}