Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent VSCode auto format on save from removing final newline

I am using the last feature of VSCode called formatOnSave, which is super cool.
I have one tiny problem, the formatter tends to delete the new line at the end of json files like packages.json for example.

My linter want those new lines at the end of the file, and me too.

Is there a setting or a method that allows me to tell the formatter to keep new lines at the end of files?

Related issue:

  • Provide an option to insert a final newline #1666
  • Add "new line at end of file" option #12076
like image 953
Cyril Gandon Avatar asked Oct 17 '16 08:10

Cyril Gandon


People also ask

How do I stop VS Code auto format?

Enable/Disable Format On Save Open up VSCode Command Palette by pressing Ctrl + Shift + P. Search and select Open Settings (UI). Just start typing and it will auto-fill. Once there's a match, you can hit enter immediately, or manually click on the right option.

Why is VS Code formatting on save?

You have configured prettier to format as per the default settings. If you don't see the code formatted automatically on file save then it might be because you have multiple formatters installed in VS Code.

How do I turn off formatting in Visual Studio?

The solution was to go to 'Tools > Options > Text Editor > Basic > VB Specific' and turn 'Pretty Listing' OFF.

How do I turn off saved changes in Visual Studio Code?

Click the (...) button and then select Undo Last Commit to undo the previous commit. The changes are added to the Staged Changes section.


2 Answers

This option has been added since the release 1.8 of November 2016:

New editor settings

  • files.insertFinalNewline - automatically add a newline at the end of files when saving.
like image 58
Cyril Gandon Avatar answered Oct 06 '22 16:10

Cyril Gandon


If you wish to preserve the last line in package.json and not affect other file types, add below lines to your vs code configuration.

  "[json]": {
    "files.insertFinalNewline": true,
    "files.trimFinalNewlines": true,
  }

This basically tells VS code to

  1. Apply settings only to json files
  2. Insert final lines at end of the file
  3. Remove extra lines at the end of the file (i.e. only keep 1 empty line)
like image 33
Adarsh Madrecha Avatar answered Oct 06 '22 17:10

Adarsh Madrecha