Label and non-plain text arguments

I have a custom macro:

\NewDocumentCommand\includefigure{mo}{
...
\caption{#2}
\label{fig:#2}
}


The optional argument is used for the caption and the label. The problem is that when I have parts of this argument formatted like \includefigure{pic}[Hi \textit{there}!] I get errors like "Missing \endcsname inserted." since \label does not allow arguments with commands in it.

Is there a meta-command like \plaintext so I could use \label{\plaintext{fig:#2}} in my command and then \includefigure{pic}[Hi \textit{there}!] would result in \label{fig:Hi there!}?

Or maybe there is an alternative for label.

-
A label is meant to be something to help you create refs: when are you adding formatting to it in the first place? – Joseph Wright Aug 23 '13 at 11:28
Because I'm reusing the #2 argument for \caption and \label. I don't want an additional argument only for the \label since it would be redundant to have \includefigure{pic}[Hi \textit{there}!][Hi there!] – user764754 Aug 23 '13 at 11:31
I think this is an attempt at getting rid of the formatting, to automatically generate labels. But using the caption for the label sounds like a bad idea to me. – jja Aug 23 '13 at 11:33
using a separate label isn't redundant, it is the main point of the cross referencing mechanism, you can re-order the figures so the number changes, and edit your caption text, while not needing to edit every place that references the figure if you use a short symbolic label that is unconnected with any of those typesetting features. – David Carlisle Aug 23 '13 at 12:01
The advantage you describe is clear to me but I still prefer having identical captions and labels and having both set automatically :) – user764754 Aug 23 '13 at 14:27

The caption text can be converted to a safe string for the \label system by converting to hex code, e.g.:

\documentclass{article}
\usepackage{pdfescape}

\makeatletter
\newcommand*{\make@hex@label}[1]{%
\def\hex@label{#1}%
\@onelevel@sanitize\hex@label
\EdefEscapeHex\hex@label{\hex@label}%
}
\newcommand*{\hexlabel}[1]{%
\@bsphack
\make@hex@label{#1}%
\label{\hex@label}%
\@esphack
}
\newcommand*{\hexref}[1]{%
\make@hex@label{#1}%
\ref{\hex@label}%
}
\newcommand*{\hexpageref}[1]{%
\make@hex@label{#1}%
\pageref{\hex@label}%
}
\makeatother

\newcommand*{\figurecaption}[1]{%
\caption{#1}%
\hexlabel{#1}%
}

\begin{document}
\begin{figure}
\figurecaption{Hi \textit{there}!}
\end{figure}
See figure \hexref{Hi \textit{there}!}.
\end{document}


Disadvantage: Warnings show the hex string, e.g.:

LaTeX Warning: Reference 4869205C746578746974207B74686572657D21' on page 1 undefined on input line 35.
`
-
This is quite nice and probably the closest to what I want. Thanks! – user764754 Aug 23 '13 at 14:31