2017-12-04 Embedding files in Org-mode

A few days ago, there was a question on the help-gnu-emacs mailing list about a way to embed an image in a text file. Of course, the OP was instantly pointed to Org-mode. However, this does not quite do what he wanted: while you can have attachments/links to images in Org, you then need two files instead of one.

This being Emacs and Org-mode, there exists an (at least partial) solution. You can use a code block and put some Elisp code recreating the image (or any file, for that matter) in there. Here’s one way how to do it.

(defun org-insert-file (filename)
  "Insert Elisp code block recreating file named FILENAME."
  (interactive "f")
  (let ((base64-string
	 (with-temp-buffer
	   (insert-file-contents-literally filename)
	   (base64-encode-region (point-min) (point-max))
	   (buffer-string))))
	(insert (format "#+BEGIN_SRC emacs-lisp :results output silent\n  (with-temp-file %S\n    (insert (base64-decode-string\n      %S)))\n#+END_SRC" filename base64-string))))

You can now call org-insert-file somewhere in your Org-mode buffer (preferably with point at the beginning of a line), choose the file and in a second you have your source block. Too see how it works, change the filename in the beginning of that code and press C-c C-c with point on your newly created source block. You may be asked whether you are sure you want to run it – answer yes, and in another second the file is recreated under the given name.

One drawback is that this does not look very pretty in your Org-mode file. See this Emacs.SE answer for some help. Another is that you need to explicitly evaluate this source code block with C-c C-c. This is actually for your own good (security-wise), but see here for a way to automate this, too.

As usual, it turns out that Emacs and Org-mode are extremely flexible and can do a lot of stuff. Not that I’m surprised;-).

CategoryEnglish, CategoryBlog, CategoryEmacs, CategoryOrgMode