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 #+END_SRC
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.Sign up to join this community
You can always write a function that inserts a string and then bind it to a key:
(defun insert-python-src-block () (interactive) (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.