[Tex/LaTex] Aligning function arguments in “algorithm” environment.

algorithmshorizontal alignmentlistings

In the "algorithm" environment, when a function call spans multiple lines, I would like to have its arguments aligned, like so:

MyFunction(long_arg_name0,
           long_arg_name1,
           long_arg_name2);

How can I achieve this effect?

(second) EDIT: Here's a minimal example that fails to achieve the desired effect:

\documentclass{article}

\usepackage{algorithmicx}
\usepackage{algpseudocode}
\usepackage{algorithm}

\begin{document}

\begin{algorithm}[t]
\begin{algorithmic}
  \While{true}
  \State MyLongWindedFunction(LongArgument0,\\ LongArgument1,\\ LongArgument2,\\ LongArgument3)
  \EndWhile
\end{algorithmic}
\end{algorithm}

\end{document}

When I stick the standard alignment marker & between the arguments, I get the error message:

! Misplaced alignment tab character &.
l.10   \State MyLongWindedFunction(LongArgument0,&
                                               \\ LongArgument1, &\\ Lon...

Best Answer

One possible solution would be to calculate the length of the string that preceeds the alignment point (in this case, the string MyLongWindedFunction( ) and then use this length to add the necessary horizontal space:

\documentclass{article}
\usepackage{algorithmicx}
\usepackage{algpseudocode}
\usepackage{algorithm}

\newlength\mylen
\settowidth\mylen{MyLongWindedFunction(}

\begin{document}

\begin{algorithm}[t]
\begin{algorithmic}
  \State MyLongWindedFunction(LongArgument0,\\\hspace{\mylen}LongArgument1,\\\hspace{\mylen}LongArgument2,\\\hspace{\mylen}LongArgument3)
\end{algorithmic}
\end{algorithm}

\end{document}

To answer the EDIT in the original question: simply add \parindent (the indentation used in the algorithm) to the length \mylen:

\documentclass{article}

\usepackage{algorithmicx}
\usepackage{algpseudocode}
\usepackage{algorithm}

\newlength\mylen
\settowidth\mylen{MyLongWindedFunction(}
\addtolength\mylen{\parindent}

\begin{document}

\begin{algorithm}[t]
\begin{algorithmic}
  \While{true}
  \State MyLongWindedFunction(LongArgument0,\\\hspace*{\mylen}LongArgument1,\\\hspace*{\mylen}LongArgument2,\\\hspace*{\mylen}LongArgument3)
  \EndWhile
\end{algorithmic}
\end{algorithm}

\end{document}
Related Question