4

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.

\documentclass{article}

\newcommand\countlines[1]{
{\setbox0\vbox{\noindent{#1}\par
\count@\z@
\loop
\unskip\unpenalty\unskip\unpenalty\unskip
\setbox0\lastbox
\ifvoid0
   \xdef\numlines{\the\count@}
\else
   \advance\count@\@ne
\repeat}}
}

\title{aaa\\b\\bb}

\begin{document}

\makeatletter

\countlines{\@title}
\typeout{Number of lines is \numlines}

\end{document}

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

\typeout{Number of lines is \countlines{\@title}}
2
  • 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

4

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

\documentclass{article}

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

\title{aaa\\b\\bb}

\begin{document}

\typeout{Number of lines is \numlines}

\end{document}
0
3

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.

Code

\documentclass{article}
\usepackage{calc}
\usepackage{pgf}

\newlength{\parline}
\newlength{\paroutindent}
\newlength{\lineheight}
\setlength{\lineheight}{\heightof{abcdefghijklmnoprstuvwxyz}}

\newcommand{\countlines}[1]{%
    \setlength{\paroutindent}{\expandafter\parindent}
    \setlength{\parline}{\heightof{\noindent\begin{minipage}{\linewidth}%
                \setlength{\parindent}{\paroutindent}#1\end{minipage}}}%
    \pgfmathparse{round(\parline / (0.9*\lineheight))}
    #1\par \noindent \texttt{line count: (\pgfmathresult)}
}

\usepackage{lipsum}

\begin{document}
    \countlines{\lipsum[1]}

    \countlines{\lipsum[2]}

    \countlines{Just one line}

    \countlines{Just two \\ lines}

\end{document}

Result

enter image description here

You must log in to answer this question.

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