# Token allowed in PDF string in \section but not in a customized (with \addcontentsline) section command

babel's frenchb option makes active e.g. ! character by making it automatically preceded by a \thinspace. Such active characters are properly supported in sections by hyperref's bookmarks. But, when I try to create my own section command with an \addcontentsline specification, this leads to the well known Package hyperref Warning: Token not allowed in a PDF string (PDFDocEncoding) warning, as pointed out by the following MWE:

\documentclass[french]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{babel}
\usepackage{hyperref}

\newcommand{\mynaivesection}[1]{%
\textbf{#1}%
}

\begin{document}
\tableofcontents
\section{Foo !}
\mynaivesection{Bar !}
\end{document}


What is missing in my (deliberately naive) customized section command in order to get rid of this warning?

BTW:

1. there isn't any warning if I remove \textbf{#1}% in this custom section command: rather strange...
2. bookmark package doesn't help here.

It is not hyperref that sanitizes the argument. The main difference between \section and your command is that the \addcontentsline is issued for the first in vertical mode. And the definition of the ! depends on the mode:

\french@sh@!@ ->\ifhmode \ifdim \lastskip >\z@ \unskip \penalty \@M \FBthinspace
\else \FDP@thinspace \fi \fi \string !


The warning disappears if you insert a \par (and also if there is no text before the \addcontentsline as you are in vmode then):

\documentclass[french]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{babel}
\usepackage[]{hyperref}
\usepackage{etoolbox}

\newcommand{\mynaivesection}[1]{%

\begin{document}

\tableofcontents

\section{Foo !}

\mynaivesection{Bar!}

\renewcommand{\mynaivesection}[1]{%

\mynaivesection{FooBar!}

\end{document}


You can locally redefine \FBthinspace to do nothing.

\newcommand{\mynaivesection}[1]{%
\textbf{#1}%
\begingroup%
\renewcommand{\FBthinspace}{}%
\endgroup%
}


MWE:

\documentclass[french]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{babel}
\usepackage{hyperref}

\newcommand{\mynaivesection}[1]{%
\textbf{#1}%
\begingroup%
\renewcommand{\FBthinspace}{}%
\endgroup%
}

\begin{document}
\tableofcontents
\section{Foo !}
\mynaivesection{Bar !}
\end{document}


Output:

• Indeed, but (1) aren't the \FBthinspace features lost also for the table of contents? (2) is it the way the "official" \section supports active characters? – Denis Bitouzé Feb 20 '15 at 9:32
• (1) No, at the time of printing the ToC \FBthinspace feature is in effect, so you don't lose it. (2) I have no idea. – karlkoeller Feb 20 '15 at 9:35
• @DenisBitouzé: You can easily test the scope of such a redefinition. Simply do \renewcommand{\FBthinspace}{HALLO} and then look where the HALLO is. – Ulrike Fischer Feb 20 '15 at 12:18