Using macros as the accepted answer is a great option, which I also used following this question. But there is one alternative that I started using and that some may prefer: define a src
block with emacs-lisp and a call it with #+CALL
for each figure we want to include.
It works like this, add the block below to your org-mode document (it can be inside a heading with the :noexport:
tag) and change it according with your preferences.
#+NAME: get-filename-by-backend
#+begin_src emacs-lisp :var filename="default" :exports none :results raw
(concat "[[file:"
(case org-export-current-backend
(html (concat filename ".svg"))
(twbs (concat filename ".svg"))
(latex (concat filename ".pdf"))
(t (concat filename ".png")))
"]]")
#+end_src
Now, whenever you want to include a figure just add something like
#+NAME: a_name_for_this_figure_call
#+CALL: get-filename-by-backend(filename="figs/my_nice_figure")
and execute the block with C-c C-c
. This will add the result as
#+RESULTS: a_name_for_this_figure_call
[[file:figs/my_nice_figure.png]]
Now you can add #+NAME: figure_label
, #+CAPTION: The figure caption.
, #+ATTR_LATEX: ...
, etc above the #+RESULTS:
line.
The trick here is that we get a png
image when we are not exporting, which can be nicely displayed with org-toggle-inline-images
. However, during the export the #+CALL:
line is re-evaluated and we get a pdf
image for latex export and an svg
image for HTML export.
The advantage of this solution, compared with a macro solution, goes beyond just displaying the image inline. Since you can pass a variable to a src
block that receives the result of another src
block it means that you can have a src
block using your preferred language that generates "backend dependent" export code.
#+begin_html
orby-backend
macro (I think I picked it from Org wiki somewhere), example here: raw.githubusercontent.com/wvxvw/introduction-to-data-structures/… . But I'm unaware of general purpose mechanism for this.#+begin_html
/#+begin_latex
blocks would be fine for a single figure or so, but I have plenty in my document. However, searching forby-backend
macros on google lead me to the solution, thank you!