Your support for our advertisers helps cover the cost of hosting, research, and maintenance of this document
Formatting Information — An introduction to typesetting with LATEX
Chapter 7: Programmability
Section 7.5: Macros and environments
As mentioned in § 4.6.3 above, it is possible to define macros to capture text in an environment and reuse it afterwards. This avoids any features of the subsequent use affecting the formatting of the text.
One example of this uses the facilities of the fancybox package, which defines a variety of framed box commands to display your text, but they require a pre-formed box as their argument, so the package provides a special environment Sbox which ‘captures’ your text for use in these boxes.
Here we put the text in a minipage environment because we want to change the width; this occurs inside the Sbox environment so that it gets typeset into memory and stored in a box. It can then be ‘released’ afterwards with the command \TheSbox as the argument of the \shadowbox command (and in this example it has also been centred).
\begin{Sbox} \begin{minipage}{3in} This text is formatted to the specifications of the minipage environment in which it occurs. Having been typeset, it is held in the Sbox until it is needed, which is after the end of the minipage, where you can (for example) align it and put it in a special framed box. \end{minipage} \end{Sbox} \begin{center} \shadowbox{\TheSbox} \end{center}
This text is formatted to the specifications of the minipage environment in which it occurs.
Having been typeset, it is held in the Sbox until it is needed, which is after the end of the minipage, where you can (for example) centre it and put it in a special framed box.
The point about this kind of construct is that it can be turned into an environment of your own, so you can reuse it wherever you need (the colouring is left as an exercise to the reader):
\usepackage{fancybox,fontawesome} \newenvironment{warning}[1]{% \begin{Sbox}\begin{minipage}{8cm}% \subsubsection*{\fa-fire-extinguisher\ #1}} {\end{minipage}\end{Sbox}\begin{center} \shadowbox{\TheSbox}\end{center}} ... \begin{warning}{Open and Close} Make sure all your open-curly-braces are matched by close-curly-braces and that every \verb+\begin+ is matched by an \verb+\end+. \end{warning}
Open and Close
Make sure all your open-curly-braces are matched by close-curly-braces and that every \begin is matched by an \end.
Here’s another one, this time to create a two-column chapter with the title spread across both columns (thanks to users on Discord for this one):
\usepackage{multicol,lipsum} \newenvironment{spanchapter}[1] {\begin{multicols}{2}[\chapter{#1}]} {\end{multicols}} ... \begin{spanchapter}{The introduction to it all} \lipsum[1] \end{spanchapter}