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?

2 comments
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?

0
Comment actions Permalink

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

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

Please sign in to leave a comment.