7

I regularly use org-mode and org-babel to create e.g. exercises or proof-of-principle documents which I export to PDF via the LaTeX exporter. I noticed that the #RESULTS generated by a #+begin_src-#+end_src block are put in a #+begin_example-#+end_example block, which is exported to LaTeX's verbatim environment.

I would like to customize this LaTeX export. I could try and add some #+LATEX_HEADER lines customizing the verbatim environment (e.g. using the fancyvrb package), however, ideally I would like to use the listings environment for the output. Is this possible?

EDIT: I currently use the listings package to format the src blocks, so ideally I would like to use the same formatting for both.

2 Answers 2

9

There may be a "smarter" way but if you don't use EXAMPLE blocks for other purpose you could instruct the latex exporter to export them as lstlisting environment, using export filters.

(defun my-latex-export-example-blocks (text backend info)
  "Export example blocks as listings env."
  (when (org-export-derived-backend-p backend 'latex)
    (with-temp-buffer
      (insert text)
      ;; replace verbatim env by listings
      (goto-char (point-min))
      (replace-string "\\begin{verbatim}" "\\begin{lstlisting}")
      (replace-string "\\end{verbatim}" "\\end{lstlisting}")
      (buffer-substring-no-properties (point-min) (point-max)))))

(add-to-list 'org-export-filter-example-block-functions
         'my-latex-export-example-blocks)
1
  • Thanks a lot! For my current use case, this is indeed enough. I simply embed your code example in an emacs-lisp SRC block so that it only applies to this Org file. Note that the environment provided by the listings package is actually called lstlisting. With this example I can even specify options (e.g. \\begin{lstlisting}[frame=single]) specifically for the output/examples. Thanks for the great MWE on export filters. I had tried to write one myself some time ago, but failed.
    – ph0t0nix
    Jan 30, 2016 at 9:03
5

For reference I found this message on the org-mode mailing list which mentions a way to do this by means of file local #+LATEX_HEADER lines which use the fancyvrb package and redefine the verbatim environment that org-mode #+RESULTS blocks get exported to via:

#+LATEX_HEADER: \RequirePackage{fancyvrb}
#+LATEX_HEADER: \DefineVerbatimEnvironment{verbatim}{Verbatim}{fontsize=\small,formatcom = {\color[rgb]{0.5,0,0}}}
1
  • Thank you for mentioning this @phaebz. I guess I found the same mailing list post at some point. I have been using it for quite some time now.
    – ph0t0nix
    Nov 10, 2019 at 11:56

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.