Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I have several macros with a similar structure, for example:

\def\firstmacro#1{\myinitializer ...actual code... \myfinalizer}
\def\secondmacro#1{\myinitializer ...actual code... \myfinalizer}
\def\thirdmacro#1{\myinitializer ...actual code... \myfinalizer}

(\myinitializer and \myfinalizer are only placeholders for more complicated initializer code.) I was thinking how I could simplify this common structure by defining a custom \def macro. I arrived at

\def\custom@def#1{
  \def#1{\myinitializer\csname custom@#1\endcsname}
  \expandafter\def\csname custom@#1\endcsname
}

\custom@def\firstmacro#1{...actual code... \myfinalizer}
\custom@def\secondmacro#1{...actual code... \myfinalizer}
\custom@def\thirdmacro#1{...actual code... \myfinalizer}

So \custom@def defines the wanted command to call \myinitializer and pass to an internal command that contains the actual definition. Everything after the first argument of \def is passed to the \def of that internal macro. However, with this approach, \myfinalizer still needs to be specified explicitly. Any idea how I could eliminiate this?

share|improve this question
add comment

1 Answer 1

up vote 7 down vote accepted

The etoolbox provides a \appto and \preto which could be used to append or prefix some code to an existing macro. However, in your case I would directly collect the parameter text and replacement text as macro arguments and add the init and final code around it.

You can collect everything until the next opening { by placing a # before the { in the macro definition. This way you collect the macro name and the parameter text:

\documentclass{article}

\makeatletter
\def\custom@def#1#{%
    \@custom@def{#1}%
}
\def\@custom@def#1#2{%
  \def#1{\myinitializer#2\myfinalizer}%
}


\custom@def\mytest{test}
\show\mytest

\custom@def\mytest#1#2{(#1)(#2)}

\show\mytest

\makeatother
\begin{document}


\end{document}

Gives:

> \mytest=macro:
->\myinitializer test\myfinalizer .
l.14 \show\mytest

? 
> \mytest=macro:
#1#2->\myinitializer (#1)(#2)\myfinalizer .
l.18 \show\mytest
share|improve this answer
    
Thanks for the pointer. For those interested: See exercise 20.6 in the TeXbook and the note about "a special extension" two paragraphs above. –  Stefan Majewsky Sep 13 '11 at 10:14
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.