Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extracting code from org-mode code blocks?

Tags:

emacs

Is there an easy way to dump code blocks in org-mode to files? Somehow naming them via markup near code-blocks perhaps? Maybe an export or something?

like image 286
lucidquiet Avatar asked Oct 23 '25 18:10

lucidquiet


1 Answers

Use the :tangle keyword in your source block (see https://orgmode.org/manual/Extracting-Source-Code.html)

Example:

#+begin_src emacs-lisp :tangle "init.el"
(defmacro add-hook! (hook &rest body)
  "Nicer add-hooking that prevents writing lambdas explicitly.
  Add a lambda containing BODY to hook HOOK."
  (declare (indent 1))
  `(add-hook ,hook 
         (lambda () ,@body)))
#+end_src

After doing M-x org-babel-tangle, the code block is exported to "init.el"

The above is part of my init.org file. At the end of my init.org, I have this:

* COMMENT Local Variables for auto-tangle                    :ARCHIVE:
# Local Variables:
# eval: (add-hook 'after-save-hook (lambda ()(org-babel-tangle)) nil t)
# End:
init.el

This updates the init.el after each safe of my init.org automatically.

like image 62
Andreas Sahlbach Avatar answered Oct 26 '25 20:10

Andreas Sahlbach