When using org mode, how can I map a specific keybinding (ex. C-c s) to create an org code snippet that looks like this:

#+BEGIN_SRC python


1 Answer 1


You can always write a function that inserts a string and then bind it to a key:

(defun insert-python-src-block ()
   (insert "#+BEGIN_SRC python\n\n#+END_SRC"))

(define-key org-mode-map (kbd "C-c s") #'insert-python-src-block)

But key bindings are scarce commodities; they also tend to be hard to remember when they proliferate. So most people prefer a templating mechanism for this. Org mode provides one based on the variable org-structure-template-alists. You get extensibility, but you don't get to choose an arbitrary keybinding for it.

Here's how that works - you add this to your init file:

(with-eval-after-load 'org
   (add-to-list 'org-structure-template-alist '("p" . "src python")))

Then you invoke any of the templates with C-c C-, (bound to org-insert-structure-template) which gives you a menu of possibilities: choosing p inserts the new template you added.

For details, do C-h v org-structure-template-alist RET to read the doc string of the variable, do C-h f org-insert-structure-template to read the doc string of the function, and read the Structure templates section of the manual either online, or locally with C-h i g(org)Structure templates RET which also describes the backward-compatible org-tempo based method as well.

There are other templating mechanisms: yasnippets seems to be the most popular, but I don't know enough about it to describe it here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.