Problems interpreting input cell box expressions

与世无争的帅哥 提交于 2019-12-04 01:26:15

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.

Honestly I am not sure what you're trying to do, but I suspect you will need to use the FrontEnd itself for processing. Here is a generic example:

FrontEndExecute@FrontEnd`CellPrint[
  BoxData[RowBox[{"StringForm", "[", RowBox[{"\"\<\!\(\*
         StyleBox[\"a\",
         FontSlant->\"Italic\"]\) = ``\>\"", ",", " ", "1"}], "]"}]]
]

However, I don't know what format you actually want to get.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!