[texhax] The last character of a string

Reinhard Kotucha reinhard.kotucha at web.de
Fri Jan 29 23:40:34 CET 2010

On 29 January 2010 Donald Arseneau wrote:

 > Michael Barr <barr at math.mcgill.ca> writes:
 > > Is there a simple way to find the last character of a string?  
 > You have to scan through the tokens from first to last.

This sounds difficult at a first glance, but fortunately the LaTeX
kernel provides a macro (\@tfor, defined in ltcntrl.dtx) which might
be useful here.

Here an example file...

\@tfor\token := abcd \do {\edef\lasttoken{\token}}

...and the result:

> \lasttoken=macro:
l.4 \show\lasttoken

If the token list is a macro, it has to be expanded in advance:


  :\expandafter=\list \do {\edef\lasttoken{\token}}

This could be a starting point.  It saves a lot of work, at least.  

 > > What I want to do is add a period unless the string already 
 > > ends in a period, question mark, or exclamation mark, 
 > Oh that's easy -- check the value of \spacefactor.
 > Easy, but not 100% reliable.

Problematic with \frenchspacing where \spacefactor is always 1000.  
Maybe one should put \let\frenchspacing\relax into the preamble if the
document contains contributions from many authors.

BTW, another option is to pre-process the files using a scripting
language like Perl, Python, or Lua.  Many problems can be solved
easier this way.  Suppose you have a solution already for determining
the last token in a macro.  Now you want to remove spaces in front of
exclamation/questionmarks too.  It's very easy to solve these
problems with regular expressions.  This is one of the reasons I'm
so much interested in LuaTeX.


Reinhard Kotucha			              Phone: +49-511-3373112
Marschnerstr. 25
D-30167 Hannover	                      mailto:reinhard.kotucha at web.de
Microsoft isn't the answer. Microsoft is the question, and the answer is NO.

More information about the texhax mailing list