16.10 Editing Source Code

Use C-c ' to edit the current code block. It opens a new major mode edit buffer containing the body of the source code block, ready for any edits. Use C-c ' again to close the buffer and return to the Org buffer.

C-x C-s saves the buffer and updates the contents of the Org buffer. Set org-edit-src-auto-save-idle-delay to save the base buffer after a certain idle delay time. Set org-edit-src-turn-on-auto-save to auto-save this buffer into a separate file using Auto-save mode.

While editing the source code in the major mode, the Org Src minor mode remains active. It provides these customization variables as described below. For even more variables, look in the customization group org-edit-structure.

org-src-lang-modes

If an Emacs major-mode named <LANG>-mode exists, where <LANG> is the language identifier from code block’s header line, then the edit buffer uses that major mode. Use this variable to arbitrarily map language identifiers to major modes.

org-src-window-setup

For specifying Emacs window arrangement when the new edit buffer is created.

org-src-preserve-indentation

Default is nil. Source code is indented. This indentation applies during export or tangling, and depending on the context, may alter leading spaces and tabs. When non-nil, source code is aligned with the leftmost column. No lines are modified during export or tangling, which is very useful for white-space sensitive languages, such as Python.

org-src-ask-before-returning-to-edit-buffer

When nil, Org returns to the edit buffer without further prompts. The default prompts for a confirmation.

Set org-src-fontify-natively to non-nil to turn on native code fontification in the Org buffer. Fontification of code blocks can give visual separation of text and code on the display page. To further customize the appearance of org-block for specific languages, customize org-src-block-faces. The following example shades the background of regular blocks, and colors source blocks only for Python and Emacs Lisp languages.

(require 'color)
(set-face-attribute 'org-block nil :background
                    (color-darken-name
                     (face-attribute 'default :background) 3))

(setq org-src-block-faces '(("emacs-lisp" (:background "#EEE2FF"))
                            ("python" (:background "#E5FFB8"))))