1

I have several files in the sub-folder ./tmp -- "a.tex" whose content is \def\aaa{aaa}, "b.tex" whose content is `\def\bbb{bbb}.

Then I input them to my main doc at one time by \foreach, as the following code tries, but it fails to work, and causes error message Undefined control sequence..

What shall I do?

Code:

\documentclass{article}
\usepackage{pgffor}
\foreach \x in {a.tex,b.tex}{
  \input{tmp/\x}
  }
\begin{document}
\aaa\bbb
\end{document}
lyl
  • 2,727

3 Answers3

3

The simplest way around the problem is to use OpTeX. It provides ts own expandable \foreach without inserting groups:

\foreach{a.tex}{b.tex}\do{\input{tmp/#1}}

If you are not using OpTeX then you can create your own macro using TeX primitives:

\def\forfiles#1{\ifx\relax#1\else \input{tmp/#1}\expandafter\forfiles\fi}
\forfiles{a.tex}{b.tex}\relax

You need not any expl3. The proposed solution uses no grouping.

wipet
  • 74,238
  • Elegant solution! Thank you. And how to modify it to make tmp as an optional argument? – lyl Jun 16 '22 at 07:21
1

I am also new to latex3. This is a method to manipulating items in token lists.

\begin{filecontents*}{a.tex}
\def\aaa{aaa}
\newcommand{\ddd}{ddd}
\end{filecontents*}
\begin{filecontents*}{b.tex}
\def\bbb{bbb}
\end{filecontents*}
\begin{filecontents*}{c.tex}
\def\ccc{ccc}
\end{filecontents*}
\documentclass{article}
\ExplSyntaxOn
\tl_new:N \tl__myfiles
\tl_set:Nn \tl__myfiles {{a.tex}{b.tex}{c.tex}}
\tl_map_variable:NNn \tl__myfiles \x {\input{\x}}
\ExplSyntaxOff
\begin{document}
\aaa\bbb\ccc\ddd
\end{document}
Tom
  • 7,318
  • 4
  • 21
1

The simplest way around the problem is to use expl3:

\documentclass{article}

\ExplSyntaxOn \NewDocumentCommand{\multiinput}{O{.}m} {% #1 = common prefix, default . for the current directory % #2 = list of file names \clist_map_inline:nn { #2 } { \input{#1/##1} } } \ExplSyntaxOff

\begin{document}

\multiinput[tmp]{a,b}

\fooA

\fooB

\end{document}

In the subdirectory tmp I put

% file a.tex
\newcommand{\fooA}{A}

\fooA

and

% file b.tex
\newcommand{\fooB}{B}

\fooB

Compiling the main file above produces

enter image description here

With \foreach every cycle in the loop is processed inside a group, which is the reason why definitions inside the \input files don't survive. The proposed solution uses no grouping.

egreg
  • 1,121,712