Automatically add parentheses if expression is composite

I'm trying to write a macro which automatically adds parentheses to an expression if the argument is composite. Specifically, I would like to define a command for the inner product of two vectors using the $v\cdot w$ notation. So I would define

\newcommand{\inner}[2]{#1\cdot #2}


However, if one argument is a composite expression like \inner{v}{w_1+w_2}, the result should be $v\cdot(w_1+w_2)$. I would like the parentheses to be added automatically. The reason is that at some point later I might decide to switch to angle notation <v,w_1+w_2>, which would make the parentheses unnecessary.

I looked into packages like xstring to test for string length. However, I didn't get it to work with subscript expressions like $x_i$ (where no parentheses should be added).

Is something like this possible?

• Welcome to TeX.SX! It's only possible if you can give clear constraints about the sub-expressions that may occur as arguments for \inner. TeX's macro expansion system is Turing-complete, so you cannot decide in general if a term is composite or not. What types of sub-expressions should be supported? – siracusa Jul 30 at 13:17
• Thank you :-) Well, the most common would be sums and products of variables (which could themselves be defined in macros), so \inner{v,a\theta} should be parenthesized, while \inner{v,\myvar} for \newcommand{\myvar}{x_i} should not – Alexander Schlüter Jul 30 at 14:34
• Can you explain why Turing-completeness would be a problem? It seems like Turing-completeness would guarantee that we can write a macro \inner which does anything we want (after the expressions in the arguments of \inner are fully expanded) – Alexander Schlüter Jul 30 at 14:40
• If you restrict your command to fully expandable arguments, I think my comment about Turing-completeness doesn't apply. If we'd also allow arguments that need TeX's execution processor to yield the result, it seems impossible to decide whether the argument results in a single or composite expression. But for most documents this is just a theoretical problem anyway. – siracusa Jul 30 at 15:20

1 Answer

\documentclass{article}
\usepackage{xstring}
\newif\ifsum
\newcommand{\inner}[2]{%
\IfSubStr{#1}{+}{\sumtrue}{\sumfalse}%
\unless\ifsum
\IfSubStr{#1}{-}{\sumtrue}{\sumfalse}%
\fi%
\ifsum%
(#1)%
\else
#1%
\fi
\cdot%
\IfSubStr{#2}{+}{\sumtrue}{\sumfalse}%
\unless\ifsum
\IfSubStr{#2}{-}{\sumtrue}{\sumfalse}%
\fi%
\ifsum%
(#2)%
\else
#2%
\fi}
\begin{document}
$\inner{v}{w_1+w_2}$ $\inner{w_1+w_2}{v}$
\end{document}

• OP has also specified that implicit multiplication should get parentheses. But +1. – Teepeemm Jul 30 at 14:50