Is there a way to find the previously printed character in LaTeX? E.g:
\newcommand{\th}{%
\ifthenelse%
{\equal{\previouscharacter}{1}}%
{st}%
{th}%
}
4\th and 21\th % would like to yield "4thand 21st"
The answer, unfortunately, is no. TeX contains a few primitives that modify things before them (\over, \atop, \above and the withdelims variants), but nothing general purpose.
In addition to the various packages which implement printing ordinal numbers, I wrote a fairly straightforward macro that does this here.
\lastbox, but could it conceivably be used to do that?
– Bruno Le Floch
Mar 13 '11 at 23:21
As to the specific application in question, there's the engord package. Examples:
\engordnumber{1}
\engordnumber{12}
\engordnumber{123}
return 1st, 12th, and 123rd. For the specific question, I can't answer.
LuaLaTeX solution:
%! TEX program = lualatex
\documentclass{article}
\begin{document}
\directlua{assert(node.types()[29]=="glyph")}
\directlua{assert(node.types()[12]=="glue")}
\def\copylastchar{%
\directlua{%
a=node.last_node();%
if a==nil then tex.print("[!?]") else %
node.write(a);%
tex.print("["..(a.id==29 and utf8.char(node.getchar(a)) or a.id==12 and " " or "???").."]")%
end%
}}
abcd\copylastchar
1\copylastchar
1 \copylastchar
ab\setbox0=\hbox{c}\box0\copylastchar
ab\setbox0=\hbox{2}\raise 1mm\box0\copylastchar
\copylastchar
\end{document}
Output:
abcd[d]
1[1]
1 [ ]
abc[b]
ab²[b]
[!?]
The function \copylastchar takes the last character then re-print it to the document for the purpose of viewing.
Note that it's not always foolproof (as can be seen in the last examples where b is printed instead of c or 2)
I don't know if there might be any disadvantage of getting the last_node then write it back like that.
\directlua{debug.debug()} to spawn a Lua interactive prompt and play with it.
– user202729
Jan 10 '23 at 01:38
n\thlook better than\nth{n}? – Tim N Mar 13 '11 at 17:30n\thwould gobble any space that follows in the text, so ... probably not. ;-) – lockstep Mar 13 '11 at 17:33