Intellij reformat on file save
Solution 1:
This solution worked better for me:
- Make a macro (I used Organize Imports, Format Code, Save All)
- Assign it a keystroke (I overrode Ctrl+S)
Note: You will have to check the box "Do not show this message again" the first time for the organized imports, but it works as expected after that.
Step-by-step for IntelliJ 10.0:
- Code -> "Optimize Imports...", if a dialogue box appears, check the box that says "Do not show this message again.", then click "Run".
- Tools -> "Start Macro Recording"
- Code -> "Optimize Imports..."
- Code -> "Reformat Code..."
- File -> "Save all"
- Tools -> "Stop Macro Recording"
- Name the macro (something like "formatted save")
- In File -> Settings -> Keymap, select your macro located at "Main Menu -> Tools -> "formatted save"
- Click "Add Keyboard Shortcut", then perform the keystroke you want. If you choose Ctrl+S like me, it will ask you what to do with the previous Ctrl+S shortcut. Remove it. You can always reassign it later if you want.
- Enjoy!
For IntelliJ 11, replace
step 2. with: Edit -> Macros -> "Start Macro Recording"
step 6. with: Edit -> Macros -> "Stop Macro Recording"
Everything else remains the same.
IntelliJ 12
8. The Preferences contain the Keymap settings. Use the input field to filter the content, as shown in the screenshot.
Solution 2:
I suggest the save actions plugin. It also supports optimize imports and rearrange code.
Works well in combination with the eclipse formatter plugin.
Search and activate the plugin:
Configure it:
Edit: it seems like it the recent version of Intellij the save action plugin is triggered by the automatic Intellij save. This can be quite annoying when it hits while still editing.
This github issue of the plugin gives a hint to some possible solutions:
https://github.com/dubreuia/intellij-plugin-save-actions/issues/63
I actually tried to assign reformat to Ctrl+S and it worked fine - saving is done automatically now.