[Tex/LaTex] Underlined blank that wraps

line-breakingrules

I'd like to create an "answer blank" in a document. It should basically look like an underline with nothing above it. I found a question about it ( How does one TeX a blank? ), but that doesn't deal with the main problem I'm having, which is that I want the blank to wrap normally to the text width. The solutions using \hspace or \rule cause the line to extend into the margin.

I'm looking for something that wraps just like normal text and so won't extend into the margin. It should be an underlined blank that has a specified length, but that length might be wrapped across multiple lines in the output document.

Best Answer

With the following we define some building blocks 0.5 cm wide; with \blank{12} you'll get a 6cm wide line that can wrap, with a minimum of two blocks on either side; the minimum can be modified with the optional argument, with \blank[4]{12} the number of blocks will be 4 on either side.

\documentclass[a4paper]{article}
\newcommand{\piece}{\hskip1sp\kern-1sp\hbox to .5cm{\hrulefill}}
\newcommand{\nbpiece}{\hbox to .5cm{\hrulefill}}

\makeatletter
\newcommand{\build}[2]{\leavevmode
  \count@=\z@ \toks@={}%
  \loop\ifnum\count@<\numexpr#1\relax
    \toks@=\expandafter{\the\toks@#2}%
    \advance\count@\@ne
  \repeat
  \the\toks@}
\makeatletter

\newcommand{\blank}[2][2]{%
  \build{#1}{\nbpiece}\build{#2-2*#1}{\piece}\build{#1}{\nbpiece}}

\begin{document}

A paragraph with \blank{12} and \blank{24} blanks.

\end{document}

Edit

If one wants to specify the length in centimeters instead of "number of blocks", it's sufficient to modify the definition of \blank as

\newcommand{\blank}[2][1]{%
  \build{#1}{\nbpiece}\build{2*(#2-#1)}{\piece}\build{#1}{\nbpiece}}

The optional argument is still the minimum number of blocks on either side; with the default the minimum rule width is 1cm. A specification such as \blank{3} now means "build a rule 3cm wide" that can be split across lines".

If long rules are needed, for example to fill rows, it's convenient to change also the definition of \piece to allow a little backspacing in order to avoid overfull boxes

\newcommand{\piece}{\hskip0pt minus 3pt\hbox to .5cm{\hrulefill}}