Function Repository Resource:

StringToBoxes

Source Notebook

Convert a string into boxes as if it were typed into a notebook

Contributed by: Richard Hennigan (Wolfram Research)

ResourceFunction["StringToBoxes"][string]

converts string into boxes as if it were typed into a notebook.

Details and Options

ResourceFunction["StringToBoxes"] generates boxes that are similar to what you would get as if typing into a cell that uses BoxData.
You can see how box structures generated by ResourceFunction["StringToBoxes"] would be displayed by using DisplayForm.
Use Image (Windows/Linux) or Image (Mac) to view the underlying boxes of a selected cell. »

Examples

Basic Examples (2) 

Convert a string into boxes:

In[1]:=
ResourceFunction["StringToBoxes"]["f[x_]:=x+1"]
Out[1]=
Image

View the DisplayForm:

In[2]:=
DisplayForm[%]
Out[2]=
Image

View as an input cell:

In[3]:=
CellPrint[Cell[BoxData[%%], "Input"]]
Image

The string does not need to be valid syntax:

In[4]:=
ResourceFunction["StringToBoxes"]["f[x_]:="]
Out[4]=
Image
In[5]:=
DisplayForm[%]
Out[5]=
Image

Scope (3) 

Convert a linear syntax string into boxes:

In[6]:=
string = "\!\(\*SuperscriptBox[\"a\", \"b\"]\)"
Out[6]=
Image
In[7]:=
ResourceFunction["StringToBoxes"][string]
Out[7]=
Image
In[8]:=
string = "\!\(\*RowBox[{SuperscriptBox[\"x\",\"2\"],\"+\",SuperscriptBox[\"y\",\"3\"]}]\)"
Out[8]=
Image
In[9]:=
ResourceFunction["StringToBoxes"][string]
Out[9]=
Image

The boxes are interpreted as if the string were typed into a notebook:

In[10]:=
ResourceFunction["StringToBoxes"]["Graphics[Disk[pt]]"]
Out[10]=
Image
In[11]:=
RawBoxes[%]
Out[11]=
Image

Compare to using ToExpression and MakeBoxes:

In[12]:=
ToExpression["Graphics[Disk[pt]]", InputForm, MakeBoxes]
Out[12]=
Image

This results in an error:

In[13]:=
RawBoxes[%]
Out[13]=
Image

StringToBoxes can handle invalid syntax:

In[14]:=
boxes = ResourceFunction["StringToBoxes"]["f[what?] := ¯\\_(ツ)_/¯"]
Out[14]=
Image

This means the resulting boxes will not be valid syntax either:

In[15]:=
ToExpression[boxes, StandardForm]
Image
Out[15]=
Image

The boxes are valid, however, and can be displayed by the front end:

In[16]:=
CellPrint[Cell[BoxData[boxes], "Input"]]
Image

Options (2) 

PreserveWhitespace (2) 

By default, whitespace will be preserved in the output:

In[17]:=
ResourceFunction["StringToBoxes"]["f[x_]        :=       x+1"]
Out[17]=
Image
In[18]:=
DisplayForm[%]
Out[18]=
Image

Ignore whitespace:

In[19]:=
ResourceFunction["StringToBoxes"]["f[x_]        :=       x+1", "PreserveWhitespace" -> False]
Out[19]=
Image
In[20]:=
DisplayForm[%]
Out[20]=
Image

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 19 April 2019

Related Resources

License Information