Creating New Blog Posts in Emacs

I use the Emacs thermonuclear word processor for everything in my life that has to do with editing text. It’s extensibility is unmatched by any other editor out there; if there’s a feature missing that would make your life easier, then pop open the hood and add it! While it’s not the prettiest language to work with, Emacs Lisp (or elisp) is a pretty straight forward, yet deeply powerful extension language.

The following bit of elisp adds a new function for creating empty blog posts for the Jekyll static blogging system. It creates the basic preamble and names the file according to the title of the blog post!

We first start out with some directories. Change blog-base-dir to point to wherever you store the source for your Jekyll blog/website.

(setq blog-base-dir "/home/bryan/Projects/personal-site/")
(setq blog-posts-dir (concat blog-base-dir "_posts/"))

Next we introduce a helper function for converting a blog title to a proper file name. Essentially we strip out and replace any non file name-friendly characters with dashes and all that.

(defun title-to-file-name (title)
  (concat
   (downcase
    (replace-regexp-in-string
     "[[:space:]]" "-"
     (replace-regexp-in-string "[^[:alnum:][:space:]]" "" title)))
   ".md"))

Finally we have the main function. The (interactive ...) bit allows us to call this function interactively (i.e. you can type M-x new-blog-post in any buffer and it will execute the function.) When invoked interactively you will be prompted to input a blog post title. This title will then be used, along with today’s date, to create the file name and preamble for the blog. The remaining bits of the function open the (new) file with the created name in the proper directory in a new buffer, and insert the preamble the Jekyll uses to create your webs pages.

(defun new-blog-post (title)
  "Prompt for a blog post title, then create the file with the
proper pre-amble."
  (interactive "sTitle: ")
  (let ((file-name (title-to-file-name title))
	(todays-date (shell-command-to-string "echo -n $(date +%Y-%m-%d)")))
    (find-file (concat blog-posts-dir todays-date "-" file-name))

    (insert "---")
    (newline)
    (insert "layout: post")
    (newline)
    (insert (concat "title: " title))
    (newline)
    (insert "---")

    (newline)
    (newline)))

Having this function around isn’t much in the grand scheme of things. Since Jekyll uses plain text (either markdown or HTML) for everything, it’s pretty easy to create new posts as it is. But it goes to show you that even the tiniest bit of friction for getting something started can be alleviated with a few minutes of programming your text editor.

 
comments powered by Disqus