26

Is there a way to automatically remove trailing spaces in Eclipse?

I see there are nice functionality in Source like Correct Indentation and Format. But they dont remove trailing spaces.

Thanks

PS: What other functionalities of this kind you use to make the code nicer?

user1796942
  • 3,228
  • 5
  • 29
  • 38

3 Answers3

40

It's available as a Save action, at least. (I can't see it under the formatter options.)

Go to Window / Preferences, Java / Editor / Save Actions. Tick "Additional Actions" and click on Configure. In the "Code Organizing" tab, the first option is "Remove trailing whitespace".

Note that this will remove all trailing whitespace from Java files - not just those you've touched. If you're working with people who don't remove trailing whitespace, this can be messy in terms of later doing a diff.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    But it is a good practice in general to remove trailing white space, so even in a large team it would be good to enforce such a global codestyle rule. – Sergiu Dumitriu Jan 06 '13 at 03:03
  • 4
    @SergiuDumitriu: Well, there are numerous factors which get involved - including whether everyone's using tools which *do* remove trailing whitespace easily. That's an argument I don't want to get into here - I just wanted to give a heads-up as a warning. – Jon Skeet Jan 06 '13 at 03:07
  • numerous of files changed and hope gonna have great time with GIT – arvindwill Feb 06 '16 at 13:46
  • It's kind of crazy how far you have to dig to find this option, the answer is much appreciated! – gtd Jul 29 '16 at 05:13
  • Thanks! I was looking for this option, and it would've taken me forever to find it on my own. – David L May 04 '17 at 15:41
20

You can easily remove all the trailing whitespace within a single file by using a regular expression with the Find/Replace dialog. Enter [ \t]+$ in the "Find:" box and leave the "Replace with:" box empty. Check the "Regular expressions" option then click "Replace All"

Jim Rhodes
  • 5,021
  • 4
  • 25
  • 38
  • Great solution! Why is there no shortcut or toolbar/menu item for this easy task? I don't want to apply it as a save action, but every now and then, when I feel like it. – user1438038 Mar 08 '17 at 10:31
0

There is also the plugin "AnyEdit" from http://andrei.gmxhome.de/eclipse/. This tool removes the whitespace in every file type on save.

Sven
  • 722
  • 1
  • 7
  • 25