3

I'd like to create an environment, which will have its own parsing rules inside, for example:

\begin{foo}
a := 42;
c := a;
\end{foo}

Would be understood as:

a \mapsto 42 \\[2pt] c \mapsto a \\[2pt]

Here, := is understood by TeX as \mapsto and ; as \\[2pt]. Is it at all possible?

yegor256
  • 12,021

2 Answers2

3

Here's a LuaLaTeX-based solution.

The Lua function that does all of the work is activated when LaTeX enters the foo environment and is deactivated when LaTeX exits the foo environment. By “activation”, I mean assignment to LuaTeX’s process_input_buffer callback. While active, the Lua function acts as a preprocessor, checking and modifying the input stream before TeX starts its usual input processing.

enter image description here

% !TEX TS-program = lualatex
\documentclass{article}

%% Lua-side code \usepackage{luacode} \begin{luacode} function do_substitutions ( s ) s = s:gsub ( ":=" , "\mapsto " ) s = s:gsub ( ";" , "\\[2pt]" ) return s end \end{luacode}

%% LaTeX-side code \newenvironment{foo}{% \directlua { luatexbase.add_to_callback (% "process_input_buffer" , do_substitutions , "do_subs" ) }}{% \directlua { luatexbase.remove_from_callback (% "process_input_buffer" , "do_subs" ) }}

\begin{document} [ \begin{foo} \begin{array}{c} a := 42; c := a \end{array} \end{foo} ] \end{document}

Mico
  • 506,678
0

A token-cycle pseudo-environment \foo...\endfoo can accomplish this directly in (La)TeX. I show not only the typeset result, but the detokenized tokens that result in the converted token list.

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{tokcycle} 
\tokcycleenvironment\foo
{\ifx;##1\addcytoks{\\[2pt]}\else
 \ifx:##1 \tcpeek\z\ifx=\z\addcytoks{\mapsto}\tcpop\z\else
   \addcytoks{##1}\fi\else
 \addcytoks{##1}\fi\fi}
{\processtoks{##1}}
{\addcytoks{##1}}
{\addcytoks{##1}}
\begin{document}
\noindent$\foo
a := 42;
c := a;
\endfoo
%
\textrm{\detokenize\expandafter{\the\cytoks}}$
\end{document}

enter image description here