[Tex/LaTex] algorithm2e – Apply commands to content block of IF … THEN … ELSE

algorithm2e

In the following picture, I use a verbose but very pedagogical style for algorithms.

enter image description here

I would like to automatically use macros that act on the content of block like in the first example but with typing just the 2nd one. Juste see the MWE. This will allow to always type the same LaTeX code but to use them in different.

\documentclass[10pt,a4paper]{article}
    \usepackage[vlined]{algorithm2e}

    \newcommand\BlockIf[1]{\KwSty{Start If} \\ #1 \\ \KwSty{End If}}
    \newcommand\BlockElseIf[1]{\KwSty{Start Else If} \\ #1 \\ \KwSty{End Else If}}
    \newcommand\BlockElse[1]{\KwSty{Start Else} \\ #1 \\ \KwSty{End Else}}

\begin{document}

\begin{algorithm}[H]
    \uIf{1}{\BlockIf{if...}}
    \uElseIf{2}{\BlockElseIf{else if...}}
    \Else{\BlockElse{else...}}
\end{algorithm} 

\begin{algorithm}[H]
    \uIf{1}{if...}
    \uElseIf{2}{else if...}
    \Else{else...}
\end{algorithm} 

\end{document}

Best Answer

The relevant internal commands in algorithm2e are \algocf@uIf, \algocf@uElseIf and \algocf@Else. The following modifications of these commands insert your extra formatting:

\documentclass[10pt,a4paper]{article}
\usepackage[vlined]{algorithm2e}

\newcommand\BlockIf[1]{\KwSty{Start If} \\ #1 \\ \KwSty{End If}}
\newcommand\BlockElseIf[1]{\KwSty{Start Else If} \\ #1 \\ \KwSty{End Else If}}
\newcommand\BlockElse[1]{\KwSty{Start Else} \\ #1 \\ \KwSty{End Else}}

\makeatletter
\renewcommand{\algocf@uIf}[2]{\If@ifthen{#1}\If@noend{\BlockIf{#2}}}
\renewcommand{\algocf@uElseIf}[2]{\ElseIf@elseif{#1}\If@noend{\BlockElseIf{#2}}}
\renewcommand{\algocf@Else}[1]{\Else@else\If@endif{\BlockElse{#1}}}
\makeatother

\begin{document}
\begin{algorithm}[H]
    \uIf{1}{if...}
    \uElseIf{2}{else if...}
    \Else{else...}
\end{algorithm} 

\end{document}

Sample output

The set-up for the display of if-then-else structures is dealt with by the command \SetKwIF which in standard form has 8 arguments, the first three of which are If ElseIf and Else. It uses these names to build the commands modified above and a number of their variants e.g. for dealing with optional arguments () for adding comments. You will need to redefine these variant commands too if you need that facility.

Related Question