2

I want to define a command to ease the font configuration as below:

\newcommand{\setfont}[2]{\fontsize{#1}{#2}\selectfont}

The new command \setfont takes two parameters: one is the size of the font, the other is the line space.

However, it is not convenient to specify the line spacing in point directly. The more intuitive way is to set, e.g. two line spacing, or 1.5 line spacing. So in my command I want to take the second parameter a scale factor. The problem is how to apply the scale factor to the line spacing arguments? With arithmetic operation or other workaround?

2 Answers2

2

TeX can multiply dimensions as in 1.5\dimenregister. So what you can do is to assign #1 to a temp dimen register and multiply it.

This works:

\documentclass{article}

\makeatletter
\newcommand\setfont[2]{\@tempdima=#1\fontsize{\@tempdima}{#2\@tempdima}%
  \selectfont}
\makeatother

\begin{document}

\setfont{25pt}{1.5} Test\\ test

\end{document}

P.S. Dan in the comments suggested an enhancement that allows commands like \setfont{25}{1.5}:

\makeatletter
\newcommand\setfont[2]{\@defaultunits\@tempdima#1pt\relax\@nnil
   \fontsize{\@tempdima}{#2\@tempdima}\selectfont}
\makeatother
Boris
  • 38,129
  • Just curious: What happens when the user supplies \setfont{25}{1.5}? – Werner Dec 06 '13 at 16:55
  • This will not work, of course. It is possible to check whether the argument is numeric or a dimen, but for user defined commands a certain laziness in checking the input is expected. Writing a package one should be more careful. – Boris Dec 06 '13 at 16:58
  • 1
    Latex has an internal command to cover this case. Using \@defaultunits\@tempdima#1pt\relax\@nnil instead of just \@tempdima=#1 will allow both \setfont{25}{1.5} and setfont{25pt}{1.5} to work. – Dan Dec 07 '13 at 03:10
2

Here's one way of doing it:

enter image description here

\documentclass{article}
\usepackage{lmodern,lipsum,setspace}% http://ctan.org/pkg/{lmodern,lipsum,setspace}
\newcommand{\setfont}[2]{\setstretch{#2}\fontsize{#1}{#1}\selectfont}
\begin{document}
\lipsum[2]

\setfont{20}{1.5}\lipsum[2]
\end{document}

Note that \fontsize takes two arguments that do not necessarily have to be dimensions. As such, using a combination of scale factor and multiplication with a dimensions might not work as expected (haven't tested it). The setspace package provides \setstretch{<num>} which helps, but also manages other things.

Also remember that line-spacing factors are not always what they seem to be. See Why is the linespread factor as it is?

Werner
  • 603,163