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")
#+END_SRC

org-insert-src-block

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."
  (interactive
   (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))))
  (progn
    (newline-and-indent)
    (insert (format "#+BEGIN_SRC %s\n" src-code-type))
    (newline-and-indent)
    (insert "#+END_SRC\n")
    (previous-line 2)
    (org-edit-src-code)))

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>")
                                           'yas/expand-from-trigger-key)
                            ;; keybinding for editing source code blocks
                            (local-set-key (kbd "C-c s e")
                                           'org-edit-src-code)
                            ;; keybinding for inserting code blocks
                            (local-set-key (kbd "C-c s i")
                                           'org-insert-src-block)
                            ))

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.


Reference:

  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