How to check if the selection is within a method body?

Within the Update method of my Action, I have:selection is, of course, a string representing whatever the user has selected in the editor. I want to check if selection is contained strictly within the body of a method, and if yes, I would like to get the IMethodDeclaration representing it. How can I do this?    var textControl = context.GetData(JetBrains.TextControl.DataContext.DataConstants.TEXT_CONTROL);           var selection = textControl.Selection.GetSelectedText();
1 comment
Comment actions Permalink

You can use context.GetData(JetBrains.ReSharper.Psi.Services.DataConstants.SELECTED_EXPRESSION) to get an ITreeNode that represents the currently selected expression (this just calls ExpressionSelectionUtil.GetSelectedExpression, with the current solution and ITextControl).
It's possible this can return null, so you can also try context.GetData(JetBrains.ReSharper.Psi.Services.DataConstants.DECLARED_ELEMENTS), which should give you a collection of IDeclaredElement, which can include IMethod, etc.

If the current element or selection isn't a method, you can simply walk up the ITreeNode.Parent chain until you either hit an IMethodDeclaration, or null.

0

Please sign in to leave a comment.