From db3d3fc6082750eda825c4f9cb225bf61ff9b661 Mon Sep 17 00:00:00 2001
From: chylex <contact@chylex.com>
Date: Thu, 19 Oct 2023 23:56:06 +0200
Subject: [PATCH] Reset insert mode when switching active editor

---
 .../idea/vim/listener/VimListenerManager.kt          | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/src/main/java/com/maddyhome/idea/vim/listener/VimListenerManager.kt b/src/main/java/com/maddyhome/idea/vim/listener/VimListenerManager.kt
index 831f8f7c7..40feee040 100644
--- a/src/main/java/com/maddyhome/idea/vim/listener/VimListenerManager.kt
+++ b/src/main/java/com/maddyhome/idea/vim/listener/VimListenerManager.kt
@@ -97,6 +97,7 @@ import com.maddyhome.idea.vim.newapi.IjVimSearchGroup
 import com.maddyhome.idea.vim.newapi.InsertTimeRecorder
 import com.maddyhome.idea.vim.newapi.ij
 import com.maddyhome.idea.vim.newapi.vim
+import com.maddyhome.idea.vim.state.mode.Mode
 import com.maddyhome.idea.vim.state.mode.inSelectMode
 import com.maddyhome.idea.vim.state.mode.selectionType
 import com.maddyhome.idea.vim.ui.ShowCmdOptionChangeListener
@@ -410,7 +411,16 @@ internal object VimListenerManager {
     override fun selectionChanged(event: FileEditorManagerEvent) {
       // We can't rely on being passed a non-null editor, so check for Code With Me scenarios explicitly
       if (VimPlugin.isNotEnabled() || !ClientId.isCurrentlyUnderLocalId) return
-
+      
+      val newEditor = event.newEditor
+      if (newEditor is TextEditor) {
+        val editor = newEditor.editor
+        if (editor.isInsertMode) {
+          editor.vim.mode = Mode.NORMAL()
+          KeyHandler.getInstance().reset(editor.vim)
+        }
+      }
+      
       MotionGroup.fileEditorManagerSelectionChangedCallback(event)
       FileGroup.fileEditorManagerSelectionChangedCallback(event)
       VimPlugin.getSearch().fileEditorManagerSelectionChangedCallback(event)