8

Consider Java file with the following code (it can be any other language, we use Java as example):

public class Foo {

    void foo(int x,
             int y) {}  // line 4

}

If IntelliJ is configured to use smart tabs, then line 4 will start with one tab (which is called indentation) and continued with 9 spaces (which are called alignment):

If IntelliJ is configured to use spaces, then line 4 will start with 13 spaces (first four spaces are indentation, and next nine spaces are alignment):

I have an object of type PsiWhiteSpace (which corresponds to both indentation and alignment in line 4). How can I retrieve information about indentation and alignment, that is number of chars in indentation and number of chars in alignment?


To be more specific here is testcase, which (hopefully) shows what I need:

import com.intellij.application.options.CodeStyle
import com.intellij.openapi.fileTypes.StdFileTypes
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiWhiteSpace
import com.intellij.testFramework.fixtures.BasePlatformTestCase

class MyTest : BasePlatformTestCase() {
    fun testExample() {
        val content = """
            public class Foo {

                void foo(int x,
                         int y) {}

            }
        """.trimIndent()

        val psiFile = myFixture.configureByText(StdFileTypes.JAVA, content)
        val document = PsiDocumentManager.getInstance(project).getDocument(psiFile)!!

        val startOffset = document.getLineStartOffset(3)
        val psiWhiteSpace = psiFile.findElementAt(startOffset) as PsiWhiteSpace

//        somehow use psiWhiteSpace to retrieve indent and alignment info:
//        val numberCharsInIndent = ???
//        val numberCharsInAlignment = ???

        val useTabs = CodeStyle.getIndentOptions(psiFile).USE_TAB_CHARACTER
        if (useTabs) {
            assert(numberCharsInIndent == 1)
            assert(numberCharsInAlignment == 9)
        } else {
            assert(numberCharsInIndent == 4)
            assert(numberCharsInAlignment == 9)
        }
    }
}
diralik
  • 6,391
  • 3
  • 28
  • 52
  • You can try to use Indent.getSmartIndent, basically it's a type of indent which tries to collapse multiple indents into single one if proper conditions are met. – Kootli Dec 03 '19 at 21:27
  • @Kootli method [`getSmartIndent`](https://github.com/JetBrains/intellij-community/blob/747b08812b83e744d130e315a54cca6b41906f57/platform/lang-api/src/com/intellij/formatting/Indent.java#L252) takes `Type` as parameter (which is basically an [enum](https://github.com/JetBrains/intellij-community/blob/747b08812b83e744d130e315a54cca6b41906f57/platform/lang-api/src/com/intellij/formatting/Indent.java#L264-L269)). And I have `PsiWhiteSpace` object. How can I use `getSmartIndent` method to get indent and alignment info from `PsiWhiteSpace` object? – diralik Dec 03 '19 at 21:41

0 Answers0