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()?

0

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.

0

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);
int
textOffset = element.getTextOffset();
int
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();
int
textOffset = interpolatedStringBody.getTextOffset();
int
lineNumber = document.getLineNumber(textOffset);


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

1

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.

1

请先登录再写评论。