[Tex/LaTex] How to keep comments on their own line with algorithmicx

algorithmicx

I'm trying to add comments on their own line. the default behaviour of \Comment{} is to place the comment on the same line as a \State. My current hack is to just do

\documentclass{article}
\usepackage{amsmath}
\usepackage{caption}
\usepackage{algpseudocode}
\usepackage{algorithm}
\captionsetup\[algorithm\]{labelformat=empty}
\begin{document}
\begin{algorithm}
\caption{Init}
\begin{algorithmic}\[1\]
  \State // Here is a comment the way I want it.
  \State $x \gets y$
  \end{algorithmic}
\end{algorithm}
\end{document}]

Desired output:

output

Is there a proper way to do this? What about making the comment italicized so that it's a little less intrusive?

Best Answer

I fixed some errors in the code:

  • replaced the 2 occurrences of \[...\] with [...]
  • deleted the last character ]

I added the \textit command to get the comment italicized.

\documentclass{article}
\usepackage{amsmath}
\usepackage{caption}
\usepackage{algpseudocode}
\usepackage{algorithm}
\captionsetup[algorithm]{labelformat=empty}

\begin{document}
    \begin{algorithm}
        \caption{Init}
        \begin{algorithmic}[1]
            \State // \textit{Here is a comment the way I want it.}
            \State $x \gets y$
        \end{algorithmic}
    \end{algorithm}
\end{document}

enter image description here

You could also define a command for your comment type (\CommentLine):

\documentclass{article}
\usepackage{amsmath}
\usepackage{caption}
\usepackage{algpseudocode}
\usepackage{algorithm}
\captionsetup[algorithm]{labelformat=empty}

\newcommand{\CommentLine}[1]{
    \State // \textit{#1}
}

\begin{document}
    \begin{algorithm}
        \caption{Init}
        \begin{algorithmic}[1]
            \CommentLine{Here is a comment the way I want it.}
            \State $x \gets y$
        \end{algorithmic}
    \end{algorithm}
\end{document}