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
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[]]