FinnM
FinnM

Reputation: 411

Vim autoindent (gg=G) is terribly broken for JS indentation

My end goal here is to use gg=G to autoindent all of my JS code compliant to an eslintrc.js file.

So, currently I have syntastic and vim-javascript looking at my JS code with the following in my .vimrc

let g:syntastic_javascript_checkers=["eslint"]

Lets say that I have some decent JS like the following

const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');

const PATHS = {
  app : path.join(__dirname, 'app'),
  build : path.join(__dirname, 'build'),
};

const commonConfig = {
  entry : {
    app : PATHS.app,
  },
  output : {
    path : PATHS.build,
    filename : '[name].js',
  },
  plugins : [
    new HtmlWebpackPlugin({
      title : 'Webpack Demo',
    }),
  ],
};

The gg=G (normal mode) command mutilates the above into the following.

const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');

const PATHS = {
app : path.join(__dirname, 'app'),
      build : path.join(__dirname, 'build'),
};

const commonConfig = {
entry : {
app : PATHS.app,
        },
output : {
path : PATHS.build,
       filename : '[name].js',
         },
plugins : [
              new HtmlWebpackPlugin({
title : 'Webpack Demo',
}),
],
    };

Which is not cool.

Btw, vim-js-indent and vim-jsx-improve didn't do anything either.

Any help is very welcome, many thanks are in advance.

Upvotes: 1

Views: 564

Answers (1)

romainl
romainl

Reputation: 196886

Your "not cool" example is the result of the "generic" indenting you get when Vim didn't recognize your buffer as JavaScript and/or didn't apply JavaScript-specific indentation rules.

That code is indented correctly with this minimal setup:

$ vim -Nu NONE --cmd 'filetype indent on' filename.js

which:

  • detects that your buffer contains JavaScript,
  • applies JavaScript-specific indentation rules.

To ensure proper indenting, you must add this line to your vimrc:

filetype indent on

Upvotes: 3

Related Questions