A small server for Emacs web development

- Hemil Ruparel 12 August, 2022

I am using Emacs for writing this blog. A very unusual choice, yes, I know! But it is what it is.

(defun live-server ()
  (interactive)
  (setq dir (file-name-directory buffer-file-name))
  (message dir)
  (async-shell-command
   (format "python -m http.server -d %s 8080" dir))
  )

Paste the above snippet into your Emacs config. That may be your init.el file or .emacs file. Wherever you store your config. Then open a file in root folder of your server and type M-x live-server. It will start a server on localhost 8080. I dont know how to take optional arguments in such a function in elisp to allow specifying a custom port. This is my first function in elisp.

I use a slightly different version:

(defun live-server ()
  (interactive)
  (setq dir (file-name-directory buffer-file-name))
  (message dir)
  (async-shell-command
   (format "python -m http.server -d %s 8080" dir))
  (shell-command "firefox --new-tab localhost:8080")
  )

The difference is this last line. It opens firefox my web browser of choice on localhost:8080.

No blog post using lisp can go without praising the symmetry of lisp. Lisp code is a list of statements. Just like a list of data. And you can manipulate code just as it were data because it actually is! i.e. code is data! The function definition is a function itself which takes parameters - function name, the argument list, and the rest of arguments are the body!

Its really mind boggling! defun is the application of the function defun with live-server being the name, () being the argument list (empty in this case) and the rest of the parameters are the body of the function!!!!!!!!

The above is equivalent to the following in other languages:

defun(
  "live-server",
  (),
  interactive(),
  setq(dir, file-name-directory(buffer-file-name()))
)

Where defun could be this in python:

def defun(name, arg_list, *body)

It still blows my mind what you can do with just list manipulation. Three functions really - cons, car, cdr is all you need to build a turing complete programming language! Like Holy Shit!