Java, Maven and Gitpod, part 5: the Formatter

This is the 5th post about using Java in Gitpod.

It assumes you have already read the first, second, third, and fourth posts.

We can benefit from automatic formatting. First, select (from F1) the command “View: Toggle Render Whitespaces”. We can see that the Maven archetype generated Java source code with spaces for indentation:

I prefer tab characters for indentation. If we select “Format Document” (by searching with F1 or by the shortcut “Strl+Shift+I”), the formatter changes the style of curly brackets in the “main” method, but it retains the current indentation characters.

Let’s configure the Java formatted for tab indentation characters. By pressing F1, we access the global search. Let’s start typing “formatter”:

We chose the second one (with “Preview”). We get a notification about a missing formatter profile:

Of course, we accept to create one. This will create a “java-formatter.xml” file in the “.vscode” directory so that our formatting profile will be part of the Git repository. It will also open a visual editor:

We select the “tab” “indentation policy” and uncheck “Detected indentation from file content” (otherwise, the formatter will still use the current indentation character from the current file). Note that the preview will show tab characters now:

Once the file for the formatted profile is saved (and we’ll commit that to the Git repository), we can try formatting our Java source code again, and this time, we get tab indentation characters (you might want to explore the other formatted settings):

If we try to format the “pom-xml”, we get an error saying there is no formatter for XML files; the pop-up offers to install one, and we get a list of available XML formatters. Let’s choose the Red Hat one:

Unfortunately, this formatter does not provide a visual editor for its settings; the customization is documented, but it requires a manual modification of the “.vscode/settings.json” (code completion is still available anyway). For example, to have tab characters (of size 4), I put this section:

When selecting “Format Document”, indentation spaces are turned into tab characters.

If we’re happy with this extension, we can follow the usual procedure to store it in “.gitpod.yml” (e.g., with the gear icon of the extension page).

That’s all for this post! Stay tuned for more 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.