Using Vim for JavaScript Development
Here is how I do it …
Plugin management
I recommend using pathogen to manage plugins, as then you can simply clone the plugin repos into your .vim/bundle directory and you’re done. (and run ‘:Helptags’ to install help).
While this is not bad, I personally prefer another Javascript syntax definition file, which provides a more complete set of keywords (eg. browser events such as ‘onmouseover’), and thus highlights them differently. To use it, download and copy it to
~/.vim/syntax/javascript.vim
Now when viewing the same .js file, you will notice a few differences:
Folding
Another feature which this syntax file adds is the ability to fold functions. You can fold a function by positioning the cursor within it and typing ‘zc’. Then it will collapse to a single blue line with the function definition highlighted in it, and the number of lines contained within the fold. This can be a handy way to defocus attention from functions you are not interested in. It works in nested functions as well.
Whitespace settings
I generally want Javascript to have spaces instead of tabs, with 4 spaces for each
indent level. This can be achieved by adding the following content as the file
.vim/after/ftplugin/javascript.vim
" set whitespace for javascript to always use 4 spaces instead of tabs
setlocal expandtab
setlocal shiftwidth=4
setlocal shiftround
setlocal tabstop=4
Indentation
Vim’s default indent file for javascript merely sets the indentation to cindent… this is not very effective. For best results, go get the web-indent plugin.
Then you can use the builtin indent commands (essentially ‘=’ in command mode, combined with a motion, eg. ‘gg=G’ for the whole file, or just select some text in visual mode and hit ‘=’).