# Restrict text to box without linebreak

This:

\fbox{\makebox[3cm][l]{long text long text long text long text}}


results into this:

I want it to stop right at the end of the box. No line-wrapping. So the text, which is 'too much', cannot be seen.

• Do you want to break at a char boundary or potentially to have a partial char appearing? – Joseph Wright Sep 16 '14 at 12:08

\documentclass{article}
\usepackage[fit,breakall]{truncate}
\begin{document}

\fbox{\truncate[]{3cm}{long text long text long text long text}}
\end{document}


Read the document to understand the options.

Here's a solution that uses as much text as will fit in the stated length; the *-form frames only the text that fits, the normal form uses the stated length anyway.

\documentclass{article}
\usepackage{xparse}

\NewDocumentCommand{\restrict}{smm}{% #2 is a length, #3 is the text
\setbox0=\vbox{\hsize=#2\relax\raggedright#3\par
\setbox2=\lastbox\unskip\unpenalty
\loop
\setbox4=\box2
\setbox2=\lastbox\unskip\unpenalty
\unless\ifvoid2
\repeat
\global\setbox1=\box4
}% end of the \vbox
\fbox{\IfBooleanTF{#1}{\unhbox}{\box}1}%
}

\begin{document}

\restrict{3cm}{A long text that should be cut at 3cm at most}

\restrict*{3cm}{A long text that should be cut at 3cm at most}

\restrict{3cm}{A long text that is cut at 3cm at most}

\restrict*{3cm}{A long text that is cut at 3cm at most}

\end{document}


The idea is to compose a paragraph with the stated length as line width, then dismantle the resulting box until getting at the first line that's finally typeset.

My solution is a similar like egreg's but the \loop isn't needed because we have only two lines of the internal praragraph. The lines are set by \parshape. First line has given width and second line (if exists) has \maxdimen width.

\def\restrict#1#2{\setbox0=\vbox{\parshape 2 0pt #1 0pt \maxdimen
\rightskip=0pt plus1fil\noindent#2\par
\setbox0=\lastbox \unskip\unpenalty \global\setbox2=\lastbox}%
\ifvoid2 #2\else \leavevmode\unhbox2 \unskip \fi
}
test: \restrict{3cm}{A long text that should be cut at 3cm at most}


The frame around restricted text isn't printed here explicitly. You can do it by another tools.

• Nice idea. It should be \global\setbox1, because even numbered scratch register should be used only for local assignments. – egreg Sep 16 '14 at 17:32