[Tex/LaTex] New math command with alternative definition for inline mode

macrosmath-mode

I'm interested in writing a command which would result in output that varies when called within $...$ tags and when called within, say, displaymath environment.

For instance, assume that I want to define \xnorm command which works as

\newcommand{\xnorm}[1]{\|#1\|}

when called in the inline mode and which works as

\newcommand{\xnorm}[1]{\Big\|#1\Big\|}

when called in the "usual" math mode. How to achieve this?

I know that there exists a control sequence like ifmmode, but it tests whether I am in any type of math mode. Are there any more specific control sequences? Or, is there any other solution?


Question answered. The goal can be achieved with \mathchoice command. An example code snippet can be found below, in the answers to this post. Thanks all very much.


Nevertheless, it is worth a warning to others who have ideas similar to mine that math layout generated by \mathchoice can differ with the original one.

For example, try the following two functions:

\newcommand{\xnorma}[1]{\Big\|#1\Big\|}

and

\newcommand{\xnormb}[1]{\mathchoice{\Big\|#1\Big\|}{}{}{}}

(the first argument of \mathchoice provides a definition for "usual" math mode, other arguments do not play role in this example).

Now, simply try

\begin{document}
\begin{displaymath}
\xnorma{x^2}^2 \xnormb{x^2}^2
\end{displaymath}
\end{document}

A difference will be visible.

Best Answer

I don't think you really wants this. However, here it is:

\documentclass{article}
\usepackage{amsmath}

\newcommand{\xnorm}[1]{%
  \mathchoice{\Bigl\|#1\Bigr\|}{\lVert#1\rVert}{\lVert#1\rVert}{\lVert#1\rVert}%
}

\begin{document}
A norm in text mode is $\xnorm{v}$, while in display math it is
\[
\xnorm{v}=\sum_{i=1}^n\lvert v_i\rvert
\]
\end{document}

The result is really ugly (and wrong):

enter image description here

If you change \Bigl and \Bigr with \bigl and \bigr you get a more acceptable result, but I can't see the point of increasing the fences' size.

enter image description here

Related Question