how can I get the word where the cursor is focused in one action

Answered

I am writing a plugin, and I want to ask everyone, how can I get the word where the cursor is focused in one action?

 
 
The scenario is that I will focus on the package name, right-click, select a specific icon, and trigger an action.
 
 
 
2 comments
Comment actions Permalink

You can find the PsiElement located at the current cursor position with:

Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
VirtualFile file = FileDocumentManager.getInstance().getFile(editor.getDocument());
int offset = editor.getCaretModel().getOffset();

PsiElement element = PsiManager.getInstance(project).findFile(file).findElementAt(offset);

Using some helper methods, you can also find the nearest parent that matches specific conditions (i.e. to grab a wider range of text).

PsiTreeUtil.findFirstParent(element, new Condition<PsiElement>() {
@Override
public boolean value(PsiElement psiElement) {
return CONDITION;
}
});
1
Comment actions Permalink

Jakub Chrzanowski

 

Thank you,It works.

0

Please sign in to leave a comment.