5

I know that IntelliJ perform code formatting using the short Key ctrl+alt+L. Is there anyway we can set it up automatically on file save as it happen in eclipse.

Ashish
  • 14,295
  • 21
  • 82
  • 127

1 Answers1

13

There is not, at least not directly. The reason being is that IDEA routinely saves files (after a period of inactivity, before a unit test is run, before make, etc.) It's a bit of a different philosophy. Because of this, doing a reformat on a save would cause a lot of "code jumping". Secondly, Since IDEA formats the code as you type, and can be set to format when pasting code, code should (mostly) already be properly formatted. Of course, the some of the more subtle things (number of blank lines between methods for example) need a code reformat. Note that you can set it so code is formatted before being committed to source control. There's an option for it in the commit dialog.

If you really want this behavior, I suggest the following. Record a macro (Edit > Macros) that does a reformat followed by a save. Save the Macro with a name (i.e. a non-temporary macro). Next, go into the keymap in Settings (File > Settings > [IDE Settings] Keymap) and remove the Ctrl+S mapping from Save and map it to your macro.

EDIT

I didn't initially notice vlcekmi3's duplicate comment. One answer to that question has a similar IDEA of using a macro.

Javaru
  • 30,412
  • 11
  • 93
  • 70
  • Thanks Mark for the great explanation. – Ashish Jan 04 '14 at 02:33
  • “IDEA formats the code as you type“ how to enable this? – Tim May 24 '18 at 14:34
  • There's not one setting... it's various settings such as items on the _Settings>Editor>General>Smart Keys_ & _Auto Import_ pages, among other places. And to clarify a bit, it doesn't format _everything_ as you type... just the primary things like indentation, auto closing of parenthesis/braces, etc.But if configured for braces on new line, and you type a brace on the same line and hit enter, it is *not* moved to the new line. You need to run the "Reformat Code" (`Ctrl+Alt+L` | `⌥⌘L`) or "Show Reformat File Dialog" actions (`Ctrl+Alt+Shift+L` | `⌥⌘⇧L`) actions. Sorry for any confusion on that – Javaru May 24 '18 at 17:57