Convert PsiElement offset to compiler message line/column?

I'm writing a Compiler plugin, and I want to add messages to the compile
output. I have a PsiElement and I've found its position in the PsiJavaFile,
as far as I can tell, by recursively summing the getOffsetInParent values
up the PSI tree. (By the way is there an API utility method for this?) I
think it works because when I call file.findElementAtPosition(that value),
it returns the deepest leaf child of the original element.

Anyway, I'm having a hard time converting this number to a line/column position
like CompilerContext.addMessage requires. I tried going through the VirtualFile
and counting characters, and lines when I see a \n, but it doesn't work -
I get seemingly random line and column numbers, vaguely near where the actual
element is. I tried going through the PsiJavaFile.getText() contents like
that, and got the same results.

I think there might be a problem with the PsiJavaFile containing \n for newline,
and the VirtualFile containing \r\n.

It's 4 AM here, maybe I'm too tired to figure out a simple thing, but is
there an easier way to convert PSI file offset into VirtualFile offset?


1 comment
Comment actions Permalink

Getting the offset within it's file is PsiElement.getTextOffset() I think.
And counting the lines should be StringUtil.offsetToLineNumber().

Keith Lea schrieb:

I'm writing a Compiler plugin, and I want to add messages to the compile
output. I have a PsiElement and I've found its position in the
PsiJavaFile, as far as I can tell, by recursively summing the
getOffsetInParent values up the PSI tree. (By the way is there an API
utility method for this?) I think it works because when I call
file.findElementAtPosition(that value), it returns the deepest leaf
child of the original element.

Anyway, I'm having a hard time converting this number to a line/column
position like CompilerContext.addMessage requires. I tried going through
the VirtualFile and counting characters, and lines when I see a \n, but
it doesn't work - I get seemingly random line and column numbers,
vaguely near where the actual element is. I tried going through the
PsiJavaFile.getText() contents like that, and got the same results.

I think there might be a problem with the PsiJavaFile containing \n for
newline, and the VirtualFile containing \r\n.

It's 4 AM here, maybe I'm too tired to figure out a simple thing, but is
there an easier way to convert PSI file offset into VirtualFile offset?

1

Please sign in to leave a comment.