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