3

I am trying to markup certain words in my text and automatically commit them to the index, with the option to modify the index entry. The \newcommand approach was not satisfying, as I did not manage to set the default value of the first argument to be the second.

With \NewDocumentCommand I managed to set the options properly, but it introduced an unwanted space when followed by punctuation. Can anyone explain, why this occurs and how to fix it?

Here is a minimal working example:

\documentclass{article}
\usepackage{xparse}
 


\newcommand{\neuold}[2][]{{\sffamily\textbf{ #2}}\index{#1 #2}}

\NewDocumentCommand{\neu}{m O{#1}}
{
\IfNoValueTF{#2}
{{\sffamily\textbf{#1}}}
{\sffamily\textbf{ #1}\index{ #2}}
}

\begin{document}
blabla  \neu{test}, blabla \neuold{test}, blabla
\end{document}
  • Well you have various spaces in your definition at the end of lines. – Ulrike Fischer Oct 4 '20 at 13:04
  • You are missing two % signs in your \NewDocumentCommand. It should be …O#1}}{%… \index{ #2}}% – David Purton Oct 4 '20 at 13:05
  • Thanks to everybody for the quick and knowledgeable replies! – user36504 Oct 4 '20 at 13:45
3

You're inserting spaces yourself.

\NewDocumentCommand{\neu}{m O{#1}}
{% <--- space
\IfNoValueTF{#2}
{{\sffamily\textbf{#1}}}
{\sffamily\textbf{ #1}\index{ #2}}% <---
}

On the other hand, the \IfNoValueTF test will always return false, so it's useless. It's to be used with an o argument type. So

\NewDocumentCommand{\neu}{m O{#1}}
 {%
  \textsf{\textbf{#1}}\index{#2}%
 }

would be what you want. I see no reason for the space in front of #1 and #2.

1

The line feeds in the command are being expanded as spaces. You need to add % at the end of lines where you don't want a space to show up.

\documentclass{article}
\usepackage{xparse}

\newcommand{\neuold}[2][]{{\sffamily\textbf{ #2}}\index{#1 #2}}

\NewDocumentCommand{ \neu }{ m O{#1} }{%
  \IfNoValueTF{#2}{%
    \sffamily\textbf{#1}%
  }{%
    \sffamily\textbf{#1}\index{#2}%
  }%
}

\begin{document}
blabla  \neu{test}, blabla \neuold{test}, blabla \neu{test}[Test], blah
\end{document}

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