4
$\begingroup$

I'm trying to set up Mathematica such that all functions/variables defined in my init.m are automatically loaded into any new notebook I open. This works as a default, but I would also ideally like to set my CellContext to Notebook, such that notebook-specific functions/variables are not shared. However, doing this also makes init.m functions not work across new notebooks. I've tried figuring out how to do this with packages, but I haven't been able to find a clear resource on how I would set this up for my purposes.

To be succinct, what is the best way to set up a central file like init.m that is automatically loaded with each new notebook, but such that notebooks have their own context? Thanks for any advice/guidance you can give.

$\endgroup$

1 Answer 1

6
$\begingroup$

Using Create new notebook at fixed size you can do:

SetOptions[$FrontEnd, NotebookEventActions :> {
   {"MenuCommand", "New"} :> (
     CreateDocument[{}
     , CellContext -> Notebook
     , NotebookDynamicExpression :> Refresh[
         Get @ "init.m"
       ; SetOptions[EvaluationNotebook[], NotebookDynamicExpression :> Null]
       , None
       ]
     ]
   )
}]

But do not define your functions in init.m, put there only Needs @ "MyPackage`" and create a proper packages. That way you don't need to read a long file each time you open a notebook but all will be done by fetching a "MyPackage`" from $Packages to a local to your notebook $ContextPath.

$\endgroup$
4
  • 2
    $\begingroup$ Big +1 for "But do not define your functions in init.m". Putting too many things in init.m is dangerous. You will forget about what you put there and eventually it may cause subtle, hard to debug problems. $\endgroup$
    – Szabolcs
    Commented Jan 20, 2020 at 12:28
  • $\begingroup$ Basically the only thing I put in init.m is setting the $Path so that my packages get picked up. $\endgroup$
    – Szabolcs
    Commented Jan 20, 2020 at 12:29
  • $\begingroup$ @Szabolcs I only have Needs@"GeneralUtilities`" there, and I try to install my utilities packages as paclets. Not suited for every type of work but fits my needs. $\endgroup$
    – Kuba
    Commented Jan 20, 2020 at 14:37
  • $\begingroup$ This method works well enough when doing ctrl-n to generate a new notebook, but does not seem to work when first opening a mathematica. Is there a way to get this to work in that case, and further to get it to apply to already created notebooks? $\endgroup$ Commented Jan 21, 2020 at 7:33

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.