While taking notes, writing blogs and managing knowledge base with org-mode, I need to insert source code blocks quite frequently, so I wrote an Elisp function to help me to do it.

Table of contents:

  1. An example of org-mode source code block
  2. org-insert-src-block
  3. Keyboard shortcut
  4. Synatx Highlighting

An example of org-mode source code block

This is an Elisp source code block (foldable) in org-mode:

#+BEGIN_SRC emacs-lisp
  (message "Some text")


In order to reduce the keystrokes, I wrote this Elisp function:

(defun org-insert-src-block (src-code-type)
  "Insert a `SRC-CODE-TYPE' type source code block in org-mode."
   (let ((src-code-types
          '("emacs-lisp" "python" "C" "sh" "java" "js" "clojure" "C++" "css"
            "calc" "asymptote" "dot" "gnuplot" "ledger" "lilypond" "mscgen"
            "octave" "oz" "plantuml" "R" "sass" "screen" "sql" "awk" "ditaa"
            "haskell" "latex" "lisp" "matlab" "ocaml" "org" "perl" "ruby"
            "scheme" "sqlite")))
     (list (ido-completing-read "Source code type: " src-code-types))))
    (insert (format "#+BEGIN_SRC %s\n" src-code-type))
    (insert "#+END_SRC\n")
    (previous-line 2)

eval it and press M-x org-insert-src-block, then type in the wanted Emacs major mode for the block, for example, emacs-lisp.

Keyboard shortcut

(add-hook 'org-mode-hook '(lambda ()
                            ;; turn on flyspell-mode by default
                            (flyspell-mode 1)
                            ;; C-TAB for expanding
                            (local-set-key (kbd "C-<tab>")
                            ;; keybinding for editing source code blocks
                            (local-set-key (kbd "C-c s e")
                            ;; keybinding for inserting code blocks
                            (local-set-key (kbd "C-c s i")

Synatx Highlighting

Set variable org-src-fontify-natively to enable syntax highlighting in the source code blocks (you may need to revert-buffer to reload the org file).

(setq org-src-fontify-natively t)

org2blog makes use of the export engine of org-mode to convert org files into HTML. The source blocks are also syntax highlighted in the generated HTML files.


  1. Delete the file corresponding to the current buffer
  2. Alarm for Breaks
  3. Insert source code block in org-mode
  4. Edit current file as root
  5. Getting rid of mouse

My site is free of ads and trackers. Was this post helpful to you? Why not BuyMeACoffee