我注意到lstlisting
当没有指定标题时,环境似乎会抑制标题名称和编号。
请参阅下面的代码:
\documentclass{article}
\usepackage{listings}
\lstset{language=C}
\begin{document}
The listing below will have no caption.
\begin{lstlisting}
int main(int argc, char *argv[])
{
return 0;
}
\end{lstlisting}
Now this code will show the caption.
\begin{lstlisting}[caption=This is the caption]
int main(int argc, char *argv[])
{
return 0;
}
\end{lstlisting}
\end{document}
我发现的唯一解决方案是将标题设置为空白并删除分隔符,但这个解决方案看起来不太好:
\documentclass{article}
\usepackage{listings}
\lstset{language=C}
\usepackage{caption}
\captionsetup{labelsep=none}
\begin{document}
This is not an elegant solution, but works:
\begin{lstlisting}[caption=\ ]
int main(int argc, char *argv[])
{
return 0;
}
\end{lstlisting}
\end{document}
有任何想法吗?
答案1
定义默认标题(我使用了\relax
)并设置标题格式,以检查给定的标题是否不同。诀窍是知道标题文本存储在中\lst@caption
。
\documentclass{article}
\usepackage{listings,caption}
\lstset{language=C,caption=\relax}
\makeatletter
%% define a caption format; if the caption
%% is the default (\relax), the separator is
%% not printed; as long as no caption text
%% starts with \relax, this will work
\DeclareCaptionFormat{alsoempty}{%
#1\if\relax\expandafter\noexpand\lst@caption\else#2#3\fi}
\makeatother
%% set this format as the default for lstlisting
\captionsetup[lstlisting]{format=alsoempty}
\begin{document}
The listing below will have no caption.
\begin{lstlisting}
int main(int argc, char *argv[])
{
return 0;
}
\end{lstlisting}
Now this code will show the caption.
\begin{lstlisting}[caption=This is the caption]
int main(int argc, char *argv[])
{
return 0;
}
\end{lstlisting}
\end{document}