The following is a very simpleminded perl function that I use for this. apply_tex_macros($macros,$tex) takes TeX code in $macros and $tex, reads macro definitions out of $macros, and expands those macros wherever they occur in $tex. It's not completely general, but it works well enough for my application.
sub apply_tex_macros {
my $macros = shift;
my $tex = shift;
my $orig = $tex;
$macros =~ s/(?<!\\)\%.*//; # remove comments
my $curly = "(?:(?:{[^{}]*}|[^{}]*)*)"; # match anything, as long as curly braces in it are matched, and not nested
my $curlycurly = "(?:(?:{$curly}|$curly)*)"; # allow one level of nesting
my $curlycurlycurly = "(?:(?:{$curlycurly}|$curlycurly)*)"; # allow two levels of nesting
my $before;
while ($macros =~ /\\newcommand{\\([a-zA-Z\-]+)}\s*(?:\[(\d+)\])\s*(?:\[($curlycurlycurly)\])\s*{($curlycurlycurly)}/g) {
my $command = $1;
if ($tex=~/\\$command/) {print STDERR "Warning in footex, command $command with optional arguments is not supported, in input $tex.\n"}
}
my $depth = 0;
do {
$before = $tex;
while ($macros =~ /\\newcommand{\\([a-zA-Z\-]+)}\s*(?:\[(\d+)\])?\s*{($curlycurlycurly)}/g) {
my ($command,$nargs,$def) = ($1,$2,$3);
if (!$nargs) {
$tex =~ s/\\$command/$def/g;
}
if ($nargs==1) {
while ($tex =~ m/\\($command\{($curlycurlycurly)\})/) {
my ($macro,$arg) = ($1,$2);
my $result = $def;
$result =~ s/#1/$arg/g;
my $foo = quotemeta $macro;
$tex =~ s/\\$foo/$result/g;
}
}
if ($nargs==2) {
while ($tex =~ m/\\($command\{($curlycurlycurly)\}\{($curlycurlycurly)\})/) {
my ($macro,$arg1,$arg2) = ($1,$2,$3);
my $result = $def;
$result =~ s/#1/$arg1/g;
$result =~ s/#2/$arg2/g;
my $foo = quotemeta $macro;
$tex =~ s/\\$foo/$result/g;
}
}
if ($nargs>2 && $tex=~/\\$command/) {print STDERR "Warning in footex, command $command with more than 2 arguments is not supported, in input $orig.\n"}
}
++$depth;
print STDERR "Warning, macro expansion isn't bottoming out, depth=$depth, tex=$tex\n" if $depth>=28;
} while ($tex ne $before && $depth<30);
return $tex;
}
listingsfor syntax highlighting orltxdocfor macro indexing: read the file verbatim but detect macro name by looking for\followed by letters. Then expand that macro once if it is in a list. This might need multiple passes. – Martin Scharrer Jul 05 '11 at 14:24sedsolution: http://stackoverflow.com/questions/17793815/using-sed-in-bash-script-to-replace-latex-aliases – Turion Aug 02 '13 at 11:40