10

I would like to include in my document some code examples that look like the IPython Notebook cells in this image:

enter image description here

I have produced something that looks a bit like it with the code below:

\documentclass{article}

\usepackage{color}
\definecolor{light-gray}{gray}{0.95}

\usepackage{listings}
\lstset{
    basicstyle=\footnotesize\ttfamily,
    escapechar=¢,
    language=python,
    frame=single,
    frameround=tttt,
    showstringspaces=false,
    backgroundcolor=\color{light-gray}
}
\newcommand*{\ipythonprompt}[1]{\makebox[0pt][r]{\textbf{In [#1]:}\hspace{1em}}}

\begin{document}
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Here are two IPython cells:
\begin{lstlisting}
¢\ipythonprompt{1}¢ n = 10
\end{lstlisting}

\begin{lstlisting}
¢\ipythonprompt{2}¢ for i in range(n):
    print('i = ', i)
\end{lstlisting}

\end{document}

Here's what it looks like:

enter image description here

But I have a couple of issues:

  • The corners aren't quite right: they're a bit wonky and too rounded;

  • The prompts In [1]: etc are in the margin, but I'd like them in the body of the text, with the gray cell area to the right of them.

Can anyone suggest how I might achieve this?

12

I'd suggest you to use the tcolorbox package and its interaction with listings:

enter image description here

The code (adjust the settings according to your needs):

\documentclass{article}
\usepackage{xcolor}
\usepackage[many]{tcolorbox}
\tcbuselibrary{listings}

\definecolor{light-gray}{gray}{0.95}

% the space reserved between for the ``In'' numbers and the code
\newlength\inwd
\setlength\inwd{1.3cm}

\newcounter{ipythcntr}

\newtcblisting{ipythonnb}[1][\theipythcntr]{
  enlarge left by=\inwd,
  width=\linewidth-\inwd,
  enhanced,
  boxrule=0.4pt,
  colback=light-gray,
  listing only,
  top=0pt,
  bottom=0pt,
  overlay={
    \node[
      anchor=north east,
      text width=\inwd,
      font=\footnotesize\ttfamily\color{blue!50!black},
      inner ysep=2mm,
      inner xsep=0pt,
      outer sep=0pt
      ] 
      at (frame.north west)
      {\stepcounter{ipythcntr}In [#1]:};
  }
  listing options={
    basicstyle=\footnotesize\ttfamily,
    language=python,
    escapechar=¢,
    showstringspaces=false,
  },
}

\begin{document}
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Here are two IPython cells:
\begin{ipythonnb}
n = 10
\end{ipythonnb}

\begin{ipythonnb}
for i in range(n):
    print('i = ', i)
\end{ipythonnb}

\begin{ipythonnb}[13]
n = 10
\end{ipythonnb}

\end{document}

The optional argument for the ipythonnb environment allows to manually control the numbering in the In part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.