0

I'm writing a long document and as a general rule, I try to write things down semantically. For example, when I introduce notation for $\mathcal{A}$ and $\mathcal{B}$, I add the following at the beginning of my section:

\section{An example section title}
\newcommand{\MySpecialA}{\mathcal{A}}
\newcommand{\MySpecialB}{\mathcal{B}}
Some example text. We see that \(\MySpecialA \neq \MySpecialB\)!

I will then always use my own commands. This makes formulas more readable and refactoring very easy.

However, these definitions are then available for the rest of the document, not only this section. I could use these later by accident. Also, when I want to use the same name for a variable later on, I have to be careful when overwriting it.

Is there a better way to handle these "scoped commands/variable names"?

Mico
  • 506,678
mixotrov
  • 141
  • 2
    You could delimit the scope of your macros by providing suitably-placed \begingroup and \endgroup directives. – Mico Jan 25 '24 at 13:05
  • Would this have the same effect as wrapping the \section command in a custom environment? Like a new environment which takes a section title, puts it into the section command and then adds the remaining content? Edit: see answer by @Cube707 – mixotrov Jan 25 '24 at 13:25
  • 1
    Not quite. While a LaTeX environment does constitute a TeX group [jargon alert!], it is not necessary to employ an environment in order to delimit the scope of your custom macros. Placing \begingroup and \endgroup directives in suitably chosen locations is what you need. – Mico Jan 25 '24 at 13:36

1 Answers1

2

In LaTeX scopes are called groups. They are created using the \begingroup and \endgroup commands or when placing { } on their own.

You could place the commands where needed yourself, but I would recommend creating you own environments that do this for you. Something like this:

\documentclass{article}

\newenvironment{scopedsection}[2]{ \section{#1} \begingroup % these are actually redundant and just here for clarity #2 }{ \endgroup % these are actually redundant and just here for clarity }

\begin{document}

\begin{scopedsection}{my section}{
    \newcommand{\MySpecialA}{\mathcal{A}}
}
    This works: \( \MySpecialA \)
\end{scopedsection}

Throws error: \( \MySpecialA \)

\end{document}

Edit: I just learned from @Mico that environments already are a group by default and the begingroup and endgroup are arctually redundant. But they are still good for clearity.

Cube707
  • 404
  • beware adding white space you need a lot of % adding to ends of lines here. – David Carlisle Jan 25 '24 at 14:26
  • Just a suggestion, always develop a notations table before you start renaming things, it will help you develop these macros in a more organized way. In general personally I am not in favour of renaming, as it makes co-operation difficult, there is more mental overhead to remember more macro names etc. – yannisl Jan 25 '24 at 15:12