[Tex/LaTex] Problem with \newcommand and \text

amsmathlyxmacrosmath-mode

I'm having a problem with \newcommand. Below is my LyX document where the first line comes from the "Insert-Latex" command and the second line is using the "Insert-Math-Inline Formula"

 \newcommand{\kon}{k_\text{on}}
 \kon

When I compile the document using "View PDF" I get this error

 Undefined control sequence
 Description:
  $\kon
      $
 The control sequence at the end of the top line
 of your error message was never \def'ed. If you have
 misspelled it (e.g., `\hobx'), type `I' and the correct
 spelling (e.g., `I\hbox'). Otherwise just continue,
 and I'll forget about whatever was undefined.

The weirdest part is that I've used this exact macro in other LyX documents and it works fine. If I remove the \text part, it also works fine. What's going on?

Best Answer

You need amsmath to be loaded in order to use \text. And the default setting for LyX is to "load [it] automatically". However, this automated loading requires you to use some amsmath-related environment (see Insert > AMS *), and unfortunately defining \text in a \newcommand doesn't invoke this loading.

You can change this choice so that amsmath is "load[ed] always" via Document > Settings... > Math Options > amsmath > "load always":

enter image description here

Note that LaTeX, like most programming languages, provides some form of scope to its definitions. So, if you Insert > TeX Code somewhere inside a table (just as an example) with the code being \newcommand{\kon}{k_\text{on}}, that macro - \kon - will only have a limited scope within the table environment. That's why it is usually best to insert definitions inside the Document > Settings... > LaTeX Preamble. Alternatively, you can always create your own definitions in a separate .style or .inc file that you include.

Related Question