Eclipse doesn’t currently offer an option to beautify Apex code. Sorry about the trick title. However, I will describe techniques that will help you clean up your code’s indentation. Neither way is perfect, but they have helped me make my code more readable. In the meantime, vote up this idea for the enhancement.
Method 1: Developer Console
This technique uses the Developer Console to indent the source code. Then we refresh the code in Eclipse.
- In the Developer Console
- Open the class
- Select all or just a section of code to indent
- Press Shift + Tab
- Save
- In Eclipse
- Right-click the class name
- Select ‘Force.com’ -> ‘Refresh from Server’
Method 2: NotePad++ with the TextFX plugin
If you use Windows and don’t have NotePad++, download it now. It is an incredibly helpful free text utility. The plugin called TextFX has a feature to reindent code. The menu for TextFX plugin appears after it is installed. The plugin feature is intended for C++, but it also works well for APEX. I think this does a better job than the Developer Console.
- Copy your code from Eclipse
- Paste it into a Notepad++ window
- Select ‘TextFX’ -> ‘TextFX Edit’ -> ‘Reindent C++ code’
- Copy the indented code
- Paste it back into Eclipse
The function will indent with tabs by default. It can be changed to use spaces by selecting ‘Settings’ -> ‘Preferences…’ -> ‘Tab Settings’.
Bonus: Indent Visualforce
This can be done in the Eclipse Force.com IDE. However, be careful because it will sometimes remove an end bracket when it is in a style attribute. For example: <div style=”width: {!MyWidth}”> will end up like <div style=”width: {!MyWidth”>
- Select the section of Visualforce code that you want to indent
- Press Ctrl + Shift + F
Eclipse editor preferences control the number of spaces that Visualforce is indented. To change the spacing, select ‘Window’ -> ‘Preferences’. Expand ‘Web’ -> ‘HTML Files’ -> ‘Editor’.