Switching from local keyboard language to English then backing to local keyboard language outside of math mode is common in non-English latex users.
How to write an Script for TexStudio to auto switch into English language inside of math mode?
texstudio have a built in such script (
Configure Texstudio-> Adv. Editor-> Bi-Di->check last two check boxes) but it is so laggy. sometimes it switches keyboard wrongly. sometimes it switches keyboard rapidly after each keypress.
Posting the source code of this script as answer would suffices.