Numbers on the left of listings overlap enclosing box

by Anush   Last Updated August 14, 2019 10:23 AM

I am trying to present some code as follows:

\documentclass[11pt]{beamer}
\usepackage{tcolorbox}
\tcbuselibrary{listings,skins}
\lstdefinestyle{compactstyle}{
    numbers=left, 
    numberstyle=\small, 
    numbersep=8pt, 
    language=Python,
    basicstyle=\tiny
}
\newtcblisting{compactlisting}[2][]{
    arc=0pt, outer arc=0pt,
    listing only, 
    listing style=compactstyle,
    title=#2,
    #1
}
\usepackage{listings,newtxtt}
\lstset{basicstyle=\ttfamily, keywordstyle=\bfseries}
\begin{document}
\begin{frame}[fragile]
    \frametitle{Title}  
    \begin{compactlisting}[hbox]{}
def peak_recursive(A):
    n = len(A)
    if n == 1:
        return 0
    if n == 2:
        return 0 if A[0]>=A[1] else 1
    if A[n//2]>=A[n//2 + 1] and A[n//2]>=A[n//2 - 1]:
        return n//2
    elif A[n//2 - 1]>=A[n//2]:
        return peak_recursive(A[0:n//2])
    else:
        return n//2+1+peak_recursive(A[n//2+1:])
    \end{compactlisting}
\end{frame}
\end{document}

However the numbers on the left overlap the enclosing box:

listings

How can one fix this?

(As a secondary question, is it possible to control how far the tab indents so that line 2 is less indented, for example?)

Tags : beamer listings


Answers 1


You can set the margin with tcolorbox keys:

\documentclass[11pt]{beamer}
\usepackage{tcolorbox}
\tcbuselibrary{listings,skins}
\lstdefinestyle{compactstyle}{
    numbers=left,
    numberstyle=\small,
    numbersep=8pt,
    language=Python,
    basicstyle=\tiny,
}
\newtcblisting{compactlisting}[2][]{
    arc=0pt, outer arc=0pt,
    listing only,
    listing style=compactstyle,
    title=#2,
    left=1cm,%<------------ adapt
    #1
}
\usepackage{listings,newtxtt}
\lstset{basicstyle=\ttfamily, keywordstyle=\bfseries}
\begin{document}
\begin{frame}[fragile]
    \frametitle{Title}
    \begin{compactlisting}[hbox]{}
def peak_recursive(A):
    n = len(A)
    if n == 1:
        return 0
    if n == 2:
        return 0 if A[0]>=A[1] else 1
    if A[n//2]>=A[n//2 + 1] and A[n//2]>=A[n//2 - 1]:
        return n//2
    elif A[n//2 - 1]>=A[n//2]:
        return peak_recursive(A[0:n//2])
    else:
        return n//2+1+peak_recursive(A[n//2+1:])
    \end{compactlisting}
\end{frame}
\end{document}

enter image description here

Ulrike Fischer
Ulrike Fischer
August 14, 2019 09:45 AM

Related Questions


Using scalebox to decrease the size of listings code

Updated December 10, 2016 08:09 AM

Getting a frame with listings in beamer

Updated June 03, 2015 22:10 PM

Using an overlay on lstinputlistings in latex

Updated February 21, 2016 03:10 AM


listings in beamer broken

Updated June 12, 2017 15:23 PM