Blog | Florian Schrödl

Org Mode Src Snippet with automatic language attribute

June 11, 2021
133 words
1 minutes

📹 Screencast of snippet in action

This snippet expands to an Org mode source block with the language type automatically prefilled, by looking at the blocks above the cursor.

This is helpful for documents like programming notes on various languages, where you don't have to type the language when you quickly want to add a snippet.

The Code

It uses yasnippet to insert the code block. Yasnippet can execute emacs-lisp code in it's own snippets, so here we call the function (+yas/org-last-src-lang) which finds the nearest src block, and takes it's language type ✨.

# -*- mode: snippet -*-
# name: #+begin_src
# uuid: src
# key: <
# --
\\#+begin_src ${1:`(+yas/org-last-src-lang)`}

You've got to remove the \\ escaping characters in the code block above, until I figure out how to include escaping in source blocks with orga 🥲

(defun +yas/org-src-lang ()
  "Try to find the current language of the src/header at point.
Return nil otherwise."
          (goto-char (line-beginning-position))
          (or (ignore-errors (1- (search-forward " " (line-end-position))))
              (1+ (point)))))
       (when (re-search-forward "header-args:")
          (or (and (forward-symbol 1) (point))
              (1+ (point))))))
        (or (and (forward-symbol 1) (point))
            (1+ (point)))))
       (search-forward "#+begin_src")
      (_ nil))))

(defun +yas/org-last-src-lang ()
    (when (search-backward "#+begin_src" nil t)
Read more stories about "emacs" ->