Jer
Jer

Reputation: 5648

How can I stop emacs from indenting the 2nd line of a javascript comma-separated list (e.g. array or json)?

Emacs indents my code like this:

var myArray = [
    1,
        2,
        3,
        4,
        5,
    ];

Instead of like this:

var myArray = [
    1,
    2,
    3,
    4,
    5,
];

How can I prevent this?

M-x version gives me: GNU Emacs 23.1.1 (x86_64-pc-linux-gnu, GTK+ Version 2.18.3) of 2010-03-26 on crested, modified by Debian

I'm not able to update my emacs version, unfortunately.

Upvotes: 2

Views: 373

Answers (1)

Chris
Chris

Reputation: 136880

It looks like you are using java-mode to edit JavaScript code. While Java and JavaScript share enough syntax that this will probably work okay, it is better to use a dedicated JavaScript mode¹.

Emacs includes js-mode from version 23.2, which is a reasonably good mode for basic JavaScript editing. If you can upgrade Emacs this is likely your easiest option. You may also be able to install js-mode (or its predecessor espresso-mode) on Emacs 23.1. Here is the latest version.

Alternatively, you can use a third-party mode like js2-mode, which actually includes a full JavaScript interpreter. There is also js3-mode, which claims to be

A chimeric fork of js2-mode and js-mode

Both js2-mode and the version of js-mode built into my Emacs 24.4 indent your sample code exactly as you want:

var myArray = [
    1,
    2,
    3,
    4,
    5,
];

¹Unfortunately, there is still enough confusion out there that it's worth stating that Java and JavaScript are completely different languages. You probably already know this; I think Emacs actually defaulted to java-mode for JavaScript code for a while.

Upvotes: 1

Related Questions