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 Feb 25 '20 at 20:41

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


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.