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}

Vincent
  • 20,157

2 Answers2

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.

egreg
  • 1,121,712
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}

meide
  • 1,165