Indenting Javascript in Vim - Problems with Lambda Functions in Functions

怎甘沉沦 提交于 2019-12-04 05:10:48

问题


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.


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/5326686/indenting-javascript-in-vim-problems-with-lambda-functions-in-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!