-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathtablex.typ
2972 lines (2494 loc) · 103 KB
/
tablex.typ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Welcome to tablex!
// Feel free to contribute with any features you think are missing.
// Version: v0.0.9
// -- table counter --
#let _tablex-table-counter = counter("_tablex-table-counter")
// -- compat --
// get the types of things so we can compare with them
// (0.2.0-0.7.0: they're strings; 0.8.0+: they're proper types)
#let _array-type = type(())
#let _dict-type = type((a: 5))
#let _bool-type = type(true)
#let _str-type = type("")
#let _color-type = type(red)
#let _stroke-type = type(red + 5pt)
#let _length-type = type(5pt)
#let _rel-len-type = type(100% + 5pt)
#let _ratio-type = type(100%)
#let _int-type = type(5)
#let _float-type = type(5.0)
#let _fraction-type = type(5fr)
#let _function-type = type(x => x)
#let _content-type = type([])
// note: since 0.8.0, alignment and 2d alignment are the same
// but keep it like this for pre-0.8.0
#let _align-type = type(left)
#let _2d-align-type = type(top + left)
// If types aren't strings, this means we're using 0.8.0+.
#let using-typst-v080-or-later = str(type(_str-type)) == "type"
// Attachments use "t" and "b" instead of "top" and "bottom" since v0.3.0.
#let using-typst-v030-or-later = using-typst-v080-or-later or $a^b$.body.has("t")
#let using-typst-v090 = using-typst-v080-or-later and str(-1).codepoints().first() == "\u{2212}"
#let using-typst-v0110 = using-typst-v090 and sys.version >= version(0, 11, 0)
// Polyfill for locate() when there is no context yet
#let _locate = if using-typst-v0110 { func => context(func(here())) } else { locate }
// Polyfill for locate() when there is already context
#let _locate-inherit = if using-typst-v0110 { func => func(here()) } else { locate }
// Polyfill for style() when there is already context
#let _style-inherit = if using-typst-v0110 { func => func((:)) } else { style }
// Polyfill for measure(_, styles)
#let _measure = if using-typst-v0110 { (value, _) => measure(value) } else { measure }
// This is true if types have fields in the current Typst version.
// This means we can use stroke.thickness, length.em, and so on.
#let typst-fields-supported = using-typst-v080-or-later
// This is true if calc.rem exists in the current Typst version.
// Otherwise, we use a polyfill.
#let typst-calc-rem-supported = using-typst-v030-or-later
// Remainder operation.
#let calc-mod = if typst-calc-rem-supported {
calc.rem
} else {
(a, b) => calc.floor(a) - calc.floor(b * calc.floor(a / b))
}
// Returns the sign of the operand.
// -1 for negative, 1 for positive or zero.
#let calc-sign(x) = {
// For positive: true - false = 1 - 0 = 1
// For zero: true - false = 1 - 0 = 1
// For negative: false - true = 0 - 1 = -1
int(0 <= x) - int(x < 0)
}
// Polyfill for array sum (.sum() is Typst 0.3.0+).
#let array-sum(arr, zero: 0) = {
arr.fold(zero, (a, x) => a + x)
}
// -- common validators --
// Converts the 'fit-spans' argument to a (x: bool, y: bool) dictionary.
// Optionally use a default dictionary to fill missing arguments with.
// This is in the common section as it is needed by the grid section as well.
#let validate-fit-spans(fit-spans, default: (x: false, y: false), error-prefix: none) = {
if type(error-prefix) == _str-type {
error-prefix = " " + error-prefix
} else {
error-prefix = ""
}
if type(fit-spans) == _bool-type {
fit-spans = (x: fit-spans, y: fit-spans)
}
if type(fit-spans) == _dict-type {
assert(fit-spans.len() > 0, message: "Tablex error:" + error-prefix + " 'fit-spans', if a dictionary, must not be empty.")
assert(fit-spans.keys().all(k => k in ("x", "y")), message: "Tablex error:" + error-prefix + " 'fit-spans', if a dictionary, must only have the keys x and y.")
assert(fit-spans.values().all(v => type(v) == _bool-type), message: "Tablex error:" + error-prefix + " keys 'x' and 'y' in the 'fit-spans' dictionary must be booleans (true/false).")
for key in ("x", "y") {
if key in default and key not in fit-spans {
fit-spans.insert(key, default.at(key))
}
}
} else {
panic("Tablex error:" + error-prefix + " Expected 'fit-spans' to be either a boolean or dictionary, found '" + str(type(fit-spans)) + "'")
}
fit-spans
}
// ------------
// -- types --
#let hlinex(
start: 0, end: auto, y: auto,
stroke: auto,
stop-pre-gutter: auto, gutter-restrict: none,
stroke-expand: true,
expand: none
) = (
tablex-dict-type: "hline",
start: start,
end: end,
y: y,
stroke: stroke,
stop-pre-gutter: stop-pre-gutter,
gutter-restrict: gutter-restrict,
stroke-expand: stroke-expand,
expand: expand,
parent: none, // if hline was broken into multiple
)
#let vlinex(
start: 0, end: auto, x: auto,
stroke: auto,
stop-pre-gutter: auto, gutter-restrict: none,
stroke-expand: true,
expand: none
) = (
tablex-dict-type: "vline",
start: start,
end: end,
x: x,
stroke: stroke,
stop-pre-gutter: stop-pre-gutter,
gutter-restrict: gutter-restrict,
stroke-expand: stroke-expand,
expand: expand,
parent: none,
)
#let cellx(content,
x: auto, y: auto,
rowspan: 1, colspan: 1,
fill: auto, align: auto,
inset: auto,
fit-spans: auto
) = (
tablex-dict-type: "cell",
content: content,
rowspan: rowspan,
colspan: colspan,
align: align,
fill: fill,
inset: inset,
fit-spans: fit-spans,
x: x,
y: y,
)
#let occupied(x: 0, y: 0, parent_x: none, parent_y: none) = (
tablex-dict-type: "occupied",
x: x,
y: y,
parent_x: parent_x,
parent_y: parent_y
)
// -- end: types --
// -- type checks, transformers and validators --
// Is this a valid dict created by this library?
#let is-tablex-dict(x) = (
type(x) == _dict-type
and "tablex-dict-type" in x
)
#let is-tablex-dict-type(x, ..dict_types) = (
is-tablex-dict(x)
and x.tablex-dict-type in dict_types.pos()
)
#let is-tablex-cell(x) = is-tablex-dict-type(x, "cell")
#let is-tablex-hline(x) = is-tablex-dict-type(x, "hline")
#let is-tablex-vline(x) = is-tablex-dict-type(x, "vline")
#let is-some-tablex-line(x) = is-tablex-dict-type(x, "hline", "vline")
#let is-tablex-occupied(x) = is-tablex-dict-type(x, "occupied")
#let table-item-convert(item, keep_empty: true) = {
if type(item) == _function-type { // dynamic cell content
cellx(item)
} else if keep_empty and item == () {
item
} else if type(item) != _dict-type or "tablex-dict-type" not in item {
cellx[#item]
} else {
item
}
}
#let rowspanx(length, content, ..cell_options) = {
if is-tablex-cell(content) {
(..content, rowspan: length, ..cell_options.named())
} else {
cellx(
content,
rowspan: length,
..cell_options.named())
}
}
#let colspanx(length, content, ..cell_options) = {
if is-tablex-cell(content) {
(..content, colspan: length, ..cell_options.named())
} else {
cellx(
content,
colspan: length,
..cell_options.named())
}
}
// Get expected amount of cell positions
// in the table (considering colspan and rowspan)
#let get-expected-grid-len(items, col_len: 0) = {
let len = 0
// maximum explicit 'y' specified
let max_explicit_y = items
.filter(c => c.y != auto)
.fold(0, (acc, cell) => {
if (is-tablex-cell(cell)
and type(cell.y) in (_int-type, _float-type)
and cell.y > acc) {
cell.y
} else {
acc
}
})
for item in items {
if is-tablex-cell(item) and item.x == auto and item.y == auto {
// cell occupies (colspan * rowspan) spaces
len += item.colspan * item.rowspan
} else if type(item) == _content-type {
len += 1
}
}
let rows(len) = calc.ceil(len / col_len)
while rows(len) < max_explicit_y {
len += col_len
}
len
}
// Check if this length is infinite.
#let is-infinite-len(len) = {
type(len) in (_ratio-type, _fraction-type, _rel-len-type, _length-type) and "inf" in repr(len)
}
// Check if this is a valid color (color, gradient or pattern).
#let is-color(val) = {
type(val) == _color-type or str(type(val)) in ("gradient", "pattern")
}
#let validate-cols-rows(columns, rows, items: ()) = {
if type(columns) == _int-type {
assert(columns >= 0, message: "Error: Cannot have a negative amount of columns.")
columns = (auto,) * columns
}
if type(rows) == _int-type {
assert(rows >= 0, message: "Error: Cannot have a negative amount of rows.")
rows = (auto,) * rows
}
if type(columns) != _array-type {
columns = (columns,)
}
if type(rows) != _array-type {
rows = (rows,)
}
// default empty column to a single auto column
if columns.len() == 0 {
columns = (auto,)
}
// default empty row to a single auto row
if rows.len() == 0 {
rows = (auto,)
}
let col_row_is_valid(col_row) = (
(not is-infinite-len(col_row)) and (col_row == auto or type(col_row) in (
_fraction-type, _length-type, _rel-len-type, _ratio-type
))
)
if not columns.all(col_row_is_valid) {
panic("Invalid column sizes (must all be 'auto' or a valid, finite length specifier).")
}
if not rows.all(col_row_is_valid) {
panic("Invalid row sizes (must all be 'auto' or a valid, finite length specifier).")
}
let col_len = columns.len()
let grid_len = get-expected-grid-len(items, col_len: col_len)
let expected_rows = calc.ceil(grid_len / col_len)
// more cells than expected => add rows
if rows.len() < expected_rows {
let missing_rows = expected_rows - rows.len()
rows += (rows.last(),) * missing_rows
}
(columns: columns, rows: rows, items: ())
}
// -- end: type checks and validators --
// -- utility functions --
// Which positions does a cell occupy
// (Usually just its own, but increases if colspan / rowspan
// is greater than 1)
#let positions-spanned-by(cell, x: 0, y: 0, x_limit: 0, y_limit: none) = {
let result = ()
let rowspan = if "rowspan" in cell { cell.rowspan } else { 1 }
let colspan = if "colspan" in cell { cell.colspan } else { 1 }
if rowspan < 1 {
panic("Cell rowspan must be 1 or greater (bad cell: " + repr((x, y)) + ")")
} else if colspan < 1 {
panic("Cell colspan must be 1 or greater (bad cell: " + repr((x, y)) + ")")
}
let max_x = x + colspan
let max_y = y + rowspan
if x_limit != none {
max_x = calc.min(x_limit, max_x)
}
if y_limit != none {
max_y = calc.min(y_limit, max_y)
}
for x in range(x, max_x) {
for y in range(y, max_y) {
result.push((x, y))
}
}
result
}
// initialize an array with a certain element or init function, repeated
#let init-array(amount, element: none, init_function: none) = {
let nones = ()
if init_function == none {
init_function = () => element
}
range(amount).map(i => init_function())
}
// Default 'x' to a certain value if it is equal to the forbidden value
// ('none' by default)
#let default-if-not(x, default, if_isnt: none) = {
if x == if_isnt {
default
} else {
x
}
}
// Default 'x' to a certain value if it is none
#let default-if-none(x, default) = default-if-not(x, default, if_isnt: none)
// Default 'x' to a certain value if it is auto
#let default-if-auto(x, default) = default-if-not(x, default, if_isnt: auto)
// Default 'x' to a certain value if it is auto or none
#let default-if-auto-or-none(x, default) = if x in (auto, none) {
default
} else {
x
}
// The max between a, b, or the other one if either is 'none'.
#let max-if-not-none(a, b) = if a in (none, auto) {
b
} else if b in (none, auto) {
a
} else {
calc.max(a, b)
}
// Gets the topmost parent of a line.
#let get-top-parent(line) = {
let previous = none
let current = line
while current != none {
previous = current
current = previous.parent
}
previous
}
// Typst 0.9.0 uses a minus sign ("−"; U+2212 MINUS SIGN) for negative numbers.
// Before that, it used a hyphen minus ("-"; U+002D HYPHEN MINUS), so we use
// regex alternation to match either of those.
#let NUMBER-REGEX-STRING = "(?:−|-)?\\d*\\.?\\d+"
// Check if the given length has type '_length-type' and no 'em' component.
#let is-purely-pt-len(len) = {
type(len) == _length-type and "em" not in repr(len)
}
// Measure a length in pt by drawing a line and using the measure() function.
// This function will work for negative lengths as well.
//
// Note that for ratios, the measurement will be 0pt due to limitations of
// the "draw and measure" technique (wrapping the line in a box still returns 0pt;
// not sure if there is any viable way to measure a ratio). This also affects
// relative lengths — this function will only be able to measure the length component.
//
// styles: from style()
#let measure-pt(len, styles) = {
if typst-fields-supported {
// We can use fields to separate em from pt.
let pt = len.abs
let em = len.em
// Measure with abs (and later multiply by the sign) so negative em works.
// Otherwise it would return 0pt, and we would need to measure again with abs.
let measured-em = calc-sign(em) * _measure(box(width: calc.abs(em) * 1em), styles).width
return pt + measured-em
}
// Fields not supported, so we have to measure twice when em can be negative.
let measured-pt = _measure(box(width: len), styles).width
// If the measured length is positive, `len` must have overall been positive.
// There's nothing else to be done, so return the measured length.
if measured-pt > 0pt {
return measured-pt
}
// If we've reached this point, the previously measured length must have been `0pt`
// (drawing a line with a negative length will draw nothing, so measuring it will return `0pt`).
// Hence, `len` must either be `0pt` or negative.
// We multiply `len` by -1 to get a positive length, draw a line and measure it, then negate
// the measured length. This nicely handles the `0pt` case as well.
measured-pt = -_measure(box(width: -len), styles).width
return measured-pt
}
// Convert a length of type length to pt.
//
// styles: from style()
#let convert-length-type-to-pt(len, styles: none) = {
// repr examples: "1pt", "1em", "0.5pt", "0.5em", "1pt + 1em", "-0.5pt + -0.5em"
if is-purely-pt-len(len) {
// No need to do any conversion because it must already be in pt.
return len
}
return measure-pt(len, styles)
}
// Convert a ratio type length to pt
//
// page-size: equivalent to 100%
#let convert-ratio-type-to-pt(len, page-size) = {
assert(
is-purely-pt-len(page-size),
message: "'page-size' should be a purely pt length"
)
if page-size == none {
panic("Cannot convert ratio to pt ('page-size' not specified).")
}
if is-infinite-len(page-size) {
return 0pt // page has 'auto' size => % should return 0
}
((len / 1%) / 100) * page-size + 0pt // e.g. 100% / 1% = 100; / 100 = 1; 1 * page-size
}
// Convert a fraction type length to pt
//
// frac-amount: amount of 'fr' specified
// frac-total: total space shared by fractions
#let convert-fraction-type-to-pt(len, frac-amount, frac-total) = {
assert(
is-purely-pt-len(frac-total),
message: "'frac-total' should be a purely pt length"
)
if frac-amount == none {
panic("Cannot convert fraction to pt ('frac-amount' not specified).")
}
if frac-total == none {
panic("Cannot convert fraction to pt ('frac-total' not specified).")
}
if frac-amount <= 0 or is-infinite-len(frac-total) {
return 0pt
}
let len-per-frac = frac-total / frac-amount
(len-per-frac * (len / 1fr)) + 0pt
}
// Convert a relative type length to pt
//
// styles: from style()
// page-size: equivalent to 100% (optional because the length may not have a ratio component)
#let convert-relative-type-to-pt(len, styles, page-size: none) = {
if typst-fields-supported or eval(repr(0.00005em)) != 0.00005em {
// em repr changed in 0.11.0 => need to use fields here
// or use fields if they're supported anyway
return convert-ratio-type-to-pt(len.ratio, page-size) + convert-length-type-to-pt(len.length, styles: styles)
}
// Note on precision: the `repr` for em components is precise, unlike
// other length components, which are rounded to a precision of 2.
// This is true up to Typst 0.9.0 and possibly later versions.
let em-regex = regex(NUMBER-REGEX-STRING + "em")
let em-part-repr = repr(len).find(em-regex)
// Calculate the length minus its em component.
// E.g., 1% + 1pt + 1em -> 1% + 1pt
let (em-part, len-minus-em) = if em-part-repr == none {
(0em, len)
} else {
// SAFETY: guaranteed to be a purely em length by regex
let em-part = eval(em-part-repr)
(em-part, len - em-part)
}
// This will give only the pt part of the length.
// E.g., 1% + 1pt -> 1pt
// See the documentation on measure-pt for more information.
let pt-part = measure-pt(len-minus-em, styles)
// Since we have the values of the em and pt components,
// we can calculate the ratio part.
let ratio-part = len-minus-em - pt-part
let ratio-part-pt = if ratio-part == 0% {
// No point doing `convert-ratio-type-to-pt` if there's no ratio component.
0pt
} else {
convert-ratio-type-to-pt(ratio-part, page-size)
}
// The length part is the pt part + em part.
// Note: we cannot use `len - ratio-part` as that returns a `_rel-len-type` value,
// not a `_length-type` value.
let length-part-pt = convert-length-type-to-pt(pt-part + em-part, styles: styles)
ratio-part-pt + length-part-pt
}
// Convert a certain (non-relative) length to pt
//
// styles: from style()
// page-size: equivalent to 100%
// frac-amount: amount of 'fr' specified
// frac-total: total space shared by fractions
#let convert-length-to-pt(
len,
styles: none, page-size: none, frac-amount: none, frac-total: none
) = {
page-size = 0pt + page-size
if is-infinite-len(len) {
0pt // avoid the destruction of the universe
} else if type(len) == _length-type {
convert-length-type-to-pt(len, styles: styles)
} else if type(len) == _ratio-type {
convert-ratio-type-to-pt(len, page-size)
} else if type(len) == _fraction-type {
convert-fraction-type-to-pt(len, frac-amount, frac-total)
} else if type(len) == _rel-len-type {
convert-relative-type-to-pt(len, styles, page-size: page-size)
} else {
panic("Cannot convert '" + type(len) + "' to length.")
}
}
// Convert a stroke to its thickness
#let stroke-len(stroke, stroke-auto: 1pt, styles: none) = {
let no-ratio-error = "Tablex error: Stroke cannot be a ratio or relative length (i.e. have a percentage like '53%'). Try using the layout() function (or similar) to convert the percentage to 'pt' instead."
let stroke = default-if-auto(stroke, stroke-auto)
if type(stroke) == _length-type {
convert-length-to-pt(stroke, styles: styles)
} else if type(stroke) in (_rel-len-type, _ratio-type) {
panic(no-ratio-error)
} else if is-color(stroke) {
1pt
} else if type(stroke) == _stroke-type {
if typst-fields-supported {
// No need for any repr() parsing, just use the thickness field.
let thickness = default-if-auto(stroke.thickness, 1pt)
return convert-length-to-pt(thickness, styles: styles)
}
// support:
// - 2pt / 2em / 2cm / 2in + color
// - 2.5pt / 2.5em / ... + color
// - 2pt + 3em + color
let len-regex = "(?:" + NUMBER-REGEX-STRING + "(?:em|pt|cm|in|%)(?:\\s+\\+\\s+" + NUMBER-REGEX-STRING + "em)?)"
let r = regex("^" + len-regex)
let s = repr(stroke).find(r)
if s == none {
// for more complex strokes, built through dictionaries
// => "thickness: 5pt" field
// note: on typst v0.7.0 or later, can just use 's.thickness'
let r = regex("thickness: (" + len-regex + ")")
s = repr(stroke).match(r)
if s != none {
s = s.captures.first(); // get the first match (the thickness)
}
}
if s == none {
1pt // okay it's probably just a color then
} else {
let len = eval(s)
if type(len) == _length-type {
convert-length-to-pt(len, styles: styles)
} else if type(len) in (_rel-len-type, _ratio-type) {
panic(no-ratio-error)
} else {
1pt // should be unreachable
}
}
} else if type(stroke) == _dict-type and "thickness" in stroke {
let thickness = stroke.thickness
if type(thickness) == _length-type {
convert-length-to-pt(thickness, styles: styles)
} else if type(thickness) in (_rel-len-type, _ratio-type) {
panic(no-ratio-error)
} else {
1pt
}
} else {
1pt
}
}
// --- end: utility functions ---
// --- grid functions ---
#let create-grid(width, initial_height) = (
tablex-dict-type: "grid",
items: init-array(width * initial_height),
width: width
)
#let is-tablex-grid(value) = is-tablex-dict-type("grid")
// Gets the index of (x, y) in a grid's array.
#let grid-index-at(x, y, grid: none, width: none) = {
width = default-if-none(grid, (width: width)).width
width = calc.floor(width)
(y * width) + calc-mod(x, width)
}
// Gets the cell at the given grid x, y position.
// Width (amount of columns) per line must be known.
// E.g. grid-at(grid, 5, 2, width: 7) => 5th column, 2nd row (7 columns per row)
#let grid-at(grid, x, y) = {
let index = grid-index-at(x, y, width: grid.width)
if index < grid.items.len() {
grid.items.at(index)
} else {
none
}
}
// Returns 'true' if the cell at (x, y)
// exists in the grid.
#let grid-has-pos(grid, x, y) = (
grid-index-at(x, y, grid: grid) < grid.items.len()
)
// How many rows are in this grid? (Given its width)
#let grid-count-rows(grid) = (
calc.floor(grid.items.len() / grid.width)
)
// Converts a grid array index to (x, y)
#let grid-index-to-pos(grid, index) = (
(calc-mod(index, grid.width), calc.floor(index / grid.width))
)
// Fetches an entire row of cells (all positions with the given y).
#let grid-get-row(grid, y) = {
let len = grid.items.len()
// position of the first cell in that row.
let first-row-pos = grid-index-at(0, y, grid: grid)
if len <= first-row-pos {
// grid isn't large enough, so no row to return
(none,) * grid.width
} else {
// position right after the last cell in this row
let next-row-pos = first-row-pos + grid.width
let cell-row = grid.items.slice(first-row-pos, calc.min(len, next-row-pos))
let cell-row-len = cell-row.len()
if cell-row-len < grid.width {
// the row isn't complete because the grid wasn't large enough.
let missing-cells = (none,) * (grid.width - cell-row-len)
cell-row += missing-cells
}
cell-row
}
}
// Fetches an entire column of cells (all positions with the given x).
#let grid-get-column(grid, x) = {
range(grid-count-rows(grid)).map(y => grid-at(grid, x, y))
}
// Expand grid to the given coords (add the missing cells)
#let grid-expand-to(grid, x, y, fill_with: (grid) => none) = {
let rows = grid-count-rows(grid)
let rowws = rows
// quickly add missing rows
while rows < y {
grid.items += (fill_with(grid),) * grid.width
rows += 1
}
let now = grid-index-to-pos(grid, grid.items.len() - 1)
// now columns and/or last missing row
while not grid-has-pos(grid, x, y) {
grid.items.push(fill_with(grid))
}
let new = grid-index-to-pos(grid, grid.items.len() - 1)
grid
}
// if occupied (extension of a cell) => get the cell that generated it.
// if a normal cell => return it, untouched.
#let get-parent-cell(cell, grid: none) = {
if is-tablex-occupied(cell) {
grid-at(grid, cell.parent_x, cell.parent_y)
} else if is-tablex-cell(cell) {
cell
} else {
panic("Cannot get parent table cell of a non-cell object: " + repr(cell))
}
}
// Return the next position available on the grid
#let next-available-position(
grid, x: 0, y: 0, x_limit: 0, y_limit: 0
) = {
let cell = (x, y)
let there_is_next(cell_pos) = {
let grid_cell = grid-at(grid, ..cell_pos)
grid_cell != none
}
while there_is_next(cell) {
x += 1
if x >= x_limit {
x = 0
y += 1
}
cell = (x, y)
if y >= y_limit { // last row reached - stop
break
}
}
cell
}
// Organize cells in a grid from the given items,
// and also get all given lines
#let generate-grid(items, x_limit: 0, y_limit: 0, map-cells: none, fit-spans: none) = {
// init grid as a matrix
// y_limit x x_limit
let grid = create-grid(x_limit, y_limit)
let grid-index-at = grid-index-at.with(width: x_limit)
let hlines = ()
let vlines = ()
let prev_x = 0
let prev_y = 0
let x = 0
let y = 0
let first_cell_reached = false // if true, hline should always be placed after the current row
let row_wrapped = false // if true, a vline should be added to the end of a row
let range_of_items = range(items.len())
let new_empty_cell(grid, index: auto) = {
let empty_cell = cellx[]
let index = default-if-auto(index, grid.items.len())
let new_cell_pos = grid-index-to-pos(grid, index)
empty_cell.x = new_cell_pos.at(0)
empty_cell.y = new_cell_pos.at(1)
empty_cell
}
// go through all input
for i in range_of_items {
let item = items.at(i)
// allow specifying () to change vline position
if type(item) == _array-type and item.len() == 0 {
if x == 0 and y == 0 { // increment vline's secondary counter
prev_x += 1
}
continue // ignore all '()'
}
let item = table-item-convert(item)
if is-some-tablex-line(item) { // detect lines' x, y
if is-tablex-hline(item) {
let this_y = if first_cell_reached {
prev_y + 1
} else {
prev_y
}
item.y = default-if-auto(item.y, this_y)
hlines.push(item)
} else if is-tablex-vline(item) {
if item.x == auto {
if x == 0 and y == 0 { // placed before any elements
item.x = prev_x
prev_x += 1 // use this as a 'secondary counter'
// in the meantime
if prev_x > x_limit + 1 {
panic("Error: Specified way too many vlines or empty () cells before the first row of the table. (Note that () is used to separate vline()s at the beginning of the table.) Please specify at most " + str(x_limit + 1) + " empty cells or vlines before the first cell of the table.")
}
} else if row_wrapped {
item.x = x_limit // allow v_line at the last column
row_wrapped = false
} else {
item.x = x
}
}
vlines.push(item)
} else {
panic("Invalid line received (must be hline or vline).")
}
items.at(i) = item // override item with the new x / y coord set
continue
}
let cell = item
assert(is-tablex-cell(cell), message: "All table items must be cells or lines.")
first_cell_reached = true
let this_x = default-if-auto(cell.x, x)
let this_y = default-if-auto(cell.y, y)
if cell.x == none or cell.y == none {
panic("Error: Received cell with 'none' as x or y.")
}
if this_x == none or this_y == none {
panic("Internal tablex error: Grid wasn't large enough to fit the given cells. (Previous position: " + repr((prev_x, prev_y)) + ", new cell: " + repr(cell) + ")")
}
cell.x = this_x
cell.y = this_y
if type(map-cells) == _function-type {
cell = table-item-convert(map-cells(cell))
}
assert(is-tablex-cell(cell), message: "Tablex error: 'map-cells' returned something that isn't a valid cell.")
if row_wrapped {
row_wrapped = false
}
let content = cell.content
let content = if type(content) == _function-type {
let res = content(this_x, this_y)
if is-tablex-cell(res) {
cell = res
this_x = cell.x
this_y = cell.y
[#res.content]
} else {
[#res]
}
} else {
[#content]
}
if this_x == none or this_y == none {
panic("Error: Cell with function as content returned another cell with 'none' as x or y!")
}
if type(this_x) != _int-type or type(this_y) != _int-type {
panic("Error: Cell coordinates must be integers. Invalid pair: " + repr((this_x, this_y)))
}
cell.content = content
// resolve 'fit-spans' option for this cell
if "fit-spans" not in cell {
cell.fit-spans = auto
} else if cell.fit-spans != auto {
cell.fit-spans = validate-fit-spans(cell.fit-spans, default: fit-spans, error-prefix: "At cell (" + str(this_x) + ", " + str(this_y) + "):")
}
// up to which 'y' does this cell go
let max_x = this_x + cell.colspan - 1
let max_y = this_y + cell.rowspan - 1
if this_x >= x_limit {
panic("Error: Cell at " + repr((this_x, this_y)) + " is placed at an inexistent column.")
}
if max_x >= x_limit {
panic("Error: Cell at " + repr((this_x, this_y)) + " has a colspan of " + repr(cell.colspan) + ", which would exceed the available columns.")
}
let cell_positions = positions-spanned-by(cell, x: this_x, y: this_y, x_limit: x_limit, y_limit: none)
for position in cell_positions {
let (px, py) = position
let currently_there = grid-at(grid, px, py)
if currently_there != none {
let parent_cell = get-parent-cell(currently_there, grid: grid)
panic("Error: Multiple cells attempted to occupy the cell position at " + repr((px, py)) + ": one starting at " + repr((this_x, this_y)) + ", and one starting at " + repr((parent_cell.x, parent_cell.y)))
}
// initial position => assign it to the cell's x/y
if position == (this_x, this_y) {
cell.x = this_x
cell.y = this_y
// expand grid to allow placing this cell (including colspan / rowspan)
let grid_expand_res = grid-expand-to(grid, grid.width - 1, max_y)
grid = grid_expand_res