There are two ways that you can do this: one is with \prevgraf
, and the other by calculating the lines manually.
If you do it with \prevgraf
, that gives you the amount of lines in the previous paragraph. This will only work if your input is meant to be only one paragraph. What we do is we use \setbox0
to put the text into a vbox which we don't print. In the vbox, we set the hsize
to your width, the second argument, and then print the first argument as a paragraph. We manually end the paragraph with \par
, and the use \xdef
to save the current value of \prevgraf
into the cs you passed as the third argument.
\def\CalcNumber#1#2#3{%
\setbox0\vbox{\hsize=#2 \noindent#1\par\xdef#3{\the\prevgraf}}}
If your input is more than one paragraph, then you can use the same setup as follows:
\makeatletter
\long\def\CalcNumber#1#2#3{%
\setbox0\vbox{\hsize=#2 \noindent#1}}
\@tempcnta=\dimexpr(\ht0+\dp0)/\baselineskip
\xdef#3{\the\@tempcnta}}
\makeatother
In a similar fashion to our other approach, we typeset our text in a box. We need to define our \CalcNumber
as \long
, so it can accept text of more than one paragraph. Then, we add the height and depth of the box, and divide by \baselineskip
, saving it in a LaTeX temporary count register (this will round the number for us). We then store this in our give control sequence, as above.
A caveat here is that this will use whatever the baselineskip is when you call the macro. You'd need to account for variations in font sizes, depending on what you plan on using this for.
\newbox\calcbox \setbox\calcbox\vbox{\hsize#2\relax#1\par} \edef#3{\the\dimexpr(\dp\calcbox+\ht\calcbox)/(\baselineskip)\relax}
Sorry, haven't tested and probably doesn't work, because of limitations of\dimexpr
and may be because of problems with the syntax (I don't know much about boxes), but something like that would work.