How do I get to PSI from a document or editor?

I want to do something everytime a user hits the enter key. I found out a way to detect the enter key except now I don't have access to a DataContext object.

I have an editor object, how do I get to the VirtualFile or the PSI structure in the editor?

6 comments

Indeed that's a very good question. I'm struggling with the same issue. I want to get the psi-element under the caret. Something like

public void actionPerformed(AnActionEvent e) {
Editor ed = e.getData(PlatformDataKeys.EDITOR);
if (ed == null) {
return;
}

String text = ed.getSelectionModel().getSelectedText(); // nice but i'd like to access the psi instead
PsiElement psiElement = ?????

Is this possible, and how?

Thanks in advance,
best,
Holger

1

*bump* 

Any ideas? I'm sure there's a way and I'd just need some clue (like an API pointer) to get started.

 

Thanks,

Holger

0
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;

class Action extends AnAction {
    public void actionPerformed(AnActionEvent e) {
        final EditorEx editor = (EditorEx) CommonDataKeys.EDITOR.getData(e.getDataContext());
        if (editor != null) {
            final Project project = editor.getProject();
            if (project != null) {
                final PsiFile psiFile = PsiManager.getInstance(project).findFile(editor.getVirtualFile());
                if (psiFile != null) {
                    final CaretModel caretModel = editor.getCaretModel();
                    PsiElement element = psiFile.findElementAt(caretModel.getOffset());
                }
            }
        }
    }
}
0

Hello Vladimir,

thanks for the complete solution.

Have a nice evening, best regards,

Holger 

 

 

0

A better way to handle ENTER customization is to implement an EnterHandlerDelegateAdapter and add it into plugin.xml

 <enterHandlerDelegate implementation="com.vladsch.idea.multimarkdown.editor.actions.handlers.EnterHandler"/>
0

Please sign in to leave a comment.