如何在逐字(或列表)环境中进行交叉引用

如何在逐字(或列表)环境中进行交叉引用

我想在某些源代码中引用文档的其他部分(例如方程式、图形)。是否有转义序列\ref可以解析而不是打印为文字 \ref?

我的最小示例如下:

\documentclass{article}

\usepackage{amsmath}
\usepackage{listings}

\begin{document}
This is the pythagorean theorem:
\begin{equation}\label{eq:pyth}
a^2+b^2=c^2
\end{equation}

I can reference it normally: Equation \ref{eq:pyth}.

I can write a code example that won't work:
\begin{verbatim}
# An R function to solve for c.
# See Equation \ref{eq:pyth} for details.
solve.for.c <- function(a,b){
  return( sqrt(a^2 + b^2))
}
\end{verbatim}

And one that works, but is very ugly and hard to maintain: \\
\verb@# An R function to solve for c.@ \\
\verb@# See Equation@ \ref{eq:pyth} \verb@for details.@ \\
\[email protected] <- function(a,b){@ \\
\verb@solve  return( sqrt(a^2 + b^2))@ \\
\verb@}@ \
How can I do this better?
\end{document}

有什么想法可以做得更好吗?我是否遗漏了一个简单的功能?

答案1

您不会缺少简单的功能;标准verbatim环境不允许解释命令。但是,该fancyvrb软件包具有此功能:

\documentclass{article}

\usepackage{amsmath}
\usepackage{listings}
\usepackage{fancyvrb}

\begin{document}
This is the pythagorean theorem:
\begin{equation}\label{eq:pyth}
a^2+b^2=c^2
\end{equation}

I can reference it normally: Equation \ref{eq:pyth}.

I can write a code example that will work:
\begin{Verbatim}[commandchars=\\\[\]]
# An R function to solve for c.
# See Equation \ref[eq:pyth] for details.
solve.for.c <- function(a,b){
  return( sqrt(a^2 + b^2))
}
\end{Verbatim}

And also a \texttt{lstlisting} environment:
\begin{lstlisting}[language=R,escapechar=',columns=fullflexible]
# An R function to solve for c.
# See Equation '\ref{eq:pyth}' for details.
solve.for.c <- function(a,b){
  return( sqrt(a^2 + b^2))
}
\end{lstlisting}

\end{document}

对于commandcharsin ,Verbatim您必须指定三个字符(用反斜杠转义),这些字符在环境文本中未使用。对于escapecharwith也是如此lstlisting。这些字符可以“本地”选择。

随意选择。

在此处输入图片描述

答案2

在此处输入图片描述

如果你有三个方便的字符没有出现在逐字文本中,你可以使用它们来代替\ { }例如

\documentclass{article}

\usepackage{amsmath}

\makeatletter
\let\oldv\@verbatim
\def\@verbatim{\oldv\catcode`\!=0 \catcode`\`=1 \catcode`\'=2 }
\makeatother

\begin{document}
This is the pythagorean theorem:
\begin{equation}\label{eq:pyth}
a^2+b^2=c^2
\end{equation}

I can reference it normally: Equation \ref{eq:pyth}.

I can write a code example that won't work:
\begin{verbatim}
# An R function to solve for c.
# See Equation !ref`eq:pyth' for details.
solve.for.c <- function(a,b){
  return( sqrt(a^2 + b^2))
}
\end{verbatim}



How can I do this better?
\end{document}

相关内容