The command \@ifnextchar cannot be used in a \section and the like. It fails with a "TeX capacity exceeded" message. This is pretty clearly related to the recycling of the section name for the table of contents and/or page marks, as shown by the following minimal pair:
\documentclass{article}
\begin{document}
\makeatletter
\section[Safe command]{This: \@ifnextchar /{A}{B} works fine}
\section{This: \@ifnextchar /{A}{B} triggers an error}
The end.
\end{document}
I believe I have ruled out superficial name clashes, so I'm putting my hopes on robustness. Is there a robust version I can try out, or some other way around this limitation?
Notes
I've seen some discussion of the
expl3equivalent (e.g., here, but they don't discuss robustness.I'm actually using a self-constructed variant of
\@ifnextcharthat does not skip over whitespace, so ultimately I'm looking for a solution with the same property.This is all related to a bug report on gb4e, called to my attention by Alan Munn.
Edit:
Since apparently my minimal example was too minimal, here's the actual use case (still simplified):
In gb4e, ^ and _ are made into \active characters so that they can be used outside math mode. In order to switch in and out of math mode correctly, they need to check if the next command is also a sub- or super-script command, hence the call to \@ifnextchar (or really to a modified version, but that's irrelevant here).
\documentclass{article}
\makeatletter
\catcode`\_=\active
\catcode`\^=\active
\def_#1{\@ifnextchar^{\automath@two_{#1}}{\ensuremath{\sb{#1}}}}
\def^#1{\@ifnextchar_{\automath@two^{#1}}{\ensuremath{\sp{#1}}}}
% handle consecutive sub- and super- scripts:
\def\automath@two#1#2#3#4{\ensuremath{#1{#2}\relax #3{#4}}}
\begin{document}
\section{This A_B fails}
\end{document}

\@ifnextcharoutside a macro definition doesn't make much sense. Can you show a real example? – egreg Jun 13 '14 at 19:55\usepackage{etoolbox} \makeatletter \robustify\@ifnextchar \makeatother... – Werner Jun 13 '14 at 19:56gb4e.sty, and it's used to detect when a subscript is immediately followed by a superscript or vice versa. If there's a solution specific to use via a macro, that's all that's needed here. – alexis Jun 13 '14 at 20:05