
當我使用 定義環境時\newenvironment
,我可以newcommand
在「之前」部分內使用,以使命令可用於環境內的程式碼。
這可以透過簡單的命令實現嗎?換句話說,我可以建立一個命令,以便使用者可以在參數中使用外部未定義的巨集嗎?
範例:假設我想編寫一個命令\set
來排版數學集定義,並且我希望\suchthat
在內部使用一個命令,如下所示:
\set{x\in X \suchthat x > 42}
這很簡單,但我希望該\suchthat
命令僅在 的參數內可用\set
。
答案1
您可以將命令定義為
\newcommand\set[1]{%%
\begingroup
\def\suchthat{... some definition...}%%
... other macro content ....
\endgroup}
這將\suchthat
在巨集內部可用。
您可以使用\bgroup
and來完成此操作\egroup
,但這會建立一個子公式,該子公式會影響在數學模式下使用時如何處理間距。和\begingroup
此處\endgroup
本地化新宏的定義。您可以使用以下任意命令來定義本機命令\def
、\edef
和\newcommand
。
按照@barbarabeeto的建議,你可以在序言中做這樣的事情:
\makeatletter
\def\ae@suchthat{... definition of such that ...}
\newcommand\aset[1]{%%
\let\suchthat\ae@suchthat
the body of the macro: #1
\let\suchthat\undefined
}
\makeatother
這好多了。除了 barbarabeeto 建議的原因之外,這還允許您的巨集(如果您願意的話)定義或設定您稍後可能想要在文件中存取的值。透過這種\begingroup/\endgroup
方法,這些都必須全球化,這可能不是您想要的。
混合方法可能看起來像
\makeatletter
\def\ae@suchthat{... definition of such that ...}
\newcommand\aset[1]{%%
\begingroup
\let\suchthat\ae@suchthat
the body of the macro: #1
\endgroup
}
\makeatother
答案2
A. Ellett 的建議很好,但這種方法有一些微妙之處。
\bgroup
用and本地化定義\egroup
是不好的,因為\set
巨集顯然是在數學模式中使用的。這樣的構造將形成一個子公式,其結果是空間被凍結並且不參與直線上的拉伸和收縮;使用\begingroup
並且\endgroup
不會遇到這個問題。無論如何都必須給出的預設定義
\suchthat
,因為您可能碰巧需要\suchthat
在節標題中。出於同樣的原因,這兩個命令都應該變得健壯。
這是一個實現。
\documentclass{article}
\usepackage{etoolbox}
\makeatletter
\newrobustcmd{\suchthat}{%
\@latex@error{Use \noexpand\suchthat only in \string\set}
{You are allowed to use \noexpand\suchthat only in the\MessageBreak
argument of \string\set}%
}
\newcommand\giga@suchthat{\mid}
\newrobustcmd{\set}[1]{%
\begingroup
\let\suchthat\giga@suchthat
\{\,#1\,\}%
\endgroup
}
\makeatother
\begin{document}
\tableofcontents
\section{The set $\set{x\in X \suchthat x>42}$}
Let's study $\set{x\in X \suchthat x>42}$.
\suchthat
\end{document}
終端機中的輸出:
! LaTeX Error: Use \suchthat only in \set.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.27 \suchthat
? h
You are allowed to use \suchthat only in the
argument of \set
輸出