The calc package

Allows arithmetic in \setlength, \setcounter and the length arguments of boxes: \setlength{\x}{\textwidth - 2cm}, plus \widthof{text} for the width of a text.

Loading the package

\usepackage{calc}

Without the package, a length argument takes one value, at most with a factor in front, such as 0.5\textwidth. A sum or difference needs several \addtolength steps. With calc, the expression is written directly with +, -, *, / and parentheses.

The expressions work in \setlength, \addtolength, \setcounter and \addtocounter, and in the length arguments of \parbox, minipage, \makebox, \rule, \hspace, \vspace, \raisebox and p{...} columns.

\widthof{text}, \heightof{text} and \depthof{text} measure a piece of text inside an expression.

Main commands

\setlength{\colwidth}{(\textwidth - 1cm) / 2}A length computed from other lengths.
\setcounter{total}{3 * 4 + 2}Integer arithmetic for a counter.
\widthof{Longest label:}The natural width of the text; \heightof and \depthof give its height and depth.
\begin{minipage}{\textwidth - 4cm}An expression directly in a length argument.
2cm * \real{1.5}Multiplication by a decimal number has to go through \real.
\textwidth * \ratio{1cm}{4cm}Multiplies by the ratio of two lengths.
\maxof{1cm}{\widthof{Label}}The larger of two values; \minof gives the smaller one.

Complete example

\documentclass{article}
\usepackage{calc}
\newlength{\colwidth}
\newlength{\keywidth}
\begin{document}
\setlength{\colwidth}{(\textwidth - 1cm) / 2}
\setlength{\keywidth}{\widthof{Longest label:} + 1em}

\noindent\begin{minipage}[t]{\colwidth}
The left column is half as wide as the text, minus half of the gap.
\end{minipage}\hspace{1cm}%
\begin{minipage}[t]{\colwidth}
The right column has the same width.
\end{minipage}

\medskip
\noindent\makebox[\keywidth][l]{Longest label:}first value\\
\makebox[\keywidth][l]{Short:}second value
\end{document}
Result
The compiled example

Open in the editor

Compiled with pdfLaTeX from TeX Live 2023.

Pitfalls

Related pages