]> mj.ucw.cz Git - ucwmac.git/commitdiff
Added facilities for defining macros with optional arguments
authorMartin Mares <mj@ucw.cz>
Thu, 31 May 2018 14:28:46 +0000 (16:28 +0200)
committerMartin Mares <mj@ucw.cz>
Thu, 31 May 2018 14:28:46 +0000 (16:28 +0200)
ucwmac.tex

index 9c99369b126c1f441829c6e38d7dacbea6b94da6..f49d765b14317fb7f81416163b1760d78d414fb4 100644 (file)
 \setmargins{1truein}
 \setpaper{a4}
 
+%%% Macros with optional arguments %%%
+
+% After \def\a{\withoptarg\b}, the macro \a behaves in this way:
+%      \a[arg]         does \def\optarg{arg} and then it expands \b
+%      \a              does \let\optarg=\relax and then it expands \b
+\def\withoptarg#1{\let\xoptcall=#1\futurelet\next\xopt}
+\def\xopt{\ifx\next[\expandafter\xoptwith\else\let\optarg=\relax\expandafter\xoptcall\fi}
+\def\xoptwith[#1]{\def\optarg{#1}\xoptcall}
+
+% A shortcut for defining macros with optional arguments:
+% \optdef\macro behaves as \def\domacro, while \macro itself is defined
+% as a wrapper calling \domacro using \withoptarg.
+\def\optdef#1{%
+       \edef\xoptname{\expandafter\eatbackslash\string#1}%
+       \edef#1{\noexpand\withoptarg\csname do\xoptname\endcsname}%
+       \expandafter\def\csname do\xoptname\endcsname
+}
+
+% Trick: \eatbackslash eats the next backslash of category 12
+\begingroup\lccode`\+=`\\
+\lowercase{\endgroup\def\eatbackslash+{}}
+
+% Expand to the optional argument if it exists
+\def\optargorempty{\ifx\optarg\relax\else\optarg\fi}
+
 %%% Placing material at specified coordinates %%%
 
 % Set all dimensions of a given box register to zero