How do I convert an arbitrary box specification extracted from a cell expression into an input expression?
This came up as a problem with my answer to Save Mathematica c
I think this is a bug. Here is a work-around that worked on a couple of examples I tested:
Clear[toExpression];
toExpression[bd_BoxData] :=
ToExpression[bd /.
s_String :>
StringReplace[
StringReplace[s, "\n" :> ""],
ShortestMatch[(start : "\(\*") ~~ body__ ~~ (end : "\)")] :>
StringJoin[start, StringReplace[body, "\"" :> "\\\""], end]
]
];
For example, we start with your case:
In[747]:=
BoxData["\"\<\!\(\*
StyleBox[\"a\",
FontSlant->\"Italic\"]\) = ``\>\""]//toExpression
Out[747]= a = ``
If we examine the cell now, it is:
BoxData["\<\"\\!\\(\\*StyleBox[\\\"a\\\",FontSlant->\\\"Italic\\\"]\\)\ = ``\"\>"]
instead of
BoxData["\"\<\!\(\*StyleBox[\"a\",FontSlant->\"Italic\"]\) = ``\>\""]
(which is the initial one with newlines removed). And, I'd argue, this is what it should have been from the start. Now:
In[746]:= ToExpression@
BoxData["\<\"\\!\\(\\*StyleBox[\\\"a\\\",FontSlant->\\\"Italic\\\"]\\) = ``\"\>"]
Out[746]= a = ``
So this already works fine.
I don't know how universal this work-around it, but it seems to work for examples I tried. The main problem was that, when "stringifying" things like a
and Italic
, it should have been \\\"a\\\"
and \\\"Italic\\\"
rather than \"a\"
and \"Italic\"
- the escapes for escapes themselves were missing.