I'm inserting code fragments in an org-mode document like this:

#+CAPTION: My Caption
#+NAME: fig:figure_name
#+BEGIN_SRC a_language
My code ...

In PDF LaTeX export, the code blocks are not easily distinguished from the main text. Ideally, I would like to have a bounding box and/or a light gray background, similar to how Stack Exchange sets apart snippets of code. I've tried changing the LaTeX background color org-mode option, but it didn't seem to do what I want. Is there any easy way to accomplish this?

  • Thanks for asking this, this question reminded me, that I had to figure out how this works. :)
    – jue
    Commented Feb 25, 2020 at 20:41

2 Answers 2


This is a solution using latex package lstlisting instead of minted
(lstlisting is not so powerful as minted but does not need a whole python stack).

You need to put following lisp code into your Emacs init.el (or try it in *scratch* buffer like I did.

(setq org-latex-listings t)
(add-to-list 'org-latex-packages-alist '("" "listings"))
(add-to-list 'org-latex-packages-alist '("" "color"))

These lines load the latex packages listings and color and advice org mode to export code block using the listings latex package.

After that you can write your code block that way:

#+CAPTION: Caption, my caption!
#+ATTR_LATEX: :options frame=single,backgroundcolor=\color{lightgray}
#+BEGIN_SRC C :results output :exports both
int i, x = 10;
for(i = 0; i < x; i++)
    printf("%d ",i);
printf(" ~ %d\n", x);

Notice the extra line of
#+ATTR_LATEX: :options frame=single,backgroundcolor=\color{lightgray},
which defines a frame around the source code and a background color.

Above settings should produce following lines (among others) in the resulting .tex file:

\lstset{language=C,label= ,caption={Caption, my caption!},captionpos=b,numbers=none,frame=single backgroundcolor=\color{lightgray}}
int i, x = 10;
for(i = 0; i < x; i++)
    printf("%d ",i);
printf(" ~ %d\n", x);

Remark: in older Org-Versions (v8 and older) #+ATTR_LATEX uses another syntax. Space () instead of = is used. The #+ATTR_LATEX needs to be changed slightly. Read more at the question org ignores attr latex

Note: here is another solution, using minted: https://stackoverflow.com/a/60396939


Assuming that you are already using minted, this is just a two-step process.

  1. Define the colour in your header, e.g.
#+LATEX_HEADER: \usepackage{minted}
#+LATEX_HEADER: \usepackage{xcolor}
#+LATEX_HEADER: \definecolor{bg}{rgb}{0.95,0.95,0.95}

I find that xcolor is not optional.

  1. Put your colour just before #+begin_src. e.g.
#+ATTR_LATEX: :options frame=single,bgcolor=bg
<your code here>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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