LaTeX tricks

Sep 21, 2009 18:31

Do you know how to create a command like \verb with completely custom format?
TeX's \def command supports this variant:

\def\eqn #1 $#2${\begin{equation}%
\label{eq:#1}%
#2%
\end{equation}}
After that, you can use this as follows:

\eqn emc $e=mc^2$
Often, you need to create a variant of a command with a star (just like \newcommand and \newcommand*). You can do this by using \@ifstar command just like this:

\def\test{\@ifstar{\message{a}}{\message{b}}
Now if you start LaTeX and enter \test\relax and \test*\relax you will see a or b:

$ latex
This is pdfTeXk, Version 3.141592-1.40.3 (Web2C 7.5.6)
%&-line parsing enabled.
**\makeatletter
entering extended mode
LaTeX2e <2005/12/01>
Babel and hyphenation patterns for english, usenglishmax, dumylang, noh
yphenation, arabic, farsi, croatian, ukrainian, russian, bulgarian, czech, slov
ak, danish, dutch, finnish, basque, french, german, ngerman, ibycus, greek, mon
ogreek, ancientgreek, hungarian, italian, latin, mongolian, norsk, icelandic, i
nterlingua, turkish, coptic, romanian, welsh, serbian, slovenian, estonian, esp
eranto, uppersorbian, indonesian, polish, portuguese, spanish, catalan, galicia
n, swedish, ukenglish, pinyin, loaded.

*\def\test{\@ifstar{\message{a}}{\message{b}}}

*\test\relax
b
*\test*\relax
a
*^C! Interruption.
<*>

? x
No pages of output.
Transcript written on texput.log.

$
You can make two commands, one \mymacrostar and \mymacronostar and make them run depending on result of \@ifstar:

\def\mymacro{\@ifstar%
{\mymacrostar}{\mymacronostar}}
Also, there is a command for checking for any symbol following the command: \@ifnextchar. It can be used this way:

\def\mymacro{\@ifnextchar[%
{\mymacrobracket}{\mymacronobracket}}
Please note that you must use \makeatletter before and \makeatother after using commands containing @ symbol.

latex

Previous post Next post
Up