[Tex/LaTex] Beamer: Indenting code inside a frame

beamerindentation

I use TexMaker. With the preamble that I have been using, I am able to get the indentation right for programs when used in a article, report, etc. But when I use the same structure within a frame in beamer, the indentation gets ignored. I have tried the fixes suggested in other posts of similar kind, but none of them work for me.

MWE:

\documentclass{beamer}
\usetheme{boadilla}
\usecolortheme{beaver}
\usepackage{listings}
\usepackage{color}

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}

\lstset{%frame=tb, % to form a frame around code
   language=Java,
   aboveskip=3mm,
   belowskip=3mm,
   showstringspaces=false,
   columns=flexible,
   basicstyle={\small\ttfamily},
   numbers=none,
   numberstyle=\tiny\color{gray},
   keywordstyle=\color{blue},
   commentstyle=\color{dkgreen},
   stringstyle=\color{mauve},
   breaklines=true,
   breakatwhitespace=true,
   tabsize=3,
}

\begin{document}
\begin{frame}[fragile]
\frametitle{Sample Program}
\begin{lstlisting}
public int increment() {
    int a = 5;
    int i = (++a) + (++a) + (a++);
    System.out.println(a);
    return i;
}
\end{lstlisting}
\end{frame}
\end{document}

The output that I get:

enter image description here

Best Answer

This is due to indentation with tabs. There are many workarounds, as well as a patch.

Equivalent questions have been asked previously [1, 2]. In those cases, the proposed solution was to use spaces rather than tabs for indentation, or to define a new command for each listing.

Another possibility is to use fragile=singleslide. That will disable overlays, but will make the tabs function correctly.

The basic problem is that the tab character vanishes when beamer writes the frame contents to a temp file with the fragile option. A patch that fixes this is below; it may be added to your document's preamble, after beamer is loaded. Note that if you use this with the XeTeX engine, you will need to use the -8bit command-line option (see this for details). I have also opened an issue at the Beamer github page for this.

\makeatletter
\def\beamer@verbatimreadframe{%
  \begingroup%
  \let\do\beamer@makeinnocent\dospecials%
  \count@=127%
  \@whilenum\count@<255 \do{%
    \advance\count@ by 1%
    \catcode\count@=11%
  }%
  \beamer@makeinnocent\^^L% and whatever other special cases
  \beamer@makeinnocent\^^I% <-- PATCH: allows tabs to be written to temp file
  \endlinechar`\^^M \catcode`\^^M=12%
  \@ifnextchar\bgroup{\afterassignment\beamer@specialprocessframefirstline\let\beamer@temp=}{\beamer@processframefirstline}}%
\makeatother