How to get method boundaries with Intellij openapi?

Hello. I am working on Intellij plugin development. Wondering is there an opportunity to get method boundaries in file? I mean, number of method starting line and number of it's last line. 
Thanks! Best regars.

0
4 comments
Avatar
Permanently deleted user

PsiNodes can easily be turned into line numbers using `Document.getLineNumber(ASTNode)`.  (Get the ASTNode from `PsiElement.getAst()`.)

The "boundary of the method" depends upon your target language and its PSI structure.  Use the PSI Viewer (https://www.jetbrains.com/help/idea/psi-viewer.html) to figure out where in the tree the method's beginning and end nodes are.  Then use the `PsiTreeUtil` methods to locate the interesting `PsiElements`, and call the line number routine above.

 

0

Thank for quick response, Eric!
Isn't PsiElement.getTextRange() also suitable for this? I currently tried 

if (element instanceof PsiMethod)
methodToBounds.put((PsiMethod) element, element.getTextRange());

but haven't tested it yet.

 

0
Avatar
Permanently deleted user

`getTextRange()` gets offsets from the beginning of the psiElement to the end, including all sub-elements.  If that is what you want, it should work.  You still have to find the element you want, but after that, turning offsets into line numbers is as simple as calling `Document.getLineNumber(offset)`.

0

Please sign in to leave a comment.