Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

What exactly do \csname and \endcsname do? What are their job?
I have glanced at the Texbook and some other books, but none of them was clear enough to me.
Can anyone please give a simple example to clarify this issue?

share|improve this question
6  
See TeX by Topic, section 11.6 –  Martin Schröder Dec 26 '11 at 22:26

5 Answers 5

up vote 70 down vote accepted

Normally, control sequence names are made only of letters or of one non-letter character.

A letter is, more precisely, a character having category code 11 at the moment the control sequence name is read. So, any character can become part of a control sequence name, provided we change its catcode before the definition and each usage.

With \csname...\endcsname we are freed from this limitation and every character can go inside them to form a control sequence name (of course, % is excluded because it disappears together what remains on the line before TeX is doing its work on characters).

However, this is not the main purpose of \csname...\endcsname. This construction is used to build commands from "variable parts". Think, for instance to LaTeX's \newcounter: after \newcounter{foo}, TeX knows \thefoo that is built precisely in this way. Roughly, what LaTeX does knows is

\newcommand{\newcounter}[1]{%
   \expandafter\newcount\csname c@#1\endcsname
   \expandafter\def\csname the#1\endcsname{\arabic{#1}}%
 }

so that \newcounter{foo} does the right job. It's more complicated than this, of course, but the main things are here; \newcount is the low-level command to allocate a counter. The \expandafter is just to build the control sequence before \newcount and \def see the token.

Inside \csname...\endcsname, category codes don't matter (with one main exception: active characters will be expanded if not preceded by \string, see final note). LaTeX exploits this in order to build control sequence names that users won't be able to access (easily). For example, the control sequence to choose the default ten point font is \OT1/cmr/m/n/10, which can be easily split internally (by the "reverse" operation that is \string) and is not available to the casual user.

