1

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.

bill999
  • 463

1 Answers1

2

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

intended for formatting email addresses, hypertext links, directories/paths, etc.

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

enter image description here

Qrrbrbirlbel
  • 119,821