5

I want to change how a notebook files save. The basic framework I'm using for this is:

SetOptions[
 EvaluationNotebook[],
 NotebookEventActions ->
  {
   {"MenuCommand", "Save"} :>
    (NotebookSave[]; $action)
   }
 ]

Because with PassEventsDown->True the $action gets called before the NotebookSave.

This is ugly and a little bit hazardous, though. Is there any way to have it otherwise? Can I trigger the event to save first, then do the $action with PassEventsDown->True?

b3m2a1
  • 46,870
  • 3
  • 92
  • 239

1 Answers1

6

So I found the answer to this in an old answer of mine. The trick is to use the undocumented EvaluationOrder.

By assigning EvaluationOrder->After our event gets called after the built-in one. To test this we can try the following. First, see what happens with "ModifiedInMemory" with the explicit order we started with:

SetOptions[
 EvaluationNotebook[],
 NotebookEventActions ->
  {
   {"MenuCommand", "Save"} :>
    (
     NotebookSave[];
     Print[Lookup[NotebookInformation[], "ModifiedInMemory"]]
     )
   }
 ]

(* prints False on save events *)

With no EvaluationOrder:

SetOptions[
 EvaluationNotebook[],
 NotebookEventActions ->
  {
   {"MenuCommand", "Save"} :>
    (
     Print[Lookup[NotebookInformation[], "ModifiedInMemory"]]
     ),
   PassEventsDown -> True
   }
 ]

(* prints True on save events *)

With no EvaluationOrder->After:

SetOptions[
 EvaluationNotebook[],
 NotebookEventActions ->
  {
   {"MenuCommand", "Save"} :>
    (
     Print[Lookup[NotebookInformation[], "ModifiedInMemory"]]
     ),
   PassEventsDown -> True,
   EvaluationOrder->After
   }
 ]

(* prints False on save events *)

This also works for EventHandler and CellEventActions

b3m2a1
  • 46,870
  • 3
  • 92
  • 239
  • It is used in stylesheet toolbar to calculate content menu on MouseEntered if I remember correctly. – Kuba Dec 20 '17 at 08:05
  • @Kuba makes sense. I found it in some input fields myself. I had simply never seen it before and thought it should be on the site. – b3m2a1 Dec 20 '17 at 08:06
  • @Kuba did you know about ToggleMenuItem? I just saw it in the ComponentwiseContextMenu and it seems potentially useful if I ever make an application with a custom menu on one of its boxes. – b3m2a1 Dec 20 '17 at 08:08
  • Yes, thanks for posting this. About ToggleMenuItem this I didn't know. Would be nice to get feedback from WRI about the future of such findings. I don't like to use too deep stuff as I usually need it to work on win/mac/player/future versions. – Kuba Dec 20 '17 at 09:01