# SuperscriptBox question

I am trying to define an object type in Mathematica as follows

Operator /: MakeBoxes[Operator[pow_, sym_], fmt_] :=
With[{sbox = If[StringQ[sym], sym, ToBoxes[sym]]},With[{abox = SuperscriptBox[#, pow]
&@sbox},InterpretationBox[abox, Operator[pow, sym]]]]


This works fine when I use integer powers for example

X = Operator[2,x]


gives me $x^2$, however it doesn't work if I use a symbol for the power for example

Y = Operator[a+b,x]


should give $x^{a+b}$ but it does not. What needs to be changed?

-
I have no experience with interpretation boxes etc. but this looks like a quick fix: Modify second with to ...With[{abox = SuperscriptBox[#, ToBoxes[HoldForm@pow]] &@sbox},.... –  Kuba Jun 26 '13 at 21:06
@Kuba Thanks! That seemed to fix it. –  Karan Jun 26 '13 at 21:12

I guess a more complex expression as exponent should be converted into a box structure as well. Why don't you just put another ToBoxes to convert the exponent?

Operator /: MakeBoxes[Operator[pow_, sym_], fmt_] :=
With[{sbox = If[StringQ[sym], sym, ToBoxes[sym]]},
With[{abox = SuperscriptBox[#, ToBoxes[pow]] &@sbox},
InterpretationBox[abox, Operator[pow, sym]]]]


Since Kuba's comment says it doesn't work without a HoldForm I'll put a screenshot. Feel free to insert a hold if it doesn't work for you either

If you want to make it more robust for situations where variables have values you could make a slight change:

Attributes[Operator] = {HoldFirst};
Operator /: MakeBoxes[Operator[pow_, sym_], fmt_] :=
With[{sbox = If[StringQ[sym], sym, ToBoxes[sym]]},
With[{abox = SuperscriptBox[#, ToBoxes[HoldForm[pow]]] &@sbox},
InterpretationBox[abox, Operator[pow, sym]]]]


Now, even something like Operator[1 + 1, x] works, although I don't know whether this is wanted.

-
I am using Mathematica 9 but it worked without HoldForm as well. –  Karan Jun 26 '13 at 22:09
@Karan I can not explain what has happened. Although I have reseted kernel repeatedly this feature showed up. After pc restart, it is gone. I will delete my previous comment as misleading. –  Kuba Jun 26 '13 at 22:16