# How to do literal replacement to format expression?

I can do a replacement of an expression with some variables to alternate symbols:

{sx^2, sxy} /. {sx -> Subscript[J, x],
sxy ->  Subscript[J, x] Subscript[J, y]}


but if this replacement includes matching square braces, for example instead of $J_x$ above using:

{sx^2, sxy} /. {sx -> [Subscript[J, x]],
sxy -> [ Subscript[J, x] Subscript[J, y]]}


then the replacement fails with:

Expression cannot begin with "[Subscript[J, x]]".


I'd like this replacement (only for display purposes) to be $sx \rightarrow [J_x]$, where square brackets is the notation we are using in class for an "ensemble average".

Is there a way to escape the square braces so that the sequence '[', J_x, ']' will be treated as an opaque entity?

## 1 Answer

A possibility:

MakeBoxes[Subscript[J_, x_], StandardForm] :=
RowBox[{"[", SubscriptBox[ToString@J, ToString@x], "]"}]


Then evaluating

{sx^2, sxy} /.
{sx -> Subscript[J, x], sxy -> Subscript[J, x] Subscript[J, y]}


should return what you want.

Another proposition

One can also directly use MakeBoxes definitions for the variables sx, sy, and so on...

MakeBoxes[sx, StandardForm] :=
RowBox[{"[", SubscriptBox["J", "x"], "]"}]


This avoids using rules as was done above, but it requires defining MakeBoxes for every variable (though I suppose this process could be automated without much trouble).

• I figured out after I posted that I could use Row[ "[", ... ] in a replacement expression, but I like your suggestion much better, since it takes the formatting decisions out of the core content. – Peeter Joot Nov 25 '15 at 2:53
• Glad you find these propositions useful. Here is yet another possibility: Format[sx] := DisplayForm[RowBox[{"[", SubscriptBox["J", "x"], "]"}]]. – user31159 Nov 25 '15 at 5:49