I have just discovered the free (as in free beer) Wolfram Engine, coming with a generous licence. After playing with Mathematica for a while, and missing the notebook feature, I would like to generate a PDF out of the .wls scripts I am going to create.
In order to do this, I assume I have to create a notebook and subsequently exporting it to a PDF.
Consider the following foo.wls
script:
(* = Title = *)
1 + 2
{x + y, 1/x + 1/y}
(* = Plots = *)
Plot[x^2, {x, -10, 10}]
I can generate the PDF like follows:
(* Options suggested by https://mathematica.stackexchange.com/a/133058/95308 *)
SetOptions[First[$Output], FormatType -> StandardForm];
(* Import script as a list of deferred expressions *)
wls = Import[FileNameJoin[{$TemporaryDirectory, "foo.wls"}], "HeldExpressions"];
exprs = wls /. HoldComplete -> Defer;
(* Convert expressions into notebook cells *)
cells = Function[e, ExpressionCell[e, "Input"]] /@ exprs;
(* This is for the eyes *)
cells = Join[{TextCell["Testing .wls Scripts", "Title"]}, cells];
UsingFrontEnd[
(* Make the cells into an in-memory notebook *)
nb = CreateDocument[cells];
(* Evaluate input cells to add the related output *)
NotebookEvaluate[nb, InsertResults -> True, EvaluationElements -> All];
(* Save the notebook to a file and export it as a PDF *)
NotebookSave[nb, FileNameJoin[{$TemporaryDirectory, "foo.nb"}]];
Export[FileNameJoin[{$TemporaryDirectory, "foo.pdf"}], nb];
NotebookClose[nb]
]
The result is not particularly bad, as per the picture below, but comments are gone.
This is due to Import[...foo.wls", "HeldExpressions"]
above. I could use "Comments"
, instead, and get them.
Still, I would not get their position with respect to expressions.
Manually parsing the file would be possible only for expressions spanning over a single line, as there is no simple way to tell in which line a multiline expression ends.
What are your suggestions?