Michael Sokol

Software engineer's take on programing languages and paradigms. Talks about my open-source projects.
~ Thursday, November 24 ~
Permalink

Emacs customization: adding hooks

Emacs is such a wonderful piece of technology. I saw Richard Stallman a few month ago and although his talk was very interesting, I just couldn’t think about anything else than “wow, he’s the guy who invented Emacs”. But anyway, I digress.

Emacs’ strenght is its extensibility. Adding functionality to it is really easy and fun. As a support for my markdown-literate-programming-for-github-pre-processor, I decided to add a function that can be triggered in the “markdown-mode” major mode that simply adds a fenced-code block, like that, after the point (the cursor):

~~~~ruby

~~~~

In order to do that, here are the steps that I needed to take:

  • Create a `md-fenced-code-blocks` function that adds the code block
  • Assign it to a key-binding whenever the major mode is markdown-mode

The `md-fenced-code-blocks` is a really easy function to create. All I needed to do was adding characters, and moving the point at the center of the code block.

(defun md-fenced-code-blocks ()
  "Adds a fenced block for code in markdown"
  (interactive)
  (insert "~~~~ruby\n\n~~~~")
  (previous-line))

This can be added in the scratch buffer, however, I have all my defuns in a separate file. Next thing I had to do was defining the key-binding when markdown-mode is selected.

Emacs modes have multiple hooks that are called when an event is triggered. Selecting markdown-mode triggers all the functions defined in the `markdown-mode-hooks` variable. Using the `add-macro` function, it’s easy to add a hook function to a list of hooks.

(add-hook 'markdown-mode-hook
  '(lambda ()
     (local-set-key [M-return] 'md-fenced-code-blocks)))

Et voilĂ ! I can now press M-return and have the `md-fenced-code-blocks` function called whenever I’m in the markdown-mode.


1 note  ()
  1. tyb reblogged this from michael-sokol
  2. michael-sokol posted this