10

I'd like to define a macro which expands to (#1) if #1 does not contain any parentheses, but expands to \big(#1\big) if it does.

I'd choose simplicity over generality: if a solution works in the most obvious use cases (i.e. \foo{x} and \foo{\sin(x)}, that would be enough for me. What's the easiest way to scan a macro argument for specific characters like this? Is there some package which already defines a ready-to-use “if stuff contains given character” kind of macro? Is there something useful in the LaTeX3 packages which are already available?

As an alternative to my approach, I'd also welcome some existing alternative to \left(#1\right) which ensures that the size chosen for the delimiters will always be bigger than the biggest size in the content, not merely as big as the content. I don't know if such a thing does exist, but if it does, it sure would be a useful thing, which could solve my above problem and a number of other ones besides.

0

1 Answer 1

6

Here's a little example using the xstring package.

screenshot

\documentclass{article}
\usepackage{xstring}

\newcommand{\mycommand}[1]{%
\StrCount{#1}{(}[\parenthesiscount]
    \ifnum\parenthesiscount>0
        \StrSubstitute{#1}{(}{\left(}[\newstring]%
        \StrSubstitute{\newstring}{)}{\right)}%
    \else
        #1
    \fi}
\begin{document}

$\mycommand{23}$

$\mycommand{\sin(x)}$

$\mycommand{(\frac{1}{2})}$

$\mycommand{((\frac{1}{2}))}$

$\mycommand{\cos(\frac{1}{3})}$

\end{document}

The idea is to count the number of (, and operate on the string if the count is greater than 0. If you don't like the spacing given by \left( and \right, you might like to look into the mleftright package.

2
  • Not quite what I had in mind in terms of the use case, but easy enough to adjust. I was aiming for a setup where the parentheses of the macro will always be one step bigger than those of its argument, but could restrict myself to the case where the argument either has no parentheses at all, or simply normal sized ones.
    – MvG
    May 19, 2013 at 17:25
  • @MvG great, glad it helped :)
    – cmhughes
    May 19, 2013 at 19:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .