5

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.

1
  • 2
    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
4

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}

enter image description here

5

In classic tex you can not look back, but in luatex things are rather different

enter image description here

\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}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.