summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/doc/generic/FAQ-en/html/FAQ-oarglikesect.html
blob: ee818a6709e9640d592a14c2219303a98e462de1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<head>
<title>UK TeX FAQ -- question label oarglikesect</title>
</head><body>
<h3>Optional arguments like <code>\</code><code>section</code></h3>
<p/>Optional arguments, in macros defined using <code>\</code><code>newcommand</code>, don&rsquo;t
quite work like the optional argument to <code>\</code><code>section</code>.  The default
value of <code>\</code><code>section</code>&rsquo;s optional argument is the value of the
mandatory argument, but <code>\</code><code>newcommand</code> requires that you &lsquo;know&rsquo; the
value of the default beforehand.
<p/>The requisite trick is to use a macro in the optional argument:
<blockquote>
<pre>
\documentclass{article}
\newcommand\thing[2][\DefaultOpt]{%
  \def\DefaultOpt{#2}%
  optional arg: #1,  mandatory arg: #2%
}
\begin{document}
\thing{manda}% #1=#2

\thing[opti]{manda}% #1="opti"
\end{document}
</pre>
</blockquote><p>
LaTeX itself has a trickier (but less readily understandable)
method, using a macro <code>\</code><code>@dblarg</code>; inside LaTeX, the example
above would have been programmed:
<blockquote>
<pre>
\newcommand\thing{\@dblarg\@thing}
\newcommand\@thing[2][\@error]{%
  optional arg: #1,  mandatory arg: #2%
}
</pre>
</blockquote><p>
In that code, <code>\</code><code>@thing</code> is only ever called with an optional and a
mandatory argument; if the default from the <code>\</code><code>newcommand</code> is
invoked, a bug in user code has bitten...
<p/><p>This question on the Web: <a href="http://www.tex.ac.uk/cgi-bin/texfaq2html?label=oarglikesect">http://www.tex.ac.uk/cgi-bin/texfaq2html?label=oarglikesect</a>
</body>