]> mj.ucw.cz Git - ucwmac.git/blob - ucw-ref.tex
74143e212b2825dd93013bdf0e1307a1ce917a0a
[ucwmac.git] / ucw-ref.tex
1 % The UCW Macro Collection: References
2 % Written by Martin Mares <mj@ucw.cz> in 2018 and placed into public domain
3 % -------------------------------------------------------------------------
4
5 \input ucw-link.tex
6
7 % We maintain a collection of objects. Each object has:
8 %    - type (namespace -- e.g., chapter)
9 %    - identifier (alphanumeric string used to refer to the object in TeX source)
10 %    - label (to be typeset in clickable links -- e.g., chapter number)
11 %    - location (it is tied to a specific place in the output document)
12
13 % Some output formats (e.g., EPUB) have output split to multiple files.
14 % We need to keep track of the file name for every object.
15 % When producing a PDF, it is always empty.
16 \def\refcurrentfile{}
17
18 % An auxiliary file to which we write definitions of all identifiers
19 \newwrite\ids
20 \def\writeid#1#2{\immediate\write\ids{\string\iddef{#1}{#2}{\refcurrentfile}}}
21 \def\delayedwriteid#1#2{\write\ids{\string\iddef{#1}{#2}{\refcurrentfile}}}
22
23 % Used in auxiliary files
24 \def\iddef#1#2#3{\ifcsname id:#1\endcsname\ucwwarn{Identifier #1 re-defined}\else
25 \expandafter\def\csname id:#1\endcsname{#2}%
26 \expandafter\def\csname ff:#1\endcsname{#3}%
27 \fi}
28
29 % Read the auxiliary file from the previous run of TeX, create a new one
30 \immediate\openin\ids=\jobname.ids.aux
31 \ifeof\ids
32 \else
33 \input \jobname.ids.aux
34 \fi
35 \immediate\closein\ids
36 \immediate\openout\ids=\jobname.ids.aux
37
38 % Define an object. It is called from macros with optional arguments
39 % as \addid{type}{label}. It defines a new object whose identifier is the
40 % optional argument.
41 % It sets \currentid to either ID prefixed by its type, or to \relax.
42 \def\addid#1#2{%
43         \ifx\optarg\relax
44                 \let\currentid\relax
45         \else
46                 \edef\currentid{#1\optarg}%
47                 \writeid{\currentid}{#2}%
48                 \destpos{\currentid}%
49         \fi
50 }
51
52 % A low-level interface for typesetting references: produces a clickable link
53 % to the identifier #2 of type #1 with a label translated by macro #3 (use \relax
54 % for no translation).
55 \def\reflink#1#2#3{\expandafter\ifx\csname id:#1#2\endcsname\relax
56         {\ifx\bo\undefined\bf\else\bo\fi ??}%
57         \immediate\write16{*** Warning: Reference #1 undefined ***}%
58 \else
59         \link{#1#2}{#3{\csname id:#1#2\endcsname}}%
60 \fi
61 }
62
63 % Typeset a link to identifier #2 of type #1
64 \def\ref#1#2{\reflink{#1}{#2}\relax}
65
66 % Define an identifier of type page pointing to the current page
67 \def\pageid#1{\delayedwriteid{page#1}{\the\count0}\destpage{page#1}}
68 \def\pageref{\ref{page}}