使用 \autoref 在「演算法」環境中建立對行的智慧交叉引用

使用 \autoref 在「演算法」環境中建立對行的智慧交叉引用

\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}

但沒有一個起作用,只有第一個可以編譯。

如果可能,我如何\autorefnamealgorithmic環境中建立一條線。

答案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}

相關內容