Getting PsiElements from selected text

 
I am trying to implement a custom ExtractHandler but I am stuck at finding all PsiElements present in the selected text.
  
public class ExtractHandler implements RefactoringActionHandler {
    @Override
    public void
invoke(@NotNull final Project project, final Editor editor, final PsiFile psiFile, DataContext dataContext) {
        final String selectedText = editor.getSelectionModel().getSelectedText()
 
        // How to get PsiElements present in the selected text.          

    
}

    @Override
    public void
invoke(@NotNull Project project, @NotNull PsiElement[] psiElements, DataContext dataContext) {}
}


Is there any way to find all PsiElements present in the selected text?

2 comments
Comment actions Permalink

First, you need to get the PSI elements at the start and end of selection:

psiFile.findElementAt(editor.getSelectionModel().getSelectionStart())

psiFile.findElementAt(editor.getSelectionModel().getSelectionEnd())

Then, in most languages an "Extract" refactoring cannot be applied to an arbitrary sequence of elements, so you probably need to find a common statement or expression to which the selected elements belong. PsiTreeUtil.getParentOfType() and PsiTreeUtil.findCommonParent() should help with this.

1
Comment actions Permalink

Sorry for resurrecting the old thread, but I'm having the same challenge. My custom language is XML-based, and I'm having a hard time figuring out how to get a collection of XmlTag objects matching the current selection. Are there any existing classes in the IntelliJ SDK that already do that? I would much rather reuse the existing code, instead of writing my own.

 

0

Please sign in to leave a comment.