How to Trim Spaces in TeX
Posted by matijs 20/07/2006 at 19h27
The problem
You created a macro package for LaTeX and promised that people could write either
\synttree[a label]
or
\synttree[a label]
and the result would be the same. Now your buggy macro for trimming spaces stands in the way of a much needed bug fix.
In short, you need a macro \trim
that will trim (The name says it all, doesn’t it?) spaces off of its argument’s beginning and end.
The solution
Of course you know about \ignorespaces
. That’s half the solution right there. Yesss, you say, of course you know about \ignorespaces
. You want the other half of the solution.
Okay, okay. The other half is \unskip
.
\unskip
?
Yes, \unskip
.
Effectively, it does exactly the same as \ignorespaces
, but to spaces that come before it.
So in short, what you want is:
\def\trim#1{\ignorespaces#1\unskip}
Discussion
You probably noticed I said “effectively” back there. That’s because in fact \unskip
does something completely different: It removes the last item of a list (that comes before it), if that item is a glue. So the space first has to be converted into a glue before it can be removed with \unskip
. \ignorespaces
on the other hand truly makes TeX ignore spaces that follow.
Also, this solution sometimes does not work. The original source of this solution, around the bend #15
says “various complications can arise”. I don’t know what those complications might be, but if they happen to arise, see the answers to around the bend #15 for more robust solutions.
And finally
A thank you to Thomer for the idea of putting solutions to seemingly simple problems in the form of a HOWTO.