# Read character preceding a command

I would like to make a command in LaTeX that prints something if it is preceded by a certain character and something else if it is preceded by any other character.

With \@ifnextchar I can base the output on the character after the command:

\documentclass{article}

\makeatletter
\newcommand\mycommand{\@ifnextchar h{I see an h\ }{I don't see an h\ }}
\makeatother

\begin{document}

\mycommand h %output: I see an h h
\mycommand n %output: I don't see an h n

\end{document}


I would like to do this, but basing the output on the character before my command.

• You can't (not like that, at least). TeX doesn't “remember” things after it has processed them. With LuaTeX you may be able to pre-process the input. What is your application for looking behind? – Phelype Oleinik Dec 17 '20 at 22:09

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}
\tokcycleenvironment\preh
{\processtoks{##1}\global\let\prechar\egroup}
\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}


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}