如何在算法中正确换行 + 为子行增加更多缩进

如何在算法中正确换行 + 为子行增加更多缩进

请参阅答案。我使用它的parState命令创建了这个 MWE:

\documentclass{article}
\usepackage{algorithm,algpseudocode}
\makeatletter
\newcommand{\algmargin}{\the\ALG@thistlm}   
\makeatother
\algnewcommand{\parState}[1]{\State%
    \parbox[t]{\dimexpr\linewidth-\algmargin}{\strut #1\strut}}

\begin{document}
\begin{algorithm}
\caption{My pseudo code.}
\begin{algorithmic}[1]
    \If{$true$}
    \parState{%
    Look at this state again, this state is just too long for algorithmic to handle, I'm just going to switch to Word. Look at this state again, this state is just too long for algorithmic to handle, I'm just going to switch to Word. Look at this state again, this state is just too long for algorithmic to handle, I'm just going to switch to Word.}
    \EndIf
\end{algorithmic}
\end{algorithm}
\end{document}

结果是:

在此处输入图片描述

第 2 行的最后 4 行怎么会比第 2 行的第一行更有目的性呢?我希望它们是根据相对于第 1 行用于规划第 2 行的空间量来规划的。

答案1

如果仅涉及一个段落,则可以使用 \hangindent/\hangafter:

\documentclass{article}
\usepackage{algorithm,algpseudocode}
\makeatletter
\newcommand{\algmargin}{\the\ALG@thistlm}
\makeatother
\algnewcommand{\parState}[1]{\State%
    \parbox[t]{\dimexpr\linewidth-\algmargin}{\strut\hangindent=\algorithmicindent \hangafter=1 #1\strut}}

\begin{document}
\begin{algorithm}
\caption{My pseudo code.}
\begin{algorithmic}[1]
    \If{$true$}
    \parState{%
    Look at this state again, this state is just too long for algorithmic to handle, I'm just going to switch to Word. Look at this state again, this state is just too long for algorithmic to handle, I'm just going to switch to Word. Look at this state again, this state is just too long for algorithmic to handle, I'm just going to switch to Word.}
    \EndIf
\end{algorithmic}
\end{algorithm}
\end{document}

在此处输入图片描述

相关内容