views:

329

answers:

5

Hi,

I'm looking for an automatic way in eclipse to reformat curly braces to K&R style, eliminating braces for single statements if, etc. Is there such a way?

Thanks.

A: 

right click in your editor => source => format

Hans Westerbeek
+3  A: 

Before you reformat you need to customize the formatter settings in the Preferences Dialog Java/ Code Style / Formatter to your K&R settings if the default settings don't match your requirements.

The Preferences Dialog is opened from Mainmenu / Window / Preferences

You can even configure a save action Java / Editor / Save Action to format source code on save.

stacker
Is there an option to disable braces in one-liners ifs?
Amir Rachum
No I don't think so code is formated but not changed, anyway the edit dialog has so many options.
stacker
You can remove braces in simple statements with using Source/Clean Up... (you have to configure it in preferences - in the Code Style page set 'Use blocks in if/while/for/do statements' to 'Only if necessary'). Also you can do this kind of clean up as a save action as well). However you cannot do this only for if-s but not while-s.
Csaba_H
+2  A: 

A lot of options for formatting can be chosen in the preferences dialog (Java -> Code Style -> Formatter).

After that, you can simply format your code by pressing ctrl-shift-f (windows)

Also, you can choose to automatically format your code whenever you save your file. This is also in the preferences dialog (Java -> Editor -> Save Actions)

Fortega
A: 

You can customize how Java code is formatted going to Window > Preferences. There, choose Java > Code Style > Formatter, click on New... to create a new profile. Then Edit... it.

However, I'm quite sure Eclipse's code formatter won't add or remove braces, it will simply position them according to your style rules. You will need a separate tool to do this or a fancy search and replace.

Santi P.
A: 

Is there a way to do it programatically e.g. using eclipse plugins.

I have created a code template. I want to enforce it so that everytime a user selects save or saveas,the code template is checked against the one I created. If it matches the file is saved otherwise the user gets an error message.

The problem I am facing is - how do I get Code Style (template) name at run time.. and where do i add this code so that to enforce it...

Any pointers is greatly appreciated.

kumar
This is a complicated enough question to be asked on its own. Also, it's not an answer...
Amir Rachum