Alexey Popkov
Alexey Popkov

Reputation: 9425

Two initialization Cells in one Notebook each autosaved in separate .m-file?

Is there a way to create Notebook in which each Initialization Cell will be auto-saved in its own .m-file with arbitrary name?

P.S. The question is related to the Mathematica program developed by Wolfram Research Inc. It is not about Mathematics or math.

Upvotes: 2

Views: 249

Answers (1)

fairflow
fairflow

Reputation: 445

I'm not sure if the following approach would satisfy you: I once wanted a way of generating compact notebooks containing only the initialisation cells found in my development notebook; the following code writes the initialization cells of the current notebook into a single new notebook and autosaves a .m file as a side-effect but it could easily be adapted to generate a separate notebook and .m file for each initialization cell.

In[162]:= nbToExtract = SelectedNotebook[]

In[163]:= 
extractInitializationCells[nb_] :=
 Block[{nbNew = CreateDocument[], count = 0},
  (SelectionMove[nb, Next, Cell];
   While[NotebookRead[nb] =!= {}, (If[InitializationCell /. 
          Options[NotebookSelection[nb], InitializationCell],
      (count++;
       NotebookWrite[nbNew, NotebookRead[nb]]), {}]; SelectionMove[nb, Next, Cell])];
   Print[ToString[count] <> " initialization cell(s) found"];
   CurrentValue[nbNew, AutoGeneratedPackage] = Automatic;
   NotebookSave[nbNew, fn];
   NotebookClose[nbNew];
   Clear[nbNew](* just in case *))]

extractInitializationCells[nbToExtract]

This only extracts the initialisation cells below the cell in which the function extractInitializationCells is called. And I'd agree with the previous caveats about using the auto generation package mechanism. Also, CurrentValue is not protected indefinitely from backwards incompatibility but it has survived several major Mathematica versions so far.

Upvotes: 1

Related Questions