[Java] [IntelliJ IDEA] How to format only local changes when saving source code

less than 1 minute read

Thing you want to do

I want to be able to execute the following in a batch when pressing cmd + s

  • Delete unnecessary import statements
  • Arrange the order of import statements
  • Only changes that have not been checked in to the repository
  • Save code

Environment

  • IntelliJ IDEA 2020.1.2 (Ultimate Edition)
  • macOS 10.15.4

Method

Format settings

Press cmd + opt + shift + l to display the “Reformat File dialog” Set Scope to “Only VCS changed text”, check Optional “Optimize imports”, and press “Run” dialog

“Only VCS changed text” can be set only when the project is version-controlled and there is a local change, so if it is grayed out, check whether it is a version-controlled project and whether it has a local change. To do.

macro registration

Press Editor -> Macros -> Start Macro Recording and then do the following

  • cmd + shift + l (reformat file)
  • cmd + s (save All)

start macro recording

Press Editor -> Macros -> Stop Macro Recording, then name and save macro Screenshots 2020-06-14 9.43.44.png

Keymap settings

Preferences -> Keymap -> Macros -> click saved macro -> Add Keyboard Shortcut Enter “cmd + s” and OK Screenshot 2020-06-14 9.45.59.png