0

I'm trying to make an environment that wraps a for loop:

\documentclass{article}
\usepackage[utf8]{inputenc}

\title{Testing} \author{This is a Name} \date{June 2022} \usepackage{pgfplots} \pgfplotsset{compat=1.18} \begin{document}

\maketitle

\newenvironment{fora}{ \pgfplotsforeachungrouped \i in {0,1,...,5} { } { } } \begin{fora} \textit{meow} \end{fora}

\end{document}

I get this error on overleaf at \end{fora}:

Missing \endcsname inserted.
TeX capacity exceeded, sorry [input stack size=5000].

My intended goal was for "meow" to be printed 5 times. Any ideas on what is wrong? I'm guessing it's an issue related to the nested curly brackets.

2 Answers2

2

You seem to be trying something like

\newcommand{\mycommand}[1]{something with #1}

\newenvironment{fora} {\mycommand{}% begin part {}}% end part

where the { in the begin part should be matched by the } in the end part.

Sorry, no, it cannot work: a “begin part” like that would have unmatched braces and, actually, TeX matches them in a way that you might find surprising, but it isn't.

What you maybe want is to grab the environments content and to pass it to the macro.

\documentclass{article}
\usepackage{pgfplots}

\pgfplotsset{compat=1.18}

\NewDocumentEnvironment{fora}{+b} {\pgfplotsforeachungrouped \i in {0,1,...,5} {#1}} {}

\begin{document}

\begin{fora} \textit{meow} \end{fora}

\end{document}

The argument type b roughly means “make #1 to be the whole content of the environment, after stripping off leading and trailing spaces”; the + prefix means that blank lines are allowed in the environment.

enter image description here

A few other comments:

  1. inputenc is no longer necessary, if the input files are UTF-8

  2. first load packages, then do declarations. Stating \title before \usepackage{pgfplots} makes it hard to find things during document maintenance

  3. declare your commands and environments in the preamble, not after \begin{document}

egreg
  • 1,121,712
0

To understand the error it helps to indent the input to better show the structure

You get the same error from

\documentclass{article}
\usepackage[utf8]{inputenc}

\title{Testing} \author{This is a Name} \date{June 2022} \usepackage{pgfplots} \pgfplotsset{compat=1.18} \begin{document}

\maketitle

\newenvironment{fora} {\pgfplotsforeachungrouped \i in {0,1,...,5} {} {}} \begin {fora}

\textit{meow} \end{fora}

\end{document}

which can be simplified to

\documentclass{article}

\begin{document}

\newenvironment{fora} {} \begin

\end{fora}

\end{document}

So the begin code of the evironment was loop with a empty body (but this is never called so I demonstrate an empty begin code here)

the end code of the environment is \begin

so \end starts by inserting \begin and you get an internal loop of unwanted expansions.

David Carlisle
  • 757,742