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

已回答

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.
 
 
 
0

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;
}
});
4

@...

 

Thank you,It works.

0

请先登录再写评论。