YAML file formatting in VSCODE

Viewed 40820

I just started using VSCODE and faced with an annoyance every time I paste in YAML code in an existing YML file. Basically the editor seems to auto format the document and in doing so messes up the significant spaces in the document. This causes builds in Azure Devops to break. Although VS code formats the document nicely into collapsible regions, the formatting annoyance makes it hard to use. Any help would be appreciated.

BEFORE:

BEFORE


AFTER: enter image description here

4 Answers

I fixed this by changing editor.autoIndent settings for yaml and dockercompose language

"[yaml]": {
  "editor.autoIndent": "advanced"
},
"[dockercompose]": {
  "editor.autoIndent": "advanced"
}

In VsCode, press ctrl+shift+p, and search for Preferences: Open User Settings (JSON). There I added this line:

"[yaml]": {
    "editor.defaultFormatter": "redhat.vscode-yaml"
},

I picked it because it contains the word yaml, so I figured "It must be yaml specific!". Anyhow, it seems to do a pretty good job for me.

Turn off the setting format on paste. This is a global setting, but plugins sometimes have their own, so if you're running a formatter like prettier, you'll need to see whether this is even an option with that plugin.

Looks like the problem is in the first line. Maybe when you copy the code, you're not copying the indentation on the first line. One trick I use, is copying from the end of the preceding line, so the copied code starts with a newline, and then the paste is perfect.

Or just add the indentation on that first line, after pasting.

Related