I am currently making my first beamer presentation, so forgive if this is a very trivial question. I have tried to research how to display code on a beamer presentation. I have managed to do this using semiverbatim
. However, I am not completely satisfied with this as the readability is so poor without any coloring of keywords, etc. I have tried to use the listings
package, with which I am familiar from writing articles in LaTeX, but I have not been successfull.
Here is an example from my presentation:
\begin{frame}[fragile]
\begin{semiverbatim}
class DampenedPendulum(Pendulum):
def __init__(self, B, L=1, M=1, g=9.81):
super().__init__(L=1, M=1, g=9.81)
self.solve_called = False
self.B = B
\end{semiverbatim}
\end{frame}
This comes out okay, but I would like to improve the readability by adding some coloring of keywords, like in the listings
package. Any tips on how to that would be much appreciated.
Here is an example of how I tried to this using the listings
package:
\documentclass{beamer}
\usetheme{Boadilla}
\usepackage{listings}
\usepackage{xcolor}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
\lstdefinestyle{mystyle}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codegreen},
keywordstyle=\color{magenta},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codepurple},
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
numbers=left,
numbersep=5pt,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2
}
\lstset{style=mystyle}
\begin{document}
\begin{frame}[fragile]
\begin{lstlisting}
class DampenedPendulum(Pendulum):
def __init__(self, B, L=1, M=1, g=9.81):
super().__init__(L=1, M=1, g=9.81)
self.solve_called = False
self.B = B
\end{lstlisting}
\end{frame}
\end{document}
This comes out with numbered lines and background color, but not coloring of keywords. The code for styling was copied from an Overleaf page, and I have used it many times in articles for pretty printing code.
listings
package so please show us what you have tried so far by giving us a minimal working example starting with\documentclass{...}
and ending with\end{document}
. – campa Nov 24 '20 at 11:40language=Python
in your\lstdefinestyle
). Also your MWE is helpful but it is missing\begin{document}
and\end{document}
. – Marijn Nov 24 '20 at 13:02\begin{document}
and\end{document}
for future reference of this question. – Fenris Nov 24 '20 at 13:08