Another important use is in environments: when you say \newenvironment{foo}, LaTeX really defines \foo and \endfoo. Upon finding \begin{foo}, LaTeX does some bookkeeping and then executes \csname foo\endcsname (that's why one can say also \newenvironment{foo*}); similarly, at \end{foo}, after some bookkeping LaTeX executes \csname endfoo\endcsname.

Other uses: \label{foo} will define control sequences based on foo via \csname...\endcsname that can be used by \ref.

When one says \csname foo\endcsname, LaTeX will look whether \foo is defined; if not, it will execute \relax and from then on (respecting grouping), \foo will be interpreted as \relax. An interesting usage for this feature is that one can say

\chapter*{Introduction}
\csname phantomsection\endcsname
\addcontentsline{toc}{chapter}{Introduction}

and keep hyperref happy if it's loaded, while doing nothing if the package is not loaded.

It's possible to give many other interesting uses of this trick. But one should always keep in mind that TeX does complete expansion of what it finds in that context and that only characters must remain. So

\csname abc\relax def\endcsname

is forbidden. But, after \def\xyz{abc},

\csname \xyz def\endcsname

will be legal and equivalent to saying \csname abcdef\endcsname or \abcdef.

Final note

It's better to add something about category codes. An active character in \csname...\endcsname will be expanded, so to get a literal ~ one has to write \string~. Comment (category 14), ignored (category 9) and invalid (category 15) characters will remain such. So

\csname %\endcsname

will give an error (Missing \endcsname); in \csname ^^@\endcsname there will be no character and \csname ^^?\endcsname will raise an error.

share|improve this answer
    
Braces don't need to be balanced. \expandafter\show\csname{\endcsname works fine with usual catcodes. Otherwise, very good response. –  Bruno Le Floch Dec 27 '11 at 2:03
    
@BrunoLeFloch Right; they have to be balanced only if used to surround arguments to macros, of course. –  egreg Dec 27 '11 at 10:37

For reference, from the TeX Book (with slight formatting changes), Chapter 7: How TeX Reads What You Type (p 40):

...you can go from a list of character tokens to a control sequence by saying \csname<tokens>\endcsname. The tokens that appear in this construction between \csname and \endcsname may include other control sequences, as long as those control sequences ultimately expand into characters instead of TeX primitives; the final characters can be of any category, not necessarily letters. For example, \csname TeX\endcsname is essentially the same as \TeX; but \csname\TeX\endcsname is illegal, because \TeX expands into tokens containing the \kern primitive. Furthermore, \csname\string\TeX\endcsname will produce the unusual control sequence \\TeX, i.e., the token <\TeX>, which you can't ordinarily write.

I have used this indirectly by using the \label-\ref system and defining labels based on counters:

\newcounter{mycount}
%...
\newcommand{\mycmd}{%
  \stepcounter{mycount}%
  \label{abc\themycount}%
  %...
}

This creates a "successive label abc1, abc2, ... for every call to \mycmd, in order to avoid creating multiply defined labels with the same name. Indirectly, \label{abc\themycount} calls \@namedef{r@abc\themycount}, which calls

\expandafter\def\csname r@abc\themycount\endcsname

thereby expanding r@abc\themycount to r@abc1 and defining \r@abc1 for the first label, \r@abc2 for the second label, etc. Yes, labels in LaTeX are actually control sequences prepended with r@ and is constructed using \csname ... \endcsname which then allows numerals.

share|improve this answer

\csname/\endcsname allows you to build commands whose names contains 1. non-letters (e.g. dots or colons or numbers) and - more importantly - 2. commands which are expanded when you define or use the command. Both is useful if you want to construct a command name from various pieces of informations.

As an example: The xskak-Package loops through the notation of a chess game and stores a lot of informations of every move in commands. Its code contains a lot of definition of this type:

\expandafter\xdef
     \csname Xskak.\xskak@val@gameid.\the\c@move.\WhiteToMove{w}{b}.piece\endcsname{%
      ....
      }

where \xskak@val@gameid is the id of the current game, \the\c@move gives the current move number, \WhiteToMove{w}{b} gives w or b depending on which player currently moves. So in the 10th move of black in the game with id "mygame" this \xdef defines a "command" \Xskak.mygame.10.b.piece which contains the name of the piece which has been moved by black in the tenth move.

share|improve this answer

Suppose you want to define a command \foo2. You cannot do this because 2 is not a letter. However, this construction works: \csname foo2\endcsname. Sometimes this is useful, e.g. when you need a series of commands, \foo1, \foo2, etc (another way is to use roman numerals). Another example, suppose you want to define a series of commands like \endsection, \endsubsection, etc. Then you can use a loop with \expandafter\def\csname end#1\csname...

share|improve this answer
    
Thanks for your example, but can you tell me what generally their job are? When and where do I need to use them? –  Vahid Damanafshan Dec 26 '11 at 22:35
3  
Well, @egreg beat me to it. Basically a TeX command is either (1) a sequence of letters starting from `, e.g. \parskip`, or (2) a special symbol optionally preceded by a backslash, e.g. \@, and (3) any sequence of symbols between \csname and \endcsname. So the job of these commands is to introduce a way to produce TeX commands. You do not need to use them unless you do TeX programming. In the latter case they are handy. –  Boris Dec 26 '11 at 23:34

Short answer: \csname and \endcsname are a "macro environment" whose contents, if they evaluate (after expanding macros) to "ordinary text", are converted into the name of a macro (or control sequence, hence "csname").


Actually, it is a perhaps strange joke that by the rules of LaTeX macros, you can actually write \begin{csname}...\end{csname} and it will act as you expect, to a certain extent. For example:

\def\macro{text}
\def\o{o}
\begin{csname}%
 macr\o
\end{csname}
% Same as \csname macr\o \endcsname

(when run with latex rather than tex) will produce the word "text" in the output. The % sign is there so that unnecessary spaces don't creep into the name of the macro we are constructing.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.