[Tex/LaTex] Set length to the line height of a particular font

fontsizefontspeclengthsunit-of-measure

How to define new length using :

\newlength{...}
\setlength{...}{...}

and equal to the line height of a particular font (for example \tiny\ttfamily)

Note : I want a solution which does not involve writing anything in the \begin{document}\end{document} part.

Best Answer

This will loop on all characters (from 0 to 255), so it's good only for pdflatex; some different heuristics would be needed for XeLaTeX or LuaLaTeX with fontspec.

The length \fonttotalheight is defined to be the height plus depth, unless the *-variant is used, which will measure only the height, disregarding descenders.

\documentclass[12pt]{article}
\usepackage[T1]{fontenc}

\newlength{\fonttotalheight}

\makeatletter
\newcommand{\setfonttotalheight}{%
  \@ifstar{\@tempswafalse\setfont@totalheight}%
          {\@tempswatrue\setfont@totalheight}%
}
\newcommand{\setfont@totalheight}[1][]{%
  \sbox{\z@}{%
    \normalfont
    #1% it should be a font selection command
    \selectfont 
    \count@=\z@
    \loop
      \char\count@
    \ifnum\count@<\@cclv
      \advance\count@\@ne
    \repeat
  }%
  \setlength\fonttotalheight{\ht\z@}%
  \if@tempswa\addtolength\fonttotalheight{\dp\z@}\fi
 }
\makeatother

\setfonttotalheight*

\begin{document}

Initial value: \texttt{\the\fonttotalheight} (only height)

\bigskip

\begingroup
Fontencoding: OT1
\fontencoding{OT1}\selectfont

\setfonttotalheight*
Normal font (only height): \texttt{\the\fonttotalheight}

\setfonttotalheight
Normal font (height and depth): \texttt{\the\fonttotalheight}

\setfonttotalheight[\ttfamily]
Typewriter type (height and depth): \texttt{\the\fonttotalheight}

\endgroup

\bigskip

Fontencoding: T1

\setfonttotalheight*
Normal font (only height): \texttt{\the\fonttotalheight}

\setfonttotalheight
Normal font (height and depth): \texttt{\the\fonttotalheight}

\setfonttotalheight[\ttfamily]
Typewriter type (height and depth): \texttt{\the\fonttotalheight}

\end{document}

enter image description here