Debian Codegraph @

texmf-dist/source/latex/tools/calc.dtx

raw
1 % \iffalse meta-comment
2 %
3 % Copyright (C) 1993-2025
4 %
5 % The LaTeX Project and any individual authors listed elsewhere
6 % in this file.
7 %
8 % This file is part of the Standard LaTeX `Tools Bundle'.
9 % -------------------------------------------------------
10 %
11 % It may be distributed and/or modified under the
12 % conditions of the LaTeX Project Public License, either version 1.3c
13 % of this license or (at your option) any later version.
14 % The latest version of this license is in
15 % https://www.latex-project.org/lppl.txt
16 % and version 1.3c or later is part of all distributions of LaTeX
17 % version 2005/12/01 or later.
18 %
19 % The list of all files belonging to the LaTeX `Tools Bundle' is
20 % given in the file `manifest.txt'.
21 %
22 % \fi
23 % \iffalse
24 %% File `calc.dtx'.
25 %% Copyright (C) 1992--1995
26 %% Kresten Krab Thorup and Frank Jensen.
27 %% Copyright (C) 1997--2007
28 %% Kresten Krab Thorup, Frank Jensen and the LaTeX Project.
29 %%
30 %% The original authors ([email protected] and [email protected]) have
31 %% contributed this package to the LaTeX distribution.
32 %% Problems with this package should now be sent using latexbug.tex to
33 %% the normal LaTeX bug report address.
34 %
35 %<*dtx>
36 \ProvidesFile{calc.dtx}
37 %</dtx>
38 %<package>\NeedsTeXFormat{LaTeX2e}
39 %<package>\ProvidesPackage{calc}
40 %<driver> \ProvidesFile{calc.drv}
41 % \fi
42 % \ProvidesFile{calc.dtx}
43 [2025/03/01 v4.3b Infix arithmetic (KKT,FJ)]
44 %
45 % \iffalse
46 %<*driver>
47 \documentclass{ltxdoc}
48 \EnableCrossrefs
49 \RecordChanges
50 \usepackage{calc}
51 \begin{document}
52 \DocInput{calc.dtx}
53 \end{document}
54 %</driver>
55 % \fi
56 %
57 % \GetFileInfo{calc.dtx}
58 %
59 % \title{The \texttt{calc} package\\Infix notation
60 % arithmetic in \LaTeX\thanks{We thank Frank Mittelbach for his
61 % valuable comments and suggestions which have greatly improved
62 % this package.}}
63 % \author{Kresten Krab Thorup, Frank Jensen (and Chris Rowley)}
64 % \date{\filedate}
65 %
66 % \MaintainedByLaTeXTeam{tools}
67 % \maketitle
68 %
69 % \changes{v4.0d}{1997/11/08}
70 % {Contributed to tools distribution}
71 % \changes{v4.1a}{1998/06/07}
72 % {Added text sizes: CAR}
73 % \changes{v4.1a}{1998/06/07}
74 % {Attempt to make user-syntax robust: CAR}
75 %
76 % \newenvironment{calc-syntax}
77 % {\par
78 % \parskip\medskipamount
79 % \def\is{\ \hangindent3\parindent$\longrightarrow$~}%
80 % \def\alt{\ $\vert$~}%
81 % \rightskip 0pt plus 1fil
82 % \def\<##1>{\mbox{\NormalSpaces$\langle$##1\/$\rangle$}}%
83 % \IgnoreSpaces\obeyspaces%
84 % }{\par\vskip\parskip}
85 % {\obeyspaces\gdef\NormalSpaces{\let =\space}\gdef\IgnoreSpaces{\def {}}}
86 %
87 % \def\<#1>{$\langle$#1\/$\rangle$}%
88 % \def\s#1{\ensuremath{[\![#1]\!]}}
89 % \def\savecode#1{\hbox{${}_{\hookrightarrow[#1]}$}}
90 % \def\gassign{\Leftarrow}
91 % \def\lassign{\leftarrow}
92 %
93 % \begin{abstract}
94 % The \texttt{calc} package reimplements the \LaTeX\ commands
95 % |\setcounter|, |\addtocounter|, |\setlength|, and |\addtolength|.
96 % Instead of a simple value, these commands now accept an infix
97 % notation expression.
98 % \end{abstract}
99 %
100 % \section{Introduction}
101 %
102 % Arithmetic in \TeX\ is done using low-level operations such as
103 % |\advance| and |\multiply|. This may be acceptable when developing
104 % a macro package, but it is not an acceptable interface for the
105 % end user.
106 %
107 % This package introduces proper infix notation arithmetic which is
108 % much more familiar to most people. The infix notation is more
109 % readable and easier to modify than the alternative: a sequence of
110 % assignment and arithmetic instructions. One of the arithmetic
111 % instructions (|\divide|) does not even have an equivalent in
112 % standard \LaTeX.
113 %
114 % The infix expressions can be used in arguments to macros (the
115 % \texttt{calc} package doesn't employ category code changes to
116 % achieve its goals).\footnote{However, it therefore assumes that the
117 % category codes of the special characters, such as \texttt{(*/)}
118 % in its syntax do not change.}
119 %
120 % \section{Informal description}
121 %
122 % Standard \LaTeX\ provides the following set of commands to
123 % manipulate counters and lengths \cite[pages 194 and~216]{latexman}.
124 % \begin{itemize}
125 % \item[]\hskip-\leftmargin
126 % |\setcounter{|\textit{ctr}|}{|\textit{num}|}| sets the
127 % value of the counter \textit{ctr} equal to (the value of)
128 % \textit{num}. (Fragile)
129 % \item[]\hskip-\leftmargin
130 % |\addtocounter{|\textit{ctr}|}{|\textit{num}|}|
131 % increments the value of the counter \textit{ctr} by (the
132 % value of) \textit{num}. (Fragile)
133 %
134 % \item[]\hskip-\leftmargin
135 % |\setlength{|\textit{cmd}|}{|\textit{len}|}| sets the value of
136 % the length command \textit{cmd} equal to (the value of) \textit{len}.
137 % (Robust)
138 % \item[]\hskip-\leftmargin
139 % |\addtolength{|\textit{cmd}|}{|\textit{len}|}| sets the value of
140 % the length command \textit{cmd} equal to its current value plus
141 % (the value of) \textit{len}. (Robust)
142 % \end{itemize}
143 % (The |\setcounter| and |\addtocounter| commands have global effect,
144 % while the |\setlength| and |\addtolength| commands obey the normal
145 % scoping rules.) In standard \LaTeX, the arguments to these commands
146 % must be simple values. The \texttt{calc} package extends these
147 % commands to accept infix notation expressions, denoting values of
148 % appropriate types. Using the \texttt{calc} package, \textit{num} is
149 % replaced by \<integer expression>, and \textit{len} is replaced by
150 % \<glue expression>. The formal syntax of \<integer expression> and
151 % \<glue expression> is given below.
152 %
153 % In addition to these commands to explicitly set a length, many \LaTeX\
154 % commands take a length argument. After loading this package, most of
155 % these commands will accept a \<glue expression>. This includes
156 % the optional width argument of |\makebox|, the width argument of
157 % |\parbox|, |minipage|, and a |tabular| |p|-column, and many similar
158 % constructions. (This package does not redefine any of these commands,
159 % but they are defined by default to read their arguments by |\setlength|
160 % and so automatically benefit from the enhanced |\setlength| command
161 % provided by this package.)
162 %
163 % In the following, we shall use standard \TeX\ terminology. The
164 % correspondence between \TeX\ and \LaTeX\ terminology is as follows:
165 % \LaTeX\ counters correspond to \TeX's count registers; they hold
166 % quantities of type \<number>. \LaTeX\ length commands correspond to
167 % \TeX's dimen (for rigid lengths) and skip (for rubber lengths)
168 % registers; they hold quantities of types \<dimen> and \<glue>,
169 % respectively.
170 %
171 % \TeX\ gives us primitive operations to perform arithmetic on registers as
172 % follows:
173 % \begin{itemize}
174 % \item addition and subtraction on all types of quantities without
175 % restrictions;
176 % \item multiplication and division by an \emph{integer} can be
177 % performed on a register of any type;
178 % \item multiplication by a \emph{real} number (i.e., a number with a
179 % fractional part) can be performed on a register of any type,
180 % but the stretch and shrink components of a glue quantity are
181 % discarded.
182 % \end{itemize}
183 % The \texttt{calc} package uses these \TeX\ primitives but provides a
184 % more user-friendly notation for expressing the arithmetic.
185 %
186 % An expression is formed of numerical quantities (such as explicit
187 % constants and \LaTeX\ counters and length commands) and binary
188 % operators (the tokens `\texttt{+}', `\texttt{-}', `\texttt{*}', and
189 % `\texttt{/}' with their usual meaning) using the familiar infix
190 % notation; parentheses may be used to override the usual precedences
191 % (that multiplication/division have higher precedence than
192 % addition/subtraction).
193 %
194 % Expressions must be properly typed. This means, e.g., that a dimen
195 % expression must be a sum of dimen terms: i.e., you cannot say
196 % `\texttt{2cm+4}' but `\texttt{2cm+4pt}' is valid.
197 %
198 % In a dimen term, the dimension part must come first; the same holds
199 % for glue terms. Also, multiplication and division by non-integer
200 % quantities require a special syntax; see below.
201 %
202 % Evaluation of subexpressions at the same level of precedence
203 % proceeds from left to right. Consider a dimen term such as
204 % ``\texttt{4cm*3*4}''. First, the value of the factor \texttt{4cm} is
205 % assigned to a dimen register, then this register is multiplied
206 % by~$3$ (using |\multiply|), and, finally, the register is multiplied
207 % by~$4$ (again using |\multiply|). This also explains why the
208 % dimension part (i.e., the part with the unit designation) must come
209 % first; \TeX\ simply doesn't allow untyped constants to be assigned
210 % to a dimen register.
211 %
212 % The \texttt{calc} package also allows multiplication and division by
213 % real numbers. However, a special syntax is required: you must use
214 % |\real{|\<decimal constant>|}|\footnote{Actually, instead of
215 % \<decimal constant>, the more general \<optional signs>\<factor> can
216 % be used. However, that doesn't add any extra expressive power to
217 % the language of infix expressions.} or
218 % |\ratio{|\<dimen expression>|}{|\<dimen expression>|}| to denote a
219 % real value to be used for multiplication/division. The first form has
220 % the obvious meaning, and the second form denotes the number obtained
221 % by dividing the value of the first expression by the value of the
222 % second expression.
223 %
224 % A later addition to the package (in June 1998) allows an additional
225 % method of specifying a factor of type dimen by setting some text
226 % (in LR-mode) and measuring its dimensions: these are denoted as
227 % follows.
228 %\begin{quote}
229 % |\widthof{|\<text>|}|\quad
230 % |\heightof{|\<text>|}|\quad
231 % |\depthof{|\<text>|}|
232 %\end{quote}
233 % These calculate the natural sizes of the \<text> in exactly the
234 % same way as is done for the commands |\settowidth| etc.~on
235 % Page~216 of the manual~\cite{latexman}.
236 % In August 2005 the package was further extended to provide the command
237 %\begin{quote}
238 % |\totalheightof{|\<text>|}|
239 %\end{quote}
240 % This command does exactly what you'd expect from its name.
241 % Additionally the package also provides the command
242 %\begin{quote}
243 % |\settototalheight{|\<cmd>|}{|\<text>|}|
244 %\end{quote}
245 %
246 %
247 % Note that there is a small difference in the usage of these two
248 % methods of accessing text dimensions. After
249 % |\settowidth{\txtwd}{Some text}| you can use:
250 %\begin{verbatim}
251 % \setlength{\parskip}{0.68\txtwd}
252 %\end{verbatim}
253 % whereas using the more direct access to the width of the text
254 % requires the longer form for multiplication, thus:
255 %\begin{verbatim}
256 % \setlength{\parskip}{\widthof{Some text} * \real{0.68}}
257 %\end{verbatim}
258 %
259 % \TeX\ discards the stretch and shrink components of glue when glue
260 % is multiplied by a real number. So, for example,
261 %\begin{verbatim}
262 % \setlength{\parskip}{3pt plus 3pt * \real{1.5}}
263 %\end{verbatim}
264 % will set the paragraph separation to 4.5pt with no stretch or
265 % shrink. Incidentally, note how spaces can be used to enhance
266 % readability. When \TeX\ is scanning for a \<number> etc.\ it is
267 % common to terminate the scanning with a space token or by inserting
268 % \cs{relax}. As of version~4.3 \textsf{calc} allows \cs{relax} tokens
269 % to appear in places where they would usually be used for terminating
270 % \TeX's scanning. In short this is just before any of \texttt{+-*/)}
271 % or at the end of the expression being evaluated.
272 %
273 % When \TeX\ performs arithmetic on integers, any fractional part of
274 % the result is discarded. For example,
275 %\begin{verbatim}
276 % \setcounter{x}{7/2}
277 % \setcounter{y}{3*\real{1.6}}
278 % \setcounter{z}{3*\real{1.7}}
279 %\end{verbatim}
280 % will assign the value~$3$ to the counter~\texttt{x}, the value~$4$
281 % to~\texttt{y}, and the value~$5$ to~\texttt{z}. This truncation
282 % also applies to \emph{intermediate} results in the sequential
283 % computation of a composite expression; thus, the following command
284 %\begin{verbatim}
285 % \setcounter{x}{3 * \real{1.6} * \real{1.7}}
286 %\end{verbatim}
287 % will assign~$6$ to~\texttt{x}.
288 %
289 % As an example of the use of |\ratio|, consider the problem of
290 % scaling a figure to occupy the full width (i.e., |\textwidth|) of
291 % the body of a page. Assume that the original dimensions of the
292 % figure are given by the dimen (length) variables, |\Xsize| and
293 % |\Ysize|. The height of the scaled figure can then be expressed by
294 %\begin{verbatim}
295 % \setlength{\newYsize}{\Ysize*\ratio{\textwidth}{\Xsize}}
296 %\end{verbatim}
297 %
298 %
299 %
300 % Another new feature introduced in August 2005 was $\max$ and $\min$
301 % operations with associated macros
302 %\begin{quote}
303 % |\maxof{|\<\textit{type} expression>|}{|\<\textit{type} expression>|}|
304 % \\
305 % |\minof{|\<\textit{type} expression>|}{|\<\textit{type} expression>|}|
306 %\end{quote}
307 % When \textit{type} is either \meta{glue} or \meta{dimen} these macros
308 % are allowed only as part of addition or subtraction but when
309 % \textit{type} is \meta{integer} they can also be used when
310 % multiplying and dividing. In the latter case they follow the
311 % same syntax rules as |\ratio| and |\real| which means they must come
312 % after the |*| or the |/|. Thus
313 %\begin{verbatim}
314 % \setcounter{x}{3*\maxof{4+5}{3*4}+\minof{2*\real{1.6}}{5-1}}
315 %\end{verbatim}
316 % will assign $3\times\max(9,12)+\min(3,4)=39$ to |x|. Similarly
317 %\begin{verbatim}
318 % \setlength{\parindent}{%
319 % \minof{3pt}{\parskip}*\real{1.5}*\maxof{2*\real{1.6}}{2-1}}
320 %\end{verbatim}
321 % will assign $\min(13.5\textrm{pt},4.5\cs{parskip})$ to \cs{parindent}.
322 %
323 %
324 %
325 % \section{Formal syntax}
326 %
327 % The syntax is described by the following set of rules.
328 % Note that the definitions of \<number>, \<dimen>, \<glue>,
329 % \<decimal constant>, and \<plus or minus> are
330 % as in Chapter~24 of The \TeX book~\cite{texbook}; and \<text>
331 % is LR-mode material, as in the manual~\cite{latexman}.
332 % We use \textit{type} as a meta-variable, standing for
333 % `integer', `dimen', and `glue'.\footnote{This version of the
334 % \texttt{calc} package doesn't support evaluation of muglue expressions.}
335 %
336 % \begin{calc-syntax}
337 % \<\textit{type} expression>^^A
338 % \is \<\textit{type} term>^^A
339 % \alt \<\textit{type} expression> \<plus or minus> \<\textit{type} term>
340 %
341 % \<\textit{type} term>^^A
342 % \is \<\textit{type} term> \<\textit{type} scan stop>
343 % \alt \<\textit{type} factor>^^A
344 % \alt \<\textit{type} term> \<multiply or divide> \<integer>^^A
345 % \alt \<\textit{type} term> \<multiply or divide> \<real number>^^A
346 % \alt \<\textit{type} term> \<multiply or divide>^^A
347 % \<$\max$ or $\min$ integer>^^A
348 %
349 % \<\textit{type} scan stop>^^A
350 % \is \<empty>^^A
351 % \alt \<optional space>^^A
352 % \alt |\relax|
353 %
354 % \<\textit{type} factor>^^A
355 % \is \<\textit{type}>^^A
356 % \alt \<text dimen factor>^^A
357 % \alt \<$\max$ or $\min$ \textit{type}>^^A
358 % \alt |(|$_{12}$ \<\textit{type} expression> |)|$_{12}$
359 %
360 % \<integer> \is \<number>
361 %
362 % \<$\max$ or $\min$ \textit{type}> \is \<$\max$ or $\min$ command>^^A
363 % |{| \<\textit{type} expression> |}|^^A
364 % |{| \<\textit{type} expression> |}|
365 %
366 % \<$\max$ or $\min$ command> \is |\maxof|^^A
367 % \alt |\minof|
368 %
369 % \<text dimen factor>^^A
370 % \is \<text dimen command>|{| \<text> |}|
371 %
372 % \<text dimen command>^^A
373 % \is |\widthof|^^A
374 % \alt |\heightof|^^A
375 % \alt |\depthof|^^A
376 % \alt |\totalheightof|^^A
377 %
378 % \<multiply or divide>^^A
379 % \is |*|$_{12}$^^A
380 % \alt |/|$_{12}$
381 %
382 % \<real number>^^A
383 % \is |\ratio{| \<dimen expression> |}{| \<dimen expression> |}|^^A
384 % \alt |\real{| \<optional signs> \<decimal constant> |}|
385 %
386 % \<plus or minus>^^A
387 % \is |+|$_{12}$^^A
388 % \alt |-|$_{12}$
389 %
390 % \<decimal constant>^^A
391 % \is |.|$_{12}$^^A
392 % \alt |,|$_{12}$^^A
393 % \alt \<digit> \<decimal constant>^^A
394 % \alt \<decimal constant> \<digit>
395 %
396 % \<digit>^^A
397 % \is |0|$_{12}$^^A
398 % \alt |1|$_{12}$^^A
399 % \alt |2|$_{12}$^^A
400 % \alt |3|$_{12}$^^A
401 % \alt |4|$_{12}$^^A
402 % \alt |5|$_{12}$^^A
403 % \alt |6|$_{12}$^^A
404 % \alt |7|$_{12}$^^A
405 % \alt |8|$_{12}$^^A
406 % \alt |9|$_{12}$
407 %
408 % \<optional signs>^^A
409 % \is \<optional spaces>^^A
410 % \alt \<optional signs> \<plus or minus> \<optional spaces>
411 %
412 % \end{calc-syntax}
413 %
414 %
415 % Relying heavily on \TeX\ to do the underlying assignments, it is
416 % only natural for \texttt{calc} to simulate \TeX's parsing machinery
417 % for these quantities. Therefore it a)~imposes the same restrictions
418 % on the catcode of syntax characters as \TeX\ and b)~tries to expand
419 % its argument fully. a)~means that implicit characters for the tokens
420 % |*|$_{12}$, |/|$_{12}$, |(|$_{12}$, and |)|$_{12}$ will not
421 % work\footnote{e\TeX\ also assumes these catcodes when parsing a
422 % \cs{numexpr}, \cs{dimexpr}, \cs{glueexpr}, or \cs{muglueexpr} and
423 % does not allow implicit characters.} but because of~b), the
424 % expansion should allow you to use macros that expand to explicit
425 % syntax characters.
426 %
427 %
428 % \MaybeStop{
429 % \begin{thebibliography}{1}
430 % \bibitem{texbook}
431 % \textsc{D. E. Knuth}.
432 % \newblock \textit{The \TeX{}book} (Computers \& Typesetting Volume A).
433 % \newblock Addison-Wesley, Reading, Massachusetts, 1986.
434 % \bibitem{latexman}
435 % \textsc{L. Lamport}.
436 % \newblock \textit{\LaTeX, A Document Preparation System.}
437 % \newblock Addison-Wesley, Reading, Massachusetts, Second
438 % edition 1994/1985.
439 % \end{thebibliography}
440 % \PrintChanges
441 % }
442 %
443 % \section{The evaluation scheme}
444 % \label{evaluation:scheme}
445 %
446 % In this section, we shall for simplicity consider only expressions
447 % containing `$+$' (addition) and `$*$' (multiplication) operators.
448 % It is trivial to add subtraction and division.
449 %
450 % An expression $E$ is a sum of terms: $T_1+\cdots+T_n$; a term is a
451 % product of factors: $F_1*\cdots*F_m$; a factor is either a simple
452 % numeric quantity~$f$ (like \<number> as described in the \TeX book),
453 % or a parenthesized expression~$(E')$.
454 %
455 % Since the \TeX\ engine can only execute arithmetic operations in a
456 % machine-code-like manner, we have to find a way to translate the
457 % infix notation into this `instruction set'.
458 %
459 % Our goal is to design a translation scheme that translates~$X$ (an
460 % expression, a term, or a factor) into a sequence of \TeX\ instructions
461 % that does the following [Invariance Property]: correctly
462 % evaluates~$X$, leaves the result in a global register~$A$ (using a
463 % global assignment), and does not perform global assignments to the
464 % scratch register~$B$; moreover, the code sequence must be balanced
465 % with respect to \TeX\ groups. We shall denote the code sequence
466 % corresponding to~$X$ by \s{X}.
467 %
468 % In the replacement code specified below, we use the following
469 % conventions:
470 % \begin{itemize}
471 % \item $A$ and $B$ denote registers; all assignments to~$A$ will
472 % be global, and all assignments to~$B$ will be local.
473 % \item ``$\gassign$'' means global assignment to the register on
474 % the lhs.
475 % \item ``$\lassign $'' means local assignment to the register on
476 % the lhs.
477 % \item ``\savecode C'' means ``save the code~$C$ until the current
478 % group (scope) ends, then execute it.'' This corresponds to
479 % the \TeX-primitive |\aftergroup|.
480 % \item ``$\{$'' denotes the start of a new group, and ``$\}$''
481 % denotes the end of a group.
482 % \end{itemize}
483 %
484 % Let us consider an expression $T_1+T_2+\cdots+T_n$. Assuming that
485 % \s{T_k} ($1\le k\le n$) attains the stated goal, the following code
486 % clearly attains the stated goal for their sum:
487 % \begin{eqnarray*}
488 % \s{T_1+T_2+\cdots+T_n}&\Longrightarrow&
489 % \{\,\s{T_1}\,\} \; B\lassign A \quad
490 % \{\,\s{T_2}\,\} \; B\lassign B+A \\
491 % &&\qquad \ldots \quad \{\,\s{T_n}\,\} \; B\lassign B+A
492 % \quad A\gassign B
493 % \end{eqnarray*}
494 % Note the extra level of grouping enclosing each of \s{T_1}, \s{T_2},
495 % \ldots,~\s{T_n}. This will ensure that register~$B$, used to
496 % compute the sum of the terms, is not clobbered by the intermediate
497 % computations of the individual terms. Actually, the group
498 % enclosing~\s{T_1} is unnecessary, but it turns out to be simpler if
499 % all terms are treated the same way.
500 %
501 % The code sequence ``$\{\,\s{T_2}\,\}\;B\lassign B+A$'' can be translated
502 % into the following equivalent code sequence:
503 % ``$\{\savecode{B\lassign B+A}\,\s{T_2}\,\}$''. This observation turns
504 % out to be the key to the implementation: The ``$\savecode{B\lassign
505 % B+A}$'' is generated \emph{before} $T_2$ is translated, at the same
506 % time as the `$+$' operator between $T_1$ and~$T_2$ is seen.
507 %
508 % Now, the specification of the translation scheme is straightforward:
509 % \begin{eqnarray*}
510 % \s{f}&\Longrightarrow&A\gassign f\\[\smallskipamount]
511 % \s{(E')}&\Longrightarrow&\s{E'}\\[\smallskipamount]
512 % \s{T_1+T_2+\cdots+T_n}&\Longrightarrow&
513 % \{\savecode{B\lassign A}\,\s{T_1}\,\} \quad
514 % \{\savecode{B\lassign B+A}\,\s{T_2}\,\} \\
515 % &&\qquad \ldots \quad \{\savecode{B\lassign B+A}\,\s{T_n}\,\}
516 % \quad A\gassign B
517 % \\[\smallskipamount]
518 % \s{F_1*F_2*\cdots*F_m}&\Longrightarrow&
519 % \{\savecode{B\lassign A}\,\s{F_1}\,\} \quad
520 % \{\savecode{B\lassign B*A}\,\s{F_2}\,\}\\
521 % &&\qquad \ldots \quad \{\savecode{B\lassign B*A}\,\s{F_m}\,\}
522 % \quad A\gassign B
523 % \end{eqnarray*}
524 % By structural induction, it is easily seen that the stated property
525 % is attained.
526 %
527 % By inspection of this translation scheme, we see that we have to
528 % generate the following code:
529 % \begin{itemize}
530 % \item we must generate ``$\{\savecode{B\lassign
531 % A}\{\savecode{B\lassign A}$'' at the left border of an
532 % expression (i.e., for each left parenthesis and the implicit
533 % left parenthesis at the beginning of the whole expression);
534 % \item we must generate ``$\}A\gassign B\}A\gassign B$'' at the
535 % right border of an expression (i.e., each right parenthesis
536 % and the implicit right parenthesis at the end of the full
537 % expression);
538 % \item `\texttt{*}' is replaced by ``$\}\{\savecode{B\lassign
539 % B*A}$'';
540 % \item `\texttt{+}' is replaced by
541 % ``$\}A\gassign B\}\{\savecode{B\lassign
542 % B+A}\{\savecode{B\lassign A}$'';
543 % \item when we see (expect) a numeric quantity, we insert the
544 % assignment code ``$A\gassign$'' in front of the quantity and let
545 % \TeX\ parse it.
546 % \end{itemize}
547 %
548 % \section{Implementation}
549 %
550 % For brevity define
551 % \begin{calc-syntax}
552 % \<numeric> \is \<number> \alt \<dimen> \alt \<glue> \alt \<muglue>
553 % \end{calc-syntax}
554 % So far we have ignored the question of how to determine the type of
555 % register to be used in the code. However, it is easy to see that
556 % (1)~`$*$' always initiates an \<integer factor>, (2)~all
557 % \<numeric>s in an expression, except those which are part of an
558 % \<integer factor>, are of the same type as the whole expression, and
559 % all \<numeric>s in an \<integer factor> are \<number>s.
560 %
561 % We have to ensure that $A$ and~$B$ always have an appropriate type
562 % for the \<numeric>s they manipulate. We can achieve this by having
563 % an instance of $A$ and~$B$ for each type. Initially, $A$~and~$B$
564 % refer to registers of the proper type for the whole expression.
565 % When an \<integer factor> is expected, we must change $A$ and~$B$ to
566 % refer to integer type registers. We can accomplish this by
567 % including instructions to change the type of $A$ and~$B$ to integer
568 % type as part of the replacement code for~`$*$'; if we append such
569 % instructions to the replacement code described above, we also ensure
570 % that the type change is local (provided that the type-changing
571 % instructions only have local effect). However, note that the
572 % instance of~$A$ referred to in $\savecode{B\lassign B*A}$ is the
573 % integer instance of~$A$.
574 %
575 % We shall use |\begingroup| and |\endgroup| for the open-group and
576 % close-group characters. This avoids problems with spacing in math
577 % (as pointed out to us by Frank Mittelbach).
578 %
579 % \subsection{Getting started}
580 %
581 % Now we have enough insight to do the actual implementation in \TeX.
582 % First, we announce the macro package.\footnote{Code moved to top of file}
583 % \begin{macrocode}
584 %<*package>
585 %\NeedsTeXFormat{LaTeX2e}
586 %\ProvidesPackage{calc}[\filedate\space\fileversion]
587 % \end{macrocode}
588 %
589 % \subsection{Assignment macros}
590 %
591 % \begin{macro}{\calc@assign@generic}
592 % \changes{v4.2}{2005/08/06}{Removed a few redundant \cs{expandafter}s}
593 % The |\calc@assign@generic| macro takes four arguments: (1~and~2) the
594 % registers to be used
595 % for global and local manipulations, respectively; (3)~the lvalue
596 % part; (4)~the expression to be evaluated.
597 %
598 % The third argument (the lvalue) will be used as a prefix to a
599 % register that contains the value of the specified expression (the
600 % fourth argument).
601 %
602 % In general, an lvalue is anything that may be followed by a variable
603 % of the appropriate type. As an example, |\linepenalty| and
604 % |\global\advance\linepenalty| may both be followed by an \<integer
605 % variable>.
606 %
607 % The macros described below refer to the registers by the names
608 % |\calc@A| and |\calc@B|; this is accomplished by
609 % |\let|-assignments.
610 %
611 % As discovered in Section~\ref{evaluation:scheme}, we have to
612 % generate code as
613 % if the expression is parenthesized. As described below,
614 % |\calc@open| is the macro that replaces a left parenthesis by its
615 % corresponding \TeX\ code sequence. When the scanning process sees
616 % the exclamation point, it generates an |\endgroup| and stops. As we
617 % recall from Section~\ref{evaluation:scheme}, the correct expansion
618 % of a right
619 % parenthesis is ``$\}A\gassign B\}A\gassign B$''. The remaining
620 % tokens of this expansion are inserted explicitly, except that the
621 % last assignment has been replaced by the lvalue part (i.e.,
622 % argument~|#3| of |\calc@assign@generic|) followed by |\calc@B|.
623 % \begin{macrocode}
624 \def\calc@assign@generic#1#2#3#4{\let\calc@A#1\let\calc@B#2%
625 \calc@open(#4!%
626 \global\calc@A\calc@B\endgroup#3\calc@B}
627 % \end{macrocode}
628 % \end{macro}
629 %
630 % \begin{macro}{\calc@assign@count}
631 % \begin{macro}{\calc@assign@dimen}
632 % \begin{macro}{\calc@assign@skip}
633 % We need three instances of the |\calc@assign@generic| macro,
634 % corresponding to the types \<integer>, \<dimen>, and \<glue>.
635 % \begin{macrocode}
636 \def\calc@assign@count{\calc@assign@generic\calc@Acount\calc@Bcount}
637 \def\calc@assign@dimen{\calc@assign@generic\calc@Adimen\calc@Bdimen}
638 \def\calc@assign@skip{\calc@assign@generic\calc@Askip\calc@Bskip}
639 % \end{macrocode}
640 % \end{macro}\end{macro}\end{macro}
641 % These macros each refer to two registers, one
642 % to be used globally and one to be used locally.
643 % We must allocate these registers.
644 % \begin{macrocode}
645 \newcount\calc@Acount \newcount\calc@Bcount
646 \newdimen\calc@Adimen \newdimen\calc@Bdimen
647 \newskip\calc@Askip \newskip\calc@Bskip
648 % \end{macrocode}
649 %
650 % \subsection{The \LaTeX\ interface}
651 %
652 % \begin{macro}{\setcounter}
653 % \begin{macro}{\addtocounter}
654 % \changes{v4.2}{2005/08/06}
655 % {Fix to make \cs{addtocounter} work with \texttt{amstext}}
656 % \begin{macro}{\steptocounter}
657 % \changes{v4.2}{2005/08/06}
658 % {Avoid redundant processing. PR/3795}
659 % \begin{macro}{\setlength}
660 % \begin{macro}{\addtolength}
661 % As promised, we redefine the following standard \LaTeX\ commands:
662 % |\setcounter|,
663 % |\addtocounter|, |\setlength|, and |\addtolength|.
664 % \begin{macrocode}
665 \def\setcounter#1#2{\@ifundefined{c@#1}{\@nocounterr{#1}}%
666 {\calc@assign@count{\global\csname c@#1\endcsname}{#2}}}
667 % \end{macrocode}
668 % \begin{macrocode}
669 \def\addtocounter#1#2{\@ifundefined{c@#1}{\@nocounterr{#1}}%
670 {\calc@assign@count{\global\advance\csname c@#1\endcsname}{#2}}}%
671 % \end{macrocode}
672 % We also fix \cs{stepcounter} to not go through the whole \texttt{calc}
673 % process.
674 % \begin{macrocode}
675 \def\stepcounter#1{\@ifundefined {c@#1}%
676 {\@nocounterr {#1}}%
677 {\global\advance\csname c@#1\endcsname \@ne
678 \begingroup
679 \let\@elt\@stpelt \csname cl@#1\endcsname
680 \endgroup}}%
681 % \end{macrocode}
682 % If the \texttt{amstext} package is loaded we must add the
683 % |\iffirstchoice@| switch as well. We patch the commands this
684 % way since it's good practice when we know how many arguments they take.
685 % \changes{v4.3b}{2025/03/01}
686 % {Delay amstext test}
687 % \begin{macrocode}
688 \AtBeginDocument{%
689 \@ifpackageloaded{amstext}{%
690 \def\addtocounter#1#2{\iffirstchoice@
691 \@ifundefined{c@#1}{\@nocounterr{#1}}%
692 {\calc@assign@count{\global\advance\csname c@#1\endcsname}{#2}}%
693 \fi}%
694 \def\stepcounter#1{\iffirstchoice@
695 \@ifundefined {c@#1}%
696 {\@nocounterr {#1}}%
697 {\global\advance\csname c@#1\endcsname \@ne
698 \begingroup
699 \let\@elt\@stpelt \csname cl@#1\endcsname
700 \endgroup}%
701 \fi}%
702 }{}%
703 }
704 % \end{macrocode}
705 % \begin{macrocode}
706 \DeclareRobustCommand\setlength{\calc@assign@skip}
707 \DeclareRobustCommand\addtolength[1]{\calc@assign@skip{\advance#1}}
708 % \end{macrocode}
709 % (|\setlength| and |\addtolength| are robust according to
710 % \cite{latexman}.)
711 % \end{macro}
712 % \end{macro}
713 % \end{macro}
714 % \end{macro}
715 % \end{macro}
716 %
717 % \subsection{The scanner}
718 %
719 % We evaluate expressions by explicit scanning of characters. We do
720 % not rely on active characters for this.
721 %
722 % The scanner consists of two parts, |\calc@pre@scan| and
723 % |\calc@post@scan|; |\calc@pre@scan| consumes left parentheses, and
724 % |\calc@post@scan| consumes binary operator, |\real|, |\ratio|, and
725 % right parenthesis tokens.
726 %
727 % \begin{macro}{\calc@pre@scan}
728 % \begin{macro}{\@calc@pre@scan}
729 % \changes{v4.2}{2005/08/06}
730 % {Added macro and force expansion}
731 %
732 % Note that this is called at least once on every use of calc
733 % processing, even when none of the extended syntax is present; it
734 % therefore needs to be made very efficient.
735 %
736 % It reads the initial part of expressions, until some \<text dimen
737 % factor> or \<numeric> is seen; in fact, anything not explicitly
738 % recognized here is taken to be a \<numeric> of some sort as this
739 % allows unary
740 % `\texttt{+}' and unary `\texttt{-}' to be treated easily and
741 % correctly\footnote{In the few contexts where signs are allowed:
742 % this could, I think, be extended (CAR).} but means that anything
743 % illegal will simply generate a \TeX-level error, often a
744 % reasonably comprehensible one!
745 %
746 % The |\romannumeral-`\a| part is a little trick which forces expansion
747 % in case |#1| is a normal macro, something that occurs from time to
748 % time. A conditional test inside will possibly leave a trailing
749 % \cs{fi} but this remnant is removed later when \cs{calc@post@scan}
750 % performs the same trick.
751 %
752 % The many |\expandafter|s are needed to efficiently end the nested
753 % conditionals so that |\calc@textsize| and |\calc@maxmin@addsub| can
754 % process their argument.
755 % \changes{v4.1a}{1998/06/07}
756 % {Added code for text sizes: CAR}
757 % \changes{v4.1b}{1998/07/07}
758 % {Correction to ifx true case}
759 % \changes{v4.2}{2005/08/06}
760 % {Added \cs{maxof} and \cs{minof} operations}
761 % \begin{macrocode}
762 \def\calc@pre@scan#1{%
763 \expandafter\@calc@pre@scan\romannumeral-`\a#1}
764 \def\@calc@pre@scan#1{%
765 \ifx(#1%
766 \expandafter\calc@open
767 \else
768 \ifx\widthof#1%
769 \expandafter\expandafter\expandafter\calc@textsize
770 \else
771 \ifx\maxof#1%
772 \expandafter\expandafter\expandafter\expandafter
773 \expandafter\expandafter\expandafter\calc@maxmin@addsub
774 \else
775 \calc@numeric% no \expandafter needed for this one.
776 \fi
777 \fi
778 \fi
779 #1}
780 % \end{macrocode}
781 % \end{macro}
782 % \end{macro}
783 %
784 % \begin{macro}{\calc@open}
785 % \begin{macro}{\calc@initB}
786 % |\calc@open| is used when there is a left parenthesis right ahead.
787 % This parenthesis is replaced by \TeX\ code corresponding to the code
788 % sequence ``$\{\savecode{B\lassign A}\{\savecode{B\lassign A}$''
789 % derived in Section~\ref{evaluation:scheme}. Finally,
790 % |\calc@pre@scan| is
791 % called again.
792 % \begin{macrocode}
793 \def\calc@open({\begingroup\aftergroup\calc@initB
794 \begingroup\aftergroup\calc@initB
795 \calc@pre@scan}
796 \def\calc@initB{\calc@B\calc@A}
797 % \end{macrocode}
798 % \end{macro}
799 % \end{macro}
800 % \begin{macro}{\calc@numeric}
801 % |\calc@numeric| assigns the following value to |\calc@A| and then
802 % transfers control to |\calc@post@scan|.
803 % \begin{macrocode}
804 \def\calc@numeric{\afterassignment\calc@post@scan \global\calc@A}
805 % \end{macrocode}
806 % \end{macro}
807 %
808 % \begin{macro}{\widthof}
809 % \begin{macro}{\heightof}
810 % \begin{macro}{\depthof}
811 % \changes{v4.1a}{1998/06/07}
812 % {Added macros: CAR}
813 % \begin{macro}{\totalheightof}
814 % \changes{v4.2}{2005/08/06}
815 % {Added macro}
816 % \changes{v4.2}{2005/08/06}
817 % {Added informative message for reserved macros}
818 %
819 % These do not need any particular definition when they are scanned
820 % so, for efficiency and robustness, we make them all equivalent to
821 % the same harmless (I hope) unexpandable command.\footnote{If this
822 % level of safety is not needed then the code can be sped up:
823 % CAR.} Thus the test in |\@calc@pre@scan| finds any of them.
824 %
825 % As we have to check for these commands explicitly we must ensure
826 % that our definition wins. Using \cs{newcommand} gives an error when
827 % loading \texttt{calc} and may be mildly surprising. This should be
828 % a little more informative.
829 % \begin{macrocode}
830 \@for\reserved@a:=widthof,heightof,depthof,totalheightof,maxof,minof\do
831 {\@ifundefined{\reserved@a}{}{%
832 \PackageError{calc}{%
833 The\space calc\space package\space reserves\space the\space
834 command\space name\space `\@backslashchar\reserved@a'\MessageBreak
835 but\space it\space has\space already\space been\space defined\space
836 with\space the\space meaning\MessageBreak
837 `\expandafter\meaning\csname\reserved@a\endcsname'.\MessageBreak
838 This\space original\space definition\space will\space be\space lost}%
839 {If\space you\space need\space a\space command\space with\space
840 this\space definition,\space you\space must\space use\space a\space
841 different\space name.}}%
842 }
843 \let\widthof\ignorespaces
844 \let\heightof\ignorespaces
845 \let\depthof\ignorespaces
846 \let\totalheightof\ignorespaces
847 % \end{macrocode}
848 % \end{macro}
849 % \end{macro}
850 % \end{macro}
851 % \end{macro}
852 %
853 % \begin{macro}{\calc@textsize}
854 % \changes{v4.1a}{1998/06/07}
855 % {Added macro: CAR}
856 % \changes{v4.1a}{1998/06/07}
857 % {Added macro: CAR}
858 % \changes{v4.2}{2005/08/06}
859 % {Extended macro with \cs{totalheightof}}
860 % The presence of the above four commands invokes this code, where
861 % we must distinguish them from each other.
862 % This implementation is somewhat optimized by using low-level
863 % code from the commands |\settowidth|, etc.\footnote{It is based on
864 % suggestions by Donald Arseneau and David Carlisle.}
865 %
866 % Within the text argument we must restore the normal meanings of
867 % the four user-level commands since arbitrary material can appear
868 % in here, including further uses of calc.
869 % \begin{macrocode}
870 \def\calc@textsize #1#2{%
871 \begingroup
872 \let\widthof\wd
873 \let\heightof\ht
874 \let\depthof\dp
875 \def\totalheightof{\ht\dp}%
876 % \end{macrocode}
877 % We must expand the argument one level if it's \cs{totalheightof}
878 % and it doesn't hurt the other three.
879 % \begin{macrocode}
880 \expandafter\@settodim\expandafter{#1}%
881 {\global\calc@A}%
882 {%
883 \let\widthof\ignorespaces
884 \let\heightof\ignorespaces
885 \let\depthof\ignorespaces
886 \let\totalheightof\ignorespaces
887 #2}%
888 \endgroup
889 \calc@post@scan}
890 % \end{macrocode}
891 % \end{macro}
892 %
893 % \begin{macro}{\calc@post@scan}
894 % \begin{macro}{\@calc@post@scan}
895 % \changes{v4.2}{2005/08/06}{Added macro and force expansion}
896 % \changes{v4.3}{2007/08/22}{Discard terminating \cs{relax} tokens and
897 % avoid extra error message from \cs{calc@next}}
898 % The macro |\calc@post@scan| is called right after a value has been
899 % read. At this point, a binary operator, a sequence of right
900 % parentheses, an optional \cs{relax}, and the end-of-expression mark
901 % (`|!|') is allowed.\footnote{Is \texttt{!} a good choice, CAR?}
902 % Depending on our findings, we call a suitable macro to generate the
903 % corresponding \TeX\ code (except when we detect the
904 % end-of-expression marker: then scanning ends, and control is
905 % returned to |\calc@assign@generic|).
906 %
907 % This macro may be optimized by selecting a different order of
908 % |\ifx|-tests. The test for `\texttt{!}' (end-of-expression) is
909 % placed first as it will always be performed: this is the only test
910 % to be performed if the expression consists of a single \<numeric>.
911 % This ensures that documents that do not use the extra expressive
912 % power provided by the \texttt{calc} package only suffer a minimum
913 % slowdown in processing time.
914 % \begin{macrocode}
915 \def\calc@post@scan#1{%
916 \expandafter\@calc@post@scan\romannumeral-`\a#1}
917 \def\@calc@post@scan#1{%
918 \ifx#1!\let\calc@next\endgroup \else
919 \ifx#1+\let\calc@next\calc@add \else
920 \ifx#1-\let\calc@next\calc@subtract \else
921 \ifx#1*\let\calc@next\calc@multiplyx \else
922 \ifx#1/\let\calc@next\calc@dividex \else
923 \ifx#1)\let\calc@next\calc@close \else
924 \ifx#1\relax\let\calc@next\calc@post@scan \else
925 \def\calc@next{\calc@error#1}%
926 \fi
927 \fi
928 \fi
929 \fi
930 \fi
931 \fi
932 \fi
933 \calc@next}
934 % \end{macrocode}
935 % \end{macro}
936 % \end{macro}
937 %
938 % \begin{macro}{\calc@add}
939 % \begin{macro}{\calc@subtract}
940 % \begin{macro}{\calc@generic@add}
941 % \begin{macro}{\calc@addAtoB}
942 % \begin{macro}{\calc@subtractAfromB}
943 % The replacement code for the binary operators `\texttt{+}' and
944 % `\texttt{-}' follows a common pattern; the only difference is the
945 % token that is stored away by |\aftergroup|. After this replacement
946 % code, control is transferred to |\calc@pre@scan|.
947 % \begin{macrocode}
948 \def\calc@add{\calc@generic@add\calc@addAtoB}
949 \def\calc@subtract{\calc@generic@add\calc@subtractAfromB}
950 \def\calc@generic@add#1{\endgroup\global\calc@A\calc@B\endgroup
951 \begingroup\aftergroup#1\begingroup\aftergroup\calc@initB
952 \calc@pre@scan}
953 \def\calc@addAtoB{\advance\calc@B\calc@A}
954 \def\calc@subtractAfromB{\advance\calc@B-\calc@A}
955 % \end{macrocode}
956 % \end{macro}
957 % \end{macro}
958 % \end{macro}
959 % \end{macro}
960 % \end{macro}
961 %
962 % \begin{macro}{\real}
963 % \begin{macro}{\ratio}
964 % \begin{macro}{\calc@ratio@x}
965 % \begin{macro}{\calc@real@x}
966 % The multiplicative operators, `\texttt{*}' and `\texttt{/}', may be
967 % followed by a |\real|, |\ratio|, |\minof|, or |\maxof| token. The
968 % last two of these control sequences are defined by \texttt{calc} as
969 % they are needed by the scanner for addition or subtraction while the
970 % first two are not defined (at least not by the \texttt{calc}
971 % package); this,
972 % unfortunately, leaves them highly non-robust. We therefore
973 % equate them to |\relax| but only if they have not already been
974 % defined\footnote{Suggested code from David Carlisle.}
975 % (by some other package: dangerous but possible!); this
976 % will also make them appear to be undefined to a \LaTeX{} user
977 % (also possibly dangerous).
978 % \changes{v4.1a}{1998/06/07}
979 % {Added macro set-ups to make them robust but undefined: CAR}
980 % \begin{macrocode}
981 \ifx\real\@undefined\let\real\relax\fi
982 \ifx\ratio\@undefined\let\ratio\relax\fi
983 % \end{macrocode}
984 % In order to test for |\real| or |\ratio|, we define these
985 % two.\footnote{May not need the extra names, CAR?}
986 % \begin{macrocode}
987 \def\calc@ratio@x{\ratio}
988 \def\calc@real@x{\real}
989 % \end{macrocode}
990 % \end{macro}
991 % \end{macro}
992 % \end{macro}
993 % \end{macro}
994 % \begin{macro}{\calc@multiplyx}
995 % \changes{v4.2}{2005/08/06}
996 % {Added $\protect\max$ and $\protect\min$ operations}
997 % \begin{macro}{\calc@dividex}
998 % \changes{v4.2}{2005/08/06}
999 % {Added $\protect\max$ and $\protect\min$ operations}
1000 % Test which operator followed |*| or |/|. If none followed it's just
1001 % a standard multiplication or division.
1002 % \begin{macrocode}
1003 \def\calc@multiplyx#1{\def\calc@tmp{#1}%
1004 \ifx\calc@tmp\calc@ratio@x \let\calc@next\calc@ratio@multiply \else
1005 \ifx\calc@tmp\calc@real@x \let\calc@next\calc@real@multiply \else
1006 \ifx\maxof#1\let\calc@next\calc@maxmin@multiply \else
1007 \let\calc@next\calc@multiply
1008 \fi
1009 \fi
1010 \fi
1011 \calc@next#1}
1012 \def\calc@dividex#1{\def\calc@tmp{#1}%
1013 \ifx\calc@tmp\calc@ratio@x \let\calc@next\calc@ratio@divide \else
1014 \ifx\calc@tmp\calc@real@x \let\calc@next\calc@real@divide \else
1015 \ifx\maxof#1\let\calc@next\calc@maxmin@divide \else
1016 \let\calc@next\calc@divide
1017 \fi
1018 \fi
1019 \fi
1020 \calc@next#1}
1021 % \end{macrocode}
1022 % \end{macro}
1023 % \end{macro}
1024 %
1025 % \begin{macro}{\calc@multiply}
1026 % \begin{macro}{\calc@divide}
1027 % \begin{macro}{\calc@generic@multiply}
1028 % \begin{macro}{\calc@multiplyBbyA}
1029 % \begin{macro}{\calc@divideBbyA}
1030 % The binary operators `\texttt{*}' and `\texttt{/}' also insert code
1031 % as determined above. Moreover, the meaning of |\calc@A| and
1032 % |\calc@B| is changed as factors following a multiplication and
1033 % division operator always have integer type; the original meaning of
1034 % these macros will be restored when the factor has been read and
1035 % evaluated.
1036 % \begin{macrocode}
1037 \def\calc@multiply{\calc@generic@multiply\calc@multiplyBbyA}
1038 \def\calc@divide{\calc@generic@multiply\calc@divideBbyA}
1039 \def\calc@generic@multiply#1{\endgroup\begingroup
1040 \let\calc@A\calc@Acount \let\calc@B\calc@Bcount
1041 \aftergroup#1\calc@pre@scan}
1042 \def\calc@multiplyBbyA{\multiply\calc@B\calc@Acount}
1043 \def\calc@divideBbyA{\divide\calc@B\calc@Acount}
1044 % \end{macrocode}
1045 % Since the value to use in the multiplication/division operation is
1046 % stored in the |\calc@Acount| register, the |\calc@multiplyBbyA| and
1047 % |\calc@divideBbyA| macros use this register.
1048 % \end{macro}
1049 % \end{macro}
1050 % \end{macro}
1051 % \end{macro}
1052 % \end{macro}
1053 %
1054 % \begin{macro}{\calc@close}
1055 % |\calc@close| generates code for a right parenthesis (which was
1056 % derived to be ``$\}A\gassign B\}A\gassign B$'' in
1057 % Section~\ref{evaluation:scheme}). After this code, the control is
1058 % returned to
1059 % |\calc@post@scan| in order to look for another right parenthesis or
1060 % a binary operator.
1061 % \begin{macrocode}
1062 \def\calc@close
1063 {\endgroup\global\calc@A\calc@B
1064 \endgroup\global\calc@A\calc@B
1065 \calc@post@scan}
1066 % \end{macrocode}
1067 % \end{macro}
1068 %
1069 % \subsection{Calculating a ratio}
1070 %
1071 % \begin{macro}{\calc@ratio@multiply}
1072 % \begin{macro}{\calc@ratio@divide}
1073 % When |\calc@post@scan| encounters a |\ratio| control sequence, it hands
1074 % control to one of the macros |\calc@ratio@multiply| and |\calc@ratio@divide|,
1075 % depending on the preceding character. Those macros both forward the
1076 % control to the macro |\calc@ratio@evaluate|, which performs two steps: (1) it
1077 % calculates the ratio, which is saved in the global macro token
1078 % |\calc@the@ratio|; (2) it makes sure that the value of |\calc@B| will be
1079 % multiplied by the ratio as soon as the current group ends.
1080 %
1081 % The following macros call |\calc@ratio@evaluate| which multiplies
1082 % |\calc@B| by the ratio, but |\calc@ratio@divide| flips the arguments
1083 % so that the `opposite' fraction is actually evaluated.
1084 % \begin{macrocode}
1085 \def\calc@ratio@multiply\ratio{\calc@ratio@evaluate}
1086 \def\calc@ratio@divide\ratio#1#2{\calc@ratio@evaluate{#2}{#1}}
1087 % \end{macrocode}
1088 % \end{macro}
1089 % \end{macro}
1090 % \begin{macro}{\calc@Ccount}
1091 % \begin{macro}{\calc@numerator}
1092 % \begin{macro}{\calc@denominator}
1093 % We shall need two registers for temporary usage in the
1094 % calculations. We can save one register since we can reuse
1095 % |\calc@Bcount|.
1096 % \begin{macrocode}
1097 \newcount\calc@Ccount
1098 \let\calc@numerator=\calc@Bcount
1099 \let\calc@denominator=\calc@Ccount
1100 % \end{macrocode}
1101 % \end{macro}
1102 % \end{macro}
1103 % \end{macro}
1104 % \begin{macro}{\calc@ratio@evaluate}
1105 % Here is the macro that handles the actual evaluation of ratios. The
1106 % procedure is
1107 % this: First, the two expressions are evaluated and coerced to
1108 % integers. The whole procedure is enclosed in a group to be able to
1109 % use the registers |\calc@numerator| and |\calc@denominator| for temporary
1110 % manipulations.
1111 % \begin{macrocode}
1112 \def\calc@ratio@evaluate#1#2{%
1113 \endgroup\begingroup
1114 \calc@assign@dimen\calc@numerator{#1}%
1115 \calc@assign@dimen\calc@denominator{#2}%
1116 % \end{macrocode}
1117 % Here we calculate the ratio. First, we check for negative numerator
1118 % and/or denominator; note that \TeX\ interprets two minus signs the
1119 % same as a plus sign. Then, we calculate the integer part.
1120 % The minus sign(s), the integer part, and a decimal point form the
1121 % initial expansion of the |\calc@the@ratio| macro.
1122 % \begin{macrocode}
1123 \gdef\calc@the@ratio{}%
1124 \ifnum\calc@numerator<0 \calc@numerator-\calc@numerator
1125 \gdef\calc@the@ratio{-}%
1126 \fi
1127 \ifnum\calc@denominator<0 \calc@denominator-\calc@denominator
1128 \xdef\calc@the@ratio{\calc@the@ratio-}%
1129 \fi
1130 \calc@Acount\calc@numerator
1131 \divide\calc@Acount\calc@denominator
1132 \xdef\calc@the@ratio{\calc@the@ratio\number\calc@Acount.}%
1133 % \end{macrocode}
1134 % Now we generate the digits after the decimal point, one at a time.
1135 % When \TeX\ scans these digits (in the actual multiplication
1136 % operation), it forms a fixed-point number with 16~bits for
1137 % the fractional part. We hope that six digits is sufficient, even
1138 % though the last digit may not be rounded correctly.
1139 % \begin{macrocode}
1140 \calc@next@digit \calc@next@digit \calc@next@digit
1141 \calc@next@digit \calc@next@digit \calc@next@digit
1142 \endgroup
1143 % \end{macrocode}
1144 % Now we have the ratio represented (as the expansion of the global
1145 % macro |\calc@the@ratio|) in the syntax \<decimal constant>
1146 % \cite[page~270]{texbook}. This is fed to |\calc@multiply@by@real|
1147 % that will
1148 % perform the actual multiplication. It is important that the
1149 % multiplication takes place at the correct grouping level so that the
1150 % correct instance of the $B$ register will be used. Also note that
1151 % we do not need the |\aftergroup| mechanism in this case.
1152 % \begin{macrocode}
1153 \calc@multiply@by@real\calc@the@ratio
1154 \begingroup
1155 \calc@post@scan}
1156 % \end{macrocode}
1157 % \end{macro}
1158 % The |\begingroup| inserted before the |\calc@post@scan| will be
1159 % matched by the |\endgroup| generated as part of the replacement of a
1160 % subsequent binary operator or right parenthesis.
1161 % \begin{macro}{\calc@next@digit}
1162 % \begin{macrocode}
1163 \def\calc@next@digit{%
1164 \multiply\calc@Acount\calc@denominator
1165 \advance\calc@numerator -\calc@Acount
1166 \multiply\calc@numerator 10
1167 \calc@Acount\calc@numerator
1168 \divide\calc@Acount\calc@denominator
1169 \xdef\calc@the@ratio{\calc@the@ratio\number\calc@Acount}}
1170 % \end{macrocode}
1171 % \end{macro}
1172 % \begin{macro}{\calc@multiply@by@real}
1173 % In the following code, it is important that we first assign the
1174 % result to a dimen register. Otherwise, \TeX\ won't allow us to
1175 % multiply with a real number.
1176 % \begin{macrocode}
1177 \def\calc@multiply@by@real#1{\calc@Bdimen #1\calc@B \calc@B\calc@Bdimen}
1178 % \end{macrocode}
1179 % (Note that this code wouldn't work if |\calc@B| were a muglue
1180 % register. This is the real reason why the \texttt{calc} package
1181 % doesn't support muglue expressions. To support muglue expressions
1182 % in full, the |\calc@multiply@by@real| macro must use a muglue register
1183 % instead of |\calc@Bdimen| when |\calc@B| is a muglue register;
1184 % otherwise, a dimen register should be used. Since integer
1185 % expressions can appear as part of a muglue expression, it would be
1186 % necessary to determine the correct register to use each time a
1187 % multiplication is made.)
1188 % \end{macro}
1189 %
1190 % \subsection{Multiplication by real numbers}
1191 %
1192 % \begin{macro}{\calc@real@multiply}
1193 % \begin{macro}{\calc@real@divide}
1194 % This is similar to the |\calc@ratio@evaluate| macro above, except that
1195 % it is considerably simplified since we don't need to calculate the
1196 % factor explicitly.
1197 % \begin{macrocode}
1198 \def\calc@real@multiply\real#1{\endgroup
1199 \calc@multiply@by@real{#1}\begingroup
1200 \calc@post@scan}
1201 \def\calc@real@divide\real#1{\calc@ratio@evaluate{1pt}{#1pt}}
1202 % \end{macrocode}
1203 % \end{macro}
1204 % \end{macro}
1205 %
1206 % \subsection{$\max$ and $\min$ operations}
1207 %
1208 % \begin{macro}{\maxof}
1209 % \begin{macro}{\minof}
1210 % \changes{v4.2}{2005/08/06}
1211 % {Added macros}
1212 % With version 4.2, the $\max$ and $\min$ operators were
1213 % added to \texttt{calc}. The user functions for them are \cs{maxof} and
1214 % \cs{minof} respectively.
1215 % These macros are internally similar to \cs{widthof} etc.\ in that they
1216 % are unexpandable and easily recognizable by the scanner.
1217 % \begin{macrocode}
1218 \let\maxof\@@italiccorr
1219 \let\minof\@@italiccorr
1220 % \end{macrocode}
1221 % \end{macro}
1222 % \end{macro}
1223 %
1224 %
1225 % \begin{macro}{\calc@Cskip}
1226 % \begin{macro}{\ifcalc@count@}
1227 % The $\max$ and $\min$ operations take two arguments so we need an extra
1228 % \<skip> register. We also add a switch for determining when to perform
1229 % a \<skip> or a \<count> assignment.
1230 % \begin{macrocode}
1231 \newskip\calc@Cskip
1232 \newif\ifcalc@count@
1233 % \end{macrocode}
1234 % \end{macro}
1235 % \end{macro}
1236 % \begin{macro}{\calc@maxmin@addsub}
1237 % \begin{macro}{\calc@maxmin@generic}
1238 % \changes{v4.2}{2005/08/06}{Macros added}
1239 % When doing addition or subtraction with a $\max$ or $\min$ operator, we
1240 % first check if |\calc@A| is a \<count> register or not and then set the
1241 % switch. Then call the real function which sets |\calc@A| to the desired
1242 % value and continue as usual with |\calc@post@scan|.
1243 % \begin{macrocode}
1244 \def\calc@maxmin@addsub#1#2#3{\begingroup
1245 \ifx\calc@A\calc@Acount%
1246 \calc@count@true
1247 \else
1248 \calc@count@false
1249 \fi
1250 \calc@maxmin@generic#1{#2}{#3}%
1251 \endgroup
1252 \calc@post@scan
1253 }
1254 % \end{macrocode}
1255 % Check the switch and do either \<count> or \<skip> assignments. Note that
1256 % |\maxof| and |\minof| are not set to |>| and |<| until after the
1257 % assignments, which ensures we can nest them without problems. Then set
1258 % |\calc@A| to the correct one.
1259 % \begin{macrocode}
1260 \def\calc@maxmin@generic#1#2#3{%
1261 \begingroup
1262 \ifcalc@count@
1263 \calc@assign@count\calc@Ccount{#2}%
1264 \calc@assign@count\calc@Bcount{#3}%
1265 \def\minof{<}\def\maxof{>}%
1266 \global\calc@A\ifnum\calc@Ccount#1\calc@Bcount
1267 \calc@Ccount\else\calc@Bcount\fi
1268 \else
1269 \calc@assign@skip\calc@Cskip{#2}%
1270 \calc@assign@skip\calc@Bskip{#3}%
1271 \def\minof{<}\def\maxof{>}%
1272 \global\calc@A\ifdim\calc@Cskip#1\calc@Bskip
1273 \calc@Cskip\else\calc@Bskip\fi
1274 \fi
1275 \endgroup
1276 }
1277 % \end{macrocode}
1278 % \end{macro}
1279 % \end{macro}
1280 %
1281 % \begin{macro}{\calc@maxmin@divmul}
1282 % \begin{macro}{\calc@maxmin@multiply}
1283 % \begin{macro}{\calc@maxmin@divide}
1284 % \changes{v4.2}{2005/08/06}{Macros added}
1285 % When doing division or multiplication we must be using \<count> registers
1286 % so we set the switch. Other than that it is almost business as usual when
1287 % multiplying or dividing. |#1| is the instruction to either multiply or
1288 % divide |\calc@B| by |\calc@A|, |#2| is either |\maxof| or |\minof| which
1289 % is waiting in the input stream and |#3| and |#4| are the calc expressions.
1290 % We end it all as usual by calling |\calc@post@scan|.
1291 % \begin{macrocode}
1292 \def\calc@maxmin@divmul#1#2#3#4{%
1293 \endgroup\begingroup
1294 \calc@count@true
1295 \aftergroup#1%
1296 \calc@maxmin@generic#2{#3}{#4}%
1297 \endgroup\begingroup
1298 \calc@post@scan
1299 }
1300 % \end{macrocode}
1301 % The two functions called when seeing a |*| or a |/|.
1302 % \begin{macrocode}
1303 \def\calc@maxmin@multiply{\calc@maxmin@divmul\calc@multiplyBbyA}
1304 \def\calc@maxmin@divide {\calc@maxmin@divmul\calc@divideBbyA}
1305 % \end{macrocode}
1306 % \end{macro}
1307 % \end{macro}
1308 % \end{macro}
1309 %
1310 % \section{Reporting errors}
1311 % \begin{macro}{\calc@error}
1312 % \changes{v4.0d}{1997/11/08}
1313 % {Use \cs{PackageError} for error messages (DPC)}
1314 % \changes{v4.0e}{1997/11/11}
1315 % {typo fixed}
1316 % If |\calc@post@scan| reads a character that is neither `\texttt{+}',
1317 % `\texttt{-}', `\texttt{*}', `\texttt{/}', nor `\texttt{)}', an error
1318 % has occurred, and this is reported to the user. Violations in the
1319 % syntax of \<numeric>s will be detected and reported by \TeX.
1320 % \changes{v4.1a}{1998/06/07}
1321 % {Improved, I hope, error message: CAR}
1322 % \begin{macrocode}
1323 \def\calc@error#1{%
1324 \PackageError{calc}%
1325 {`#1' invalid at this point}%
1326 {I expected to see one of: + - * / )}}
1327 % \end{macrocode}
1328 % \end{macro}
1329 %
1330 % \section{Other additions}
1331 % \begin{macro}{\@settodim}
1332 % \changes{v4.2}{2005/08/06}
1333 % {Changed kernel macro}
1334 % \changes{v4.3a}{2024/11/03}
1335 % {Suspend Tagging}
1336 % \begin{macro}{\settototalheight}
1337 % \changes{v4.2}{2005/08/06}
1338 % {Added macro}
1339 % The kernel macro \cs{@settodim} is changed so that it runs through a list
1340 % containing \cs{ht}, \cs{wd}, and \cs{dp} and then advances the length
1341 % one step at a time. We just have to use a scratch register in case the
1342 % user decides to put in a \cs{global} prefix on the length register.
1343 % A search on the internet confirmed that some people do that kind of thing.
1344 % \begin{macrocode}
1345 \def\@settodim#1#2#3{%
1346 \setbox\@tempboxa\hbox
1347 {{\SuspendTagging{\@settodim}#3\ResumeTagging{\@settodim}}}%
1348 \dimen@ii=\z@
1349 \@tf@r\reserved@a #1\do{%
1350 \advance\dimen@ii\reserved@a\@tempboxa}%
1351 #2=\dimen@ii
1352 \setbox\@tempboxa\box\voidb@x}
1353 % \end{macrocode}
1354 % Now the user level macro is straightforward.
1355 % \begin{macrocode}
1356 \def\settototalheight{\@settodim{\ht\dp}}
1357 % \end{macrocode}
1358 % \end{macro}
1359 % \end{macro}
1360 %
1361 % That's the end of the package.
1362 % \begin{macrocode}
1363 %</package>
1364 % \end{macrocode}
1365 %
1366 % \Finale
1367 \endinput