# Strip environment command in hyperref PDF meta data

When adding PDF meta data using hyperref you can also use certain LaTeX commands which are magically stripped away during the conversion into a PDF string. But this doesn't seem to work with environments.

\documentclass{article}
\newcommand\foo[1]{foo #1}
\newenvironment{fooenv}{foobegin}{fooend}
\usepackage{hyperref}
\hypersetup{pdfauthor=\foo{Author}} % works
\hypersetup{pdftitle={\begin{fooenv}Title\end{fooenv}.}} % error
\begin{document}
\end{document}


Is there any way to make enviroments behave like regular commands in this setting?

• hyperref contains code (in the definition of \pdfstringdef), but it is faulty. It uses #1 instead of ##1. Make a bug report. (But imho it is not a good idea to use environments there, that's probably the reason nobody ever reported the error.) – Ulrike Fischer Mar 5 '15 at 17:13
• It's not very clear why you'd embed the title in an environment or the author's name in a command to begin with. – egreg Mar 5 '15 at 18:58
• In my opinion, using environments here is as bad as using commands. I just want to end up with something useful in the meta data when arbitrary LaTeX code is copied directly into one of the fields - being aware of the drawbacks. I think that's the overall idea of hyperref allowing LaTeX commands in such places. – porst17 Mar 6 '15 at 8:25
• @UlrikeFischer: Where to report the bug? Is it possible to patch the command using etoolbox or something in the short run? – porst17 Mar 6 '15 at 8:42
• Write @HeikoOberdiek, and in the short run, I would simply change hyperref.sty and replace the #1 by ##1 in \def\begin#1{\csname#1\endcsname}% \def\end#1{\csname end#1\endcsname}% – Ulrike Fischer Mar 6 '15 at 8:58

The following workaround allows to use environments as intended by patching the \pdfstringdef:

\documentclass{article}
\newcommand\foo[1]{foo #1}
\newenvironment{fooenv}{foobegin}{fooend}
\usepackage{hyperref}

\usepackage{etoolbox}
\catcode\#=12
\newcommand{\patchpdfstringdef}{%
\patchcmd\pdfstringdef%
{\def \begin #1{\csname #1\endcsname }}%
{\def \begin ##1{\csname ##1\endcsname }}%
{}{}%
\patchcmd\pdfstringdef%
{\def \end #1{\csname end#1\endcsname }}%
{\def \end ##1{\csname end##1\endcsname }}%
{}{}%

}
\catcode\#=6
\patchpdfstringdef

\hypersetup{pdfauthor=\foo{Author}} % works
\hypersetup{pdftitle={\begin{fooenv}Title\end{fooenv}.}} % error
\begin{document}
Hello!
\end{document}


It utilizes the answer given in Patching arguments inside a macro.

This results in the following meta data being stored in the PDF (queried by pdfinfo):

Title:          foobeginTitlefooend.
Author:         foo Author