You should use \foreach
after doing
\usepackage{pgffor}
(or \usepackage{tikz}
). However there's a problem with \foreach
: each cycle is performed in a group, so you'd be including the files in a group, which might have undesired consequences.
Also \i
would be interpreted incorrectly if used in one of the files.
Solution:
\newtoks\listoffilestoinput
\foreach \i in {1,...,10}{%
\edef\temp{%
\the\listoffiles
\noexpand\InputIfFileExists{chapters/\i.tex}{}{}%
}%
\global\listoffilestoinput=\expandafter{\temp}
}
\the\listoffilestoinput
Don't forget the trailing arguments to \InputIfFileExists
Of course you can use \include
instead of \InputIfFileExists
, if you so prefer:
\newtoks\listoffiles
\foreach \i in {1,...,10}{%
\edef\temp{%
\the\listoffilestoinput
\noexpand\include{chapters/\i}%
}%
\global\listoffilestoinput=\expandafter{\temp}
}
\the\listoffilestoinput
Note that the extension should not be added with \include
(it is optional with \InputIfFileExists
, where .tex
is implicit if no extension is present).
You might even abstract this in a macro to be defined in the preamble.
\newtoks\listoffilestoinput
\newcommand{\multiinclude}[3][\i]{%
\global\listoffilestoinput={}% reinitialize
\foreach #1 in {#2}{%
\edef\temp{%
\the\listoffilestoinput
\noexpand\include{#3}%
%\noexpand\InputIfFileExists{#3}{}{}% alternative version
}%
\the\listoffilestoinput
}
Then in the document you can use
\multiinclude{1,...,10}{chapters/\i}
or also
\multiinclude[\ChapterNumber]{1,...,10}{{chapters/\ChapterNumber}
The first mandatory argument is the list for \foreach
, the second mandatory argument is the template. The optional argument (default \i
) is the variable to use.
Note that with this approach (independently of the form you use), the variable \i
is used just temporarily and has no side effects even if it is already defined (provided you don't use \foreach
or \include
as the variable name, of course); \i
is perfectly good for this purpose.
\ForEach
should be\foreach
.\foreach
(not\ForEach
), you have to add\usepackage{pgffor}
.\InputIfFileExists{filename}{true branch}{false branch}
, as far as I know (amongst\foreach
) of course