A command without brackets specifying the argument takes just the first element after it as an argument, so that a^bc will only have the superscripted b. I would like to exploit this with typeset functions in LaTex like \ln,\sin, and so on. In the case of just one argument, like \ln{a}bc or \ln abc, the function would not be typeset with parentheses. In the case of multiple elements in an argument, like \ln{abc}, there would be parentheses typeset around the argument, the triple product shown.

The motivation for this is the variable need for parentheses in logarithms and readibility of code. For example, I could write \ln{a + b} to unambigiously refer to the logarithm of a sum, and \ln ab to unambigiously refer to the logarithm of a product (by most conventions). Since the logarithm or other mathematical operator is only a standalone typeset, the spurious argument in the absence of bracketing (\ln ab would be equivalent to \ln{a}b) doesn't have an effect on the typesetting. This has an advantage in readibility, for example, contrast \ln\left(a + \frac bc\right) and \ln{a + \frac bc}.

How do I define a command which recognizes how many elements are in the argument and would add parentheses if there are more than one?

  • With xparse and mleftright loaded, you can do \let\lnop\ln \RenewDocumentCommand\ln{d()}{\lnop\IfValueT{#1}{\mleft(#1\mright)}}. That way you use \ln ab and \ln(a+b) and \ln(a+\frac bc). – Manuel Oct 7 '17 at 19:59

My solution uses \@gobble with a simple if-statement to test if a macro argument contains more than one character. There might be better ways to do this. Once you have a macro that adds parentheses on certain conditions, you can add it to any function with \g@addto@macro.

Here is a MWE with examples you mentioned:




$\ln ab$


$\ln{a + b}$

$\ln{a + \frac bc}$


ln with or without parentheses

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.