将列表中引用的文本样式更改为行号

将列表中引用的文本样式更改为行号

请考虑以下文档:

% Document
\documentclass[10pt]{article}
% Packages
\usepackage{lipsum}
\usepackage{xcolor}
\usepackage{listings}
\usepackage[
    colorlinks, 
    citecolor = blue, 
    filecolor = blue, 
    linkcolor = blue, 
    urlcolor = blue
]{hyperref}
% Contents
\begin{document}
\section{First section}\label{sec:first}
\lipsum[1]
\begin{lstlisting}[
    language = C++,
    escapechar = `,
    numbers=left,
    basicstyle = \ttfamily,
    showstringspaces = false,
    keywordstyle = \color{blue},
    commentstyle = \color{red},
]
#include <iostream>
int main(int argc, char *argv[])
{
    std::cout << "Hello, World!" << std::endl;`\label{lst:line}`
    return 0;
}
\end{lstlisting}
This is a reference to section \ref{sec:first}.
This is a reference to line \ref{lst:line}.
\end{document}

我希望列表中行号的引用(并且只有这种类型的引用)能够像 中的常规文本(非彩色)一样出现\texttt{}。我可以定义\newcommand{\coderef}[1]{...#1...}来实现这一点(用...适当的命令替换)。

答案1

以下宏似乎可以满足您的要求。它基于\ref*检索参考文本而不生成超链接,因为\hyperref本身会创建超链接。正如预期的那样,结果文本是指向参数指示的参考的超链接。

\newcommand*{\coderef}[1]{%
  \colorlet{currcol}{.}% retrieve the current color (.)
  \hyperref[#1]{\textcolor{currcol}{\texttt{\ref*{#1}}}}%
}

另一种可能性是使用包\getrefbykeydefault中的refcount链接来检索参考文本。这样,当所需信息尚未在文件中时,您甚至可以选择打印的内容.aux(这里,我使用标准??):

\newcommand*{\coderef}[1]{%
  \colorlet{currcol}{.}% retrieve the current color (.)
  \refused{#1}%
  \hyperref[#1]{\textcolor{currcol}{\texttt{%
    \getrefbykeydefault{#1}{}{??}}}}%
}

使用该方法的完整代码\ref*(均给出相同的输出):

\documentclass{article}
\usepackage{lipsum}
\usepackage{xcolor}
\usepackage{listings}
\usepackage[
    colorlinks,
    citecolor = blue,
    filecolor = blue,
    linkcolor = blue,
    urlcolor = blue
]{hyperref}

\newcommand*{\coderef}[1]{%
  \colorlet{currcol}{.}% retrieve the current color (.)
  \hyperref[#1]{\textcolor{currcol}{\texttt{\ref*{#1}}}}%
}

\begin{document}

\section{First section}\label{sec:first}

\lipsum[1]
\begin{lstlisting}[
    language = C++,
    escapechar = `,
    numbers=left,
    basicstyle = \ttfamily,
    showstringspaces = false,
    keywordstyle = \color{blue},
    commentstyle = \color{red},
]
#include <iostream>
int main(int argc, char *argv[])
{
    std::cout << "Hello, World!" << std::endl;`\label{lst:line}`
    return 0;
}
\end{lstlisting}
This is a reference to section \ref{sec:first}.
This is a reference to line \coderef{lst:line}.

\textcolor{red!40!black}{%
  Now with \texttt{red!40!black} as the ambiant text color:
  the line containing \texttt{std::cout} is line~\coderef{lst:line}.%
}

\end{document}

在此处输入图片描述

相关内容