Line and column number of element within containing file

How can I get a line and column number corresponding to element.getTextRange() within element.getContainingFile()?


The PSI does not contain any information about line numbers. You can use PsiDocumentManager.getDocument() to get the document for the file and use Document.getLineNumber() and Document,getLineStartOffset() to determine the position.


This is the code I was able to figure out by following the available method list for each class along the way:

PsiFile containingFile = element.getContainingFile();
Project project = containingFile.getProject();
PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
Document document = psiDocumentManager.getDocument(containingFile);
textOffset = element.getTextOffset();
lineNumber = document.getLineNumber(textOffset);

The problem is that `document` is `null`, so then I walked through `doTest(boolean)` and found I could get a document through the `FileViewProvider`:

assertEquals("doc text mismatch", text, myFile.getViewProvider().getDocument().getText());

Using this for my example above:

PsiFile containingFile = interpolatedStringBody.getContainingFile();
FileViewProvider fileViewProvider = containingFile.getViewProvider();
Document document = fileViewProvider.getDocument();
textOffset = interpolatedStringBody.getTextOffset();
lineNumber = document.getLineNumber(textOffset);

`lineNumber` is `1` just as I would expect.


Thought I should add a note: IntelliJ displays line numbers as 1-indexed, but `Document.getLineNumber` will return a 0-indexed number, so you need to add `+ 1` to get the line number that the user can see.


Please sign in to leave a comment.