1
$\begingroup$

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.)

$\endgroup$
2
$\begingroup$

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])}}
*)
$\endgroup$
  • $\begingroup$ 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 ... $\endgroup$ – volk Jul 19 '18 at 0:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.