Tuesday, September 7, 2010

Flymake and Erlang

Flymake is a really useful tool for programming Erlang, or for programming in general, that gives you on the fly error detection in source files. It does this by compiling your source code in the background and showing the results in file you are editing. It doesn't actually know anything about languages or how to compile, it is built in a very abstract way such that it can be used for any language. In this case we can use it for programming Erlang. It will only catch the errors that the erlang compiler can warn about but even still it vastly reduces the edit/compile/debug loop.

Flymake is available out of the box in emacs, so all we need to is add a script to do the compile and tell flymake where it is.

I have a directory in my home directory called ~/.erlang_code. In this directory I have a file called eflymake. The contents of this file are listed below. (make sure the file is executable). This isn't my code, I pulled the snippet from the net a while ago and have forgotten the source, so unfortunatly I can't give proper attribution.

#!/usr/bin/env escript
-export([main/1]).

main([File_Name]) ->
compile:file(File_Name, [warn_obsolete_guard, warn_unused_import,
warn_shadow_vars, warn_export_vars,
strong_validation, report,
{i, "../include"}]).

This will do the compilation for you, and you can see how to change the compile flags to suit your needs. Now that that is done you need to tell flymake where it is and how to use it. You can do this buy adding the following code to your emacs configuration.

(require 'flymake)
(setq flymake-log-level 3)

(defun flymake-erlang-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 "~/.erlang_code/eflymake" (list local-file))))

(add-to-list 'flymake-allowed-file-name-masks
'("\\.erl\\'" flymake-erlang-init))

(defun my-erlang-mode-hook ()
(flymake-mode 1))

(add-hook 'erlang-mode-hook 'my-erlang-mode-hook)

You can learn this and other pro Erlang and OTP programming tips at the ErlangCamp. These kinds of simple improvements can seriously improve the efficiency of your Erlang programming workflow.

No comments: