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 (Windows/Linux) or (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]=

View the DisplayForm:

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

View as an input cell:

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

The string does not need to be valid syntax:

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

Scope (3) 

Convert a linear syntax string into boxes:

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

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

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

Compare to using ToExpression and MakeBoxes:

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

This results in an error:

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

StringToBoxes can handle invalid syntax:

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

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

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

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

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

Options (2) 

PreserveWhitespace (2) 

By default, whitespace will be preserved in the output:

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

Ignore whitespace:

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

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 19 April 2019

Related Resources

License Information