# Allow special character (underscore) in loop (using pgffor)

I would like to allow special characters (in my case, an underscore) to be displayed in a loop.

Say I have this MWE:

\documentclass[12pt]{article}
\usepackage{pgffor}

\begin{document}
\foreach \g in {ab, cd}{
\g
}

\end{document}


This works, and prints ab cd.

However, if I instead tweak cd in the loop to be c_d, I get an error.

\documentclass[12pt]{article}
\usepackage{pgffor}

\begin{document}
\foreach \g in {ab, c_d}{
\g
}

\end{document}


Error:

Missing \$ inserted.


Now, normally, I would just write c_d as c\_d, but I can't do so given the loop. Is there a workaround? Perhaps a function that allows the special characters to be displayed? Note that in my application, I would like to be able to print c_d in a figure caption or in a subsection.

• Why can't you use c\_d in the loop? \foreach \g in {ab, c\_d}{ \g} works for me. Dec 6, 2022 at 17:40
• Admittedly, that does work for my MWE. But in my actual application I also need to open a file based on \g. I get this error if I replace c_d with c\_d: Missing endcsname inserted <to be read again> protect Dec 6, 2022 at 18:05
• Then we need more information on what you are trying to do. \foreach might not be the right tool for the job to begin with. It will also depend on what “opening a file” entails. Dec 6, 2022 at 18:27
• That's fair, and don't feel like you need to answer questions I didn't ask! (By opening a file, I just mean \includegraphics.) Dec 6, 2022 at 18:33

Using _ as part of a filename for \includegraphics works inside the body of \foreach without extra work.

Typesetting that name will be trouble but the url package can handle that for you. Despite it name it is also

You can use the \urlstyle command to change the font of the “url”: tt (default), rm, sf or same.

Here, I have used \DeclareUrlCommand so that you have a purposeful \mygraphicsfile command that acts just as \url but with the same font as the surrounding text (if that's what you want).

The \expandafters are needed so that the package doesn't assume \g to be the url/filename.

## Code

\documentclass[12pt]{article}
\usepackage{pgffor}
\usepackage{graphicx}
\usepackage{url}
\DeclareUrlCommand\mygraphicsfile{\urlstyle{same}}
\begin{document}
\foreach \g in {ab, c_d}{%
Name \expandafter\mygraphicsfile\expandafter{\g}: \includegraphics[width=3cm]{\g}
\par
}
\end{document}


## Output

• You might be able to use \_ in the loop when you do \renewcommand*\_{_} only for the \includegraphics. Dec 6, 2022 at 19:13