How enable auto-format code for Intellij IDEA?

Solution 1:

The formatting shortcuts in Intellij IDEA are :

  • For Windows : Ctrl + Alt + L
  • For Ubuntu : Ctrl + Alt + Windows + L
  • For Mac : ⌥ (Option) + ⌘ (Command) + L

Solution 2:

I have found two ways to do this:

  1. Go to Settings> Keymap.In the right portion go to Editor Actions> complete current statement.Click on it and select add keyboard shortcut. Press ; and select ok.

  2. Use macro. Go to

Edit> Macros> Start Macro Recording.

Now press semicolon and keyboard shortcut to reformat code (you can find the keyboard shortcut from other answers or from settings > keymap).

After doing reformat go to

Edit> Macros> Stop Macro Recording

Save the macro with a name (auto format or something else). Then go to

Settings> Keymap> Macros> auto format (the macro name).

Click there and select add keyboard shortcut, then press semicolon and click ok. Now whenever you will press semicolon it will write semicolon and do auto format.

Solution 3:

You can do this with Save Actions plugin Refer This article on how to configure the plugin.

Save Actions plugin Supports configurable, Eclipse like, save actions, including "optimize imports", "reformat code", "rearrange code", "compile file" and some quick fixes for Java like "add / remove 'this' qualifier", etc. The plugin executes the configured actions when the file is synchronised (or saved) on disk.

  1. Install the plugin
  2. Go to Settings > Other settings > Save actions
  3. Tick Activate save actions on save
  4. Tick Reformat file
  5. Apply > OK

enter image description here

I prefer the hot-keys though, For Mac,

To format the code : Ctrl+Alt(Option)+L

And additionally I do,: Ctrl+Alt(Option)+O , This will remove unused imports and format the import list as well.