1

I have a module defining handlers of KeyDown events that I reuse in various notebooks. In some cases I need to define separate handlers for additional keys. Unfortunately, later calls to SetOptions[...] seem to undo earlier ones. For example, I might first evaluate

SetOptions[EvaluationNotebook[], NotebookEventActions -> {
   {"KeyDown", "\ "} :> Speak["Space"],
    "EscapeKeyDown" :> (Speak["Escape"]; 
     SetOptions[EvaluationNotebook[], NotebookEventActions -> None])}]

As a consequence, spacebar presses cause the computer to say "space" until this behavior is cancelled (by pressing the Esc key). However, if I don't press Esc and evaluate in a separate cell

SetOptions[EvaluationNotebook[], NotebookEventActions -> {
   {"KeyDown", "\.08"} :> Speak["Backspace"],
    "EscapeKeyDown" :> (Speak["Escape"] ; 
     SetOptions[EvaluationNotebook[], NotebookEventActions -> None])}]

the computer correctly responds to "backspace" key presses by speaking but has reverted to the default response to spacebar presses.

How can I get successive event-handler definitions to be cumulative?

(Using Windows 10, Mathematica 11.3.)

volk
  • 65
  • 4

1 Answers1

2

Why can't you just prepend your new actions? For example:

SetOptions[
    EvaluationNotebook[],
    NotebookEventActions->{
        {"KeyDown"," "} :> Speak["Space"],
        "EscapeKeyDown" :> (
            Speak["Escape"];
            SetOptions[EvaluationNotebook[],NotebookEventActions->None]
        )
    }
];

SetOptions[
    EvaluationNotebook[],
    NotebookEventActions -> Prepend[
        OptionValue[Options @ EvaluationNotebook[], NotebookEventActions],
        {"KeyDown", "\.08"} :> Speak["Backspace"]
    ]
];

Options[EvaluationNotebook[], NotebookEventActions]

(*
{NotebookEventActions -> {{"KeyDown", "\.08"} :> 
    Speak["Backspace"], {"KeyDown", " "} :> Speak["Space"], 
   "EscapeKeyDown" :> (Speak["Escape"]; 
     SetOptions[EvaluationNotebook[], NotebookEventActions -> None])}}
*)
Carl Woll
  • 130,679
  • 6
  • 243
  • 355
  • That's great, and so easy! Thanks so much for the prompt reply. I guess I expected Mathematica to append additional handlers automatically, and when it didn't, I stopped thinking ... – volk Jul 19 '18 at 00:38