Always execute code when ESC is pressed

I’m currently using:

    val editorActionManager = EditorActionManager.getInstance()
    val escapeAction = IdeActions.ACTION_EDITOR_ESCAPE
    val originalEscapeHandler = editorActionManager.getActionHandler(escapeAction)
    editorActionManager.setActionHandler(escapeAction, MyAction(originalEscapeHandler).handler)

and

/**
 * We are overriding the ESC handler's behavior to remove our inlay component if it exists. Otherwise,
 * we will execute the original handler.
 */
class MyAction(originalHandler: EditorActionHandler) :
    EditorAction(MyActionHandler(originalHandler)), InlineChatAction {

  private class MyActionHandler(val originalHandler: EditorActionHandler) :
      EditorActionHandler() {
    override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext) {
      val sameEditorAsInlay = MyManager.getInlayComponent()?.editor == editor
      if (sameEditorAsInlay) {
        MyManager.dispose()
      } else {
        originalHandler.execute(editor, caret, dataContext)
      }
    }

    override fun isEnabledForCaret(
        editor: Editor,
        caret: Caret,
        dataContext: DataContext?
    ): Boolean {
      val sameEditorAsInlay = MyManager.getInlayComponent()?.editor == editor
      if (sameEditorAsInlay) return true
      return originalHandler.isEnabled(editor, caret, dataContext)
    }
  }
}

… but somehow this doesn’t always work.
I suspect it’s because other handlers in the chain intercept the execution and stop it.

Is there a way to simply always ensure this gets run?

Hi Jérémi,
Do I understand correctly, that it does work, but not always? Did you try to debug it?
I would start with invocations of isEnabledForCaret(), or in com.intellij.openapi.editor.actionSystem.EditorActionHandler#execute()

If it doesn’t work at all, did you try to register it with:

<editorActionHandler action="EditorEscape" implementationClass="com.example.MyActionHandler"/>

?

Hi @karol.lewandowski, sorry for the late response.

I had already tried to debug this issue, to no avail. The issue is somehow not always reproducible, so it’s pretty hard to really understanding what’s happening. Some times, the handler is called, some times not.

Anyhow, I did a little debugging session once again:

For whatever reason, I can reproduce the issue in the sandbox when I simply run it with no debugger attached. But when I run the sandbox with a debugger attached, then the issue goes away.
This is with absolutely no code changes whatsoever.
Any ideas on what might be happening?

Moreover, does my implementation of MyAction look correct? This should indeed allow it to always execute when ESC is pressed, right?