Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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[]]
share|improve this question
    
Related: mathematica.stackexchange.com/a/1113/121 –  Mr.Wizard May 21 '12 at 16:41
add comment

1 Answer 1

up vote 15 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 :>
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 {})

share|improve this answer
add comment

Your Answer

 
discard

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.