0
# References and Cross-referencing
1
2
Label creation and cross-referencing system for equations, figures, sections, and pages with automatic formatting. PyLaTeX provides comprehensive support for LaTeX's labeling and referencing system, enabling automatic numbering, cross-references, and intelligent reference formatting.
3
4
## Capabilities
5
6
### Label and Reference System
7
8
The core labeling system allows you to mark elements and reference them throughout the document with automatic numbering.
9
10
```python { .api }
11
class Marker(LatexObject):
12
def __init__(self, name, prefix="", del_invalid_char=True):
13
"""
14
Create a marker for labeling and referencing.
15
16
Parameters:
17
- name: str, unique identifier for the marker
18
- prefix: str, optional prefix for organization (e.g., 'fig', 'eq', 'sec')
19
- del_invalid_char: bool, automatically remove invalid characters
20
"""
21
22
class Label(RefLabelBase):
23
def __init__(self, marker):
24
"""
25
Create a label at current position.
26
27
Parameters:
28
- marker: str or Marker, label identifier
29
"""
30
31
class Ref(RefLabelBase):
32
def __init__(self, marker):
33
"""
34
Create a reference to a labeled element.
35
36
Parameters:
37
- marker: str or Marker, label identifier to reference
38
"""
39
```
40
41
Usage example:
42
43
```python
44
from pylatex import Document, Section, Subsection
45
from pylatex.labelref import Label, Ref, Marker
46
47
doc = Document()
48
49
# Create labeled sections
50
with doc.create(Section('Introduction')) as intro:
51
intro.append(Label(Marker('intro', 'sec')))
52
intro.append('This section introduces the main concepts.')
53
54
with doc.create(Section('Methods')) as methods:
55
methods.append(Label(Marker('methods', 'sec')))
56
methods.append('As discussed in ')
57
methods.append(Ref(Marker('intro', 'sec')))
58
methods.append(', we now present the methodology.')
59
60
with methods.create(Subsection('Data Collection')) as data:
61
data.append(Label('data-collection'))
62
data.append('Details about data collection procedures.')
63
64
# Reference sections by number
65
with doc.create(Section('Results')):
66
doc.append('Building on the methods from Section ')
67
doc.append(Ref('methods'))
68
doc.append(' and specifically ')
69
doc.append(Ref('data-collection'))
70
doc.append(', we present our findings.')
71
```
72
73
### Page References
74
75
Reference the page number where a labeled element appears.
76
77
```python { .api }
78
class Pageref(RefLabelBase):
79
def __init__(self, marker):
80
"""
81
Reference the page number of a labeled element.
82
83
Parameters:
84
- marker: str or Marker, label identifier to reference
85
"""
86
```
87
88
Usage example:
89
90
```python
91
from pylatex import Document, Section, NewPage
92
from pylatex.labelref import Label, Ref, Pageref
93
94
doc = Document()
95
96
with doc.create(Section('First Section')):
97
doc.append(Label('first-section'))
98
doc.append('This content appears on the first page.')
99
100
doc.append(NewPage())
101
102
with doc.create(Section('Later Section')):
103
doc.append('Reference to Section ')
104
doc.append(Ref('first-section'))
105
doc.append(' on page ')
106
doc.append(Pageref('first-section'))
107
doc.append(' contains important background information.')
108
```
109
110
### Equation References
111
112
Specialized referencing for mathematical equations with proper formatting.
113
114
```python { .api }
115
class Eqref(RefLabelBase):
116
def __init__(self, marker):
117
"""
118
Reference an equation with proper formatting.
119
120
Parameters:
121
- marker: str or Marker, equation label identifier
122
123
Requires:
124
- amsmath package (automatically added)
125
"""
126
```
127
128
Usage example:
129
130
```python
131
from pylatex import Document, Section, NoEscape
132
from pylatex.math import Alignat
133
from pylatex.labelref import Label, Eqref
134
135
doc = Document()
136
137
with doc.create(Section('Mathematical Analysis')):
138
# Labeled equations
139
with doc.create(Alignat(numbering=True)) as equations:
140
equations.append(NoEscape(r'E &= mc^2'))
141
equations.append(Label('einstein'))
142
equations.append(NoEscape(r'\\'))
143
equations.append(NoEscape(r'F &= ma'))
144
equations.append(Label('newton'))
145
equations.append(NoEscape(r'\\'))
146
equations.append(NoEscape(r'a &= \frac{F}{m}'))
147
equations.append(Label('acceleration'))
148
149
# Reference equations
150
doc.append('From Einstein\'s mass-energy equivalence ')
151
doc.append(Eqref('einstein'))
152
doc.append(' and Newton\'s second law ')
153
doc.append(Eqref('newton'))
154
doc.append(', we can derive the acceleration formula ')
155
doc.append(Eqref('acceleration'))
156
doc.append('.')
157
```
158
159
### Intelligent References
160
161
Advanced referencing with automatic context-aware formatting.
162
163
```python { .api }
164
class Autoref(RefLabelBase):
165
def __init__(self, marker):
166
"""
167
Automatic reference with type prefix (e.g., 'Figure 1', 'Section 2').
168
169
Parameters:
170
- marker: str or Marker, label identifier
171
172
Requires:
173
- hyperref package
174
"""
175
176
class Cref(RefLabelBase):
177
def __init__(self, marker):
178
"""
179
Clever reference with intelligent formatting.
180
181
Parameters:
182
- marker: str or Marker, label identifier
183
184
Requires:
185
- cleveref package (automatically added)
186
"""
187
188
class Hyperref(RefLabelBase):
189
def __init__(self, marker, text=None):
190
"""
191
Create hyperlinked reference.
192
193
Parameters:
194
- marker: str or Marker, label identifier
195
- text: str, custom link text (optional)
196
197
Requires:
198
- hyperref package
199
"""
200
```
201
202
Usage example:
203
204
```python
205
from pylatex import Document, Section, Package
206
from pylatex.figure import Figure
207
from pylatex.table import Table, Tabular
208
from pylatex.labelref import Label, Autoref, Cref
209
210
doc = Document()
211
doc.packages.append(Package('hyperref'))
212
doc.packages.append(Package('cleveref'))
213
214
with doc.create(Section('Results')) as results:
215
results.append(Label('results'))
216
217
# Labeled figure
218
with results.create(Figure(position='htbp')) as fig:
219
fig.add_image('data_plot.png')
220
fig.add_caption('Experimental data visualization.')
221
fig.append(Label('fig:data'))
222
223
# Labeled table
224
with results.create(Table(position='htbp')) as table:
225
table.add_caption('Summary statistics.')
226
table.append(Label('tab:stats'))
227
228
with table.create(Tabular('lcc')) as tabular:
229
tabular.add_row(['Metric', 'Value', 'Error'])
230
tabular.add_hline()
231
tabular.add_row(['Mean', '12.5', '±0.3'])
232
tabular.add_row(['StdDev', '2.1', '±0.1'])
233
234
with doc.create(Section('Discussion')):
235
# Automatic references with type detection
236
doc.append(Autoref('fig:data')) # Produces "Figure 1"
237
doc.append(' shows the trend, while ')
238
doc.append(Autoref('tab:stats')) # Produces "Table 1"
239
doc.append(' provides numerical summaries.')
240
241
# Clever references with better formatting
242
doc.append(' As shown in ')
243
doc.append(Cref('results')) # Produces "section 1" with proper formatting
244
doc.append(', the data supports our hypothesis.')
245
```
246
247
## Advanced Reference Features
248
249
### Multiple References
250
251
```python
252
from pylatex import Document, Section, NoEscape
253
from pylatex.labelref import Label, Ref
254
255
doc = Document()
256
257
# Multiple labeled items
258
with doc.create(Section('Multiple Items')):
259
doc.append('Item A')
260
doc.append(Label('item-a'))
261
doc.append(' and Item B')
262
doc.append(Label('item-b'))
263
doc.append(' and Item C')
264
doc.append(Label('item-c'))
265
266
# Reference multiple items
267
with doc.create(Section('References')):
268
doc.append('Items ')
269
doc.append(Ref('item-a'))
270
doc.append(', ')
271
doc.append(Ref('item-b'))
272
doc.append(', and ')
273
doc.append(Ref('item-c'))
274
doc.append(' are all related.')
275
276
# Using cleveref for range references
277
doc.append('Items ')
278
doc.append(NoEscape(r'\crefrange{item-a}{item-c}')) # Produces "items 1 to 3"
279
doc.append(' form a series.')
280
```
281
282
### Custom Reference Types
283
284
```python
285
from pylatex import Document, Section, Package, Command, NoEscape
286
from pylatex.labelref import Label, Cref
287
288
doc = Document()
289
doc.packages.append(Package('cleveref'))
290
291
# Define custom reference types
292
doc.preamble.append(Command('crefname', arguments=['algorithm', 'Algorithm', 'Algorithms']))
293
doc.preamble.append(Command('Crefname', arguments=['algorithm', 'Algorithm', 'Algorithms']))
294
295
with doc.create(Section('Algorithms')):
296
# Custom labeled environment
297
doc.append(NoEscape(r'\refstepcounter{algorithm}'))
298
doc.append(NoEscape(r'\textbf{Algorithm \thealgorithm}:'))
299
doc.append(Label('alg:quicksort'))
300
doc.append(' Quicksort implementation.')
301
302
doc.append(NoEscape(r'\refstepcounter{algorithm}'))
303
doc.append(NoEscape(r'\textbf{Algorithm \thealgorithm}:'))
304
doc.append(Label('alg:mergesort'))
305
doc.append(' Mergesort implementation.')
306
307
with doc.create(Section('Analysis')):
308
doc.append(Cref('alg:quicksort')) # Produces "Algorithm 1"
309
doc.append(' has better average case performance than ')
310
doc.append(Cref('alg:mergesort')) # Produces "Algorithm 2"
311
doc.append('.')
312
```
313
314
### Hierarchical Labeling
315
316
```python
317
from pylatex import Document, Chapter, Section, Subsection
318
from pylatex.labelref import Label, Ref, Marker
319
320
doc = Document(documentclass='report')
321
322
# Organized label hierarchy
323
with doc.create(Chapter('Introduction')) as intro:
324
intro.append(Label(Marker('introduction', 'chap')))
325
326
with intro.create(Section('Background')) as bg:
327
bg.append(Label(Marker('background', 'sec')))
328
329
with bg.create(Subsection('Historical Context')) as hist:
330
hist.append(Label(Marker('history', 'subsec')))
331
hist.append('Historical overview of the field.')
332
333
with bg.create(Subsection('Current State')) as current:
334
current.append(Label(Marker('current', 'subsec')))
335
current.append('Current developments in the area.')
336
337
with doc.create(Chapter('Methods')) as methods:
338
methods.append(Label(Marker('methods', 'chap')))
339
methods.append('Building on the background from ')
340
methods.append(Ref(Marker('background', 'sec')))
341
methods.append(' in ')
342
methods.append(Ref(Marker('introduction', 'chap')))
343
methods.append(', we now present our approach.')
344
```
345
346
### Figure and Table References
347
348
```python
349
from pylatex import Document, Section
350
from pylatex.figure import Figure, SubFigure
351
from pylatex.table import Table, Tabular
352
from pylatex.labelref import Label, Ref, Autoref
353
354
doc = Document()
355
356
with doc.create(Section('Data Presentation')):
357
# Multi-panel figure with individual labels
358
with doc.create(Figure(position='htbp')) as fig:
359
with fig.create(SubFigure(width=NoEscape(r'0.45\textwidth'))) as subfig_a:
360
subfig_a.add_image('plot_a.png')
361
subfig_a.add_caption('Dataset A results.')
362
subfig_a.append(Label('fig:data-a'))
363
364
fig.append(NoEscape(r'\hfill'))
365
366
with fig.create(SubFigure(width=NoEscape(r'0.45\textwidth'))) as subfig_b:
367
subfig_b.add_image('plot_b.png')
368
subfig_b.add_caption('Dataset B results.')
369
subfig_b.append(Label('fig:data-b'))
370
371
fig.add_caption('Comparison of experimental datasets.')
372
fig.append(Label('fig:comparison'))
373
374
# Complex table with sections
375
with doc.create(Table(position='htbp')) as table:
376
table.add_caption('Detailed experimental results.')
377
table.append(Label('tab:results'))
378
379
with table.create(Tabular('lccc')) as tabular:
380
tabular.add_row(['Parameter', 'Method A', 'Method B', 'Method C'])
381
tabular.add_hline()
382
tabular.add_row(['Accuracy', '92.3%', '89.7%', '94.1%'])
383
tabular.add_row(['Speed', '150ms', '200ms', '120ms'])
384
385
with doc.create(Section('Discussion')):
386
doc.append('The results shown in ')
387
doc.append(Autoref('fig:comparison'))
388
doc.append(' demonstrate clear trends. Specifically, ')
389
doc.append(Ref('fig:data-a'))
390
doc.append(' shows one pattern while ')
391
doc.append(Ref('fig:data-b'))
392
doc.append(' shows another. The quantitative analysis in ')
393
doc.append(Autoref('tab:results'))
394
doc.append(' supports these observations.')
395
```
396
397
## Reference Management Strategies
398
399
### Consistent Naming Conventions
400
401
```python
402
from pylatex.labelref import Label, Marker
403
404
# Recommended naming patterns
405
figure_labels = [
406
Marker('architecture', 'fig'), # fig:architecture
407
Marker('results-plot', 'fig'), # fig:results-plot
408
Marker('comparison', 'fig') # fig:comparison
409
]
410
411
section_labels = [
412
Marker('introduction', 'sec'), # sec:introduction
413
Marker('methodology', 'sec'), # sec:methodology
414
Marker('conclusions', 'sec') # sec:conclusions
415
]
416
417
equation_labels = [
418
Marker('energy-conservation', 'eq'), # eq:energy-conservation
419
Marker('momentum', 'eq'), # eq:momentum
420
Marker('angular-momentum', 'eq') # eq:angular-momentum
421
]
422
```
423
424
### Automated Label Generation
425
426
```python
427
from pylatex import Document, Section
428
from pylatex.figure import Figure
429
from pylatex.labelref import Label, Ref, Marker
430
431
def create_labeled_figure(doc, image_path, caption, label_name):
432
"""Create a figure with automatic labeling."""
433
with doc.create(Figure(position='htbp')) as fig:
434
fig.add_image(image_path)
435
fig.add_caption(caption)
436
fig.append(Label(Marker(label_name, 'fig')))
437
return f'fig:{label_name}'
438
439
def create_labeled_section(doc, title, label_name):
440
"""Create a section with automatic labeling."""
441
section = doc.create(Section(title))
442
section.append(Label(Marker(label_name, 'sec')))
443
return section, f'sec:{label_name}'
444
445
# Usage
446
doc = Document()
447
448
# Create labeled content
449
section, sec_label = create_labeled_section(doc, 'Results', 'results')
450
451
with section:
452
fig_label = create_labeled_figure(doc, 'plot.png', 'Main results', 'main-plot')
453
doc.append('This section presents findings as shown in ')
454
doc.append(Ref(fig_label))
455
doc.append('.')
456
457
# Reference the section later
458
with doc.create(Section('Discussion')):
459
doc.append('As demonstrated in ')
460
doc.append(Ref(sec_label))
461
doc.append(', our approach is effective.')
462
```
463
464
### Cross-Document References
465
466
```python
467
from pylatex import Document, Package, Command
468
from pylatex.labelref import Label, Ref
469
470
# Enable cross-document references
471
doc = Document()
472
doc.packages.append(Package('xr'))
473
doc.preamble.append(Command('externaldocument', arguments='other-document'))
474
475
# Reference labels from other documents
476
with doc.create(Section('Related Work')):
477
doc.append('As shown in the previous report ')
478
doc.append(Ref('other-doc:main-result')) # From other-document.tex
479
doc.append(', this approach has been validated.')
480
```
481
482
## Package Dependencies
483
484
Reference functionality requires specific LaTeX packages:
485
486
- **Basic references**: No additional packages
487
- **Equation references**: `amsmath` package (automatically added with Eqref)
488
- **Automatic references**: `hyperref` package
489
- **Clever references**: `cleveref` package (automatically added with Cref)
490
- **Cross-document**: `xr` package
491
492
```python
493
from pylatex import Document, Package
494
495
doc = Document()
496
497
# Reference packages
498
doc.packages.append(Package('hyperref'))
499
doc.packages.append(Package('cleveref'))
500
doc.packages.append(Package('xr'))
501
```
502
503
## Best Practices
504
505
### Label Organization
506
507
```python
508
# Clear, descriptive labels
509
Label('fig:system-architecture') # Good
510
Label('fig1') # Avoid
511
512
# Consistent prefixes
513
Label('sec:methodology')
514
Label('sec:results')
515
Label('sec:conclusions')
516
517
# Hierarchical organization
518
Label('sec:methods')
519
Label('subsec:data-collection')
520
Label('subsubsec:survey-design')
521
```
522
523
### Reference Formatting
524
525
```python
526
from pylatex import Document, NoEscape
527
from pylatex.labelref import Ref, Autoref
528
529
doc = Document()
530
531
# Use appropriate reference types
532
doc.append(Autoref('fig:results')) # "Figure 1"
533
doc.append(' shows that...')
534
535
doc.append('As seen in ')
536
doc.append(Ref('sec:methods')) # "2" (section number only)
537
doc.append(', we used...')
538
539
# Combine with text for clarity
540
doc.append('Section ')
541
doc.append(Ref('sec:background'))
542
doc.append(' provides context.')
543
```
544
545
The reference system in PyLaTeX enables professional document cross-referencing with automatic numbering, intelligent formatting, and seamless integration with LaTeX's native labeling capabilities.