5

This question already has an answer here:

Maybe a stupid question...but I often see the usage of \csname in code -- especially in packages. Can someone explain what its purpose is?

As far as I see it generates a new command based on an argument.

marked as duplicate by egreg, David Carlisle, Alan Munn, Mico, Jesse Jan 10 '14 at 12:30

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

Quoting from the TeXbook, p. 213 [part of Chapter 20, "Definitions (also called Macros)"]:

\csname ... \endcsname. When TeX expands \csname it reads to the matching \endcsname, expanding tokens as it goes; only character tokens should remain after this expansion has taken place. Then the "expansion" of the entire \csname ... \endcsname text will be a single control sequence token, defined to be like \relax if its meaning is currently undefined.

Several things to take away from this definition:

  • Whereas "ordinary" TeX macro names must consist of either exactly one non-letter character -- e.g., \,, \!, and \/ -- or one or more letters (more precisely, characters that have category code "letter" (11), usually A-Z and a-z) -- e.g., \relax and \kern -- the \csname ... \endcsname method lets you create macro names that can contain characters -- including whitespace and (isolated) backslash characters -- that are not be permitted by the rules of TeX syntax.

  • The main restriction on the use of the \csname ... \endcsname method is that what's between \csname and \endcsname must be expandable to yield "character tokens". Hence, unexpandable tokens (such as TeX "primitive" control sequence tokens, e.g., \kern and \vcenter) are not permitted.

There are many uses for this method.

3

Section 11.6 of TeX by Topic contains the following:

With \csname it is possible to construct control sequences that cannot ordinarily be written, because the constituent character tokens may have another category than 11, letter.

A simple example (again from TeX by Topic) is

\csname a b\endcsname

There are many other applications; often \csname and \endcsname are used in the automatic construction of macros.

2

\cs is only a command use to documente a command, in a handbook of package. It's used to :

  • change typo
  • index command
  • add automatically the backslash

If you want to create a command dynamically, you should use :

  • or \csname endcsname pair : \expandfter\def\csname toto\endcsname{content}. That create a \toto command.
  • or easier, use the \csdef command of the etoolbox package : \csdef{toto}{content}

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