Search code examples
javascriptvimindentationauto-indent

Vim - how to achieve correct indentation when code has parentheses in literal string


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?


Solution

  • Using double-quote seems to work:

    var color="rgba(";