Miskatonic University Press

More about Emacs and Jekyll

emacs jekyll

Thanks to Blogging with Emacs Org-mode and Jekyll my Emacs and Jekyll integration is much better—even though I’m not using Org. I’m still just using plain old Markdown to write things. I use Org for everything else, so I may convert, but for now it’s all working nicely.

If I want to draft a new post, somehow I need to:

  • create a new file in ~/web/_drafts/
  • with a title of my choosing, which will become the filename
  • put the YAML front matter into it
  • write in it

I could do all that by hand the hard way, sure, but it seems like something nice for Emacs to automate. And now it does! I hit C-c j n (C-c is for local commands, j means Jekyll, n means new post), Emacs asks me for a post title, and it creates a draft post for me.

Here’s the Lisp stuff that makes this part of things work. This is what Emacs config files look like.

(global-set-key (kbd "C-c j n") 'jekyll-draft-post)

(defvar jekyll-directory "~/web/" "Path to Jekyll blog.")
(defvar jekyll-drafts-dir "_drafts/" "Relative path to drafts directory.")
(defvar jekyll-post-ext ".md"  "File extension of Jekyll posts.")

(defun jekyll-make-slug (s) "Turn a string into a slug."
  (replace-regexp-in-string " " "-"  (downcase (replace-regexp-in-string "[^A-Za-z0-9 ]" "" s))))

(defun jekyll-draft-post (title) "Create a new Jekyll blog post."
  (interactive "sPost Title: ")
  (let ((draft-file (concat jekyll-directory jekyll-drafts-dir
                            (jekyll-make-slug title)
                            jekyll-post-ext)))
    (if (file-exists-p draft-file)
        (find-file draft-file)
      (find-file draft-file)
      (insert (format jekyll-post-template (jekyll-yaml-escape title))))))

When I’m ready to post the draft, I hit C-c j p while I’m editing it, and Emacs gets it ready for publication by renaming the file to include the datestamp and moving it to ~/web/_posts/.

All of the code is in setup-jekyll.el from my .emacs.d.

Being able to do all this from within Emacs is just what I wanted. Beautiful!