Using flymake in emacs to validate html as you type

February 23, 2009 at 11:46 pm

Flymake is a general emacs plugin which allows you to run an external validator against a buffer’s content and visually report errors. The effects are quite similar to the red underlining you will see in some IDEs (e.g visual studio) – but can, with some work, be used for any file format with a validator. The following settings let flymake validate html in emacs.

Motivation

Seeing mistakes earlier can make them easier to correct

Valid html makes future browsers less likely to mangle your page

Remembering to run a validator takes effort

Setup

Install html tidy (this is available under cygwin on windows, and using apt under most linuxes)

Create this perl script[1]; make it executable and place it on your path. Call it flymakehtml. #!/usr/bin/perl open(INPUT, "rxp $ARGV[0] 2>&1|"); while (<INPUT>){ /^Error/ && chomp; print; }

Add the following code to your .emacs file:

(defun flymake-html-init () (let* ((temp-file (flymake-init-create-temp-buffer-copy 'flymake-create-temp-inplace)) (local-file (file-relative-name temp-file (file-name-directory buffer-file-name)))) (list "tidy" (list local-file)))) (add-to-list 'flymake-allowed-file-name-masks '("\\.html\\'" flymake-html-init)) (add-to-list 'flymake-err-line-patterns '("line \\([0-9]+\\) column \\([0-9]+\\) - \\(Warning\\|Error\\): \\(.*\\)" nil 1 2 4))

Ensure that you have the following command somewhere in your .emacs file (add-hook 'find-file-hook 'flymake-find-file-hook)

You might like to change the face used to show errors with M-x customize-face flymake-errline. Hovering over an error will show you a description of the error

[1] This is to trim the tidied document from the output and only leave error messages.

Caveats

Sometimes error messages will use slightly strange tenses – since html tidy is a tool to tidy html rather than validate it – but the meaning is usually clear enough.

You might be interested in the nxhtml plugin as an alternative: this has more features such as context dependent autocompletion. Beware that this can take some setting up, and is a little overwhelming at times.

Share this: Twitter

Facebook

Like this: Like Loading... Related

Entry filed under: Uncategorized.