I have a Mathematica expression generated by another program, which I would like to open in a notebook, properly formatted. For instance, the other program generates this:
Plot[{Exp[x],Interpolation[Table[{k/5,Exp[(k-1/2)/5]},{k,0,5}],
InterpolationOrder->0][x]},{x,0,1},Filling->{1->{{2},{Yellow,Orange}}},
PlotLabel->Style["Formatting",Blue,FontFamily->"Courier"]]
The text is written into a file, crudely suffixed ".nb", and launched, and the expression opens in a notebook without formatting. To achieve formatting, writing a file manually with BoxData seems impractical.
The file is actually being launched from .Net using Process.Start("filename.nb"), but a command line launch seems equally problematic.
You can use the following wrapping:
then commands NotebookSave and NotebookClose can be used to save and close the thing ;)
Here is the solution I adopted. Thanks for all the help.
The main step of the solution is to format the command via the kernel:-
Then the formatted data is encapsulated to create a notebook:-
This is written to a file, suffixed ".nb". All fine and dandy.
This approach works well for multi-statement blocks of code, but some additional processing was included to format a single function call of the form Function[expression, options] to add a line-break before each option. Here is the C# code used to produce both types of output:-
Unless you create the
BoxData
expressions explicitly there is no way to format your expression without actually invoking at least the Mathematica FrontEnd.The closest I can think of is that you add the following:
which automatically formats the
Plot
command when the cell is evaluated. (BTW: You probably should either addEvaluate
in front of the list or add the (not-so-well documented)Evaluate->True
option.How about this:
I tested it and it seems to work (importing from the plain file, exporting to the one you will then open). This does create explicit boxes, but with a very little effort on the user's side. I did not test, but you should be able to run this code in the script mode, from the command line.
EDIT
To test from within Mathematica, you can use e.g.
before running the code above.