Editing Javascript in Emacs

2010/4/2

Steve Yegge of Google has created a new Javascript mode 'js2-mode' for Emacs.

It works very well as it uses true parsing, not heuristics, to analyse code.

Installation

  • Download http://js2-mode.googlecode.com/files/js2-20090723b.el,

  • Rename the file as js2-mode.el,

  • Move it to a directory in your 'load-path' (~/.emacs.d/ should work),

  • To compile, start Emacs and run the following command:

M-x byte-compile-file
js2-mode.el

Use

Add the following to your .emacs file:

(require 'js2-mode)
  (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))

This associates all Javascript files with JS2 mode.

Some features of the mode are:

  • Highlighting of syntax errors and doubtful structures, e.g. missing ';', and undeclared variables,

  • The auto-indentation system works.

I often make Javascript files dynamic in Rails projects, and the only feature I would wish for is for handling of Ruby ERB tags - currently they completely confuse the parser.