包中的換行演算法2e

包中的換行演算法2e

我正在使用演算法2e偽代碼包。我有一些很長的線需要換行。有沒有辦法縮排以下(斷行)行和/或在第一行標記以表示發生了換行(類似於列表包解決方案

我發現了一個類似的問題對於列表包,之前已回答過,但我正在明確尋找演算法2e解決方案。

答案1

以下最小範例定義

  • \nosemic:刪除行尾 (EOL) 字元的列印(通常為;);
  • \dosemic:恢復 EOL 字元的列印;
  • \pushline:縮排一行1em(典型縮排);由algorithm2eas提供\Indp
  • \popline:刪除縮排\pushline(取消縮排?);由algorithm2eas提供\Indm

在此輸入影像描述

\documentclass{article}
\usepackage{algorithm2e}% http://ctan.org/pkg/algorithm2e
\makeatletter
\newcommand{\nosemic}{\renewcommand{\@endalgocfline}{\relax}}% Drop semi-colon ;
\newcommand{\dosemic}{\renewcommand{\@endalgocfline}{\algocf@endline}}% Reinstate semi-colon ;
\newcommand{\pushline}{\Indp}% Indent
\newcommand{\popline}{\Indm\dosemic}% Undent
\makeatother
\begin{document}
\begin{algorithm}[H]
  \SetAlgoLined
  \KwData{this text}
  \KwResult{how to write algorithm with \LaTeX2e }
    initialization\;
  \While{not at end of this document}{
    read current\;
    \eIf{understand}{
      go to next section\;
      \nosemic this is a very long statement that has to be\;
        \pushline\dosemic wrapped over two lines\;
      \popline current section becomes this one\;
    }{
      go back to the beginning of current section\;
    }
  }
  \caption{How to write algorithms}
\end{algorithm}
\end{document}​

因為我對你不熟悉algorithm2e設置,我不確定您希望如何組合這四個命令。因此,我將它們分開以最大限度地(但手動)使用。

答案2

事實上,有一個更簡單的解決方案:使用經典的\hangafter\hangindent。這與algorithm2e.

筆記:

  1. \skiptext是演算法中新區塊的文字縮排長度;所以我選擇這個縮排的1/2;

  2. 無需重新定義內部宏,因為\algocf@endline幾乎所有宏都可以在algorithm2e.用於\SetEndCharOfAlgoLine重新定義行尾

\hangafter請參閱下面的使用和的範例\hangindent

在此輸入影像描述

\documentclass{article}
\usepackage{algorithm2e}% http://ctan.org/pkg/algorithm2e
%
\newcommand{\nosemic}{\SetEndCharOfAlgoLine{\relax}}% Drop semi-colon ;
\newcommand{\dosemic}{\SetEndCharOfAlgoLine{\string;}}% Reinstate
\newcommand{\pushline}{\Indp}% Indent
\newcommand{\popline}{\Indm\dosemic}% Undent
%
\begin{document}
\begin{algorithm}[H]
  \SetAlgoLined
  \KwData{this text}
  \KwResult{how to write algorithm with \LaTeX2e }
    initialization\;
  \While{not at end of this document}{
    read current\;
    \eIf{understand}{
      go to next section\;
      \nosemic this is a very long statement that has to be\;
        \pushline\dosemic wrapped over two lines\;
      \popline current section becomes this one\;
      \hangindent=.5\skiptext\hangafter=1
      this is a very long statement that should be indented automatically on the next
      lines if this statement is longer than one line\;
      Following lines should be indented normally\;
    }{
      go back to the beginning of current section\;
    }
  }
  \caption{How to write algorithms}
\end{algorithm}
\end{document}​

答案3

\Indp並可\Indm在套件中用於algorithm2e縮排和刪除縮排。我已經測試過了。

相關內容