Using c-mode to edit Javascript in Emacs

March 17, 2005

As part of my foray into the Greasemonkey world, I've been on the lookout for a good environment for editing standalone Javascript files.

Emacs being the One True Editor, you'd think that there would be a decent major emacs mode for editing Javascript, and you'd be wrong.

I tried installing:

Using Emacs, I get the following message when trying to switch to javascript-mode:

File mode specification error: (file-error "Cannot open load file" "c-mode")

I tried a few things to fix this, but they only seemed to make things worse.

Just using straight c-mode with Javascript works fairly well, although for some reason c-mode in Emacs 21 out of the box has an irritating indentation offset of only two spaces.

We can fix that up right quick, however.

Add the following to your .emacs file to fix the indentation problem and associate .js files with c-mode:

; Indent c code four spaces

(setq c-basic-offset 4)

; Associate c-mode with the .js extension

(setq auto-mode-alist (append '(("\\.js$" . c-mode)) auto-mode-alist))