# Compile error with MWE using pgfkeys, beamer, xparse and \includegraphics

First, please apologize the vague title, but I do not understand the problem enough to give a more exact title.

The following MWE does not compile with a missing \endcsname inserted error around \linewidth with pdflatex and lualatex.

\documentclass{beamer}
% \documentclass{article}

\usepackage{pgfkeys}
\usepackage{xparse}
\usepackage{graphicx}

\pgfkeys{
/tikzscale/.is family, /tikzscale,
width/.code = {\the#1},
}

\RenewDocumentCommand{\includegraphics}{O{}}{%
% \renewcommand{\includegraphics}[1][]{%
\pgfkeys{/tikzscale, #1}%
}

\begin{document}
\includegraphics[width=\linewidth]
text
\end{document}


If either of both commented lines is uncommented (while commenting the line above), the file compiles, i.e. the combination of pgfkeys, beamer, xparse and \includegraphics seems to trigger the error. Putting \AtBeginDocument around the redefinition of \includegraphics does also solve the problem.

Why doesn't this combination work? What is the difference between \RenewDocumentCommand and \renewcommand in this context?

-
The problem is that beamer redefines \includegraphics at begin document in terms of the meaning it had at that moment.
With \renewcommand things seem to go straight, but with \RenewDocumentCommand there's a different scanning mechanism for optional arguments and chaos ensues.
I wouldn't mix the two ways. In any case, redefining commands declared robust (as beamer does with \includegraphics) can be very risky.
Is there any way how to detect this different scanning mechanism or to see that a robust command is redefined? I think about interpreting \meaning\includegraphics or something like that. Reading beamer's source could also be an option, but if possible I'd like to avoid that. –  Patrick Häcker Jan 22 '13 at 18:02
@MMM Say \tracingmacros=1 before the command to be tested and this will give plenty of information in the log file –  egreg Jan 22 '13 at 18:44