Question

I have autoindent and smartindent in vim turned on, but nocindent turned off. I'm trying to indent some JSON text without pretty-printing the whole thing, which would be too intrusive:

{
  "a" : "value1",
  "b": "value2",
  "c": "value3",
  ...

Gets formatted by gg=G as:

{
  "a" : "value1",
    "b": "value2",
    "c": "value3",
    ...

What's the logic going on there, and what options can I set to fix it, if it's possible? I tried toggling options like autoindent, smartindent, and cindent (with their "no" counterparts), but it doesn't have an effect on the = command. My latest attempt had these options:

autoindent
smartindent
nocindent
cinoptions=
indentexpr=
indentkeys=0{,0},:,0#,!^F,o,O,e
Was it helpful?

Solution

I can explain the logic, but I'm not sure of an easy fix. Vim's internal indenter is following C-style syntax, so since the "a" : "value1", line doesn't end with a ; it assumes that the following lines are a continuation of that statement and they should be indented to show that.

:help C-indenting goes into great depth discussing the various indent options and how they interact. I skimmed it and nothing jumped out at me, but it's worth a read.

If you have an external formatter that better recognizes the structure of your code, you can always set equalprg to run that instead of using the internal formatter.

Edit: On second thought, set cinoptions+=+0 will disable indenting for line continuation. This will also affect regular code, but it might be a reasonable tradeoff depending which annoys you more. You can also set it per filetype if you're editing standalone .json files.

OTHER TIPS

The built-in indent settings won't totally cover a complex, non-C language like JSON. Better use a tailored indent setting, like the indent/json.vim indent plugin that is part of vim-json.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top