8

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.

2
  • 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? Commented Dec 17, 2020 at 22:09
  • Use case: custom kerning (where package microtype is not an option).
    – Maëlan
    Commented Sep 24, 2024 at 11:55

2 Answers 2

5

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

6

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}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .