When I edit a Markdown file in emacs, it automatically gets converted on save to an HTML file. Since such conversions often entail customisation, I use a standard .convert-markdown
script to signal to emacs that it is possible to convert Markdown within a particular directory.
The source of the present file, for example, was a file called drafts/emarks.md
. This sits alongside a drafts/.convert-markdown
script, which uses hoedown to convert Markdown to HTML in a separate articles/
directory.
When emacs is asked to save the drafts/emarks.md
file, it calls any registered post-save hooks, one of which is called automatically-convert-markdown
:
(defun string/ends-with (s ending)
(let ((elength (length ending)))
(string= (substring s (- 0 elength)) ending)))
(defun automatically-convert-markdown ()
(let ((name (buffer-file-name)))
(if (string/ends-with name ".md")
(let ((convert (concat (file-name-directory name)
".convert-markdown")))
(if (file-exists-p convert)
(shell-command (concat convert " " name)))))))
Because the .convert-markdown
path is general, and applicable to a wide range of setups, the following tiny shell command correctly specifies how to manually update all of the Markdown files within a signalled directory:
for fn in *.md
do ./.convert-markdown $fn
done
Here's a simple example bash script that can be used as a converter:
#!/bin/bash
OUT=${1%.md}.html
echo "<title>$(sed -n '/^# /{s/^# //;p;q;}')</title>" > $OUT
hoedown $1 | sed 's% *</p>$%%' >> $OUT
echo Wrote to $OUT
The .convert-markdown
method makes it feel as though the Markdown is the actual source of the rendered page. It gives the impression of being able to use Markdown directly on the web.