Indenting Javascript in Vim - Problems with Lambda Functions in Functions

I have a problem with javascript indenting in vim. Everything works great, except that the indenting of inline functions as parameters of a function do not work. This is a javascript only problem (no html involed).

Example

someFunc(function() {
    if(foo) {
        bar;
    } else {
        bar;
    }
});

is indented to

someFunc(function() { 
        if(foo) { 
        bar; 
        } else { 
        bar; 
        } 
        });

Do you have the same problems? How can I fix that? I tried some scripts from vim.org but they seem to have the same problem.

A script that emulates TextMates javascript indenting functionality would be perfect.

Answers:

Answer

Vim's built in expression for evaluating javascript indentation is terrible. You can fix it by installing the Better Javascript Indentation plugin, or get the source on github if you prefer to install your plugins as git submodules. Installing this plugin will ease the pain. Each time you press return at the end of a line of JavaScript, your cursor should be positioned with the correct level of indentation. Also, you'll be able to use the = command to auto-indent your javascript. Install the plugin - you'll wonder how you got by without it.

Answer

You are probably using 'cindent' with JavaScript. You can try using 'smartindent' instead.

From the docs, what 'smartindent' does is:

Do smart autoindenting when starting a new line. Works for C-like programs, but can also be used for other languages. 'cindent' does something like this, works better in most cases, but is more strict...

You can switch to smartindent by:

set nocindent smartindent

I tested with your code above and it indents as you expect.

See also: Indenting source code - Vim Tips Wiki

Answer

I believe the answer to this problem is to remove any cindent/smartindent/autoindent from your .vimrc and use filetype indent instead (the "set no*" lines aren't necessary, just being pedantic).

set nocindent
set nosmartindent
set noautoindent
filetype indent on

I was having the same problem, and this is what made vim behave. This also stopped vim from "unindenting" CSS rules at the colon (:) when typing them into an HTML style tag, my other pet peeve.

vim should set the correct indenting rules if you open/save a file with the *.js extension, but you may need to explicitly set ":set filetype=javascript" if you start editing a new (unsaved) file.

vim's indenting isn't horrible, just misunderstood. For as many programmers that use it, it'd be hard to believe the default indent rules were really that bad.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.