[Tex/LaTex] Properly indent comments with no line-numbering in algorithmicx

algorithmicxcommentsindentationline-numbering

Writing comments in pseudocode, I wanted to insert comments to the right side of the line which is commented. This thread help me a lot.

The algorithm is line-numbered, however I need the comments with no number! (as a regular \comment command do), but because the macro has the \State command in it, it really is a normal line with number.

\algnewcommand{\LineComment}[1]{\State \(\triangleright\) #1}

Thanks in Advance!

Best Answer

The following definition of \LineComment provides the appropriate indentation without numbering the line:

\makeatletter
\algnewcommand{\LineComment}[1]{\Statex \hskip\ALG@thistlm \(\triangleright\) #1}
\makeatother

\Statex sets an \item[] (note that the algorithm is actually a list, so \item[] sets an empty item and therefore has no line number), while \ALG@thistlm contains the appropriate indentation of the current list item.

enter image description here

\documentclass{article}
\usepackage{algorithm}% http://ctan.org/pkg/algorithms
\usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx
\makeatletter
\algnewcommand{\LineComment}[1]{\Statex \hskip\ALG@thistlm \(\triangleright\) #1}
\makeatother
\begin{document}
\begin{algorithm}[!ht]
  \caption{My Algo.}\label{myalgo}
  \begin{algorithmic}[1]
    \State $\epsilon$ = 1.0; \Comment{Explore Latency Dimension}
    \While {explorationTime $\leq$ timeLimit}
      \State $\epsilon = \epsilon / 2$;
      \State calculateIncrements($\epsilon$);
      \LineComment{Explore L dimension}
      \While {lQuery $\leq$ lUpperLimit}
        \State Query (0, Query, bQuery, pQuery);
        \If {result = WORKING}
          \State mark points 
          \LineComment{no need to explore more. we just want to stop over here.}
          \State Break
        \Else
          \If {result = NOT WORKING}
            \State mark from 0 to lQuery as NOT WORKING.
          \EndIf
        \EndIf
        \State lQuery += lEpsIncr;
      \EndWhile
    \EndWhile
    \State calcPoints()
  \end{algorithmic}
\end{algorithm}
\end{document}