I would like to write a macro that behaves differently at the start of a paragraph. How can I do this?

(Ultimately I would like this macro to take an argument, but am assuming that's not relevant to the MWE.)

Non-working example:

  \ifAtParagraphBeginning% How to do this?

\foo{} % This should print "Hello"
says the quick brown fox jumping over the lazy dog.

The lazy dog says bark \foo{} % This should print "(hello)"
to the brown fox.

Edit: Here's a new example, where I hit a problem. I can't get the "@ifnextchar A" to work when it's in the else clause of the \if (is @ifnextchar looking at "\fi" instead of the character that follows?):

    \@ifnextchar A%
      {\textsuperscript{#1}\kern -0.15em}%
      {\textsuperscript{#1}\kern 0pt}%
  • Someone should mention \everypar. It isn't what you want, but it could be useful. Oct 1 '19 at 23:31
  • Regarding your edit: the way the code is structured, the \@ifnextchar test will always yield false because it will not see the next character (that you expect it to see), but the \fi (as you concluded yourself in another edit). To make that work you need to take the \fi out of the way: \newcommand*\foo[1]{% \ifvmode \expandafter\@gobble \else \expandafter\@firstofone \fi \testAchar} where \testAchar contains the actual test you want to do. Oct 1 '19 at 23:56
  • OK, maybe I got it. I really have \testAchar{#1}, and it seems to work if I group it: {\testAchar{#1}}.
    – dedded
    Oct 2 '19 at 0:11
  • @dedded Yes, here TeX expects a single macro argument, which is either a single token (like \testAchar or \fi or a) or a {-}-balanced list of tokens, like {\testAchar{#1}}. P.S.: In comments use the @<name> feature to reply to comments so people receive a notification. Oct 2 '19 at 9:26
  • Accepting @campa 's answer, since it answers the original question. But I don't understand @phelype-oleinik 's comment as much as I thought I did. Why doesn't this work?: \newcommand*\foo[1]{% \ifvmode% \expandafter\@gobble% \fi% {\testAchar{#1}}} The \@firstofone seems to be needed even with no \fi in the way.
    – dedded
    Oct 2 '19 at 23:07

At the start of a paragraph TeX is in vertical mode, so you can use the \ifvmode primitive. Be careful about trailing spaces.


    Hello #1%
    (hello #1)%

\foo{baz} says the quick brown fox jumping over the lazy dog.

The lazy dog says bark \foo{baz} to the brown fox.

enter image description here

  • This is so close (and works for the example I gave). I tried it in my application, however, and hit a snag. I'll update the question with a second example.
    – dedded
    Oct 1 '19 at 23:49

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.