我使用 cleveref\cref
命令进行引用,并\lstnewenvironment
创建新的列表类型。我的文档有多种类型的列表,每种都有自己的计数器。
listing
然而,尽管我\crefname
为自定义列表类型定义了 , cleveref 仍坚持调用所有类型的列表。
如何使用正确的标签来引用自定义列表?
最小工作示例:
\documentclass{article}
\usepackage{listings,cleveref}
% Define listing type for queries
\newcounter{query}
\makeatletter
\lstnewenvironment{query}[1][]
{%
\lstset{#1}%
\renewcommand\lstlistingname{Query}%
\let\c@lstlisting=\c@query%
\let\thelstlisting=\thequery%
}
{}
\makeatother
% Set up reference label
\crefname{query}{query}{queries}
\begin{document}
\begin{lstlisting}[label=lst:MyListing,caption=My listing]
# Hello world
\end{lstlisting}
\begin{query}[label=qry:MyQuery,caption=My query]
SELECT * FROM MyTable;
\end{query}
Reference to \cref{lst:MyListing} and \cref{qry:MyQuery}.
\end{document}
答案1
您可以强制listings
使用正确的计数器而不是默认值lstlisting
:
\documentclass{article}
\usepackage{etoolbox,listings,cleveref}
% Define listing type for queries
\newcounter{query}
\makeatletter
\lstnewenvironment{query}[1][]
{%
% make \lst@MakeCaption use query instead of lstlisting
\patchcmd{\lst@MakeCaption}{{lstlisting}}{{query}}{}{}%
\lstset{basicstyle=\ttfamily,columns=fullflexible,#1}%
\renewcommand\lstlistingname{Query}%
\let\thelstlisting=\thequery
}
{}
\makeatother
% Set up reference label
\crefname{query}{query}{queries}
\begin{document}
\begin{lstlisting}[label=lst:MyListing,caption=My listing]
# Hello world
\end{lstlisting}
\begin{query}[label=qry:MyQuery,caption=My query]
SELECT * FROM MyTable;
\end{query}
\begin{lstlisting}[label=lst:MyListing2,caption=My listing]
# Hello world
\end{lstlisting}
\begin{query}[label=qry:MyQuery2,caption=My query]
SELECT * FROM MyTable;
\end{query}
Reference to \cref{lst:MyListing} and \cref{qry:MyQuery}.
Reference to \cref{lst:MyListing2} and \cref{qry:MyQuery2}.
\end{document}
修复与hyperref
\documentclass{article}
\usepackage{etoolbox,listings,hyperref,bookmark,cleveref}
% Define listing type for queries
\newcounter{query}
\makeatletter
\patchcmd{\lst@MakeCaption}{{lstlisting}}{{\verborgh@counter}}{}{}%
\def\verborgh@counter{lstlisting}
\def\verborgh@prefix{L}
\AtBeginDocument{%
\patchcmd{\theHlstnumber}{\thelstnumber}{\verborgh@prefix\thelstnumber}{}{}%
}
\lstnewenvironment{query}[1][]
{%
% make \lst@MakeCaption use query instead of lstlisting
\def\verborgh@counter{query}%
\def\verborgh@prefix{Q}%
\lstset{basicstyle=\ttfamily,columns=fullflexible,#1}%
\renewcommand\lstlistingname{Query}%
}
{}
\makeatother
% Set up reference label
\crefname{query}{query}{queries}
\begin{document}
\begin{lstlisting}[label=lst:MyListing,caption=My listing]
# Hello world
\end{lstlisting}
\begin{query}[label=qry:MyQuery,caption=My query]
SELECT * FROM MyTable;
\end{query}
\begin{lstlisting}[label=lst:MyListing2,caption=My listing]
# Hello world
\end{lstlisting}
\begin{query}[label=qry:MyQuery2,caption=My query]
SELECT * FROM MyTable;
\end{query}
Reference to \cref{lst:MyListing} and \cref{qry:MyQuery}.
Reference to \cref{lst:MyListing2} and \cref{qry:MyQuery2}.
\end{document}