Convenient way to add inline formatting to usage Messages

与世无争的帅哥 提交于 2019-11-30 20:40:29

One of the problems of handling strings like that is that most operations with strings in Mathematica automatically replace the backslash (\) with the escaped backslash (\\).

If you try this:

you may think you have the string you're looking for (minus the \! to make it an expression), but in fact it is: "\\(x\\_\\(1, 2\\) \[Equal] \\(\\(-b\\) \[PlusMinus] \\@\\(b\\^2 -\\(4\\ a\\ c\\)\\)\\)\\/\\(2\\ a\\)\\)"

My solution is far from elegant, but it works.

  1. Generate boxes from your formatted expression:

  2. Select the output, and go to menu item Cell > Convert to > InputForm. Result:

  3. You can now edit the string, putting \! in front of it and quotes around it: "\!\(x \_ \(1, 2\) == \(\(-b\) \[PlusMinus] \@\(b \^2 - \(4\ a\ c\)\)\) \/ \(2\ a\)\)"

If you perform step 3 in an external editor, leave away the quotes and just have \! in front and paste back the result in MMA it is directly converted to the formatted expression

I think the easiest way is to just use the Front End to format your string. If you are writing a package, you can use "auto-save packages" (i.e. when the contents of the initialization cells of a notebook become the package). If you use a text editor to write the package then it might just be too much trouble to use formatting ...

This answer is an addition to Sjoerd's answer.

First of all, we do not have to use the FrontEnd command Cell > Convert to > InputForm to get the linear form of boxes. We can get it just by applying InputForm to the output of MakeBoxes:

In[1]:= InputForm@MakeBoxes[Subscript[x, 1,2]==(-b\[PlusMinus]Sqrt[b^2-4 a c])/(2 a)]
Out[1]//InputForm=
\(x\_\(1, 2\) == \(\(-b\) \[PlusMinus] \@\(b\^2 - \(4\ a\ c\)\)\)\/\(2\ a\)\)

Secondly, we can export the final typesetting in-line string representation of boxes by the following two ways with equivalent result (the only difference is that Put wraps the text):

OutputForm@
  StringInsert[
   ToString[
    InputForm@
     MakeBoxes[
      Subscript[x, 1, 2] == (-b \[PlusMinus] Sqrt[b^2 - 4 a c])/(
       2 a)], OutputForm], "\\!", 1] >> "C:\\input.txt"

Export["C:\\input.txt", 
 StringInsert[
  ToString[InputForm@
    MakeBoxes[
     Subscript[x, 1, 2] == (-b \[PlusMinus] Sqrt[b^2 - 4 a c])/(2 a)],
    OutputForm], "\\!", 1], "String"]

In both cases we get a file with one line: \!\(x\_\(1, 2\) == \(\(-b\) ± \@\(b\^2 - \(4\ a\ c\)\)\)\/\(2\ a\)\).

Inserting this line in a Notebook in the FrontEnd gives the original expression (try it by yourself!):

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