Adding Tab support to TextArea's TextEditor (almost done)

Hi,

I want my TextArea to support entering tabs. After a lot of search I finally came up with this:

Event ev = Event.current;
string mPlaintext = GUILayout.TextArea(myText, GUILayout.ExpandHeight(true));
TextEditor mEditor = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), GUIUtility.keyboardControl);
                
if (GUIUtility.keyboardControl==mEditor.controlID &&  ev.Equals(Event.KeyboardEvent("tab"))) {
   if (mPlaintext.Length > mEditor.pos) {
      mPlaintext = mPlaintext.Insert(mEditor.pos, "	");
      mEditor.pos++;
      mEditor.selectPos = mEditor.pos;
      }
   ev.Use();
}
                
myText = mPlaintext;

While this works (\ is added to the text in the TextArea), ev.Use() seems to be ignored, so the default behaviour of tab kicks in and the next control is selected.

Anybody knows how I can eat the tab event to prevent control switching?

Edit: Seems to be a problem with GUILayout.TextArea. Using GUI.TextArea does the trick!

Thanks
Jake

PS: Don’t know if it matters, but the code is placed in EditorWindow.OnGUI()

Hi! there,

What you probably want to do is force focus on the TextField.
You can do this by using the following commands:

//Before you call the text field, give it a special identifier
GUI.SetNextControlName("1");

//You can then call the following to force focus on the text field with that identifier
GUI.FocusControl("1");

I have found this useful more often than not. If you have multiple text fields, you can keep track of them yourself, and only change the focus, when other exit events happen :slight_smile:

Hope this helps, Benproductions1

GUI.FocusControl() doesn’t help, but I figured out that using GUI.TextArea instead of GUILayout.TextArea works. Thanks anyway!