[Tex/LaTex] Macro only to be defined in math mode

macrosmath-mode

I often use short macros in mathematical formulas for frequently used symbols, e.g. \d x for a differential dx or, say, \v if I need a vector v very often in my text to make things more readable.
However, I get a clash with predefined macros because \d stands for a dot under the next character and v for the hacek accent, which I don't want to override (maybe I need them in the bibliography…).

So, I came up with the following to override those macros only in math mode:

\documentclass{article}

\usepackage{everyhook}
\newcommand{\mathdef}[2]{%
  \PushPostHook{math}{\expandafter\def\csname #1\endcsname{#2}}%
  \PushPostHook{display}{\expandafter\def\csname #1\endcsname{#2}}}
\mathdef{d}{\mathrm{d}}%

\begin{document}
  \d x  is an x with a dot below and $\int f(x) \d x$ is an integral over $x$.
\end{document}

However, I would like the command to be defined like normal macros too, i.e. \mathdef{\d}{\mathrm{d}}, and also be able to take arguments, but all my experiments with expandafter, unexpanded, etc. didn't work out and led only to the usual strange error messages. Any hint how I can do that?

Furthermore, do you think there is a big performance penalty using \everymath like that in a large document?

Best Answer

My idea is very similar to egreg's, but I'd like to add an optional argument, so the math command could process arguments itself. The code:

\documentclass{article}

\usepackage{xparse}
\DeclareDocumentCommand{\mathdef}{mO{0}m}{%
  \expandafter\let\csname old\string#1\endcsname=#1
  \expandafter\newcommand\csname new\string#1\endcsname[#2]{#3}
  \DeclareRobustCommand#1{%
    \ifmmode
      \expandafter\let\expandafter\next\csname new\string#1\endcsname
    \else
      \expandafter\let\expandafter\next\csname old\string#1\endcsname
    \fi
    \next
  }%
}

\mathdef{\v}[1]{\tilde{#1}}
\mathdef{\d}{\mathrm{d}}

\begin{document}
Ha\v{c}ek and tilde $\v{a}+\v{b}=1$.

\d x  is an x with a dot below and $\int f(x) \d x$ is an integral over $x$.
\end{document}

The result:

enter image description here

Related Question