Message Boards Message Boards

5 Replies
8 Total Likes
View groups...
Share this post:

How could I programmatically write results of Show Expression to a file?

Posted 11 years ago
Using Cell->Show Expression or FrontEndTokenExecute["ToggleShowExpression"], it is possible to see the RawData for a cell.

I am wondering if I can programmatically go through a notebook and write the results of Show-Expression for each cell to a file.

I could do it by parsing the text of a saved notebook---but I think this is reinventing the wheel?

Does anyone have a pointer (or a simple example) about how I would go about doing this?  I am still learning how to do front-end programming.

Thanks, Craig
POSTED BY: W. Craig Carter
5 Replies
Posted 11 years ago
Hi Craig,

Assuming you'd be reading these files back in with Mathematica, I think a Cells/NotebookRead/Put/Get combo might be what you're looking for:

 In[10]:= targetNb = EvaluationNotebook[];
 cellExprs = NotebookRead@Cells@targetNb
 Out[11]= {Cell[
   BoxData[{RowBox[{RowBox[{"targetNb", "=",
         RowBox[{"EvaluationNotebook", "[", "]"}]}], ";"}],
     RowBox[{"cellExprs", "=",
       RowBox[{"NotebookRead", "@",
        RowBox[{"Cells", "@", "targetNb"}]}]}]}], "Input"],
Cell[BoxData[{RowBox[{RowBox[{"listFile", "=",
        "\"cellExprList.m\""}], ";"}], "\[IndentingNewLine]",
    RowBox[{RowBox[{"Put", "[",
        RowBox[{"cellExprs", ",", "listFile"}], "]"}], ";"}],
    RowBox[{RowBox[{"Get", "@", "listFile"}], "===", "cellExprs"}]}],
Cell[BoxData[{RowBox[{RowBox[{"seqFile", "=", "\"cellExprSeq.m\""}],
      ";"}], "\[IndentingNewLine]",
    RowBox[{RowBox[{"Put", "[",
        RowBox[{RowBox[{"Sequence", "@@", "cellExprs"}], ",",
          "seqFile"}], "]"}], ";"}], "\[IndentingNewLine]",
    RowBox[{RowBox[{"Get", "@", "seqFile"}], "===",
      RowBox[{"cellExprs", "[",
        RowBox[{"[", RowBox[{"-", "1"}], "]"}], "]"}]}]}], "Input"],
   RowBox[{RowBox[{"ReadList", "@", "seqFile"}], "===",
     "cellExprs"}]], "Input"]}

In[12]:= listFile = "cellExprList.m";
Put[cellExprs, listFile];
Get@listFile === cellExprs

Out[14]= True

In[15]:= seqFile = "cellExprSeq.m";
Put[Sequence @@ cellExprs, seqFile];
Get@seqFile === cellExprs[[-1]]

Out[17]= True

In[18]:= ReadList@seqFile === cellExprs

Out[18]= True

POSTED BY: William Rummler
Thank you Vitaliy and Shenghui,

I should have been more clear.  I want to preserve the formatting in the Cells as well. I am  writing these to files and then using this as formatted input for a different purpose (i.e.,

For example, suppose I have formatted Input and Text like this:

The Show-Cell-Expression forms of these are:
   RowBox[{"f", "[", "x_", "]"}], ":=",
   "\[IndentingNewLine]", " ",
   RowBox[{"Module", "[", "\[IndentingNewLine]",
     RowBox[{"{", "z", "}"}], ",",
     RowBox[{"z", " ", "=", " ",
      RowBox[{"x", "^", "2"}]}], ";",
     RowBox[{"x", " ", "z"}]}]}],
   "\[IndentingNewLine]", "]"}]}]], "Input"]
1. item 1
2. item 2
3. item 3
4. item 5\
\>", "Section"]
Saving notebook as .m doesn't preserve the formating.  Saving it as .txt preserves the formatting---only if the cells are in their Show-Cell-Expression form.

I could just save it as a .nb and then parse the text of the .nb file as text and extract the cells.... but this doesn't seem very elegant to me.

Shenghui's method is along the lines of what I want to do programmatically, but the formatting is not preserved:

I think that saving the notebook with everything converted to the Show-Cell-Expression Form is currently the clearest path forward for me, but that also seems to be inelegant.

Thanks, Craig
POSTED BY: W. Craig Carter
Here is a practical example: Controlling sound player object's size. Imagine you got some expression, say this one:
Integrate[1/Sin[x], x]
(* output *)
-Log[Cos[x/2]] + Log[Sin[x/2]]
To get programmatically underlying box expression use
exp = ToBoxes[%]
(* output *)
    RowBox[{"Log", "[",
      RowBox[{"Cos", "[", FractionBox["x", "2"], "]"}], "]"}]}], "+",
  RowBox[{"Log", "[",
    RowBox[{"Sin", "[", FractionBox["x", "2"], "]"}], "]"}]}]
To put it back together use
To save it as a file I'd recommend .m format
Export["exp.m", exp]
Here how you import it back
And put it back together
I am not sure what you are planning to do, but it seems to defeat the purpose, because if you'd like to preserve expression exactly in a file you could just use native Mathematica .m format.
POSTED BY: Vitaliy Kaurov
Also, without specification, the myfile.txt is created under $HomeDirectory (mac) or $UserDocumentsDirectory (win)
POSTED BY: Shenghui Yang
@ Craig, this can be done from the functions in the documentation of "Manipulating the FrontEnd with Kernel". Here is an example:
In[11]:= nb = CreateDocument[{1/x + 1/y, Sin[7.5]}];
In[19]:= SelectionMove[nb, Nest, Cell]
In[20]:= NotebookRead[nb]
In[21]:= ToString[%]
In[22]:= % >>> "myFile.txt"
First you create a notebook with two outputs (I put a Sin[7.5] here so when you see the numeric results in the notebook you know immediately they are outputs). In the new notebook, the cursor should be on the top of this page (if you want to check, select the new notebook by clicking its frame not the white place). Say, I want to get the expression of the first cell. I  have to select it and xray the cell. These two steps are done by
In[19]:= SelectionMove[nb, Nest, Cell]
In[20]:= NotebookRead[nb]
The Out[20] is indeed a valid hold expression, thus it keeps its unevaluated form. To put it into a new text file, you want to flip it to String and then PutAppend (>>>) to "myfile.txt" . 
As you run the In[19] -> In[22] twice (run In[11] only once), you should have the following result in your "myfile.txt":
POSTED BY: Shenghui Yang
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract