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?