Switch active IntelliJ Code Style for all local projects

I would like to standardize my java code style as per Google Java Style Guide. I downloaded intellij-java-google-style.xml, made a few custom tweaks and imported it in IntelliJ in the global IDE section:

Preferences… >> Editor >> Code Style >> gear icon >> Import Scheme >> IntelliJ code style xml

This applies the Code Style to the current project. However, existing IntelliJ projects keep their existing code style. I can see the new Google Style in the other projects’ drop-down menus, but I have to manually reselect it for each project. My problem is I have hundreds of projects.

I would like to automatically select the new Google code style for all existing projects without having to go through the Preferences for each one. But how?

NOTE: I don’t want to actually auto-format the code in my projects, that would be a git nightmare.

Answer

IntelliJ does not provide a way to automatically change code style on existing local repos. So we need to think outside the box.

Recursive Search-And-Replace

It turns out IntelliJ stores the active code style in .idea/codeStyles/codeStyleConfig.xml:

<component name="ProjectCodeStyleConfiguration">
  <state>
    <option name="PREFERRED_PROJECT_CODE_STYLE" value="OldCodeStyle" />
  </state>
</component>

We can do a recursive search-and-replace on all the code style config files in a folder and replace the value field in each. First, make sure you import the Google Style XML into IntelliJ as described in the question and call it GoogleStyle.

Here’s the bash command. find recursively searches for all the paths to codeStyleConfig.xml. sed replaces the current code style with GoogleStyle.

find ~/projects -name codeStyleConfig.xml -type f -print0 | xargs -0 sed -i "" -E "s/(.+PREFERRED_PROJECT_CODE_STYLE" value=")(.+)(" />)/1GoogleStyle3/"

This command has been tested on MacOS 11 and IntelliJ 2020.2. I have not tested on Linux. To understand how the command works, see here and here. For Windows, you can use Notepad++ to do a regex find-and-replace, install a bash library like Cygwin or find PowerShell equivalents (see here and here).