# Manipulating spacing in a text object

I want to visually illustrate substitution in a mathematical expression. This is an example:

Graphics[Text[
Style[3 x^2 + 2 (1 + y) // TraditionalForm, FontFamily -> "Arial",
24], {0, 0}], PlotRange -> {{-2, 2}, {-.2, .2}}]


I would like to replace the y by 15, then replace 1 + 15 by 16, each time moving the characters in the text box to have proper typographical spacing. (Eventually I want to make the parentheses vanish as well, but never mind that now.) What I want to do is manipulate the spacing by operating on the text box, not by evaluating 3x^3 +2(1+15). This would seem to require accessing the location in the text box of each character. I can't find anything in the documentation that shows how to do this.

If you use ToBoxes on something generated by TreeForm you CAN see the locations of the nodes (although they are buried in a big mess of detail), but ToBoxes doesn't do that in the case of formulas as text.

-
I edited your post to format the code (indent 4 spaces), and put the Arial in quotation marks because otherwise you get Helvetica. –  Jens Jul 11 '12 at 1:29
When you say "visually illustrate" - do you mean to make an animation? That's the interpretation I used in my answer. –  Jens Jul 11 '12 at 5:38

To "manipulate spacing in a text object" one can use AdjustmentBox. For example, the first step in your visualization could be something like this:

Manipulate[
Graphics[Text[DisplayForm[ToBoxes[
Style[3 x^2 + 2 (1 + y) // TraditionalForm,
FontFamily -> "Arial", 24]
] /. "y" -> AdjustmentBox["y", BoxMargins :> d]], {0, 0}],
PlotRange -> {{-2, 2}, {-.3, .3}}],
{d, 0, 1}]


Of course I'm not sure to what extent you want to animate things, so I just used a Manipulate to show the effect. The main point is that I picked out the variable "y" as it appears in the box form of the formula, then post-processed it by making a substitution that surrounds the "y" by AdjustmentBox["y", BoxMargins :> d]. Here, d is the extra space that you'd need to create before replacing the y by 15.

The space is given by BoxMargins - if you want to create only horizontal space, you'd use BoxMargins :> {{d, d}, {0, 0}}.

-
That is going to be very useful for what I want to do. Thanks. –  SixWingedSeraph Jul 12 '12 at 2:48

Your question doesn't make a lot of sense to me. Perhaps you are not aware of HoldForm:

Graphics[Text[
Style[3 x^2 + 2 (1 + 15) // HoldForm // TraditionalForm,
FontFamily -> "Arial", 24], {0, 0}],
PlotRange -> {{-2, 2}, {-.2, .2}}]


If this is not what you're after perhaps you could add an explanation of why this is not appropriate.

-
I did not know about HoldForm. Thanks. –  SixWingedSeraph Jul 12 '12 at 2:45