# Defining a command with star argument to be used in pdf strings (e.g. via \section)

I want to define a command with an optional star argument and be able to use it inside pdf strings, e.g. via \section. With the MWE below, I get a Token not allowed in a PDF string warning and \foo is just removed.

I can't think of a safe expandable way to replace \@ifstar in order to do this. For my application, it would be okay to default to \s@foo inside a pdf string, but the * should be removed if present.

Is there any way to achieve this?

\documentclass{article}

\usepackage{hyperref}

\makeatletter
\protected\def\foo{%
\@ifstar\s@foo\@foo
}
\def\@foo#1{one #1 one}
\def\s@foo#1{two #1 two}
\makeatother

\begin{document}

\section{\foo{bar}}

\end{document}

• Depending on what you're actually trying to do, you can use \texorpdfstring{regular tex}{inside pdf string} from hyperref. – Teepeemm Aug 27 at 11:51

With xparse, of course ;-)

\documentclass{article}
\usepackage{xparse}
\usepackage{hyperref}
\NewExpandableDocumentCommand \foo { s m }
{%
\IfBooleanTF{#1}
{one #2 one}% Starred
{two #2 two}% Non-starred
}
\begin{document}
\section{\foo*{bar}}
\section{\foo{baz}}
\end{document}


The command that goes into the PDF bookmark has to be expandable, so you need an expandable mechanism to grab the optional *. Same goes for optional [...] arguments.

In the code above, the PDF bookmarks are one bar one and two baz two.