Greg Mattes
Greg Mattes

Reputation: 33949

How to disable code formatting for some part of the code using comments?

I'd like to selectively disable the IntelliJ IDEA code formatter for a portion of code just like I can in Eclipse. Does IntelliJ support this feature, and if so, how do I use it?

Upvotes: 445

Views: 155599

Answers (6)

Ryan
Ryan

Reputation: 1

A related question is how to stop IntelliJ formatting all files of a certain extension. I recently started using ktlint for my codebase and wanted IntelliJ to not interfere.

Using the ktlint IntelliJ plugin, I setup ktlint to run on any save in distract-free mode.

Under Tools -> Action on Save I modified the reformat code action to exclude Kotlin files.

Under Keymap, I modified the Reformat Code command to not use the hot key I normally use for saving (CMD-s).

Under Keymap, I modified the Save All command to have the hotkey CMD-s.

Current for IntelliJ 2023.3.3, Ktlint IntelliJ plugin 0.21.0

Upvotes: -1

olsli
olsli

Reputation: 871

In xml files, use:

<!-- @formatter:off -->
<!-- @formatter:on -->

Upvotes: 36

Carlos Fonseca
Carlos Fonseca

Reputation: 8201

Since version 13 it's possible to wrap the code with

// @formatter:off
...
// @formatter:on 

IntelliJ IDEA v.2018+:

File > Settings > Editor > Code Style

IntelliJ IDEA v.2016+:

Preferences > Editor > Code Style

IntelliJ IDEA v.14+:

Preferences > Editor > Code Style > Formatter Control

You can change the formatter control markers, as long as they're in comments.


Ensure formatter markers in comments are enabled, as shown in the following figure:

Formatter Control Preference

Upvotes: 787

Holger Brandl
Holger Brandl

Reputation: 11192

It's currently not possible to exclude entire files (like regression test data xmls) from formatting. See https://youtrack.jetbrains.com/issue/IDEA-167112

Upvotes: 0

Louis St-Amour
Louis St-Amour

Reputation: 4135

Note for Carlos' answer of @formatter:off and @formatter:on to work, you may need to enable the preference first:

In IntelliJ Preferences, under Code Style, General, Formatter Control there is a checkbox "Enable formatter markers in comments"

Discovered via How to config intellij-idea not format some part of the code?

IDEA-56995 Disabled code formatting per region using comments

Upvotes: 190

CrazyCoder
CrazyCoder

Reputation: 401945

Obsolete answer from 2010:

No, it's not possible right now, I've submitted a new issue which you can track.

As a temporary solution you can use external formatter plug-in for IDEA which can utilize Eclipse code formatter (I didn't check whether this particular option is supported).

Upvotes: 9

Related Questions