How to make Eclipse clean up & format your code for you

Discussion in 'Resources' started by Njol, Jun 1, 2012.

Thread Status:
Not open for further replies.
  1. Offline

    Njol

    There are likely not many people here on Bukkit who about this: Eclipse has built-in code clean up & formatting. It is a function I use constantly because it helps to keep the code organized and well-looking and makes writing code easier.
    It can e.g. automatically change this code:
    Code:
    import something.i.dont.need;
     
    public void onEnable() {Logger logger=getLogger();
    logger.info("enabled");}
    to this cleaned up version:
    Code:
    @Override
    public void onEnable() {
        final Logger logger = getLogger();
        logger.info("enabled");
    }
    Eclipse splits code clean up in two parts: clean up and formatting. You can run each one separately, but I suggest to use both together as it has the best results and it is what I'm trying to explain in this tutorial.

    How to enable clean up and set your preferences
    1) Code clean up
    Clean Up itself improves code by adding missing annotations, removing unused imports, declaring variables final if they can be final, etc., but doesn't actually change the layout of the code. This is done by the Formatter which is explained later on.

    Eclipse already has some default Clean Up settings, but these barely do anything. You'll have to make your own settings to make Clean Up actually clean up your code.

    To start open the preferences window from the menu bar:
    [​IMG]

    And then got to Java -> Code Style -> Clean Up:
    [​IMG]

    Eclipse saves settings in profiels so you can easily change them, but you'll likely only ever use one profile. Since you can't edit the default profiles you have to make your own profile by clicking on 'New...'. You can give it any name you want, I personally named my profile after my username "Njol".

    [​IMG]

    When you click OK, a new windows pops up. Here you can set what Eclipse should change when you tell it to clean up your code. In the beginning you shouldn't change anything but tick the following checkboxes:

    [​IMG]
    [​IMG]

    When you're done click on OK to save and close the window.

    In the 'preferences' window (where the clean up profiles are listed) I suggest to untick this checkbox:
    [​IMG]
    It will prevent an unneccessary window which would otherwise pop up every time you want to clean up your code.

    2) Code formatting

    Clean Up can also format the code, i.e. correct indentation, manage empty lines, brackets, spaces, etc. This is handled with a Formatter profile, i.e. you will have to create another profile, but this time in the Formatter section. The Formatter preferences can be found here:
    [​IMG]

    Now create the new profile, preferably named the same as your Clean Up profile:
    [​IMG]
    I suggest to use the Eclipse formatter as base for your formatter, but you can also use the official Java formatter which e.g. limits lines to 80 characters.

    The formatter has many options, and setting them all can take quite a while. But not changing Eclipse's default formatter will likely mess up your comments, thus I suggest to disable formatting of comments in the beginning. For reference here are my settings for comment formatting:
    [​IMG]
    As you can see I only allow Javadoc comments to be formatted.

    An interesting tab is 'Braces' where you can set whether you want Eclipse to put braces on the same line as functions or on the next line, i.e. whether it should format functions like this:
    Code:
    void myFunc() {
        // code
    }
    or like this:
    Code:
    void myFunc()
    {
        // code
    }
    So, what was this work all for?
    After writing some (maybe messy) code you can simply right click your project and select source->clean up:
    [​IMG]

    Eclipse will now apply your clean up and formatting to the code.
    If you do this for the first time your code will likely look quite differently now, and if you think that Eclipse changed too much/too little you should change your settings to fit your code style.

    If you intend to use clean up often you should make a keyboard shortcut for it (the settings for that are in the preferences window under General -> Keys).

    My Settings
    If you're curious or want some example settings other that Eclipse's defaults you can download my personal preferences:
    Clean Up preferences: clean up.xml
    Formatter preferences: formatter.xml
    You can import them with the 'Import' button on the clean up/formatter preferences page:
    [​IMG]
    (Don't worry, none of your profiles will be overwritten, but a new profile called "Njol" will be added)

    An additional Tip
    If your indentation is messed up you can simply select the wrong lines and press crtl+I and Eclipse will fix the indentation.
     
  2. Offline

    chaseoes

    I've always used CTRL + SHIFT + F without ever having to go through all that.. what's wrong with using that vs. what you could change? It seems to work fine.
     
  3. Offline

    Njol

    Clean Up does more than just format code, it can make variables final, remove unused imports, etc., but by default does nothing, so you have to go through it's configuration. And since I already made a tutorial I also explained how to make a custom formatter, since I think that the default settings are bad as it e.g. messes up commented code.
    I think I should change the thread's title a little though ;)
     
  4. Good job adding this, people should know there's an easy way to format and clean your code.
    I already knew this tough since I've found it in the right click menu and messed with it, I have a reliable code cleaner that makes all my code nice and tidy XD
     
  5. Offline

    Derjyn

    Very nice tidbit to share for those that didn't know. Heh... kinda nice to run through that, and see "The refactoring does not change any source code" on a project.
     
  6. Offline

    HollowCube

    Set the maximum line width for line wrapping to 9999. Hopefully it never will wrap my code again. (It better not get that long anyways.)

    Thanks for pointing out the fact you could customize the way Eclipse formats and cleans up your code, very helpful that I don't manually have to undo code wrapping and other small annoyances I have with the formatter and clean up tools.

    Oh wait, did that take an entire hour? :confused: (Of course I read every possible option, what else?)
     
  7. HollowCube
    You can just disable the wrapping... but now I understand why it was kinda confusing how to, let me explain how:
    - Click in the list on the left with "Annotations", "Class definitions", etc
    - Press Ctrl+A to select all of them
    - Pick from "line wrap policy" below the "Do not warp" option and that's it !

    EDIT:
    Njol
    Do you happen to know/have the exact requirements that the CraftBukkit team is requiring people to use when editing the source ? It would be ALOT easier to just asign a custom formatter to the CB source and format properly when we want to release.
    I've seen alot of pull requests getting rejected because of the format :/
     
  8. Offline

    Njol

    There's a pull requests guideline somewhere (IIRC on these forums). Creating a formatter profile from it shouldn't be a big problem ;)
     
  9. Offline

    chaseoes

    https://github.com/Bukkit/CraftBukkit/blob/master/README.md
     
  10. Yeah I know about that readme...
    Anyway, I'll tweak a copy of the default formatter until Ctrl+Shift+F doesn't format diferently from the original CB files.

    EDIT: Actually that doesn't seem possible because there are inconsistencies in the code :/

    I'm not sure if the Bukkit team will find this a good ideea, but I would format all files according to the format I made which reflects their readme description and I'll post the format settings too, it would be ALOT easier for everybody to keep the same coding style they want.

    Does anyone find this a good idea ? XD
    I would need some help from other IDE users to make the same format settings.
     
  11. Offline

    Scullyking

    Thanks!
     
Thread Status:
Not open for further replies.

Share This Page