I would like to have a macro that counts the number of lines in a block of text. I was able to create one based on the answer for "counting the newlines in title", but I would prefer that the macro returns the number of lines directly rather than having to retrieve it via \numlines. If anyone knows how to do this I would appreciate being told how.






\typeout{Number of lines is \numlines}


What I specifically desire is that \countlines return the number of lines directly as indicated below.

\typeout{Number of lines is \countlines{\@title}}
  • 1
    You can always add \numlines into the end of the macro definition.
    – cfr
    Jul 3, 2016 at 2:43
  • is it ok if we replace \\ by \newline the count becomes wrong?
    – Cfun
    Jul 3, 2016 at 4:55

2 Answers 2


You can do the calculation in \title macro and then you can use the result in \numlines macro:


\newcount\numli \def\numlines{\the\numli}
\def\title#1{\numli=0 \titleA#1\\\\{#1}}
   \advance\numli by1 \expandafter\titleA\fi}



\typeout{Number of lines is \numlines}


This is my approach using height lengths. I think it can be better, maybe someone can make some recommendations to improve it, but works for the examples. My intention is not to improve your code, but show you another way to count lines in a block of text.




    \pgfmathparse{round(\parline / (0.9*\lineheight))}
    #1\par \noindent \texttt{line count: (\pgfmathresult)}




    \countlines{Just one line}

    \countlines{Just two \\ lines}



enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .