![使用 \autoref 在「演算法」環境中建立對行的智慧交叉引用](https://rvso.com/image/348651/%E4%BD%BF%E7%94%A8%20%5Cautoref%20%E5%9C%A8%E3%80%8C%E6%BC%94%E7%AE%97%E6%B3%95%E3%80%8D%E7%92%B0%E5%A2%83%E4%B8%AD%E5%BB%BA%E7%AB%8B%E5%B0%8D%E8%A1%8C%E7%9A%84%E6%99%BA%E6%85%A7%E4%BA%A4%E5%8F%89%E5%BC%95%E7%94%A8.png)
\autoref
要設定我使用的演算法的命令名稱:
\newcommand{\algorithmautorefname}{Algorithm}
喜歡評論這裡。我還希望能夠使用 來引用algorithmic
環境中的行line x
。
\begin{algorithm}
\label{alg:myalg}
\begin{algorithmic}[1]
\State Do X
\State Do Y \label{algl:y}
\State $x = y + z$
\end{algorithmic}
\end{algorithm}
\autoref{alg:myalg}
給我正確的演算法1。另外,我還想擁有\autoref{algl:y}
生成2號線。到目前為止我正在使用:line~\ref{algl:y}
.
看到相同的答案您可以透過以下方式定義自動引用名稱:\....autorefname
。但隨後他提到一些計數器是隱藏的,例如行編號:\c@ALG@line
。是否可以為它們建立一個自動引用名稱?
我努力了:
\newcommand{\ALGlineautorefname}{line}
\newcommand{\ALG_lineautorefname}{line}
\newcommand{\ALG@lineautorefname}{line}
但沒有一個起作用,只有第一個可以編譯。
如果可能,我如何\autorefname
在algorithmic
環境中建立一條線。
答案1
線路計數器被隱藏hyperref
因為\autoref
計數器是使用\addtocounter{ALG@line}{1}
而不是步進的\refstepcounter{ALG@line}
。以下補丁修正了這個問題,讓您定義\ALG@lineautorefname
:
\documentclass{article}
\usepackage{algorithm,algpseudocode}
\usepackage{hyperref,etoolbox}
\makeatletter
\patchcmd{\ALG@step}{\addtocounter{ALG@line}{1}}{\refstepcounter{ALG@line}}{}{}
\newcommand{\ALG@lineautorefname}{Line}
\makeatother
\newcommand{\algorithmautorefname}{Algorithm}
\begin{document}
See \autoref{alg:myalg}, specifically \autoref{algl:y}.
\begin{algorithm}
\caption{An algorithm}\label{alg:myalg}
\begin{algorithmic}[1]
\State Do X
\State Do Y \label{algl:y}
\State $x = y + z$
\end{algorithmic}
\end{algorithm}
\end{document}
答案2
以下是cleveref
基於 的解決方案。注意:(套件\cref
的主要用戶巨集cleveref
)的工作方式非常類似於\autoref
,只不過它實際上比 更強大和靈活\autoref
。例如,\cref
可以採用多個參數;請參閱下面的程式碼範例。進一步的好消息:cleveref
“開箱即用”的程式設計知道algorithmic
環境中的線條應該被稱為“線條”——無需您自己提供此設定。
\documentclass{article}
\usepackage{algorithm,algpseudocode}
\usepackage[colorlinks]{hyperref}
\usepackage[noabbrev,capitalize,nameinlink]{cleveref}
\begin{document}
\begin{algorithm}
\caption{Baseline}\label{ALG_baseline}
\begin{algorithmic}[1]
\State Do X
\State Do Y \label{algl:y}
\State $x = y + z$ \label{algl:sum}
\end{algorithmic}
\end{algorithm}
\cref{algl:y} in \cref{ALG_baseline} is \dots
\cref{algl:y,algl:sum} of the algorithm are based on \dots
\end{document}