I'm sorry if the title suggests a question that has been asked a lot of times (see below), but I couldn't find an answer that also fulfills another need...
As a math teacher, I want my students to get used (at least at the beginning) to always write parenthesis around functions like cos, sin, tan, log, ln, etc., so to have cos(x) instead of cos x. I therefore wanted my LaTeX files to always put (...) around those functions automatically, by calling them as \cos{x}.
For this, I already found more than one question/answer that allows me to achieve this, e.g.
I chose the following version from the first link:
\makeatletter
\newcommand*{\redefinesymbolwitharg}[1]{%
\expandafter\let\csname ltx#1\expandafter\endcsname\csname #1\endcsname
\@namedef{#1}{\@ifnextchar{^}{\@nameuse{#1@}}{\@nameuse{#1@}^{}}}%
\expandafter\def\csname #1@\endcsname^##1##2{%
\csname ltx#1\endcsname\ifx!##1!\else^{##1}\fi\mathopen{}\mathclose\bgroup\left(##2\aftergroup\egroup\right)
}%
}
\makeatother
and then call for example
\redefinesymbolwitharg{cos}
The above code allows me to write
\cos x + \cos{y} + \cos^{2}{z} + \cos^3{k}
by always adding the bracket around the argument, but not to write
\cos_a{x}
Trying to understand the above code, I see that the @ifnextchar{^} case is specifically handled, but I've not been able to also integrate the "_" case, necessary for e.g. the \log function. Could someone help me to add this functionality to the above code (or suggest another way of achieving this?).
Thank you in advance for any suggestion! :)
Bonus question:
Would it also be possible to integrate the case \cos'{x} to be converted in \cos^{'}{x}, and so on for ' ' and ' ' ' ? This is not mandatory, but would improve the writing of a lot of lines...
\cos{y}
why not simply use parens instead\cos(y)
it requires no definition and is much less likely to conflict with other math macro packages, and requires just the same number of characters in the input? – David Carlisle Apr 14 '20 at 19:45f^{'}
. See difference between \prime and'
in math mode – barbara beeton Apr 14 '20 at 23:32