18
$\begingroup$

Is it possible to automatically execute some code every time a new notebook is opened?

So for example I would like to print a message "New notebook" every time a new notebook is opened.

This question was prompted by this answer about fixing indentation when moving to a new line. The "fix" requires that some code is applied to the notebook every time it is opened. But I think this question in interesting enough to stand on it own.

I even have some working code, but it based on polling, so I would like to avoid that if possible. (also is it possible to get rid of the global variable $OldNotebooks?)

Clear[GetNewNotebooks, $OldNotebooks];
$OldNotebooks = Notebooks[];
GetNewNotebooks[] := 
  Module[{new}, 
   new = Complement[Notebooks[], $OldNotebooks]; $OldNotebooks = 
    Notebooks[]; new];
(*new=GetNewNotebooks[];*)

NBHistory = {}; Dynamic[NBHistory]

StartScheduledTask@
  CreateScheduledTask[NBHistory = NBHistory~Join~GetNewNotebooks[]];

Now every time you open a new notebook, it will get added to the list of NBHistory and displayed.

(*When you had enough:) *)
RemoveScheduledTask[ScheduledTasks[]]
$\endgroup$
1

1 Answer 1

17
$\begingroup$

After a few modifications based on comments and chats with Ajasja and Szabolcs, this is the code:

i = 0; SetOptions[$FrontEndSession,
FrontEndDynamicExpression :>
Refresh[Notebooks[];
If[GetNewNotebooks[] =!= {}, Print["New one ", ++i]],
TrackedSymbols :> {}]]

The Print statement would be the code you want to run.

The TrackedSymbols:>{} setting of Refresh is there to prevent any external symbols introduced in your code that get changed inside the dynamic expression to trigger an update of FrontEndDynamicExpression. This can easily lead to infinite recursion as given in this example (do not run this code unless you would like to crash your mma session)

i = 0; SetOptions[$FrontEndSession, 
 FrontEndDynamicExpression :> (Notebooks[]; Print["New one ", i++])]

(Also perhaps the Notebooks built-in is handled specially, that is why this code works even though TrackedSymbols is set to {})

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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