12

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"
Tim N
  • 10,219
  • 13
  • 63
  • 88

3 Answers3

8

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.

TH.
  • 62,639
  • I know nothing about \lastbox, but could it conceivably be used to do that? – Bruno Le Floch Mar 13 '11 at 23:21
  • @Bruno: alas, my experience as recorded in the following discussion suggests not: http://tex.stackexchange.com/questions/6183/reading-the-contents-of-a-box/6186#6186. – Ryan Reich Mar 14 '11 at 04:14
3

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.

Mike Renfro
  • 20,550
1

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.

user202729
  • 7,143