0

I have following javascript code:

function abc(alpha) {
    if(alpha == undefined) { alpha='0.5' };
    var color='rgba(';
    for(var ii =0; ii < 3; ii++) {
       color += Math.round(Math.random()*255) + ",";
    }
    color += alpha;
    color += ')';
    return color;
}

Vim indents above code as:

function abc(alpha) {
        if(alpha == undefined) { alpha='0.5' };
        var color='rgba(';
                        for(var ii =0; ii < 3; ii++) {
                        color += Math.round(Math.random()*255) + ",";
                        }
                        color += alpha;
                        color += ')';
                        return color;
                        }

This kind of behavior occurs in many programming languages, whenever we have '(' or '{' as part of a literal string. Rest of the file gets incorrect indentation as well. How to achieve correct indentation in such cases?

workwise
  • 1,003
  • 16
  • 33

2 Answers2

1

Using double-quote seems to work:

var color="rgba(";
tivn
  • 1,883
  • 14
  • 14
  • That's odd if that's what vim requires - by convention I use single quotes for JS strings since that then allows for correct use of double quotes for HTML attributes embedded within those strings. – Alnitak Mar 18 '15 at 07:46
  • I guess the default formattter for javascript is simply treat your text as a C source code ( see $VIMRUNTIME/indent/javascript.vim, also http://stackoverflow.com/questions/1652765/how-can-i-format-js-code-in-vim answer by @jamessan ). As you know, C string only using double-quote. Perhaps this is the reason single-quote not working. – tivn Mar 18 '15 at 13:15
0

Try this plugin:

JavaScript Indenter

qiubix
  • 1,302
  • 13
  • 22