How to remove unnecessary blank line on code formatting in IntelliJ?

Intellij IdeaPhpstormWebstormJetbrains IdeGoland

Intellij Idea Problem Overview


Is it possible to remove empty/blank lines using code formatting in Intellij IDEA?

Intellij Idea Solutions


Solution 1 - Intellij Idea

Yes. It is possible to configure the number of blank lines in the settings menu (CTRL+ATL+S): File -> Settings -> Editor -> Code Style -> Java(or Scala or whatever your language is) -> Blank Lines

Blank lines configuration

Solution 2 - Intellij Idea

  • File >> Setting >> Editor >> Code style java >>Blank lines tab

  • You should change to 0 in code label(as picture), It would remove all unnecessary blank line when press format shortcut: ctrl + alt + L

enter image description here

Solution 3 - Intellij Idea

You can find and replace with regex option also ^(?:[\t ]*(?:\r?\n|\r))+. It searches all empty lines in file. You need to just replace it with empty

Solution 4 - Intellij Idea

I use regular expression to remove extra blank line from code. Here are the instructions

  • Open Find and Replace dialog. Use shortcut CTRL+SHIFT+R.
  • In the search box type ^(?:[\t ]*(?:\r?\n|\r)){2,}. This will search for two ore more blank lines.
  • In a replace box type \n. This will replace with one blank line.

enter image description here

  • Open Reformat Code dialog and click Run. Use shortcut CTRL+ALT+L.

This works on all JetBrains IDEs. Use the screenshot as referece.

Solution 5 - Intellij Idea

Just in case it helps someone using newer versions of Intellij, in Intellij IDEA 2016.2.4 it is File -> Other Settings -> Default Settings -> Editor -> Code Style -> Java(or Scala or whatever your language is) -> Blank Lines

Solution 6 - Intellij Idea

For those trying to remove blank lines at the end of the file, this became a feature as of August 2020.

The proper place to configure this action is under Settings|Editor|General|On Save. Check "Remove trailing blank lines"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEugeneView Question on Stackoverflow
Solution 1 - Intellij IdeaVicView Answer on Stackoverflow
Solution 2 - Intellij Ideahuu duyView Answer on Stackoverflow
Solution 3 - Intellij IdeaAjaykumarView Answer on Stackoverflow
Solution 4 - Intellij IdeaMadan SapkotaView Answer on Stackoverflow
Solution 5 - Intellij IdeamithunpaulView Answer on Stackoverflow
Solution 6 - Intellij IdeaPeterView Answer on Stackoverflow