Make cursor stay in input cell provides a function for keeping the cursor in a cell after it was evaluated. I tried adding that function directly into KeyEventTranslations.tr to create a keyboard shortcut but that led to Mathematica sending an error when loading. I tried wrapping it in KernelExecute but that did not work. I would also like to modify shift plus enter to remove the setting from the function in the link when I want the standard way of evaluating a cell.
1 Answers
The following adds a new menu item "Evaluate Cells (Keep Selection)" with shortcut "Alt+Shift+Return" that keeps the cursor where it is:
FrontEndExecute@FrontEnd`AddMenuCommands[
If[$OperatingSystem == "Windows", "EvaluateCells", "HandleShiftReturn"], {
MenuItem["Evaluate Cells (Keep Selection)",
KernelExecute@evaluateKeepSelection[],
System`MenuKey[
"Return",
System`Modifiers -> {"Shift", "Option"}
],
System`MenuEvaluator -> Automatic
]}]
evaluateKeepSelection[] :=
With[{nb := EvaluationNotebook[], c := EvaluationCell[]},
With[{cv :=
CurrentValue[nb, {"TaggingRules", "LastCursorPosition"}],
pos := FrontEndExecute@
FrontEnd`UndocumentedGetSelectionPacket[nb]},
cv = "CharacterRange" /. pos;
FrontEndExecute@FrontEndToken["EvaluateCells"];
SetOptions[nb,
CellEpilog :>
If[ListQ[cv], SelectionMove[c, Before, CellContents];
SelectionMove[nb, Next, Character, First[cv]];
SelectionMove[nb, After, Character];
FrontEndExecute@
Table[FrontEndToken["SelectNext"], -Subtract @@ cv];
cv = False]]]
]
Note that this keeps the usual behavior of "Shift+Return" as it is, it just adds an additional shortcut that keeps the selection.
- 33,963
- 1
- 51
- 97

AddMenuCommandsslightly, hopefully that makes it more robust... – Lukas Lang Apr 16 '23 at 14:38FrontEndExecute@FrontEnd`AddMenuCommands, so I am a bit surprised my code didn't work for you (or MichaelE2). As I already mentioned, I tweaked the call slightly in the hopes to make the call work now – Lukas Lang Apr 16 '23 at 14:39"HandleShiftReturn"instead of"EvaluateCells"on Linux for some reason (I assume it's the same on macOS as well). I updated the answer to include a check for the OS, and it works now for a fresh install on Ubuntu for me. Can you check again on macOS? – Lukas Lang Apr 16 '23 at 16:21