ClearAngel
ClearAngel

Reputation: 41

How to change VS Code settings for Java to put open curly brace on the new line

I have been looking for answer for a long time in google, but unfortunately I haven't found anything. As in topic I am looking for tips to force VS code formatting java files like this:

if()
{
}

not this:

if(){
}

Upvotes: 4

Views: 3557

Answers (2)

Steven-MSFT
Steven-MSFT

Reputation: 8411

I agree with Snurrig, but I want to add some information.

In fact, the "Language Support for Java(TM) by Red Hat" extension build in a format setting under 'formatters' folder. But it does not work in default, for example, even you delete it, the format of "Language Support for Java(TM) by Red Hat" still works. This is because the format rules build in the plugins. But you can set the format settings explicitly through 'java.format.settings.url' in settings.json file. So you can point to the settings XML file under "Python" extension -> 'formatters' folder. In this file, if you like you can replace all the 'end_of_line' to 'next_line'.

Upvotes: 0

Mjaustro
Mjaustro

Reputation: 827

There is a way. It just takes a little bit of setup.

  1. Install this Java formatter in VS Code: Language Support for Java(TM) by Red Hat.
  2. You already now have working formatting. In your Java file, press Alt+Shift+F, or if that's not working, right click and select Format Document.
  3. To change formatting settings, first, download Google's Java style for Eclipse and save it.
  4. Open VS Code settings, File > Preferences > Settings, and search for "java format url". Enter the path to the style file you just downloaded. Java formatting setting
  5. Open your style file, and edit the formatting options you want. In your case, in order to change this (the default formatting):
    if (true) {
    
    }
    
    to this:
    if (true)
    {
    
    }
    
    you have to change the following line:
    <setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/>
    
    to this:
    <setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="next_line"/>
    
  6. Save. You might want to restart VS Code in order for the new formatting to work. Do 2. again and it should work.

As a side note: VS Code are working on a better experience for editing these formatting options: Java formatter.

Upvotes: 6

Related Questions