2

I have a doc.tex and a myclass.cls file, and trying to keep the first as clean as possible.

I need to define in myclass.cls some macros to use and be visible only inside the two environments: algorithm and clase (the last is just a modification of algorithm).

myclass.cls

...
\usepackage[ruled,vlined,spanish,onelanguage]{algorithm2e}
\makeatletter
\newcounter{clase}
\newenvironment{clase}[1][htb]{%
    \renewcommand{\algorithmcfname}{Clase}% Update algorithm name
    \let\c@algocf\c@clase% Update algorithm counter
    \begin{algorithm}[#1]%
}{\end{algorithm}}
\makeatother
...

doc.tex

...
\begin{document}
...
\begingroup
    \definecolor{green2}{RGB}{0,156,0}
    \newcommand\true{\textcolor{red2}{$true$}}
    \newcommand\store{\textcolor{green2}{$store()$}}
    % And 40+ others like these
    % I want them in myclass.cls and avoid that \begingroup

    \begin{clase}
        % Defined macros are visible here
    \end{clase}
    \paragraph{Another stuff} I don't need the macros to be visible here
    \begin{algorithm}
        % also visible here
    \end{algorithm}
\endgroup
...
6
  • It would be helpful which of the various algorithm and OhterEnvi environments you are using and what is inside of your myclass.cls that you try to build around your doc.tex ;-)
    – user31729
    Mar 8, 2017 at 17:07
  • question (not answer, as I wrote) updated, I hope it is helpful :). Thanks again
    – onlycparra
    Mar 8, 2017 at 17:42
  • 1
    The short answer is that you refine the algorithm environment such that those macros are defined in and only in its scope. macro definitions are local unless made global explicitly. Check out etoolbox package for patching environment
    – Yan Zhou
    Mar 8, 2017 at 18:04
  • @YanZhou: \AtBeginEnvironment{clase}{\newcommand{\true}{...}} should do as well
    – user31729
    Mar 8, 2017 at 18:39
  • @ChristianHupfer yes, I forgot that.
    – Yan Zhou
    Mar 8, 2017 at 18:53

1 Answer 1

1

If code changes should be done for an environment only sometimes \AtBeginEnvironment is a better option than \patchcmd, but this depends on the real application.

Since \renewcommand is not global, the meaning of a macro changed within an environment does not leak outside, so \AtBeginEnvironment is a suitable choice.

I've reduced the O.P's example to a minimal one, for some fake environment foo. (Of course, in a real world example, the environment isn't defined usually in the same file and then changed afterwards with \AtBeginEnvironment)

\documentclass{article}

\newcommand{\foobar}{This is foobar}

\newenvironment{foo}{%
\bfseries\foobar


}{}

\usepackage{etoolbox}

\AtBeginEnvironment{foo}{%
  \renewcommand{\foobar}{This is foobar inside foo}%
}{}


\begin{document}

Foobar before foo: \foobar

\begin{foo}
Hello World
\end{foo}

Foobar after foo: \foobar


\end{document}

enter image description here

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .