I'm not able to format my code in IntelliJ.
I can see the margin line (by default at 120 columns) but it seems that the activation from the menu:
Code -> Reformat Code
is just ignoring this margin.
I'm not able to format my code in IntelliJ.
I can see the margin line (by default at 120 columns) but it seems that the activation from the menu:
Code -> Reformat Code
is just ignoring this margin.
Do you mean that the formatter does not break long lines? Check Settings / Project Settings / Code Style / Wrapping.
Update: in later versions of IntelliJ, the option is under Settings / Editor / Code Style. And select
Wrap when typing reaches right margin
.Enabling "Ensure right margin is not exceeded" doesn't work for me in Intellij IDEA 2018.2. I have found the workaround, we need to change every elements below from "Do not wrap" to "Wrap if long".
After that, we can preview what kind of wrap type will be changed by looking into right panel. If we are satisfied, Click "OK" or "Apply" to apply the changes. Finally we need a mannual format by using CTRL+ ALT+ L in Windows and Command+ Shift+ L in MacOS.
IntelliJ IDEA 14, 15, 2016 & 2017
Format existing code
Ensure right margin is not exceeded
File > Settings > Editor > Code Style > Java > Wrapping and Braces > Ensure right margin is not exceeded
Reformat code
Code > Reformat code...
or press Ctrl + Alt + L
If you have something like this:
it will be converted to
instead of
This is why I select pieces of code before reformatting if the code looks like in the previous example.
Wrap when typing reaches right margin
IntelliJ IDEA 14: File > Settings > Editor > Code Style > Wrap when typing reaches right margin
IntelliJ IDEA 15, 2016 & 2017: File > Settings > Editor > Code Style > Wrap on typing
Or you can use the shortcut:
You can create a macro for Ctrl +Shift + S (for example) that do all this things:
Edit > Macros > Start Macro Recording (the recording will start). Click where you need.
For example:
Then, click on red button in bottom-right of the IDE to stop the Macro recording.
Set a macro name.
Go to File > Settings > Macros > YOUR MACRO NAME.
Right Click > Add Keyboard Shortcut, and type Ctrl + Shift + S.