How do I fix incorrect inline Javascript indentation in Vim?

I can't seem to get inline Javascript indenting properly in Vim. Consider the following:

  $(document).ready(function() {

  // Closing brace correctly indented
    $("input").focus(function() {
      $(this).closest("li").addClass("cur-focus");
    }); // <-- I had to manually unindent this

  // Closing brace incorrectly indented
    $("input").blur(function() {
      $(this).closest("li").removeClass("cur-focus");
      }); // <-- This is what it does by default. Argh!

  });

Vim seems to insist on automatically indenting the closing brace shown in the second case there. It does the same if I re-indent the whole file. How do I get it to automatically indent using the more standard JS indenting style seen in the first case?


The most comprehensive and bug-free Javascript indentation script is the one by Preston Koprivica. The so called OOP script that is in the proposed answer has severe bugs, and does not indent code properly that has square brackets.


Use JavaScript Indent: Javascript indenter (HTML indent is included) by Preston Koprivica. Thanks for the heads-up from oligofren - give him an up-vote.


The scripts mentioned above do not format the closure-syntax often used in jQuery correctly:

$(function() {
  // only one level of indentation, not two
});

This script works better for me: http://www.vim.org/scripts/script.php?script_id=2765


Most of these answers are from 2009 and, frankly, are out of date.

vim-javascript is much more recent and up-to-date than Preston's script.

Installation is a bit more complicated if you haven't started using Vundle yet, but it doesn't seem to suffer from the issues of the alternatives.