Check if cursor inside <?php

I am trying to check whether the cursor is encapsulated in <?php ?>.
I need to check this to determine whther a string for a write actions needs to contain a php opening tag or not.

I tried to check it via the language of the psi element at the current caret, but mostly the psi element is null.
Is there any other method to check this?

Comment actions Permalink

My code is:

int caretOffset = editor.getCaretModel().getOffset();
PsiElement psiElement = psiFile.findElementAt(caretOffset);
String language = psiElement.getLanguage().getDisplayName();

If the caret is at whitespace language is null.
Will it always be null at whitespace?

Comment actions Permalink

I got a solution it may not be the best, but it works:

boolean isInPhpTags = false;
(int i = cursorOffset; i > cursorOffset - 50; i--) {
   PsiElement psiElement = psiFile.findElementAt(i);
(psiElement != null) {
      if(psiElement.getLanguage().getDisplayName().toLowerCase().equals("php")) {
         isInPhpTags = true;

Please sign in to leave a comment.