Fork me on GitHub

Javascript Syntax Checking From Vim

Syntax checking from vim is handy. By checking your Javascript syntax from vim, rather than the browser, you'll save time and aggravation. To do it, you'll need Spidermonkey, which allows you to run Javascript without a browser, and JsLint, a Javascript syntax-checker writter in Javascript.

Installing Spidermonkey

Consult the build instructions page for installation instructions for many architectures, or use the quick instructions below for Ubuntu and Centos.

Quick install for Ubuntu
sudo apt-get install spidermonkey-bin.
Quick install for Centos 5
tar zxvf js-1.7.0.tar.gz
cd js/src
make -f Makefile.ref
mv Linux_All_DBG.OBJ/js /usr/bin

Once you've installed Spidermonkey you'll be able to enter a Javascript shell by entering the command 'js' (exit with CTRL-d).

Setting Up JsLint

Next you'll need to download the JsLint Javascript syntax checking library. JsLint is composed of one Javascript file: fulljslint.js.

Download it and put it somewhere handy, for example:

mv fulljslint.js /home/admin/bin/js

Running JsLint

Next you'll need to add a Javascript file which will implement JsLint, using the technique outlined by Ian Bicking.

For example, I could create a file called runjslint.js like this as /home/admin/bin/js/runjslint.js:

var body = arguments[0];
var result = JSLINT(body);
if (result) {
 print('All good.');
} else {

This file, when ran using Spidermonkey, will check the syntax of Javascript data passed as a command line argument.

Integrating with Vim

Next you'll need to add a line to your .vimrc script to allow you to enter a command for syntax checking.

Here's an example that enables me to syntax check by typing ":js".

cabbr js !js /home/admin/bin/js/runjslint.js "`cat %`"

Formatting JsLint's Results

Last, but not least, you may want to add this Python script to change JsLint's results from HTML/CSS to plain text. Put this script in an appropriate place, for example '/home/admin/bin/python/'.

import sys
import re
def format_lint_line(line):
 line = line.replace('<p>', '\n')
 line = line.replace('&nbsp;', ' ')
 return line
def remove_html_tags(data):
 p = re.compile(r'<.*?>')
 return p.sub('', data)
for line in sys.stdin:
 print remove_html_tags(format_lint_line(line)),

Change your .vimrc file to use it as a filter.

For example:

cabbr js !js /home/admin/bin/js/runjslint.js "`cat %`" \| /home/admin/bin/python/