Search code examples
kotlinintellij-ideareformatting

How to suppress reformatting for selected code in Intellij?


I have some Kotlin code, over 100 lines long, within a larger class. The code should look similar to this:

fun generateAllCards(): Array<Card> {
    return arrayOf(
        Card(FORMAT_1, COLOUR_BLACK, TYPE_RUN, 1, POINTS_1, arrayOf(RunAbility(arrayOf(TRIGGER_RAN_BLUE), EFFECT_CAN_FLY_10_SEC))),
        Card(FORMAT_2, COLOUR_YELLOW, TYPE_DRIVE, 3, POINTS_3, arrayOf(DriveAbility(arrayOf(TRIGGER_DROVE_RED, TRIGGER_DROVE_BLUE), arrayOf(GET_ONE_VICTORY_TOKEN)))),
        ...
    )
}

But IntelliJ's automatic reformatting replaces my preferred format with this:

fun generateAllCards(): Array<Card> {
    return arrayOf(
        Card(
            FORMAT_1,
            COLOUR_BLACK,
            TYPE_RUN,
            1,
            POINTS_1,
            arrayOf(RunAbility(arrayOf(TRIGGER_RAN_BLUE), EFFECT_CAN_FLY_10_SEC))
        ),
        Card(
            FORMAT_2,
            COLOUR_YELLOW,
            TYPE_DRIVE,
            3,
            POINTS_3,
            arrayOf(
                DriveAbility(
                    arrayOf(TRIGGER_DROVE_RED, TRIGGER_DROVE_BLUE),
                    arrayOf(GET_ONE_VICTORY_TOKEN)
                )
            )
        ),
        ...
    )
}

I've created a script to fix it whenever the reformatter breaks it, but this isn't sustainable. I would like to prevent reformatting (automatic or manual) just within this code block, not the whole file or any larger scope. I want IntelliJ to continue reformating code everywhere else, including the rest of the file this code came from.

I thought there might be something like @SuppressFormatting to put at the top of a block. I tried using //@formatter:off ... //@formatter:on, but as noted here, it doesn't seem to stop the reformatting. Is there something else that works?


Solution

  • To use //@formatter:off///@formatter:on you need to enable them first.

    Go to Settings->Code style->Formatter->Turn formatter on/off with markers in code comments

    enter image description here