TeX/def
外觀
< TeX
\def <命令> <引數文字>{<替換文字>}
\def 允許您定義新的宏。命令必須以跳脫字元開頭(類別程式碼 0)並且由一系列字母組成(類別程式碼 11)或一個非字母字元,緊隨跳脫字元。(例如,\delta 或 \{。)或者,<命令> 可以是活動字元(類別程式碼 13)。然後,引數文字告訴 TeX 被定義的命令的有效語法;此外,在引數文字中,可以包含引數(用 #1 等表示,最多 #9),這些引數可以在替換文字中重複使用。例如,在
\def \foo [#1]#2{The first argument is ``#1'', the second one is ``#2''}
第一個引數必須用兩個方括號分隔,而第二個引數可以是單個字元(嚴格來說,單個標記具有與 1 或 2 不同的類別程式碼)或用大括號 {...} 包含的任何平衡文字。最後,替換文字告訴 TeX 命令應該擴充套件到什麼以及如何處理任何引數(參見上面的示例)。
注意,引數文字之後不應該有任何空格。如果您定義的命令跨多行,可以使用 % 字元,例如
\def \foo [#1]#2%
{The first argument is ``#1''.
The second one is ``#2''}
與 LaTeX(使用 \newcommand)相反,TeX 不檢查要定義的命令是否重要。您可能想說 \def \def 等,但最有可能的是您很快就會遇到一些問題。在這方面保持安全的另一種方法是寫入
\ifx <command> \undefined \def <command> . . . \fi
\def 可以用 \global 替換(重新定義不受當前組限制,也受 \globaldefs 控制),\long(該命令接受長引數),\outer(該命令在高速讀取的程式碼部分中不被容許)。
這定義了一個簡單的快捷方式
\def \NAS {National Academy of Science}
\def \author {William {\sc Smith}}
這定義了一個引用環境
\def \beginquote {\par \begingroup \narrower}
\def \endquote {\par \endgroup}
一個帶有 \def 的一個小測試器,它帶有一個引數,以及帶有兩個引數的 \def,可以在沒有排版的情況下執行(例如,可以貼上在 pdflatex shell 中(\end{document} 被省略,因此 shell 在執行貼上的程式碼後保持開啟狀態))
\documentclass{article}
\begin{document}
% one arg def:
\def\testonearg[#1]{\typeout{Testing one arg: '#1'}}
%call:
\testonearg[test this]
% two arg def:
\def\testtwoarg[#1]#2{\typeout{Testing two args: '#1' and '#2'}}
%call:
\testtwoarg[test this first]{this is, the second test.}
% two arg def (B):
\def\testtwoargB#1#2{\typeout{Testing two args B: '#1' and '#2'}}
%call:
\testtwoargB{test this first}{this is, the second test.}
% output:
%*Testing one arg: 'test this'
%*Testing two args: 'test this first' and 'this is, the second test.'
%*Testing two args B: 'test this first' and 'this is, the second test.'