I'm writing an elisp script to expand commands defined in the preamble to their definition. I need to do this replacements for my job and, also, to simplify the reading of math texts to a sight-impaired math student. I'm not the author of the documents. I'm a typesetter and my job is "to format" scientific papers.
E.g. if I have in the preamble:
\def\PA{\ensuremath{\mathrm{A}}}
I need to expand each instance of \PA in the document to its definition.
The way I do this is: In the elisp part of my script, in a while loop, I:
- search for a user-defined command (e.g.,
\COMMAND), - insert "
\writetotempfile\COMMAND" and compile, - then I remove
\writetotempfile
Thus I use the \writetotempfile command once at a time in the document, for every instance of user defined commands. Here \writetotempfile is the following code:
\newcommand{\writetotempfile}[1]
{#1\newwrite\tempfile%
\immediate\openout\tempfile=expandedCommand.tmp%
\immediate\write\tempfile{\unexpanded\expandafter{#1}}%
\immediate\closeout\tempfile}%
so, e.g., when I have
\writetotempfile\PA
that returns me the string "\ensuremath {\mathrm {A}}" in the expandedCommand.tmp file. My .tmp file is overwritten each time.
When I have \ensuremath in the definition I need to remove it and to expand the command fitting the context (e.g., in this case, $\mathrm{A}$ or simply \mathrm{A}). With some elisp regexp replacements I can clean the string to "\mathrm {A}" but it would be simpler to me if I could get the "$" or "not $" form of the expansion, fitting the context. That is, I need to get the $\mathrm{A}$ expansion in text (e.g. some text \PA some text) , and the \mathrm{A} expansion when I have $\PA$ (or \PA in math environments).
Some code may clarify my purpose:
\documentclass{article}
\usepackage{xspace}
\def\PA{\ensuremath{\mathrm{A}}\xspace}
\newcommand{\writetotempfile}[1]
{#1\newwrite\tempfile%
\immediate\openout\tempfile=expandedCommand.tmp%
\immediate\write\tempfile{\unexpanded\expandafter{#1}}%
\immediate\closeout\tempfile}
\begin{document}
\writetotempfile\PA % to be expanded to $\mathrm{A}$
$\writetotempfile\PA$ % to be expanded to \mathrm{A}
\begin{equation}
\writetotempfile\PA % to be expanded to \mathrm{A}
\begin{equation}
\end{document}
IMPORTANT! In the example above, I have 3 instance of \writetotempfile, but in reality I will use it once at a time.
\writetotempfile\PAjust once, or every time it is used or??? if\PAis used three times, twice in math mode and once in text, how often do you do\writetotempfile\PAand what do you want to write each time? – David Carlisle Jun 03 '17 at 20:43\writetotempfilecommand once at time in the document (I use a while loop to insert the command and compile for every instance of user defined commands). – Gabriele Jun 03 '17 at 21:06\show\fooand scan thelog-file? Nevertheless this does not work in every case (think about catcode tricks while definition) and so won't your suggestion. – Schweinebacke Jun 04 '17 at 13:34