I am looking for a way to get something similar to the "Input Text" form of an arbitrary box structure, but without the extra whitespaces.

Before I explain the requirements in a bit more detail, let's look at two examples:

cell1 = Cell[BoxData[
      RowBox[{"f", "[", RowBox[{"a", ",", "b"}], "]"}],
      RowBox[{"g", "[", RowBox[{"c", ",", "d"}], "]"}]
    ], "Input"];

cell2 = Cell[BoxData[
     RowBox[{"f", "[", RowBox[{
         RowBox[{"(", GridBox[{{"a", "b"}, {"c", "d"}}], ")"}],
         ",", "3"}], "]"}],
    ], "Input"];

cells = {cell1, cell2};

These cells look like this:

enter image description here

The function I'm looking for (let's call it toInputString in the following) should return the following:

toInputString /@ cells
(* {
} *)


These are the properties of toInputString that I'm looking for, in order of priority:

  • I need to do "Box structure IN" -> "String STR" -> "Box structure OUT" in the end. This question is about the first step (the second is done using MathLink`CallFrontEnd[FrontEnd`UndocumentedTestFEParserPacket[STR,False]])
  • The two box structures IN and OUT must be semantically equivalent, i.e. evaluating either of them should yield the same result. (This rules out FrontEndExecute@FrontEnd`ExportPacket[IN,"PlainText"])
  • The string STR should be as readable as possible, i.e. no embedded box structures in the string if possible
  • The two box structures IN and OUT should be as similar as possible:
    • For example, postfix notation and line breaks should be preserved
    • No extraneous whitespaces should be present in STR (which are typically added by Mathematica when converting to text), as they will then be present in OUT as well.
    • The GridBox in the example above can be removed for instance, since the string would be harder to read otherwise.


Here are some of my attempts:

(* generates too many whitespaces that get kept in OUT *)
toInputString[box_]:=FrontEndExecute@FrontEnd`ExportPacket[box, "InputText"]

(* gives the same result as the first one *)
  Append[TextClipboardType -> "Package"]@box,

(* gives the same result as the first one *)
  Append[AutoSpacing -> False]@box,

(* doesn't preserve semantics, e.g. cell2 breaks with this *)
toInputString[box_]:=FrontEndExecute@FrontEnd`ExportPacket[box, "PlainText"]

One possibility might be to post-process the string to strip out any superfluous whitespace (ignoring those within strings), but that seems a bit hacky…


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.