列表标题中包含章节引用

列表标题中包含章节引用
\documentclass{article}
\usepackage{listings}
\usepackage{biblatex}
\usepackage{filecontents}

\addbibresource{\jobname.bib}

\begin{filecontents}{\jobname.bib}
@book{foo}
\end{filecontents}

\begin{document}
This is normal text. Text taken from~\cite[Chapter~x]{foo}.

\begin{lstlisting}[caption={This is the caption. Code taken from~\cite[Chapter~x]{foo}}]
clear all;
\end{lstlisting}

\end{document}

这是实际结果:

在此处输入图片描述


foo为什么标题中显示参考文献的实际名称( ),我该如何删除该部分?

标题应该很简单This is the caption. Code taken from [1, Chapter x]

答案1

如果您稍微改变一下花括号,就可以得到所需的输出。下面的 MWE 显示了两种可能的解决方案。

\documentclass{article}
\usepackage{listings}
\usepackage{biblatex}

\addbibresource{biblatex-examples.bib}

\begin{document}
This is normal text. Text taken from~\cite[Chapter~x]{sigfridsson}.

\begin{lstlisting}[caption=This is the caption. Code taken from~{\cite[Chapter~x]{sigfridsson}}]
clear all;
\end{lstlisting}

\begin{lstlisting}[caption={{{{This is the caption. Code taken from~\cite[Chapter~x]{sigfridsson}}}}}]
clear all;
\end{lstlisting}

\end{document}

清单 1:这是标题。代码取自 [1,第 x 章] 清单 2:这是标题。代码取自 [1,第 x 章]

首先,我们需要至少一对花括号来“隐藏”可选参数的方\cite括号内的可选参数lstlisting。如果我们不隐藏括号,则无法正确解析可选参数。(参见] 位于可选参数内

不幸的是,直接使用一对花括号来表示整个标题的想法并不可靠。这是因为的可选参数lstlisting被解析为键值选项列表。在 LaTeX 世界中有不同的键值实现(每个 keyval 包的大列表),这里使用的 (众所周知的keyval) 在处理过程中会从参数中剥离最多两层外括号。我没有追踪侧面究竟发生了什么listings,但有可能额外的处理步骤会剥离额外的外层括号,并且不会采取措施阻止方括号在可选参数中断开。

因此,一种解决方案是不要对整个标题进行括号处理,而只对需要括号的部分进行括号处理。这种方法只需要相对较少的括号,因为在处理过程中不会剥离括号(因为它们不是外括号)。另一种解决方案是使用尽可能多的外括号,以确保不会剥离所有括号。反复试验表明,这里需要四对括号(一般来说,如果不跟踪代码,您无法提前知道需要多少对括号)。

相关内容