5

I would like to add a new command to an existing environment. The \renewenvironment command does not help a lot since I need to copy and paste the entire environment definition.

For an example I would like to make a \FORALL_P for the algorithmic environment such that instead of producing

forall ... do 

as original \FORALL, it produces

forall ... do in parallel
Werner
  • 603,163
iKid
  • 227

3 Answers3

9

The etoolbox package offers you some commands that could be useful, for example:

\AtBeginEnvironment{<environment>}{<code>}
\AtEndEnvironment{<environment>}{<code>}

Perhaps if you give us some mor information about your actual intent, we could provide more helpful information.

Now that new information has been provided in the question, I would suggest to use the algorithmicx package to define the new block; while the algorithmic package doesn’t allow you to easily modify predefined structures, or to create new ones, the algorithmicx package gives you full control over the definitions. Using algcompatible, you can have full compatibility with the syntax of the algorithmic package; a little example of the definition of the new block:

\documentclass{article}
\usepackage{algorithm}
\usepackage{algcompatible}

\algblockdefx{FORALLP}{ENDFAP}[1]%
  {\textbf{for all }#1 \textbf{do in parallel}}%
  {\textbf{end for}}

\begin{document}

\begin{algorithm}
\caption{A test algorithm}
\begin{algorithmic}[1]
\FORALL {$v \in V(G)$}
\STATE $l(v) \leftarrow \infty$
\ENDFOR
\FORALLP{$v \in V(G)$}
\STATE $l(v) \leftarrow \infty$
\ENDFAP
\end{algorithmic}
\end{algorithm}

\end{document}

enter image description here

To have the \RETURN command as defined by algorithmic, you need to add the following definition:

\algloopdefx{RETURN}[1][]{\textbf{return} #1}
Gonzalo Medina
  • 505,128
4

You can say

\usepackage{algorithmic}
\usepackage{etoolbox}
\newcommand{\algorithmicdoinparallel}{\textbf{do in parallel}}
\makeatletter
\AtBeginEnvironment{algorithmic}{%
  \newcommand{\FORALLP}[2][default]{\ALC@it\algorithmicforall\ #2\ %
    \algorithmicdoinparallel\ALC@com{#1}\begin{ALC@for}}%
}
\makeatother

The definition of \FORALLP is modeled on that of \FORALL; you can't call it \FORALL_P, however.

egreg
  • 1,121,712
1

In your specific case, using commands of the etoolbox package to change the look of the \FORALL statement might not work because you're trying to change the subsequent statement, viz. "do..."

The algorithmic package allows for a fair bit of customization of various algorithm-like statements. For example, you could issue the command

\renewcommand{\algorithmicdo}{\textbf{do in parallel}}

However, this will change the output of the "do" statement in all instances, which may not be to your liking.

Mico
  • 506,678