Parse and execute the next word as a command?

Assuming @ is a letter:

\def\csword{\def\csword@{}\@csword}
\def\@csword{\futurelet\next\@@csword}
\def\@@csword{\ifcat a\noexpand\next
  \expandafter\@@@csword
  \else\expandafter\expandafter\csname\csword@\endcsname\fi}
\def\@@@csword#1{\edef\csword@{\csword@#1}\@csword}

Edit: Removed a \expandafter from line 3. It is unnecessary, and causes the macro to fail in cases like \csword foo\bar.


I would use one of the keyval-packages (keyval, xkeyval, pgfkeys ...) and define keys optionA etc so that you can use them like this:

 \myfancycommand{optionA, optionB=[with]{args}, optionC={fun}}

On the off-chance that you'd like this to be expandable, here's another expl3 version. While this is longer than Harald's, I actually think it's more readable. On second thoughts: no, I think I'm just thinking that because I just wrote it :)

Slight downside: commands like f{o}o are executed as if they were foo. Which also means you can't have something like foo{A}, unfortunately. But foo{abc} is okay. Also, spaces mean nothing: foo foo is processed as \foofoo.

\documentclass{article}
\usepackage{expl3}

\ExplSyntaxOn
\cs_new:Npn \csword #1 {
  \cs:w \csword_aux:n #1
}
\cs_new:Nn \csword_aux:n {
  \tl_if_empty:nTF {#1}
  { \cs_end: } % e.g., '{}' in 'foo{}': end scanning
  {
    \tl_if_single:nTF {#1}
    {
      % e.g., 'o' in 'foo' or '{A}' in 'foo{A}' or '[' in 'foo[a]':
      \token_if_letter:NTF #1
      { #1 \csword_aux:n } % e.g., 'o' in 'foo'         : keep scanning
      { \cs_end: #1 }      % e.g., '[' in 'foo[a]'      : end scanning
    }
    { \cs_end: {#1} }      % e.g., '{abc}' in 'foo{abc}': end scanning
  }
}
\ExplSyntaxOff

\begin{document}

\newcommand\foo[1][opt]{[foo: #1]}
\newcommand\baz[2][opt]{[baz: #1/#2]}

\typeout{
\csword foo
\csword f{o}o
\csword foo{A}
\csword foo{ABC}
\csword foo[1]
\csword baz{2}
\csword baz{22}
\csword baz[333]{222}
}

\end{document}

I just bench-marked this against Harald's solution, and it's five times slower. So it's really of academic use only :)

Tags:

Macros