LaTeX: expandafter, csname…endcsname

Some straightforward examples that help think clearly about the commands in the subject line.

The theory

From the reference given at the bottom:

\expandafter is usually followed by calls to two macros. It expands the first macro following it only after it has expanded the second.

\csname ...\endcsname is an alternative way to define and invoke a \TeX command. It takes tokens and turns them into a control sequence.

*.tex

\documentclass{article}
\usepackage[english]{babel}
\def\foo{\csname LaTeX\endcsname}
\expandafter\def\csname bar\endcsname{\LaTeX}
\expandafter\def\csname qu#\endcsname{\LaTeX} %oddly enough
\begin{document}
\noindent
\csname LaTeX \endcsname\\ %1
\foo\\ %2
\bar\\ %3
\csname qu#\endcsname\\ %4 But can't do \qu#
\end{document}

Display

\LaTeX
\LaTeX
\LaTeX
\LaTeX

Remarks

  • Amy Hendrickson, Getting TEXnical: Insights into TEX Macro Writing Techniques, TUGboat, Volume 11 (1990), No. 3|1990 Conference Proceedings
  • \LaTeX support by WordPress.com
About these ads

2 Responses to LaTeX: expandafter, csname…endcsname

  1. The LaTeX kernel provides a wrapper around this:

    \makeatletter
    \@namedef{qu#}{\LaTeX}
    \@nameuse{qu#}
    \makeatother
    

    ConTeXt also provides similar wrapper around these: \setvaue and \getvalue.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s