Emacs: Org Mode, Work with Source Code
org-mode can embed programing language source code, and you can interactively evaluate it, edit it, or export to HTML with evaluated results embedded/updated in the exported file.
If you've never used org-mode before, first see Emacs: Outline, org-mode
Source Code Marked Up
Source code in org mode is marked up like this:
#+BEGIN_SRC emacs-lisp (+ 1 3) #+END_SRC
#+BEGIN_SRC python return 3 + 7 #+END_SRC
#+BEGIN_SRC ruby p 3 + 4 #+END_SRC
- In emacs 27, to insert source code markup, press Ctrl+c Ctrl+, (
- In emacs 26, to insert source code markup, press < s Tab
The following are the keyword of supported languages, as of GNU Emacs 27.1. (2020-12-15)
C C++ D R asymptote awk calc clojure css ditaa dot emacs-lisp eshell fortran gnuplot haskell java js latex ledger lilypond lisp lua matlab mscgen ocaml octave org oz perl plantuml processing python ruby sass scheme screen sed sh sql sqlite vala
To evaluate code block, put cursor in the code block, then press Ctrl+c Ctrl+c.
Here's a example you can copy paste into org mode file to test.
#+BEGIN_SRC emacs-lisp (+ 3 4) #+END_SRC #+RESULTS: : 7
Setup Which Languages to Allow Eval
By default, only emacs lisp code is allowed to eval. If you need other languages, you need put this in your Emacs Init File:
(require 'org) (require 'ob) ;; make org mode allow eval of some langs (org-babel-do-load-languages 'org-babel-load-languages '((emacs-lisp . t) (python . t) (ruby . t)))
Here's a example of Python. Try to eval it.
#+BEGIN_SRC python return 3 + 7 #+END_SRC #+RESULTS: : 10
Note: for Python, when in non-session mode, you need to have a
return … at the end, in order to print result, else the result is
Stop Emacs from Confirming Eval
Everytime you eval a source code in org mode, emacs will ask you to confirm.
You can turn that off by putting the following in your emacs init.
;; stop emacs asking for confirmation (setq org-confirm-babel-evaluate nil)
Or, if you want it to be per buffer, you can put the following at the top of your org file, and eval it everytime you open that file.
#+BEGIN_SRC emacs-lisp ;; stop emacs asking for confirmation, for this buffer only (setq-local org-confirm-babel-evaluate nil) #+END_SRC
Turn on Syntax Coloring
To make org mode syntax color embeded source code, put the following in your emacs init:
(setq org-src-fontify-natively t)
Editing Source Code
• When cursor is inside the source code block, Alt+x
org-edit-special 【Ctrl+c '】 to create a new buffer in split pane, dedicated to the language.
• edit it, and Alt+x
org-edit-src-save 【Ctrl+x Ctrl+s】 will save it back in the original org mode file.
org-edit-special 【Ctrl+c '】 again to remove this edit mode buffer.
Org Babel History
Org mode's source code feature (originally known as Org Babel) is written by Eric Schulte. Thank you Eric Schulte. [https://eschulte.github.io/] . Eric is also the author of emacs starter kit. https://github.com/eschulte/emacs24-starter-kit/