Read character preceding a command
In classic tex you can not look back, but in luatex things are rather different
\documentclass{article}
\def\zz{\directlua{
local n=tex.nest[tex.nest.ptr].tail
if (n.id==29) % glyph
then
tex.print("[previous node was \string\\char" .. n.char .. "]")
end
}}
\begin{document}
abc\zz\ xyz\zz\ 123
\end{document}
Not sure if your application allows the whole thing to be embedded in an environment or not. If so, I create a tokcycle pseudo-environment \preh
, in which occurrences of \mymacro
are able to examine the prior token to see if it is an h
or not.
In essence, the token cycle saves the most recent token (only approximately in the case of cat-2 or cat-10 tokens), and instances of \mycommand
trigger a check on that most recent token.
\documentclass{article}
\usepackage{tokcycle}
\def\mycommand{\tctestifx{h\prechar}
{\addcytoks{[PRIOR h]}}{\addcytoks{[NOT PRIOR h]}}}
\tokcycleenvironment\preh
{\addcytoks{##1}\let\prechar##1}
{\processtoks{##1}\global\let\prechar\egroup}
{\ifx\mycommand##1##1\else\addcytoks{##1}\fi\let\prechar##1}
{\addcytoks{##1}\let\prechar\space}
\begin{document}
\preh
A test\mycommand{} of a bash\mycommand ful \rule{1ex}{1ex} environment.
Look! Paragraphs and embedded macros pose no problem
\endpreh
\end{document}