Jonathan Lam

Core Developer @ Hudson River Trading


Automating website build using Elisp

On 7/14/2021, 6:23:32 PM

Return to blog

I made some custom Elisp functions to be able to build and serve this website easily from Emacs! It's not much and it's not very fancy, but it automates the somewhat-tedious setup. This works well if you have a very basic two-window setup: one window for editing files, and one window for the command-line output.

I learnt about buffers, windows, and regex in Elisp. Regex was used to extract the new post id from the output of running npm run new-post even though it would have been simpler to simply return the new post id; I just wanted to try using regex.

(setq website-base "~/Documents/jonathan-lam-website")
(defun website-npm-run (target)
  (format "cd %s;npm run %s" website-base target))

(defun website-serve ()
  "Serve the website locally"
  (async-shell-command (website-npm-run "serve") "npm-serve"))

(defun website-build ()
  "Start an NPM build and hide window in the background"
  (async-shell-command (website-npm-run "build") "npm-build")
  (let ((current-window (selected-window)))
    (select-window (get-buffer-window "npm-build"))
    (select-window current-window)))

(defun website-terminate ()
  "Stop the NPM server and kill the build buffer"
  (kill-buffer "npm-serve")
  (kill-buffer "npm-build"))

(defun website-new-post (post-title)
  "New blog post for website"
  (interactive "MPost title: ")
   (format "cd %s;echo '%s'|npm run new-post" website-base post-title)
  (set-window-buffer (selected-window) "npm-new-post")
  (re-search-forward "id=\\([[:digit:]]+\\)" nil t)
  (find-file (format "%s/src/posts/%s.pug"
		     (substring-no-properties (match-string 1)))))

(defun website-edit ()
  "Goto website source directory (dired)"
  (find-file (format "%s/src" website-base)))

;;; keybindings
(global-set-key (kbd "C-c C-w e") 'website-edit)
(global-set-key (kbd "C-c C-w s") 'website-serve)
(global-set-key (kbd "C-c C-w b") 'website-build)
(global-set-key (kbd "C-c C-w t") 'website-terminate)
(global-set-key (kbd "C-c C-w n") 'website-new-post)

© Copyright 2023 Jonathan Lam