tags:

views:

2331

answers:

5

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?

A: 

maybe some combination of these settings should be in your VIMRC file.

syntax on 
set syn=auto 
set showmatch 
filetype on 
filetype plugin on 
filetype indent on 
set tabstop=4 
set softtabstop=4 
set shiftwidth=4 
set expandtab
42
Many thanks for the suggestions, but I've already got most of these set and they don't seem to help.
Charles Roper
42
A: 

I think that's what

set cindent

is for.

Tomalak
Thanks, but I already tried that. It made no difference whatsoever.
Charles Roper
+14  A: 

I found the answer. The following indent file fixed the problem with inline Javascript:

html improved indentation : A better indentation for HTML and embedded javascript

And this one fixed the problem with a pure Javascript file:

OOP javascript indentation : This indentation script for OOP javascript (especially for EXTJS)

Charles Roper
I was just suggesting in comment to your reply that maybe the vim syntax file might be missing. :)
42
i've been wondering why javascript indentation is all wonky, thanks a lot!
FurtiveFelon
A: 

Assuming the syntax file has good indenting for java script, visually highlight the block and press =. This works for java so I would expect it to do something half decent for java script. The results probably also depend on the settings of tabstop, expandtab and maybe shiftwidth.

gq is useful too, it formats lines rather than indents them.

Thanks for that. The combo I usually use for indenting a whole file is gg=G. My problem was that when I did this, JS didn't indent correctly. My own answer above solved the problem.
Charles Roper
A: 

I had this same issue. This is the best of all javscript indentation scripts:

http://www.vim.org/scripts/script.php?script_id=1840

It requires the IndentAnything plugin

http://www.vim.org/scripts/script.php?script_id=1839

As an added bonus, I wrote this indent script that will make javascript blocks quite pretty. It uses the default html indenter by default (and the IndentAnything one when within a javascript block)

http://gist.github.com/371902

mikelikespie