This is just the kind of problem for which the tokcycle
package was made.
I've only implemented a handfull of the Greek, but you just need a \tcmapto z\zeta
type statement for each new mapping. In the MWE, I also use |...|
to escape characters back to the original Latin. Macros are automatically intercepted and preserved with the Latin interpretation of the name. All grouping considerations of the \greek
environment are preserved in the transformed output.
\documentclass{article}
\usepackage{tokcycle}
\tokcycleenvironment\greek% NEW TOKCYCLE ENVIRONMENT:
{\addcytoks[4]{\tcremap{##1}}}% HOW TO TREAT CHARACTERS
{\processtoks{##1}}% HOW TO TREAT GROUP CONTENTS
{\addcytoks{##1}}% HOW TO TREAT MACROS
{\addcytoks{##1}}% HOW TO TREAT SPACES
\newcommand*\tcmapto[2]{\expandafter\def\csname tcmapto#1\endcsname{#2}}
\newcommand*\tcremap[1]{\ifcsname tcmapto#1\endcsname
\csname tcmapto#1\expandafter\endcsname\else\expandafter#1\fi}
\tcmapto a\alpha \tcmapto b\beta \tcmapto e\epsilon
\tcmapto g\gamma \tcmapto p\pi
\begin{document}
\[
y = \greek a^2b\frac{2e}{g + p^|x|}\endgreek + x
\]
\end{document}

I edited the answer to NOT make use of \expanded
since not everyone has an updated TeX installation. So, \addcytoks[4]{...}
indicates to perform 4 expansions on the argument before storing the result, which is sufficient here to achieve the goal. The alternate syntax of \addcytoks[x]{...}
invokes \expanded
on the argument before storing the result. With the [x]
option, the \tcremap
macro can also be simplified, by eliminating the \expandafter
s as such: \newcommand*\tcremap[1]{\ifcsname tcmapto#1\endcsname\csname tcmapto#1\endcsname\else#1\fi}
Note: MikTeX doesn't quite load the package properly. You will have to manually download tokcycle.tex to your localtexmf
at \tex\generic\tokcycle\tokcycle.tex
. See https://www.ctan.org/pkg/tokcycle