Stage 6 · Production, macros and packages 44 / 48 ≈ 16 min read

Writing Your Own LaTeX Environment with newenvironment

An environment is two macros and a group. Once you can picture where the group opens and closes, the classic errors stop being mysterious: arguments that vanish in the end code, definitions that leak, environments that refuse to split across a page, and option lists that seem to do nothing.

    What newenvironment actually defines

    \newenvironment{name}{begin code}{end code} creates exactly two control sequences: \name and \endname. The begin code is defined through the kernel's \new@command, so it can take arguments and it is \long unless you used the starred form. The end code is defined with a bare \def — the kernel comment says so in as many words: it does not take arguments, though it may contain paragraphs.

    That asymmetry is the single most useful fact on this page. Writing \newenvironment{law}[2][Clause]{…}{\label{#2}} fails with Illegal parameter number in definition of \endlaw, because the end code has no parameters to number. The workaround is the idiom every package uses: in the begin code, copy what the end code will need into a macro — \def\law@name{#2} — and read that macro back in the end code.

    Reading and writing the .aux file: \begin{env} itself expands to \@currenvir-setting machinery, then \begingroup, then your begin code; \end{env} runs \endenv and closes the group. The \@currenvir macro is how LaTeX detects the mismatch that produces \begin{qt} ended by \end{q}. and, in a nested tangle, Extra \end{…} or a Runaway argument.

    An environment cannot be split across files either: a \begin{…} in one \input file and its \end{…} in another is legal (TeX does not care where the tokens come from), but a mismatched pair inside a table cell or a \parbox argument produces the vertical-Mode errors that make people blame the file rather than the box.

    Where the group of a newenvironment begins and ends, and which assignments survive it THE TWO MACROS \newenvironment ACTUALLY CREATES \def\proof{\long\... begin code, takes #1 defined through \new@command → it CAN have parameters \def\endproof{end code} ← no parameter text at all what \begin{proof} wraps around them \begingroup \def\@currenvir{proof} \proof ... \endproof \endgroup THE GROUP, DRAWN AS A TIME LINE \begingroup → \begin code → body material → \end code → \endgroup the end code still runs INSIDE the group, so it can read every definition the begin code made — which is why “stash the arguments in a macro in the begin code, use them in the end code” works DOES IT LEAK? local, gone at \end{proof} \newskip lengths, \setlength, \def/\newcommand, \@currentlabel, \parskip, \baselineskip, font switches, counters inside \stepcounter? no — escapes the group counters (\stepcounter is global), \global\defs, \write / \addcontentsline / \addtocontents, box registers you ship out, page-breaking state
    The begin and end code are two macros wrapped in one group — and the end code runs before that group closes.

    Arguments, defaults and the doubling rule again

    The arity syntax is inherited from \newcommand verbatim: \newenvironment{law}[2][Clause]{…}{…} gives the environment one optional and one mandatory argument, written as \begin{law}[Art.]{Cargo}. The ## rule applies with full force, because the environment body is a definition: any \newcommand, \def, \setlength of something parameterised, or nested \NewDocumentEnvironment inside begin code must double its inner slot numbers.

    \NewDocumentEnvironment{name}{spec}{begin}{end} changes two things. The argument spec is descriptive rather than numeric, and — this is the one people miss — both the begin code and the end code may use the arguments, because xparse builds the end macro with the same parameter text. So the "stash it in a macro" dance exists to work around a kernel limitation that xparse has already fixed.

    A defaulted argument can also be the default of another argument in xparse: O{#2} is legal, which is how you build an environment whose optional label defaults to its mandatory title. And + is per argument, so {O{} +b} says plainly "one optional, and the body may contain paragraphs" — while the kernel's unstarred \newenvironment is long everywhere and the starred form short everywhere.

    Defaults deserve one extra warning. A \newenvironment default is expanded when the environment begins, so a default containing a fragile command will misbehave inside a moving argument — an environment inside a \section title is a mistake anyway, but a default that calls \parskip or \item is a real trap.

    \begin{gathered} \text{(i) } A \text{ is closed} \\ \text{(ii) } A \text{ is bounded} \\ \text{(iii) } A \text{ is convex} \end{gathered}
    \begin{gathered} \text{(i) } A \text{ is closed} \\ \text{(ii) } A \text{ is bounded} \\ \text{(iii) } A \text{ is convex} \end{gathered}
    \documentclass[11pt,a4paper]{article}
    \usepackage{amsmath}
    \usepackage{keyval}
    \usepackage{framed}       % breakable frame, no options
    \usepackage{mdframed}     % breakable frame, keyval options
    \usepackage{xparse}
    
    \mdfdefinestyle{law}{linecolor=black!40, linewidth=0.6pt,
      backgroundcolor=black!3, innertopmargin=8pt, innerbottommargin=8pt,
      skipabove=\baselineskip, skipbelow=\baselineskip, splittopskip=12pt}
    
    % ---- classic kernel version, with the arguments stashed for the end code
    \makeatletter
    \newenvironment{oldlaw}[2][\lawdefaultname]{%
      \def\law@name{#2}%               #1/#2 are visible ONLY here
      \begin{mdframed}[style=law]%
      \par\noindent\textbf{#1\law@name.}\itshape%
    }{%
      \par\end{mdframed}%              can read \law@name: still inside the group
    }
    \makeatother
    \newcommand{\lawdefaultname}{Clause }
    
    % ---- xparse version: the end code may use the arguments directly
    \NewDocumentEnvironment{law}{ O{Clause} m +b }{%
      \par\medskip\noindent\textbf{#1~#2}\quad\itshape%
    }{%
      \par\medskip%
    }
    
    \newtheorem{theorem}{Theorem}
    
    \begin{document}
    \begin{law}{Duty of care}
      A carrier shall take reasonable care of the goods.
    \end{law}
    
    \begin{oldlaw}[Art.]{Cargo liability}
      The carrier is liable for loss occurring while the goods are in charge.
    \end{oldlaw}
    
    \begin{theorem}
      $\det(AB)=\det A\,\det B$.
    \end{theorem}
    \end{document}

    What leaks across the boundary, and what does not

    Everything the begin code defines or assigns is local, and disappears at \end{env} — \defs, \newcommands, \setlength, font switches, \@currentlabel, penalties. That is what makes an environment a safe scope, and it is why you can write \begin{compactlist}\setlength{\itemsep}{0pt}… without ruining the rest of the document.

    Five things escape anyway, and each has caused somebody an hour. Counters: \stepcounter and \refstepcounter are global by design, so an environment that increments a counter changes it permanently. Assignments prefixed with \global, including \global\defs made by packages. Writes: \write, \addcontentsline and \addtocontents take effect the moment they are executed, not when the group closes. Box registers and \newbox allocations, which are memory allocations rather than assignments. And page-building state — a \raggedbottom or \pagestyle change inside an environment applies to whatever page the environment happens to end on.

    The corollary that solves most "my end code sees nothing" bugs: the end code runs inside the group. Anything the begin code defined is available there; what is not available is the arguments (previous section) and anything defined after \end{env}. Local \label handling works precisely because of this: setting \@currentlabel in the begin code is what makes a \label inside the environment print your own numbering.

    A blank line before \end{env} is worth understanding too, since it is the most common vertical-space bug in hand-written environments: the blank line becomes an empty paragraph inside the environment, so your \vspace in the end code is measured against the wrong baseline. Prefer \par plus \addvspace in the end code, and let the environment tolerate \parskip being anything.

    \begin{aligned} u_{n} &\le L^{n}\, u_{0} \\ \lim_{n\to\infty} u_{n} &= 0 \end{aligned}
    \begin{aligned} u_{n} &\le L^{n}\, u_{0} \\ \lim_{n\to\infty} u_{n} &= 0 \end{aligned}

    Option lists: turning begin{env}[color=red] into behaviour

    To the kernel, \begin{law}[color=blue, head=short] is one argument containing a comma-separated blob. Turning that into behaviour is the job of a key parser, and the standard route is the keyval package: declare each key with \define@key{law}{color}{\def\law@color{#1}}, then call \setkeys{law}{#1} at the top of the begin code. xkeyval layers on families, \define@cmdkeys for string keys, \define@boolkeys for flags that accept =true|false, and \presetkeys for defaults, which is why its name appears in almost every box-and-frame package on CTAN.

    Two failure modes dominate. An unknown or misspelled key stops the run with Package keyval Error: framewidth not allowed. — read it as "the option name is wrong", never as "the value is wrong". And values containing commas must be braced, head={a, b}, because the splitter cuts on commas before your code ever sees the value.

    The timing constraint is the subtle one: keys read in the begin code can only affect material typeset afterwards. An option that changes a length used by a frame must be applied before the frame is built, and an option that should affect the end code has to be stored in a macro rather than acted on immediately. Every environment with per-instance styling obeys this, which is why mdframed styles are declared with \mdfdefinestyle once and merely selected per instance.

    New code has a cleaner path: ltcmd's = modifier grabs an optional argument as a keyval list with a named default key, and LaTeX3 l3keys supplies the family structure, unknown-key handling and .code:n blocks underneath. That combination is what a fresh package should use; the \define@key route is what you need in order to read and patch other people's code.

    How an environment option list is parsed: bracket argument into a keyval family, each key into its own code 1 · THE USER WRITES AN OPTION LIST \begin{law}[color=blue, head=short, number=4] to \newenvironment this is ONE argument: #1. Nothing understands commas or = signs yet. 2 · THE BEGIN CODE HANDS THE STRING TO A FAMILY \newenvironment{law}[1][]{% \setkeys{law}{#1}% \vskip2pt \set@law@frame } \define@key{law}{color}{...} declares one key per line keyval’s \setkeys does the splitting 3 · EACH KEY RUNS ITS OWN CODE color → \def\law@color{blue} head → \def\law@head{#1} number → \setcounter{law}{...} values arrive braced, so commas inside a value need their own braces: head={a,b} WHERE THE PITS ARE Unknown key → “Package keyval Error: numbering not allowed.” A plural typo in a name is the most common cause; xkeyval’s \define@cmdkeys and \define@boolkeys cut the boilerplate, \presetkeys supplies defaults. Options must be set BEFORE the frame is built, so anything that depends on them has to be deferred to the begin code — not to the preamble. New code should skip the hand-rolled dance: ltcmd’s = modifier turns an optional argument into a keyval list with a named default key, and l3keys gives unknown-key handling and .code:n blocks.
    An option list is one argument until a keyval family splits it: each key runs its own code, in the order the parser reaches it.

    Environments that refuse to break across a page

    An environment that puts its body in a box is unbreakable, and no amount of configuration will change that. \fbox, \parbox, minipage, a \vbox, a tikzpicture node, a tabular inside a float — all of them are one indivisible vertical list. The symptom is not an error: it is a page that ends early with a hole in it, or an Overfull \vbox that runs into the footer.

    The fix is to stop building a box and start building a frame. The framed package supplies framed, shaded and snugshade, which let the paragraph machinery split the content and redraw the rule per page via \FrameCommand. mdframed adds the keyval layer — linecolor, backgroundcolor, innertopmargin, and the two skips that matter for splits, splittopskip and splitbottomskip — plus framemethod=tikz for rounded corners. tcolorbox is the most capable and the one most likely to surprise you: it is a box by default, so the breakable key from the breakable library must be set, and it will still overflow rather than complain if you forget.

    The tables have their own answer, because a frame around a table is not the same as a table that splits: longtable breaks rows and repeats a head, xltabular combines that with tabularx column widths, and tabularray offers the same with a keyval interface. Attempting to wrap a tabular in a breakable box gets you a frame that splits but a table that does not.

    Two cases have no good answer, and pretending otherwise wastes days. Content inside a minipage, a table cell or a margin note cannot split under any package, because the outer box already fixed its height. And a \newenvironment that opens a quote inside a tcolorbox with breakable is fine, but the same idea with height=4cm is not — the fixed height is the box again.

    Why a boxed environment cannot split across a page and how mdframed, tcolorbox and framed fix it A BOX IS ONE VERTICAL LIST: IT CANNOT BE CUT page 12 \newenvironment{note} {\par\noindent\fbox\bgroup \begin{minipage}{...} {\end{minipage}\egroup \par} whole box must fit → or overfull page 13 the box was pushed whole onto this page, so page 12 ends with a big white hole A FRAME BUILT BY THE OUTPUT ROUTINE CAN BE CUT page 12 first part of the box bottom rule drawn by \bottomframecode, then \splitbottomskip before the page ends page 13 second part continues top rule from \topframecode, \splittopskip keeps the first line clear of the frame PICKING THE RIGHT TOOL framed \begin{framed} … \end{framed} splits, but the frame is drawn per page with \FrameCommand; no options, no titles mdframed \begin{mdframed}[style=law] keyval options, backgrounds, frametitle, splittop/bottomskip, framemethod=tikz for rounded tcolorbox \tcbuselibrary{breakable,skins} \newtcolorbox needs the breakable key or it silently stays single-page like a minipage Rule of thumb: any environment whose begin code opens a box (\vbox, \parbox, minipage, \fbox, tikz node) is unbreakable by construction — restyle it with a frame builder instead of patching it.
    A box cannot be cut; a frame built by the output routine can, and it redraws itself on both pages.
    \documentclass[11pt,a4paper]{article}
    \usepackage{amsmath}
    \usepackage{tcolorbox}
    \tcbuselibrary{breakable,skins,titles}   % breakable is a library, not a default
    
    \newtcolorbox{remark2}[1][]{breakable, colback=black!3, colframe=black!45,
      boxrule=0.5pt, arc=2pt, left=6pt, right=6pt,
      fonttitle=\bfseries, title={Remark}, #1}
    
    \newtcolorbox{lawbox}[2][]{breakable, colback=black!2,
      colframe=black!50, title={#2}, #1}
    
    \begin{document}
    % A box built from \vbox or minipage cannot split. These can.
    \begin{remark2}[colback=blue!5]
      Long material that has to run across a page boundary: the frame is closed
      at the bottom of one page and reopened at the top of the next.
    \end{remark2}
    
    \begin{lawbox}[title=Art. 7]{Carrier}
      Every long clause survives a page break with this setup; without the
      breakable key, tcolorbox silently keeps the whole thing on one page and
      overflows it instead.
    \end{lawbox}
    \end{document}

    Environments that read their own body, and what that costs

    Occasionally the begin code must see the whole body — to move it, repeat it, count it, or typeset it after the closing material. xparse has the right tool: end the argument spec with b, marked +b if paragraphs are expected, and the body arrives as one argument. The end code then becomes redundant, but it must still be supplied as an empty {}. For verbatim bodies there is c, which collects the environment text with catcodes already changed — the same trick the verbatim environment uses.

    The cost is real, and it is mostly about grouping and catcodes. A body grabbed as an argument is read before the begin code runs, so any assignment the begin code makes is invisible to the grabbing process, and any \par in the body requires the long variant. A + on the b type is not optional in practice. Verbatim-ish collection is why the standard verbatim environment cannot appear in another command's argument, and why beamer needs a fragile frame option for it.

    The alternative implementation strategy, used by the environ package and by plenty of older code, is to define the environment so that its body is stored in a macro at \end time and typeset there — \NewEnviron{...}{…\BODY…} in that package. It gets you the same result with the same restriction: the body is typeset in a context you control at the end, which is exactly what breaks environments that must open and close material around it.

    Decide early which of the two designs you want: stream the body as it comes (a normal environment, cheap, breakable, sees assignments in order) or hold it (flexible, can repeat or suppress, unbreakable, and every group inside must still be balanced).

    \int_{0}^{1} x^{s-1} e^{-x}\,\mathrm{d}x \;=\; \Gamma(s) \;\sim\; \sqrt{\frac{2\pi}{s}}\left(\frac{s}{e}\right)^{s}
    \int_{0}^{1} x^{s-1} e^{-x}\,\mathrm{d}x \;=\; \Gamma(s) \;\sim\; \sqrt{\frac{2\pi}{s}}\left(\frac{s}{e}\right)^{s}
    A derivation this long is the case where streaming wins: holding the whole body in a macro forbids the page break that the text needs.
    \documentclass{article}
    \usepackage{xparse}
    \usepackage{environ}   % \CollectBody, the pre-xparse way to grab a body
    
    % b grabs the whole body as one argument; + allows paragraphs inside it.
    % With b in the spec the end code is redundant but must still be given.
    \NewDocumentEnvironment{answer}{ O{} +b }{%
      \def\@answer@body{#2}%
      \par\noindent\textbf{Answer.}\ #1%
    }{%
      \par%
    }
    
    % A body-grabbing environment can put material AFTER the body, or drop it:
    \NewDocumentEnvironment{problem}{ m +b }{%
      \par\addvspace{\medskipamount}\noindent\textbf{#1}\par\nopagebreak%
    }{}
    
    \NewDocumentEnvironment{hintbox}{ s +b }{%
      \begin{quote}\IfBooleanTF{#1}{\bfseries\textbf{Solution: }}{\itshape Hint: }#2\end{quote}%
    }{}
    
    \begin{document}
    \begin{problem}{Exercise 3.1}
      Show that $\lVert AB\rVert_2\le\lVert A\rVert_2\lVert B\rVert_2$.
    \end{problem}
    
    \begin{hintbox}
      Apply the definition of the operator norm to a unit vector.
    \end{hintbox}
    \end{document}

    Theorem-like environments, and when to stop hand-writing them

    If what you want is a heading with an auto-number, a counter that resets per section and a \label that works, amsthm already did it: \newtheorem{theorem}{Theorem}[section] plus \theoremstyle{definition} and \newtheoremstyle{…} for the spacing and head font. Writing your own counter machinery for this duplicates five features — shared numbering, resets, \@currentlabel, the QED box, and interaction with hyperref — and you will get two of them wrong.

    The \qedhere case is a good illustration of why existing environments are worth reading. In a proof ending with a displayed equation, the tombstone has to be placed inside the equation, not after it; amsthm exposes \qedhere for exactly that, and a hand-written environment has no such hook until you invent one.

    A useful habit: when a package environment is 90 per cent right, \renewenvironment the wrapper rather than rebuilding the frame. The law environment in the first listing on this page is a mdframed instance with a title line in the begin code — about six lines — while the same thing written from box primitives is a page of code and a permanent source of spacing bugs.

    Everything above has one shared cause. Environments feel like formatting, but they are code with a lifetime: a group that opens, a stream of material that arrives, and a closing action that runs in the scope the opening created. Picture those three things and the remaining pages of this stage — beamer overlays, book-class matter switching, build diagnostics — are all the same shape wearing different clothes.

    \boxed{\;\det(AB) = \det A\,\det B\;} \qquad \text{Proposition 2.4}
    \boxed{\;\det(AB) = \det A\,\det B\;} \qquad \text{Proposition 2.4}

    Lesson cheat sheet

    One key line of code from each section — jump to it or copy it straight from here.

    Section Key code
    \documentclass[11pt,a4paper]{article}
    \begin{aligned} u_{n} &\le L^{n}\, u_{0} \\ \lim_{n\to\infty} u_{n} &= 0 \end{aligned}
    \boxed{\;\det(AB) = \det A\,\det B\;} \qquad \text{Proposition 2.4}

    Common mistakes

    • Illegal parameter number in definition of \endlaw — the end code of a kernel environment cannot see #1. Stash the argument in a macro in the begin code, or use \NewDocumentEnvironment, where the end code does take the arguments.
    • \begin{qt} ended by \end{quote}. — a misspelled terminator, or an environment whose \end landed in a different box than its \begin. Fix the pair before touching anything else; the follow-on errors are noise.
    • Wrapping a long body in \fbox or minipage and then wondering why the page ends early. Boxed material cannot split; use framed, mdframed, or tcolorbox with the breakable key.
    • Forgetting \tcbuselibrary{breakable}, or setting height=… on a tcolorbox that also has breakable: the fixed size turns the frame back into a box and it overflows again.
    • Assuming a counter set inside an environment is local. \stepcounter is global, so numbering does leak — which is convenient for theorem numbers and surprising everywhere else.
    • Writing a blank line before \end{…} and then chasing the extra vertical space: the blank line is an empty paragraph inside the environment, measured against your end code's glue.
    • Grabbing an environment body with b but without +, so the first paragraph inside it raises Paragraph ended before … was complete.

    Questions about this lesson

    Can the end part of a newenvironment use the environment arguments?
    Not with the kernel \newenvironment: the end code is defined with a bare \def that takes no parameters, so #1 is an illegal parameter number. Store what you need in a macro inside the begin code and read it in the end code — the end code still runs inside the environment group, so it sees those definitions. \NewDocumentEnvironment from xparse allows both its begin and end code to use the arguments directly, which removes the workaround.
    Why does my LaTeX environment not break across pages?
    Because its begin code opens a box — \fbox, \parbox, minipage, \vbox, a fixed-height tcolorbox or a tikz node — and a box is one indivisible vertical list. Replace the box with a frame that the output routine draws per page: the framed package for a plain rule, mdframed when you want keyval options and split top and bottom skips, or tcolorbox with \tcbuselibrary{breakable} and the breakable key. Tables need a splitting table environment such as longtable rather than a frame.
    How do I add options like color and title to my own environment?
    Grab one optional argument and pass it to a key parser: declare keys with \define@key{family}{key}{code} from keyval and call \setkeys{family}{#1} at the start of the begin code. xkeyval adds \define@cmdkeys, \define@boolkeys and \presetkeys for defaults; a misspelled key then reports Package keyval Error: <name> not allowed. New code can use ltcmd with the = argument modifier plus LaTeX3 keys instead.
    What is the difference between newenvironment and NewDocumentEnvironment?
    Same two macros under the hood, different ergonomics. NewDocumentEnvironment declares arguments by type (o, O{...}, m, +b, s), lets the end code use the arguments, lets one default reference another argument, and controls longness per argument with +. The kernel form counts arguments numerically, makes the end code parameterless, and applies \long to everything or nothing depending on the star.
    Can a LaTeX environment access the text between begin and end?
    Yes, by grabbing it as an argument: end the xparse argument spec with b (or +b if the body has paragraphs) and the whole body arrives as one token list, which lets you repeat it, move it, or typeset it after the closing material. Use c for a verbatim collection. The price is that the body is read before the begin code runs, so the environment cannot split across a page and assignments made at the start are not visible during the grab.
    Should I write my own theorem environment instead of newtheorem?
    Usually no. amsthm already handles shared numbering, resets by section, label values, the QED symbol and hyperref interaction, and \newtheoremstyle lets you restyle spacing and head fonts. Write an environment when the structure is genuinely yours — a clause box, an exercise with a solution toggle — and when you need a theorem style that only differs in appearance, layer amsthm or tcolorbox rather than rebuilding counters by hand.

    Live playground: edit the LaTeX, see it render

    The preview updates as you type — break it on purpose to see how errors look.

    KaTeX error
    Try an example

    Keep reading

    Three ways into the same idea: the notation itself, the lesson that teaches it, and an article that applies it.