5

I am trying to create a paired delimiter command that will work outside of text mode. I was not able to accomplish this simply by defining a new command with \ensuremath, so I've resorted to the use of \ifmmode and \@ifstar instead; however, the code (given below) does not run as expected. Does anyone know how to accomplish this? (I would prefer it if the command were to be defined through \DeclarePairedDelimiter or its variants \DeclarePairedDelimiterX and \DeclarePairedDelimiterXPP.)

I realize it's often considered bad practice to rely on code such as \ensuremath, but I'm mostly just doing this for the TeXnical learning experience.

\documentclass[12pt, reqno]{amsart}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{xparse}
\usepackage{mathtools}
\usepackage[version=3]{mhchem}

\makeatletter
\DeclarePairedDelimiterXPP{\conctext}[1]{\(}{\lbrack}{\rbrack}{\)}{\ce{#1}}
\DeclarePairedDelimiterX{\concmath}[1]{\lbrack}{\rbrack}{\ce{#1}}
\newcommand{\conc}{\ifmmode \@ifstar\concmath*\concmath
                    \else   \@ifstar\conctext*\conctext
                    \fi
}
\makeatother
\begin{document}
The molarity is calculated from \conc{NaOH}, \conc{H3O+}, and \conc{OH-}.
\end{document}
  • What's to keep you from telling LaTeX that \conc has one argument and it must be placed between your \concmath and \conctext macros? \newcommand{\conc}[1]{\ifmmode \@ifstar\concmath* #1\concmath\else \@ifstar\conctext* #1\conctext\fi}? – 1010011010 Dec 20 '14 at 10:12
  • Do you really need growing delimiters around \ce{...}? – egreg Dec 20 '14 at 10:37
3

A simpler approach with xparse:

\documentclass[12pt, reqno]{amsart}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{xparse}
\usepackage{mathtools}
\usepackage[version=3]{mhchem}

\DeclarePairedDelimiter{\cebrack}{[}{]}
\NewDocumentCommand{\conc}{sO{}m}{%
  \IfBooleanTF{#1}
   {\ensuremath{\cebrack*{\ce{#3}}}}
   {\ensuremath{\cebrack[#2]{\ce{#3}}}}%
}

\begin{document}
The molarity is calculated from \conc{NaOH}, \conc{H3O+}, and \conc{OH-}.

Test: \conc{H3O+}, \conc*{H3O+}, \conc[\big]{H3O+}, \conc[\Big]{H3O+}.

Test: $\conc{H3O+}, \conc*{H3O+}, \conc[\big]{H3O+}, \conc[\Big]{H3O+}$.

\end{document}

enter image description here

By the way, this is, in my opinion, a legitimate usage of \ensuremath.

  • (Thanks, I mentioned \ensuremath largely due to your comments regarding its improper usage.) Does your code correctly account for the use of a star argument? – Bob Dec 20 '14 at 12:05
  • I'm thinking \IfBooleanTF{#1}{\ensuremath{\cebrack*{\ce{#3}}}}{\ensuremath{\cebrack[#2]{\ce{#3}}}}, but I could be mistaken. – Bob Dec 20 '14 at 12:07
  • 1
    @Anthony You're correct! I forgot the *. Fixed. – egreg Dec 20 '14 at 12:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.