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[] := 
   new = Complement[Notebooks[], $OldNotebooks]; $OldNotebooks = 
    Notebooks[]; new];

NBHistory = {}; Dynamic[NBHistory]

  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:) *)

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

i = 0; SetOptions[$FrontEndSession,
FrontEndDynamicExpression :>
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 {})

| improve this answer | |

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.