我在文档中创建了一些自定义命令,这样如果我更改变量,所有出现的情况都可以轻松更改。但是,我的一些命令变量包含在数学环境 ($$) 中。我在纯文本和方程式中使用它们。当我在方程式中使用它们时,我得到了Missing $ inserted. [ $\mycommand]
,大概是因为数学模式值第二次嵌套在数学模式中。以下是一个例子:
\documentclass[a4paper,12pt]{article}
\usepackage{xspace}
\begin{document}
\newcommand{\mycommand}{$my_{command}$\xspace}
Here is my \mycommand working fine.
Here is my \mycommand not working in math mode:
$\mycommand$
\end{document}
有办法解决这个问题吗?
答案1
对于使用数学模式但应该在数学模式和文本模式下工作的命令,您应该使用\ensuremath{…}
而不是$…$
:
\documentclass[a4paper,12pt]{article}
\usepackage{xspace}
\newcommand{\mycommand}{\ensuremath{my_{command}}\xspace}
\begin{document}
Here is my \mycommand working fine.
Here is my \mycommand working in math mode:
$\mycommand$
\end{document}
顺便说一句:为了将形式与内容分开,定义应该放在文档序言中,即之前\begin{document}
。
另请注意:在您的示例中,是、等command
的数学乘积。如果这不是有意为之,则应使用单个变量或使用或(需要包)作为文本。c
o
m
\mathit{command}
command
\mathrm{command}
\text{command}
amsmath
command
不过,我建议使用类似的东西:
\documentclass[a4paper,12pt]{article}
\newcommand{\mycommand}{\mathit{my}_{\mathrm{command}}}
\begin{document}
Here is my $\mycommand$ working fine.
Here is my $\mycommand$ working in math mode:
\[
\mycommand
\]
\end{document}
明确切换到数学模式来学习数学材料。或者:
\documentclass[a4paper,12pt]{article}
\usepackage{amsmath}
\usepackage{xspace}
\newcommand{\mycommand}{my\textsubscript{command}\xspace}
\begin{document}
Here is my \mycommand working fine.
Here is my \mycommand working in math mode:
\[
\text{\mycommand}
\]
\end{document}
如果命令不是数学而是文本。
答案2
\documentclass[a4paper,12pt]{article}
\usepackage{xspace}
\NewDocumentCommand{\mycommand}{}{\relax\ifmmode my_{command} \else $my_{command}$\xspace \fi}
\begin{document}
Here is my \mycommand working fine.
Here is my $\mycommand$ working fine.
Here is my \mycommand not working in math mode:
Here is my $\mycommand$ not working in math mode:
\end{document}