views:

626

answers:

3

How can I replace all occurrence of user defined latex macros with their definitions?

For example, given this file

old.tex

\newcommand{\blah}[2]{#1 \to #2}
...
foo \blah{egg}{spam} bar
...

how to generate the file below in an automatic way

new.tex

...
foo egg \to spam bar
...

Instead of reimplementing latex macro logic with perl, can I use latex or tex engine itself to do this?

A: 

Never seen this done, but 2 half-baked ideas:

  1. If the reason why you want to expand all these macros inline is for debugging, then setting \tracingmacros=1 in your document will expand all your macros, but the output goes to a log file.

  2. The CTAN archive provides a package that you can use to inline expansions within definitions (but not newcommand), but I didn't know if you might take a look and see how painful it might be to modify to perform inline expansions of \newcommand instead of \def.

DaveParillo
A: 

Consider using a template engine such as Jinja2 with Python.

You may wish to change the syntax from the default {%, {{, etc. in order to make it more compatible with LaTeX's own. For example:

env = jinja2.Environment(
      loader=jinja2.FileSystemLoader( JINJA_DIRS ),
      comment_start_string='["', # don't conflict with e.g. {#1
      comment_end_string = '"]',
      block_start_string = '[%',
      block_end_string = '%]',
      variable_start_string = '[=',
      variable_end_string = ']',
      autoescape=True,
      finalize=_jinja2_finalize_callback, # make a function that escapes TeX
      )

template = env.get_template( self.template )

tex = template.render( content )

In addition to functions that are passed to the template's environment, Jinja2 supports macros. For example, your above code should work as expected as:

[% macro blah(egg, spam) -%]
foo [=egg] \to [=spam] bar
[%- endmacro %]

[= blah("chicken","pork") ]
% substitutes with "foo chicken \to pork"

I'm not sure what your goals are, and this requires a bit of work, but isn't an insurmountable problem at all if you're familiar with Python.

I hope that helps.

Brian M. Hunt
+4  A: 

VOILÀ http://tug.ctan.org/cgi-bin/ctanPackageInformation.py?id=de-macro

Alessandro Checco
Nice. (It's a Python script, but still may be helpful to someone reading this question.)
ShreevatsaR