[Tex/LaTex] Text in squared box

boxesframed

I'd like to bot a square box around some text. I'd like to denote a labelled object of size 1, in combinatorics this is often symbolised by something like \boxed{1}. It would be nicer if the box was a square. Is there an adequate command for this?

Best Answer

Here a solution based on my collectbox package. This makes it support verbatim and other special text.

It doesn't change the baseline of the content, which is what you normally want.

\documentclass{article}

\usepackage{collectbox}

\makeatletter
\newcommand{\sqbox}{%
    \collectbox{%
        \@tempdima=\dimexpr\width-\totalheight\relax
        \ifdim\@tempdima<\z@
            \fbox{\hbox{\hspace{-.5\@tempdima}\BOXCONTENT\hspace{-.5\@tempdima}}}%
        \else
            \ht\collectedbox=\dimexpr\ht\collectedbox+.5\@tempdima\relax
            \dp\collectedbox=\dimexpr\dp\collectedbox+.5\@tempdima\relax
            \fbox{\BOXCONTENT}%
        \fi
    }%
}
\makeatother

\usepackage{graphicx}% just for the example text
\begin{document}

.. \sqbox{Text} .. \sqbox{Very very long Text} .. \sqbox{\scalebox{.1}[10]{Stretched}} .. \sqbox{$\sum\limits_{k=0}^{10} x_k = i$} .. \sqbox{\verb+$%^&+}


\end{document}

Result


Alternatively you can avoid the package and box the content directly:

\documentclass{article}


\makeatletter
\newcommand{\sqbox}[1]{%
    \@begin@tempboxa\hbox{#1}%
    \@tempdima=\dimexpr\width-\totalheight\relax
    \ifdim\@tempdima<\z@
        \fbox{\hbox{\hspace{-.5\@tempdima}\usebox\@tempboxa\hspace{-.5\@tempdima}}}%
    \else
        \ht\@tempboxa=\dimexpr\ht\@tempboxa+.5\@tempdima\relax
        \dp\@tempboxa=\dimexpr\dp\@tempboxa+.5\@tempdima\relax
        \fbox{\usebox\@tempboxa}%
    \fi
    \@end@tempboxa
}
\makeatother

\usepackage{graphicx}% For example only
\begin{document}

\noindent
.. \sqbox{Text} .. \sqbox{Very very long Text} .. \sqbox{\scalebox{.1}[10]{Stretched}} .. \sqbox{$\sum\limits_{k=0}^{10} x_k = i$} .. 

\end{document}