Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:) *)
share|improve this question
Related: – Mr.Wizard May 21 '12 at 16:41
up vote 16 down vote accepted

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 {})

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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