Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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}
share|improve this question

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
    
Thanks, I will look more precisely in the code of algorithm2e for more customization. –  projetmbc Oct 29 '12 at 6:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.