[comp.text.tex] LaTeX optional arguments

bagchi@eecs.umich.edu (Ranjan Bagchi) (01/06/91)

	When doing a LaTeX \newcommand, is it possible to
ask for optional arguments as per the "build-in" commands?

	-rj
--
--------------------------------------------------------------------------------
Ranjan Bagchi - At Large.  Well Kinda.  |  what kind of person
bagchi@[eecs                            |  would want to count syllables
        caen,                           |  just to write haiku?
	math.lsa].umich.edu     	|  
--------------------------------------------------------------------------------

allbery@NCoast.ORG (Brandon S. Allbery KB8JRR) (01/08/91)

As quoted from <BAGCHI.91Jan5204032@snarf.eecs.umich.edu> by bagchi@eecs.umich.edu (Ranjan Bagchi):
+---------------
| 	When doing a LaTeX \newcommand, is it possible to
| ask for optional arguments as per the "build-in" commands?
+---------------

Not as such.  You can use a .sty file and \def to do it, however:

[[WARNING:  Minor LaTeX wizardry coming up]]

\def\mycommand{\@ifnextchar[{\@mycommand}{\@mycommand[default]}}
\def\@mycommand[#1]#2{%your code here
}

"\@ifnextchar" compares the next character on the input stream to its first
argument; if they're the same, it executes its second argument, otherwise it
executes its third argument.  You then use the way TeX (raw TeX, this is not
subject to control by macro packages) reads commands and their arguments to
insert the default value to be used for the *real* command, which similarly
uses raw TeX's mechanism for parsing arguments.  (To fully understand this,
read chapter 20 of the TeXbook.)  If the default-value and explicit-value
behaviors differ, you can call different macros in arguments 2 and 3 of
\@ifnextchar.

Similarly, \@ifnextchar can be used to create *-forms:

\def\mycommand{\@ifnextchar*{\@mycommandA}{\@mycommandB}}

Remember, however, that the arguments to \@ifnextchar are just that ---
arguments.  Don't code all your logic in them; you can run TeX out of memory
rather quickly that way.  Call other macros to do the real work.

This is all much easier to understand after reading the TeXbook to learn how
TeX works --- while much of the TeXbook is predicated on "plain TeX", it is
also a reference to the raw TeX program upon which both "plain TeX" and LaTeX
are built.

++Brandon
-- 
Me: Brandon S. Allbery			    VHF/UHF: KB8JRR on 220, 2m, 440
Internet: allbery@NCoast.ORG		    Packet: KB8JRR @ WA8BXN
America OnLine: KB8JRR			    AMPR: KB8JRR.AmPR.ORG [44.70.4.88]
uunet!usenet.ins.cwru.edu!ncoast!allbery    Delphi: ALLBERY