19

By default, after evaluating an input cell by hitting Enter or Shift-Return the cursor jumps below the corresponding output cell. Is there a way to make the cursor stay exactly where it was before the evaluation?

Kuba
  • 136,707
  • 13
  • 279
  • 740
murphy
  • 1,249
  • 8
  • 20

1 Answers1

10

Undocumented tweak:

With[
  { nb := EvaluationNotebook[]
  , c := EvaluationCell[]
  }
, With[
    { cv := CurrentValue[nb, {"TaggingRules", "LastCursorPosition"}]
    , pos := FrontEndExecute@FrontEnd`UndocumentedGetSelectionPacket[nb]
    }
  , With[
      { savePosition := (
          cv = If[MemberQ[pos, "CharacterRange" -> _], Last["CharacterRange" /. pos], False]
        )
      }
    , SetOptions[nb
      , CellEventActions :> {
          {"MenuCommand", "HandleShiftReturn"} :> savePosition
        , {"MenuCommand", "EvaluateCells"} :> savePosition
        , PassEventsDown -> True
        }
      , CellEpilog :>  If[
          IntegerQ[cv]
        , SelectionMove[c, Before, CellContents]
        ; SelectionMove[nb, Next, Character, cv]
        ; cv = False
        ]
      ]
    ]
  ]
]

So it doesn't stay but at least it goes back :) Haven't tested it heavily though.

Kuba
  • 136,707
  • 13
  • 279
  • 740
  • 1
    Instead of using FrontEndExecute@FrontEnd`UndocumentedGetSelectionPacket[nb] one might also use Developer`CellInformation[nb] which also contains the selected character range. See comment under the answer: https://mathematica.stackexchange.com/questions/13246/cursor-position-insertion-point – Qbyte Feb 01 '21 at 20:11
  • @Kuba Your code was applied to Wolfram Cloud, but now evaluation using shift+enter does not work. The software should have gone back to normal after refreshing it. It likely is a bug – Tyma Gaidash Mar 21 '24 at 23:43
  • 1
    @TymaGaidash you can CurrentValue[ notebook_, CellEpilog ] = Inherited etc to reset them. – Kuba Mar 22 '24 at 05:33