答案1
一种方法是使用在每一行\alglinenumber
自动插入\tkizmark
,然后后您可以通过 插入注释\AddNote
。因此,如果您想为第 1 行至第 5 行和第 7 行至第 9 行添加注释,您可以使用:
\AddNote[blue]{1}{5}{Comments for lines 1--5.}
\AddNote[red]{7}{9}{Comments for lines 7--9.}
笔记:
如果有重叠的线,你需要
\VerticalOffset
通过以下方式进行调整\renewcommand*{\VerticalOffset}{0.15ex}%
这确实需要两次运行。第一次确定位置,第二次进行绘图。
来自
\tikzmark
在正文旁边添加大括号。
参考:
- 相关问题:源代码边距注释
代码:
\documentclass{article}
\usepackage{algpseudocode}
\usepackage{algorithm}
\usepackage{tikz}
\usetikzlibrary{decorations.pathreplacing,calc}
\newcommand{\tikzmark}[1]{\tikz[overlay,remember picture] \node (#1) {};}
\newcommand*{\SpaceReservedForComments}{2.5cm}%
\newcommand*{\HorizontalOffset}{-0.5em}%
\newcommand*{\VerticalOffset}{0.7ex}%
\newcommand*{\AddNote}[4][]{%
%% #1 = draw options
%% #2 = top line number to start comment from
%% #3 = bottom line number where comment ends
%% #4 = text of comment
\begin{tikzpicture}[overlay, remember picture]
\draw [decoration={brace,amplitude=0.5em},decorate,ultra thick,red, #1]
($(#3)+(\HorizontalOffset,-\VerticalOffset)$) -- ($(#2)+(\HorizontalOffset,\VerticalOffset)$)
node [align=left, text width=\SpaceReservedForComments-1.0em, pos=0.5, anchor=east] {#4};
\end{tikzpicture}
}%
\makeatletter% Add a \tkizmark for each line so we can reference it later
\algrenewcommand\alglinenumber[1]{\tikzmark{\arabic{ALG@line}}\tiny#1:}
\makeatother
\begin{document}
\algnewcommand{\algorithmicgoto}{\textbf{go to}}%
\algnewcommand{\Goto}[1]{\algorithmicgoto~\ref{#1}}%
\begin{algorithm}[1]
\hspace*{\SpaceReservedForComments}{}%
\begin{minipage}{\dimexpr\linewidth-\SpaceReservedForComments\relax}
\caption{Euclid’s algorithm}\label{euclid}
\begin{algorithmic}[1]
\Procedure{Euclid}{$a,b$} \Comment{The g.c.d. of a and b}
\State $r\gets a\bmod b$
\While{$r\not=0$} \Comment{We have the answer if r is 0} \label{marker}
\State $a\gets b$
\State $b\gets r$
\State $r\gets a\bmod b$
\EndWhile
\State \textbf{return} $b$\Comment{The gcd is b}
\State \Goto{marker}
\EndProcedure
\end{algorithmic}%
% ---------------
% Now insert all to comments that we desire on specific line numbers:
\AddNote[blue]{1}{5}{Comments for lines 1--5.}
\AddNote[red]{7}{9}{Comments for lines 7--9.}
% ---------------
\end{minipage}%
\end{algorithm}
\end{document}