# Problem with text mode in \substack

I have defined a differential command in this way

\let\underdot\d
\renewcommand{\d}{\ifmmode\mathop{}\!\mathrm{d}\else\expandafter\underdot\fi}


so that I don't loose the text accent (I don't know how expandafter works, I put it there just after trial and error). But I have a problem, if I use \d as the first command in a substack, it gives me the text \d. Here is an example code:

\documentclass{scrartcl}
\usepackage{mathtools}

\let\underdot\d
\renewcommand{\d}{\ifmmode\mathop{}\!\mathrm{d}\else\expandafter\underdot\fi}

\begin{document}
$\substack{\d x = \sigma \d y}$
\end{document}


I don't know why this happens, may be my command is bad defined, or may be there is a bug in \substack (subarray). I can solve it with {}\!\d x = … but I would like to fix it globally.

### How can I fix that? Which is the best way to solve that (may be redefine the command \d in another way)?

-
A better definition of \underdot would be the (admittedly complicated) incantation \expandafter\let\expandafter\underdot\csname\encodingdefault\string\d\endcsname‌​ –  egreg Feb 10 '13 at 13:11
@egreg I don't have any more problems, but I believe you, and I will substitute the line \let\underdot\d by the one you provided (if I haven't misunderstood you, this is what you say, isn't it?). –  Manuel Feb 10 '13 at 13:22
The simpler \let\underdot\d might, under some circumstances, lead to infinite loops, because the expansion of \d refers to \d itself. When you redefine \d in terms of \underdot you could fall into one of those (rare) circumstances. –  egreg Feb 10 '13 at 13:51
The redefinition of \d is exactly the same as before; the \expandafter in it is for getting rid of \fi; in the complicated \let instruction it is for making \csname act before \let is executed. –  egreg Feb 10 '13 at 14:58
Ok. Thanks @egreg –  Manuel Feb 10 '13 at 15:00

You need to use \DeclareRobustCommand or put \relax at the start of your definition otherwise an \ifmmode test at the start of any alignment cell will be false as it is expanded before the cell starts (and math mode is entered) while TeX is looking for \omit (\multicolumn)