0

I have a few commands that I have defined as follows:

\newcommand{\G}{
    \ifmmode%
    \mathcal{G}
    \else$\mathcal{G}$\fi
}

Annoyingly, if I write This a graph \G such that it outputs the \G and the such together. I know it is because the space after \G is there to finish the command, and not to be a proper space. So I tried:

 \newcommand{\G}{
    \ifmmode%
    \mathcal{G}
    \else
    $\mathcal{G}$
    \fi
}

And this leaves a space behind. But, if I write we have graph \G, which... it will leave a space between the \G and the ,.

Is there a way of saying "automatically leave a space, except if it is punctuation." ?

Thanks

  • Welcome! Please edit your question to make your fragments into a compilable example. As I understand, the answer is probably 'No, unless you don't need to worry about corner cases, edge cases, complications and complexities.' There are some existing questions (and packages) if you don't have to worry about those things. One problem is that it is easy enough to peek at the next character, but what should you check for? ., ,, :, ;, ', -, !, ~, ), ]? And what if the next character is a backslash? Moreover, pretty much anything will work only in standard (English?) contexts ... – cfr Mar 14 '18 at 03:40
  • 1
    By the way, why not \ensuremath{\mathcal{G}}? – cfr Mar 14 '18 at 03:43
  • 1
    As you can imagine, you aren't the first person to wonder about this, so this has come up many many times before. For example, search the site for xspace, in questions like space-after-latex-commands, drawbacks-of-xspace, acceptable-use-cases-for-xspace-when-will-it-fail, etc. Basically xspace is the state-of-the-art (as far as I can tell), but nothing is perfect and it may be better to get used to the standard ways. – ShreevatsaR Mar 14 '18 at 03:52
  • Thanks, these comments answer my question. Also, I was not aware of \ensuremath, thanks for that – excalibur1491 Mar 14 '18 at 04:09
  • You gain very little from such a complicated definition. Do \newcommand{\G}{\mathcal{G}} and type The graph $\G$ is interesting. – egreg Mar 14 '18 at 07:28
  • 1
    note using $\G$ as well as being simpler and more robust (try your definition in a array cell) has the benefit of avoiding \xspace (which it really is best to avoid) as the space is not dropped after $ – David Carlisle Mar 14 '18 at 07:48

0 Answers0