# Problem with a code to draw a box around text

I want to enclose a text in a box. My problem is that when the code below is placed at the beginning of a line it causes a line-break/carriage-return (the box stays on a line by itself, the rest of paragraph starts at the next line). But it is OK when I use it in the middle or the end of a line. What is causing this behavior?

\def\boxit#1#2{\hbox{\vrule
\vtop{%
\vbox{\hrule\kern#1%
\hbox{\kern#1#2\kern#1}}%
\kern#1 \hrule}%
\vrule}}
\vfil}}}

-
\hbox doesn't start horizontal mode; add \leavevmode as the first token in the replacement text. – egreg Oct 15 '12 at 19:15

Contrary to what can be thought at first, \hbox doesn't start horizontal mode. The reason is that a \vbox can be made up by stacking \hboxes:

\vbox{\hbox{A}\hbox{B}\hbox{C}}


and this would result in

A
B
C

and the width of the resulting \vbox would be that of the widest \hbox.

The same is true about \vbox, \vtop, \box and \copy. Conversely, \unhbox and \unhcopy applied to a box register containing an \hbox will start horizontal mode. If you intend to use those commands as starting paragraphs, add \leavevmode:

\def\boxit#1#2{\leavevmode
\hbox{\vrule
\vtop{
\vbox{\hrule\kern#1%
\hbox{\kern#1#2\kern#1}
}%
\kern#1 \hrule
}%
\vrule}%
}
\def\emptybox#1#2#3{\leavevmode
\vfil}%
}%
}


A more efficient macro for creating an empty box with specified height, depth and width is

\def\emptybox#1#2#3{%
\leavevmode
\begingroup\setbox0=\hbox{}%
\ht0=#1%
\dp0=#2%
\wd0=#3%
\box0
\endgroup}

-