在我的某些笔记中,我想包含一个示例问题以及如何在一个 tcolorbox 中执行该功能的代码列表,类似于下面的图像,所有内容都包含在一个框内,而不是省略代码行:
当我使用begin{lstlistings}
和时end{lstlistings}
,会出现编译错误,并且无法将代码块放入 tcbtheorem 框中。
现在,我正在使用基于数学的 tcb 环境,它的设置如下:
\newtcbtheorem[number within=section, list inside=examplelist]{tcbexample}{Example}{%
colback=gray!5, colbacktitle=gray!40, coltitle=black,
frame hidden, arc=2pt, titlerule=0pt, toptitle=2pt, bottomtitle=2pt,
fonttitle=\bfseries, breakable, enhanced, parbox=false
}{ex}
是否可以更改 tcolorbox 以使其同时支持代码(lstlistings
环境)和数学/文本?如果可以,该怎么做?如果不行,是否有其他方法可以使框尽可能干净?(例如,框之间没有间隙,可以轻松重置颜色和标题)
谢谢!
答案1
要包含listings
其他内容,您可以使用listing and comment
或comment and listing
框。列表部分写入 tcolorbox 环境中,注释写入选项中。
一个例子:
\documentclass{article}
\usepackage[most]{tcolorbox}
\newtcblisting[auto counter, number within=section, list inside=examplelist]{tcbexample}[2][]{%
colback=gray!5, colbacktitle=gray!40, coltitle=black,
frame hidden, arc=2pt, titlerule=0pt, toptitle=2pt, bottomtitle=2pt,
fonttitle=\bfseries, breakable, enhanced, parbox=false,
comment and listing,
title=Example~\thetcbcounter,
comment={#2},#1
}
\begin{document}
\section{Section}
\begin{tcbexample}{This is a comment which will be shown on upper part\\ \begin{equation}x=3\end{equation}}
First line of a listing
Secon line
third line
\end{tcbexample}
\begin{tcbexample}[colback=blue!30, listing side comment]{This is a comment which will be shown on upper part\\ \begin{equation}x=3\end{equation}}
First line of a listing
Secon line
third line
\end{tcbexample}
\end{document}
更新:合并列表和仅文本框
可以使用tcblisting
框来仅显示文本内容,而无需任何listing
。这可以通过选项text only
或来实现comment only
。在第二种情况下,框内容仍然声明在comment
选项中,并且避免使用环境内容。使用text only
选项,不需要comment
,文本写在环境中。使用此选项,不需要为列表或非列表内容声明不同的 tcolorboxes,并且所有框共享相同的计数器。
\documentclass{article}
\usepackage[most]{tcolorbox}
\newtcblisting[auto counter, number within=section, list inside=examplelist]{tcbexample}[2][]{%
colback=gray!5, colbacktitle=gray!40, coltitle=black,
frame hidden, arc=2pt, titlerule=0pt, toptitle=2pt, bottomtitle=2pt,
fonttitle=\bfseries, breakable, enhanced, parbox=false,
comment and listing,
title=Example~\thetcbcounter,
comment={#2},#1
}
\begin{document}
\section{Section}
\begin{tcbexample}{This is a comment which will be shown on upper part\\ \begin{equation}x=3\end{equation}}
First line of a listing
Secon line
third line
\end{tcbexample}
\begin{tcbexample}[comment only]{This is a comment which will be shown on upper part\\ \begin{equation}x=3\end{equation}}
This listing is not shown. It could be empty.
First line of a listing
Secon line
third line
\end{tcbexample}
\begin{tcbexample}[text only]{This comment can be left empty}
this is the contents of a \texttt{text only} box
\end{tcbexample}
\end{document}