5

I need to change the width of a saved box and want it to look as if it was constructed at that width.

For example, this centers A in a 4cm wide box:

\hbox to 4cm{\hfil A\hfil} 

But this centers B in the original 2cm wide box, and then adds 2cm to the right making the resulting box the desired width, but without telling the glues about it:

\setbox0=\hbox to 2cm{\hfil B\hfil} \wd0=4cm \box0 

And this just puts the text on the left with zero-width glues:

\setbox0=\hbox{\hfil C\hfil} \wd0=4cm \box0 

Is there a way to change the width in a way that centers B and C in the adjusted boxes like A?

result

I'm not sure if this will make it easier or harder, but how do I do this in LuaTeX, because in practice I'm collecting boxes, adjusting them in Lua code and then put them back, like so:

\setbox0=\hbox{\hfil D\hfil}% \directlua{ local b = node.copy(tex.box[0]) b.width = tex.sp('4cm') node.write(b) } 

i.e. at the point where I'm handling the box it has already been typeset, which would make a solution that stores the tokens and creates a new box of the target width and typesets it again quite complicated. I'm hoping there's a simple API call that will simply recompute this?

2
  • 1
    regarding glue and boxes in LuaTeX, see tex.stackexchange.com/a/207367/2891 Commented Mar 16, 2015 at 13:13
  • 1
    After \setbox0=\hbox to 2cm{\hfil B\hfil} you can do \hbox to 4cm{\unhbox0}. In the picture I added X at the sides of the boxes and \hrulefill instead of \hfil to see the effect Commented Mar 16, 2015 at 13:26

2 Answers 2

3
\setbox0=\hbox{\hfil C\hfil} \setbox0=\hbox to 4cm{\unhbox0} \box0 
6
  • I arrived four seconds earlier. :-P Commented Mar 16, 2015 at 13:27
  • @egreg But mine's an answer Commented Mar 16, 2015 at 13:27
  • cool I didn't know about \unhbox. But is there a way to do this with a box object in Lua? Commented Mar 16, 2015 at 13:42
  • @pascal yes you'll just need to move the node list representing the horizontal list to the new box node. I'd have to look up the lua syntax (unlike the TeX that I could write in my sleep:-) Commented Mar 16, 2015 at 13:44
  • @DavidCarlisle I arrived one day later. :( Commented Mar 18, 2015 at 8:26
4

For completeness, here's the Lua version, turns out \unhbox is simply accessing head, effectively discarding the old hbox, and constructing a new hbox with an exact width, just like the plain version:

\setbox0=\hbox{\hfil D\hfil}% \directlua{ local b = node.copy(tex.box[0]) b = node.hpack(b.head, tex.sp('4cm'), 'exactly') node.write(b) } 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.