I have been using org-mode + emacs for a while now, and I love how easy it is to produce contents. I often use the html + pdf export combo from the same document (first, a web page, following, a pdf document). My problem is about exporting code blocks (#+BEGIN_SRC
...) to pdf.
To html, the export command (C-c C-e h h
) gives me a satisfactory solution: it uses a frame to encapsulate the code (showing the programming language when you rest the mouse pointer on it) and uses a different frame for the resulting messages (as I set :export both
). When using #+CAPTION: my caption here
before the #+BEGIN_SRC
, resulting html page includes "Listing #: my caption here" before the code frame.
To pdf, the document generated by export command (C-c C-e l p
) doesn't have frames around neither code or results (a real mess), and captions show up as "Figure #: my caption here" in between the code and results.
How do I get both different frames for code and results and Listings-like captions for my code blocks when exporting from org-mode to pdf?
Here is a minimal example:
#+TITLE: EXPORT TESTINGS
#+OPTIONS: toc:nil
#+CAPTION: Caption, my caption!
#+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
Here is the resulting html and the resulting pdf.
Based on the Alex Ott answer (and a couple hours of web browsing) I finally did it.
We are going to use the minted
package. For completness, this how I had to set up everything:
minted
use a Python package to highlight syntax called Pygmets. You could install it with:
pip install Pygments
#+LaTeX_HEADER: \usepackage{minted}
org-latex-listings
. You have to set it with: (setq org-latex-listings 'minted)
.pdflatex
to execute shell commands in order to use the Python package Pygments
. The option is -shell-escape
. And the emacs variable that describes the call to the LaTeX compiler is org-latex-pdf-process
.To achieve those 3 points, I have added this snipet in my init file
;; inside .emacs file
(setq org-latex-listings 'minted
org-latex-packages-alist '(("" "minted"))
org-latex-pdf-process
'("pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
"pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
"pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"))
NB: see here to understand why three calls to pdflatex are needed. If you use bibtex you have to insert the appropriate line.
Now you can add the LaTeX attribute on top of your source code block:
#+ATTR_LATEX: :options frame=single
#+BEGIN_SRC emacs-lisp
(defun Fib (n)
(if (< n 2) n (+ (Fib (- n 1)) (Fib (- n 2)))))
#+END_SRC
Et voilà !
To use different frame styles go and check the manual
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With