[Tex/LaTex] redefine \includegraphics for beamer

beamergraphicspandoc

I'm using Pandoc to convert from markdown to LaTeX or Beamer.
The LaTeX template of Pandoc has nice command so that images are resized to fit the text width but the Beamer output is not.

\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth
\else\Gin@nat@width\fi}
\makeatother
\let\Oldincludegraphics\includegraphics
\renewcommand{\includegraphics}[1]{\Oldincludegraphics[width=\maxwidth]{#1}}

So I tried to copy the commands to the Beamer template, but then it gives an error while compiling with pdflatex.
I checked the preamble but couldn't figure out which one is incompatible. Maybe beamer class itself is the problem?

Here is my sample beamer code.

\documentclass[ignorenonframetext,]{beamer}
\usepackage{amssymb,amsmath}
\usepackage{ifxetex,ifluatex}
\usepackage{fixltx2e} % provides \textsubscript
\ifxetex
  \usepackage{fontspec,xltxtra,xunicode}
  \defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}
\else
  \ifluatex
    \usepackage{fontspec}
    \defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}
  \else
    \usepackage[utf8]{inputenc}
  \fi
\fi

\usepackage{graphicx}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth
\else\Gin@nat@width\fi}
\makeatother
\let\Oldincludegraphics\includegraphics
\renewcommand{\includegraphics}[1]{\Oldincludegraphics[width=\maxwidth]{#1}}
% Comment these out if you don't want a slide with just the
% part/section/subsection/subsubsection title:
\AtBeginPart{\frame{\partpage}}
\AtBeginSection{\frame{\sectionpage}}
\AtBeginSubsection{\frame{\subsectionpage}}
\AtBeginSubsubsection{\frame{\subsubsectionpage}}
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}
\setlength{\emergencystretch}{3em}  % prevent overfull lines
\setcounter{secnumdepth}{0}


\begin{document}

\begin{frame}\frametitle{Introduction}

Testing image size from R saved by various methods.

\end{frame}

\begin{frame}\frametitle{Results}

All images were set width = 7. For ggsave, the dpi =300.

\begin{block}{Saved by ggsave}

\begin{figure}[htbp]
\centering
\includegraphics{./plot_by_ggsave.pdf}
\caption{Saved by ggsave}
\end{figure}

\end{block}
\end{frame}

\end{document}

Best Answer

The beamer class redefines \includegraphics, but "at begin document", so your redefinition must be given at the same time:

\usepackage{letltxmacro}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\makeatother
\AtBeginDocument{
  \LetLtxMacro\Oldincludegraphics\includegraphics
  \renewcommand{\includegraphics}[2][]{%
    \Oldincludegraphics[#1,width=\maxwidth]{#2}}
}

See the documentation of letltxmacro for understanding why \LetLtxMacro is needed.