[Tex/LaTex] What does \do do

tex-core

I saw some code using \do and I would like to understand it, which to me means finding out what exactly \do does. However, I haven't been able to find it in any sort of reference manual, and it is, quite obviously, ungoogleable. I suspect it's part of basic TeX, but I'm not sure.

What does \do do and when would I use it? Where can I find it in the TeX or LaTeX documentation?

Best Answer

\do is short for \performsomeactiononanargument and is typically redefined depending on the action that needs to be performed.

For example, consider the verbatim environment (or \verb). We know that the verbatim environment allows you to use certain characters that are otherwise restrictive in their use or application, like $, \, ~, &, %, ... So, in order to set up the environment to treat these characters as characters and not their aforementioned special behaviour, \@verbatim does (see latex.ltx)

\let\do\@makeother \dospecials

where

\def\@makeother#1{\catcode`#112\relax}
\def\dospecials{\do\ \do\\\do\{\do\}\do\$\do\&%
  \do\#\do\^\do\_\do\%\do\~}

Therefore, \dospecials performs a bunch of category code changes (\do's). It's just a condensed notation that varies depending on the definition of \do. It's used in other contexts as well for a similar outcome.

etoolbox adopted this usage/notation for "performing some action on an argument" when processing a list of items. For example, when calling

\docsvlist{first,second,third,last}

\do is applied to each of the elements sequentially, as in \do{first}, \do{second}, \do{third} and \do{last}. This allows the user to (re)define what the meaning of \do is exactly. Here's an example:

enter image description here

\documentclass{article}

\usepackage{etoolbox}

\begin{document}

\begin{enumerate}
  \renewcommand{\do}{\item}
  \docsvlist{first,second,third,last}
\end{enumerate}

\noindent
\begingroup
\renewcommand{\do}[1]{\textbullet~#1 \quad}
\docsvlist{first,second,third,last}
\endgroup

\end{document}

In a very limited context, \do is sometimes used to delimit macro arguments. But in that context it makes literal sense, even though a completely different delimiter could have been used. One example of this is used in \@whilenum or as part of \@for (loop) constructions.