Problems interpreting input cell box expressions

前端 未结 2 762
北海茫月
北海茫月 2021-02-20 02:36

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

相关标签:
2条回答
  • 2021-02-20 03:03

    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.

    0 讨论(0)
  • 2021-02-20 03:08

    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.

    0 讨论(0)
提交回复
热议问题