Toxic Elephant

How to Trim Spaces in TeX

Posted by matijs Thu, 20 Jul 2006 19:27:00 GMT

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.

Posted in ,  | no comments | no trackbacks

No comments

No trackbacks

Comments are disabled

Toxic Elephant is Matijs van Zuijlen's weblog.

Powered

Categories

Archives