![如何在算法左侧排版代码区域注释?](https://linux22.com/image/300892/%E5%A6%82%E4%BD%95%E5%9C%A8%E7%AE%97%E6%B3%95%E5%B7%A6%E4%BE%A7%E6%8E%92%E7%89%88%E4%BB%A3%E7%A0%81%E5%8C%BA%E5%9F%9F%E6%B3%A8%E9%87%8A%EF%BC%9F.png)
答案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}