Skip to main content

programming - Programmatically generate packages from notebook files?


Currently, there are two ways I know of to generate a package (.m) file from a notebook file; one is to set the AutoGeneratedPackage option in the Option Inspector, and the other is to use the menu optoin to "Save as" a package. The first doesn't really suit my needs because it creates the auto-generated packages in the same directory as the notebook file, which clutters things up (there are dozens of notebooks in this directory) and adds a needless complication to keeping the set-up version controlled. The second option is less than ideal because I don't know how to invoke the option programmatically.


In theory, I know it might be possible with FrontEnd commands, but I'd really prefer to be able to do this without a front end if at all possible. This is something I want to do from GNU make, and while I know you can now set up front ends from the command line, ideally I could avoid that.



Answer



I tried the ExportPacket approach described in Chris Degnen's answer, and while it's very simple, the need for FrontEndExecute and the difficulties dealing with cells of text and section headings and the like make it less appealing. Here's a sketch of the approach I'll ultimately be using, though I haven't filled all the details in yet:


notebookToPackage[notebook_String, package_String] :=
With[{nbObj = Get@notebook},
If[
nbObj === $Failed,
$Failed,

Export[package, notebookToStrings@nbObj, {"Text", "Lines"}]]]

This just loads the notebook file and does some basic error handling and exports the result after notebookToStrings converts the mess into strings. Using Get to get the notebook is the easiest way to get it as an object with head Notebook, and from there you can get at the Cell structures.


notebookToStrings[nbObj_] :=
With[{cells =
Cases[nbObj,
Cell[body_, style : "Code" | "Text", ___] :> {body, style},
Infinity]},
Riffle[
Replace[cells,

$cellRules, {1}],
""]]

Since notebook objects are Mathematica structures like everything else, you can use the same old structural manipulations and rule replacements that you use everywhere else. Cases proves once again that, with the Infinity level specification, it's the most useful function in the Mathematica library, and the pattern matching means you can whitelist some cells while not having to decide what you want to do about input or output cells or subsections or whatever. Everything else is done using rules. Riffle is just there to add white space to aesthetics.


Lastly, we have the rules, and some helper functions:


$cellRules = {
{body_, "Code"} :> boxesToStrings[body],
{body_String, "Text"} :> commentate[body]};

The contents of the "Code" cells are going to be boxes, and I turn the text in text cells into comments:



$scratchContext = "Scratch`Private`";

Attributes[stringulate] = {HoldAllComplete};
stringulate[expr_] :=
ToString[Unevaluated[expr], InputForm, CharacterEncoding -> "ASCII",
PageWidth -> 72]

boxesToStrings[boxes_] :=
Block[{$Context = $scratchContext},
stringulate @@

ToExpression[StripBoxes[boxes], StandardForm, HoldComplete]]

There's a little extra ceremony to keep this function from interning symbols into random contexts, and I had to introduce an extra function, stringulate, to keep everything held until I make it into a string. The handling for text is simpler:


commentate[s_String] :=
ToString["(*\n" <> s <> "\n*)", OutputForm,
CharacterEncoding -> "ASCII", PageWidth -> Infinity]

Ultimately, I'll probably add some rules for handling "Title" cells, "Section"/"Subsection"/... cells, and the like. In particular, if you have a pair of comments like this:


(* ::Section:: *)    
(* The section title *)


the code editor in Wolfram Workbench will fold the thing up like a notebook section when you double click on it. In the end, I'll probably also want to hold onto the whole Cell expressions so that I can pick out input cells that are also initialization cells, because those should be dumped to the package as well.


Comments

Popular posts from this blog

front end - keyboard shortcut to invoke Insert new matrix

I frequently need to type in some matrices, and the menu command Insert > Table/Matrix > New... allows matrices with lines drawn between columns and rows, which is very helpful. I would like to make a keyboard shortcut for it, but cannot find the relevant frontend token command (4209405) for it. Since the FullForm[] and InputForm[] of matrices with lines drawn between rows and columns is the same as those without lines, it's hard to do this via 3rd party system-wide text expanders (e.g. autohotkey or atext on mac). How does one assign a keyboard shortcut for the menu item Insert > Table/Matrix > New... , preferably using only mathematica? Thanks! Answer In the MenuSetup.tr (for linux located in the $InstallationDirectory/SystemFiles/FrontEnd/TextResources/X/ directory), I changed the line MenuItem["&New...", "CreateGridBoxDialog"] to read MenuItem["&New...", "CreateGridBoxDialog", MenuKey["m", Modifiers-...

How to thread a list

I have data in format data = {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}} Tableform: I want to thread it to : tdata = {{{a1, b1}, {a2, b2}}, {{a1, c1}, {a2, c2}}, {{a1, d1}, {a2, d2}}} Tableform: And I would like to do better then pseudofunction[n_] := Transpose[{data2[[1]], data2[[n]]}]; SetAttributes[pseudofunction, Listable]; Range[2, 4] // pseudofunction Here is my benchmark data, where data3 is normal sample of real data. data3 = Drop[ExcelWorkBook[[Column1 ;; Column4]], None, 1]; data2 = {a #, b #, c #, d #} & /@ Range[1, 10^5]; data = RandomReal[{0, 1}, {10^6, 4}]; Here is my benchmark code kptnw[list_] := Transpose[{Table[First@#, {Length@# - 1}], Rest@#}, {3, 1, 2}] &@list kptnw2[list_] := Transpose[{ConstantArray[First@#, Length@# - 1], Rest@#}, {3, 1, 2}] &@list OleksandrR[list_] := Flatten[Outer[List, List@First[list], Rest[list], 1], {{2}, {1, 4}}] paradox2[list_] := Partition[Riffle[list[[1]], #], 2] & /@ Drop[list, 1] RM[list_] := FoldList[Transpose[{First@li...

plotting - How to draw lines between specified dots on ListPlot?

I would like to create a plot where I have unconnected dots and some connected. So far, I have figured out how to draw the dots. My code is the following: ListPlot[{{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 4}, {2, 5}, {3, 6}, {4, 7}, {1, 7}, {2, 8}, {3, 9}, {4, 10}, {1, 10}, {2, 11}, {3, 12}, {4,13}, {2.5, 7}}, Ticks -> {{1, 2, 3, 4}, None}, AxesStyle -> Thin, TicksStyle -> Directive[Black, Bold, 12], Mesh -> Full] I have thought using ListLinePlot command, but I don't know how to specify to the command to draw only selected lines between the dots. Do have any suggestions/hints on how to do that? Thank you. Answer One possibility would be to use Epilog with Line : ListPlot[ {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 4}, {2, 5}, {3, 6}, {4, 7}, {1, 7}, {2, 8}, {3, 9}, {4, 10}, {1, 10}, {2, 11}, {3, 12}, {4, 13}, {2.5, 7}}, Ticks -> {{1, 2, 3, 4}, None}, AxesStyle -> Thin, TicksStyle -> Directive[Black, Bold, 12], Mesh -> Full, Epilog -> { Line[ ...