3

Is there a way to make a command ignore any space and new line immediately preceding its use?

For example, the code

\documentclass{article}

\newcommand{\foo}{foo}

\begin{document}
% Case 1
Lorem ipsum dolor sit amet. \foo

% Case 2
Lorem ipsum dolor sit amet.\foo

% Case 3
Lorem ipsum dolor sit amet.
\foo

% Case 4
Lorem ipsum dolor sit amet.

\foo
\end{document}

produces the following:

Lorem ipsum dolor sit amet. foo
Lorem ipsum dolor sit amet.foo
Lorem ipsum dolori sit amet. foo
Lorem ipsum dolor sit amet.
foo

Is there a way to define \foo so that it always produces the second line and the example code gives the following?

Lorem ipsum dolor sit amet.foo
Lorem ipsum dolor sit amet.foo
Lorem ipsum dolor sit amet.foo
Lorem ipsum dolor sit amet.foo
2
  • 1
    The first three are easy: \newcommand*{\foo}{\unskip foo}. The fourth would heavily mess with the way TeX works. – campa Mar 24 at 11:36
  • @campa There are many ways to skin a cat. – Steven B. Segletes Apr 2 at 3:26
1

Voila!

EDITED to remove \makeatletter code that enables \tcpeek, which is now incorporated into tokcycle[2021-05-27].

The logic is simple: if a space or a \par is encountered in the \dofoo environment input stream, it calls \foocheck (before adding the space or \par to the output stream). In turn, \foocheck peeks at (i.e., \futurelets) the next token in the input stream. If it is \foo or \par, it discards the prior space or \par.

\documentclass{article}
\usepackage{tokcycle}
\def\foo{foo}
\newcommand\foocheck[1]{\tcpeek\z\ifx\foo\z\else
  \ifx\par\z\else\addcytoks{#1}\fi\fi}
\tokcycleenvironment\dofoo
  {\addcytoks{##1}}
  {\processtoks{##1}}
  {\ifx\par##1\foocheck{##1}\else\addcytoks{##1}\fi}
  {\foocheck{##1}}
\begin{document}
\dofoo
% Case 1
Lorem ipsum dolor sit amet. \foo 

% Case 2
Lorem ipsum dolor sit amet.\foo 

% Case 3
Lorem ipsum dolor sit amet.
\foo 

% Case 4
Lorem ipsum dolor sit amet.

\foo 
\enddofoo
\end{document}

enter image description here

3
  • +1 for you, you sadistic cat skinner :-) – campa Apr 2 at 7:16
  • @campa After I wrote that, I worried that you (and readers), me not being familiar with your cultural background, would not be familiar with the idiomatic expression. It is pretty crass at face value (oops, another idiomatic expression) – Steven B. Segletes Apr 2 at 12:24
  • Oh, don't worry about me. I am familiar with the expression but I just find it funny because my brain tends to understand it literally before idiomatically, so I couldn't resist... – campa Apr 2 at 19:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.