6

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 ...
#+END_SRC

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?

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

1 Answer 1

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);
#+END_SRC

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:

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

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

0

Your Answer

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

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