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.

I am writting algorithm which has two stages. How can I indent code for stage one and for stage two?

\begin{algorithm}[H]
\caption*{my algorithm}
\begin{algorithmic}
    \STATE \textbf{Stage one:} this is stage one
    \FORALL{i}
        \STATE do something
    \ENDFOR
    \STATE \textbf{Stage two:} this is stage two
    \STATE Update the trie: 
    \FORALL{j}
    \STATE do something
    \ENDFOR
\end{algorithmic}
\end{algorithm}
share|improve this question
add comment

1 Answer 1

up vote 6 down vote accepted

In the following example code I defined two new commands allowing you to change the indentation; simply enclose the desired fragment using \bindent, \eindent; the length \myindent controls the indent amount:

\documentclass{article}
\usepackage{algorithm,algorithmic}
\usepackage{caption}

\newlength\myindent
\setlength\myindent{2em}
\newcommand\bindent{%
  \begingroup
  \setlength{\itemindent}{\myindent}
  \addtolength{\algorithmicindent}{\myindent}
}
\newcommand\eindent{\endgroup}

\begin{document}

\begin{algorithm}[H]
\caption*{my algorithm}
\begin{algorithmic}
    \STATE \textbf{Stage one:} this is stage one
    \bindent
    \FORALL{i}
        \STATE do something
    \ENDFOR
    \eindent
    \STATE \textbf{Stage two:} this is stage two
    \bindent
    \STATE Update the trie: 
    \FORALL{j}
    \STATE do something
    \ENDFOR
    \eindent
\end{algorithmic}
\end{algorithm}

\end{document}

enter image description here

Some comments to the code:

\newlength\myindent % define a new length \myindent
\setlength\myindent{6em} % assign the length 2em to \myindet
\newcommand\bindent{%
  \begingroup % starts a group (to keep changes local)
  \setlength{\itemindent}{\myindent} % set itemindent (algorithmic internally uses a list) to the value of \mylength
  \addtolength{\algorithmicindent}{\myindent} % adds \mylength to the default indentation used by algorithmic
}
\newcommand\eindent{\endgroup} % closes a group
share|improve this answer
    
this is perfect, just curious what does this line \newlength\myindent mean? –  msh Sep 1 '12 at 21:48
    
could you add some comment explaining what does each line do? thank you –  msh Sep 1 '12 at 21:50
    
@capoluca sure! I've updated my answer adding some comments. –  Gonzalo Medina Sep 1 '12 at 21:55
add comment

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.