As I never found (or perhaps I never search for it enough) a good article about how to manage the init.m files, I ended up developing my own \"standard\", but I wonder how bad I
My Kernel/init.m
looks like this:
AppendTo[$Path, Environment["MMA_LIB"]]
Needs["WRUtil`"]
WRUtil
contains all of my little utilities and performs other initialization that takes into account the platform and Mathematica version. MMA_LIB
is an environment variable that points to a directory full of Mathematica packages. That directory is kept under version control and can be shared by multiple Mathematica instances. I like to keep init.m
short so that moving into a new Mathematica installation is as simple as typing two lines that I have committed to memory -- it is surprising how often I seem to have to do this.
Firstly, I would strongly recommend against putting anything significant init.m
, since this invariably results in old stuff being broken when you come back to it after a few years. Much better to put your customizations on the path so you can quickly load it at the head of each notebook: That way the context is explicitly stated and you can easily change versions without breaking old stuff.
My current setup is to start with Needs["Janus`"]
where the Janus
directory has a custom init.m
file that loads every file in the directory into the context. This means I can add utility functions in each their own file like this one (clear_cache.m
):
ClearCache::usage="ClearCache[f] unsets all numeric-only downvalues of f, \
see http://stackoverflow.com/questions/5086749"
Begin["`Private`"];
ClearCache[f_Symbol] :=
DownValues[f] = DeleteCases[DownValues[f], _?(FreeQ[First[#], Pattern] &)]
End[]
Here is the file Janus/init.m
. Note that it prints out the name of the loaded extensions, all in the spirit of keeping the context explicit without too much hassle.
Module[{packageName,packageFileName,fileNames},
(* $Input is set to Foo.m when evaluating Foo/init.m *)
If[$Input=="", Print["init.m cannot run interactively"];Abort[]];
packageName=StringDrop[$Input,-2];
packageFileName=FindFile[packageName<>"`"];
If[packageFileName==$Failed, Print["Unable to find package "<>packageName];Abort[]];
fileNames=Select[
FileNames["*.m",{DirectoryName@packageFileName},1],
FileBaseName[#]=!="init"&];
Print["Loading extensions from "<>DirectoryName@packageFileName<>" to context "<>packageName<>"`:"];
BeginPackage[packageName<>"`"];
Do[Print["Loading "<>fn]; Get@fn, {fn,fileNames}];
EndPackage[]]
Having also not followed an official doctrine, I can only tell you what I do.
My Kernel/init.m
contains no functions itself. I use it to:
$HistoryLength
SetDirectory
etc.DeclarePackage
calls