23

The return key does not work as expected in an InputField, how can I overcome this?

Murta
  • 26,275
  • 6
  • 76
  • 166
M.R.
  • 31,425
  • 8
  • 90
  • 281

6 Answers6

22

Ah, figured it out:

Panel @ DynamicModule[{input = ""}, 
  Column[{TextCell["Enter your text here:"], 
    EventHandler[
     InputField[Dynamic[input], String, ContinuousAction -> True, 
      FieldSize -> {40, 7}], 
     "ReturnKeyDown" :> 
      FrontEndExecute[{NotebookWrite[InputNotebook[], "\n", After]}]
     ], Dynamic@InputForm[input]}]]
M.R.
  • 31,425
  • 8
  • 90
  • 281
  • On a related note: I wonder if that could also be used to intercept "Shift-return" - but I doubt it... – Jens Jun 05 '12 at 17:53
  • This doesn't appear to work in version 7. – Mr.Wizard Jun 06 '12 at 01:10
  • This solves a long standing question of mine, so thanks! I made an edit for it to handle Shift-Return: EventHandler[ InputField[Dynamic[demo2], String, FieldHint -> "Quarter 1 Turnover", Alignment -> {Left, Center}], {{"MenuCommand", "HandleShiftReturn"} :> FrontEndExecute[{NotebookWrite[InputNotebook[], "\n", After]}], "ReturnKeyDown" :> FrontEndExecute[{NotebookWrite[InputNotebook[], "\n", After]}]}] – Charlotte Hadley Feb 20 '13 at 16:44
  • Doesn't work in the cloud. – M.R. Jan 02 '21 at 08:37
12

Perhaps something like this?

text = "";
EventHandler[
 InputField[Dynamic@text, String, ContinuousAction -> True],
 {"ReturnKeyDown" :> Paste["\n"]}
 ]
Michael E2
  • 235,386
  • 17
  • 334
  • 747
  • Cool!.. Tks I'll wait to accept just to follow the protocols. :) – Murta Feb 23 '14 at 16:12
  • Doesn't work in the cloud. – M.R. Jan 02 '21 at 08:37
  • @M.R. Maybe tell it to WRI? I'm not sure there's a real Front End in the Cloud. I told a developer in passing about some glitch a year ago at the 2019 tech conf, and they put me in contact with the lead developer right away. He seemed to realize there were some issues, but they seemed to want to make it work. – Michael E2 Jan 02 '21 at 13:56
11

Here is a widget which I constructed some time ago for my purposes. This is an InputField as well, but it operates on boxes, and as a bonus, the standard syntax highlighting works inside it:

ClearAll[codeInputField];
Attributes[codeInputField] = {HoldFirst}; 
Options[codeInputField] = {
   BaseStyle -> {FontSize -> 14, FontWeight -> Plain, FontFamily -> "Courier"},
   FieldSize -> {20, {2, Infinity}},
   ImageSize -> Automatic, 
   KeyEventActions -> Automatic,
   EnterPressedCustomFunction :> Automatic
};

codeInputField[startingCode_, opts : OptionsPattern[]] :=
  With[{bs = OptionValue[BaseStyle], fsize = OptionValue[FieldSize], 
    acts = OptionValue[KeyEventActions],
    EnterPressedF = OptionValue[EnterPressedCustomFunction], 
    ims = OptionValue[ImageSize]},
   Module[{nb, enterPressed},
     With[{actions = 
       Sequence @@ 
        If[acts === Automatic,
          {},
          Replace[acts, 
           (s_ -> f_) :> (s :> f[Hold[startingCode], Hold[enterPressed], s, nb]),
           {1}]
        ],
        enterF  = If[EnterPressedF === Automatic, Hold, EnterPressedF]
      },
     EventHandler[
       InputField[
          Dynamic[
             startingCode, 
             (nb = InputNotebook[]; startingCode = #) &
          ],
          Boxes, 
          FieldSize -> fsize, ContinuousAction -> True, 
          BaseStyle -> bs, ImageSize -> ims
       ],
       {"ReturnKeyDown" :>
          (
              enterPressed = True;
              enterF[Hold[startingCode], nb];
              FrontEndExecute[NotebookWrite[InputNotebook[], "\n"]];
              If[! ValueQ[nb], nb = InputNotebook[]];
              SetOptions[NotebookSelection[nb], ShowSelection -> True]; 
          ),
          actions
       },
       PassEventsDown -> True
  ]]]];

Here is an example of use:

code = MakeBoxes[Plot[Sin[x], {x, 0, 4 Pi}]];
Dynamic[code]
 RowBox[{"Plot","[",RowBox[{RowBox[{"Sin","[","x","]"}],",",RowBox[{" 
     {",RowBox[{"x",",","0",",",RowBox[{"4"," ","\[Pi]"}]}],"}"}]}],"]"}]

The above dynamic is to monitor the code variable. Now, the input field:

codeInputField[code]

enter image description here

The highlighting is enabled after "Enter" is pressed the first time. You can edit the code to see the highlighting at work and how the code variable is updated.

I also coded an interactive REPL-style cell based on this, which can evaluate code inside it. If there is an interest in it, I could expand to include that as well.

Leonid Shifrin
  • 114,335
  • 15
  • 329
  • 420
5

This dialog box version was put together some time ago for Mathematica 7 :-

text = "";
DialogInput[{TextCell["Try to type a text with linebreaks :-)"], 
  InputField[Dynamic[text], String, FieldSize -> {30, 6}], 
  DefaultButton[DialogReturn[text]]}, 
 NotebookEventActions -> {"ReturnKeyDown" :> 
    FrontEndExecute[NotebookWrite[InputNotebook[], "\n"]]}]

enter image description here

Chris Degnen
  • 30,927
  • 2
  • 54
  • 108
4

It appears that an undocumented InputFieldBoxOptions -> {"ReturnEntersInput" -> False} does this:

InputField[
  Dynamic[x], String
, BaseStyle -> InputFieldBoxOptions -> {"ReturnEntersInput" -> False}
]

It does not help with numpad Enter which can accidentally evaluate the cell. But that is the case with other answers too so the full answer is:

EventHandler[
  InputField[Dynamic[x], String
  , BaseStyle -> InputFieldBoxOptions -> {"ReturnEntersInput" -> False}
  ]
, {"MenuCommand", "EvaluateCells"} :> Paste["\n"]
]
Kuba
  • 136,707
  • 13
  • 279
  • 740
2

In version 13.2, I just typed Options[InputField] and found an undocumented option named ReturnEntersInput. Well... it works. This must by my shortest answer ever:

InputField[Dynamic[text], String, ReturnEntersInput -> False,  FieldSize -> {30, 10}]

I wonder when was this option added. It is undocumented, but it is not displayed in red by the front end.

Gustavo Delfino
  • 8,348
  • 1
  • 28
  • 58