summaryrefslogtreecommitdiff
path: root/tex/context/base/mkiv/page-cst.lua
blob: 583e6af0cad4273e5e352770125090c23ba4477c (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
if not modules then modules = { } end modules ["page-cst"] = {
    version   = 1.001,
    comment   = "companion to page-cst.mkiv",
    author    = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
    copyright = "PRAGMA ADE / ConTeXt Development Team",
    license   = "see context related readme files"
}

-- todo: check what is used

local next, type, tonumber = next, type, tonumber
local ceil, odd, round = math.ceil, math.odd, math.round
local lower = string.lower
local copy = table.copy

local trace_state   = false  trackers.register("columnsets.trace",   function(v) trace_state  = v end)
local trace_details = false  trackers.register("columnsets.details", function(v) trace_details = v end)
local trace_cells   = false  trackers.register("columnsets.cells",   function(v) trace_cells  = v end)

local report       = logs.reporter("column sets")

local setmetatableindex = table.setmetatableindex

local properties        = nodes.properties.data

local nodecodes         = nodes.nodecodes

local hlist_code        = nodecodes.hlist
local vlist_code        = nodecodes.vlist
local kern_code         = nodecodes.kern
local glue_code         = nodecodes.glue
local penalty_code      = nodecodes.penalty
local rule_code         = nodecodes.rule

local nuts              = nodes.nuts
local tonode            = nuts.tonode
local tonut             = nuts.tonut

local hpack             = nuts.hpack
local vpack             = nuts.vpack
local flushlist         = nuts.flush_list
----- removenode        = nuts.remove

local setlink           = nuts.setlink
local setlist           = nuts.setlist
local setnext           = nuts.setnext
local setprev           = nuts.setprev
local setsubtype        = nuts.setsubtype
local setbox            = nuts.setbox
local getwhd            = nuts.getwhd
local setwhd            = nuts.setwhd
local getkern           = nuts.getkern
local getpenalty        = nuts.getpenalty
local getwidth          = nuts.getwidth
local getheight         = nuts.getheight

local getnext           = nuts.getnext
local getprev           = nuts.getprev
local getid             = nuts.getid
local getlist           = nuts.getlist
local getsubtype        = nuts.getsubtype
local takebox           = nuts.takebox
local takelist          = nuts.takelist
local splitbox          = nuts.splitbox
local getattribute      = nuts.getattribute
local copylist          = nuts.copy_list

local getbox            = nuts.getbox
local getcount          = tex.getcount
local getdimen          = tex.getdimen

local texsetbox         = tex.setbox
local texsetcount       = tex.setcount
local texsetdimen       = tex.setdimen

local theprop           = nuts.theprop

local nodepool          = nuts.pool

local new_vlist         = nodepool.vlist
local new_trace_rule    = nodepool.rule
local new_empty_rule    = nodepool.emptyrule

local context           = context
local implement         = interfaces.implement

local variables         = interfaces.variables
local v_here            = variables.here
local v_fixed           = variables.fixed
local v_top             = variables.top
local v_bottom          = variables.bottom
local v_repeat          = variables["repeat"]
local v_yes             = variables.yes
local v_page            = variables.page
local v_first           = variables.first
local v_last            = variables.last
----- v_wide            = variables.wide

pagebuilders            = pagebuilders or { } -- todo: pages.builders
pagebuilders.columnsets = pagebuilders.columnsets or { }
local columnsets        = pagebuilders.columnsets

local data = { [""] = { } }

-- todo: use state

local function setstate(t,start)
    if start or not t.firstcolumn then
        t.firstcolumn = odd(getcount("realpageno")) and 1 or 2
    end
    if t.firstcolumn > 1 then
        t.firstcolumn = 1
        t.lastcolumn  = t.nofleft
        t.state       = "left"
    else
        t.firstcolumn = t.nofleft + 1
        t.lastcolumn  = t.firstcolumn + t.nofright - 1
        t.state       = "right"
    end
    t.currentcolumn = t.firstcolumn
    t.currentrow    = 1
end

function columnsets.define(t)
    local name            = t.name
    local nofleft         = t.nofleft or 1
    local nofright        = t.nofright or 1
    local nofcolumns      = nofleft + nofright
    local dataset         = data[name] or { }
    data[name]            = dataset
    dataset.nofleft       = nofleft
    dataset.nofright      = nofright
    dataset.nofcolumns    = nofcolumns
    dataset.nofrows       = t.nofrows or 1
    dataset.distance      = t.distance or getdimen("bodyfontsize")
    dataset.maxwidth      = t.maxwidth or getdimen("makeupwidth")
    dataset.lineheight    = t.lineheight or getdimen("globalbodyfontstrutheight")
    dataset.linedepth     = t.linedepth or getdimen("globalbodyfontstrutdepth")
    --
    dataset.cells         = { }
    dataset.currentcolumn = 1
    dataset.currentrow    = 1
    --
    dataset.lines         = dataset.lines or setmetatableindex("table")
    dataset.start         = dataset.start or setmetatableindex("table")
    --
    dataset.page          = 1
    --
    local distances = dataset.distances or setmetatableindex(function(t,k)
        return dataset.distance
    end)
    dataset.distances = distances
    --
    local widths = dataset.widths or setmetatableindex(function(t,k)
        return dataset.width
    end)
    dataset.widths = widths
    --
    local width = t.width
    if not width or width == 0 then
        local dl = 0
        local dr = 0
        for i=1,nofleft-1 do
            dl = dl + distances[i]
        end
        for i=1,nofright-1 do
            dr = dr + distances[nofleft+i]
        end
        local nl = nofleft
        local nr = nofright
        local wl = dataset.maxwidth
        local wr = wl
        for i=1,nofleft do
            local w = rawget(widths,i)
            if w then
                nl = nl - 1
                wl = wl - w
            end
        end
        for i=1,nofright do
            local w = rawget(widths,nofleft+i)
            if w then
                nr = nr - 1
                wr = wr - w
            end
        end
        dl = (wl - dl) / nl
        dr = (wr - dr) / nr
        if dl > dr then
            report("using %s page column width %p in columnset %a","right",dr,name)
            width = dr
        elseif dl < dr then
            report("using %s page column width %p in columnset %a","left",dl,name)
            width = dl
        else
            width = dl
        end
    end
 -- report("width %p, nleft %i, nright %i",width,nofleft,nofright)
    width         = round(width)
    dataset.width = width
    local spans   = { }
    dataset.spans = spans
    for i=1,nofleft do
        local s = { }
        local d = 0
        for j=1,nofleft-i+1 do
            d = d + width
            s[j] = round(d)
            d = d + distances[j]
        end
        spans[i]  = s
    end
    for i=1,nofright do
        local s = { }
        local d = 0
        for j=1,nofright-i+1 do
            d = d + width
            s[j] = round(d)
            d = d + distances[j]
        end
        spans[nofleft+i]  = s
    end
    --
    local spreads   = copy(spans)
    dataset.spreads = spreads
    local gap       = 2 * getdimen("backspace")
    for l=1,nofleft do
        local s = spreads[l]
        local n = #s
        local o = s[n] + gap
        for r=1,nofright do
            n = n + 1
            s[n] = s[r] + o
        end
    end
    --
    texsetdimen("d_page_grd_column_width",dataset.width)
    --
    setstate(dataset,true)
    --
    return dataset
end

local function check(dataset)
    local cells  = dataset.cells
    local page   = dataset.page
    local offset = odd(page) and dataset.nofleft or 0
    local start  = dataset.start
    local list   = rawget(start,page)
    if list then
        for c, n in next, list do
            local column = cells[offset + c]
            if column then
                for r=1,n do
                    column[r] = true
                end
            end
        end
        start[page] = nil
    end
    local lines = dataset.lines
    local list  = rawget(lines,page)
    local rows  = dataset.nofrows
    if list then
        for c, n in next, list do
            local column = cells[offset + c]
            if column then
                if n > 0 then
                    for r=n+1,rows do
                        column[r] = true
                    end
                elseif n < 0 then
                    for r=rows,rows+n+1,-1 do
                        column[r] = true
                    end
                end
            end
        end
        lines[page] = nil
    end
end

local function erase(dataset,all)
    local cells   = dataset.cells
    local nofrows = dataset.nofrows
    local first   = 1
    local last    = dataset.nofcolumns
    --
    if not all then
        first = dataset.firstcolumn or first
        last  = dataset.lastcolumn  or last
    end
    for c=first,last do
        local column = { }
        for r=1,nofrows do
            if column[r] then
                report("slot (%i,%i) is not empty",c,r)
            end
            column[r] = false -- not used
        end
        cells[c] = column
    end
end

function columnsets.reset(t)
    local dataset = columnsets.define(t)
    erase(dataset,true)
    check(dataset)
end

function columnsets.prepareflush(name)
    local dataset     = data[name]
    local cells       = dataset.cells
    local firstcolumn = dataset.firstcolumn
    local lastcolumn  = dataset.lastcolumn
    local nofrows     = dataset.nofrows
    local lineheight  = dataset.lineheight
    local linedepth   = dataset.linedepth
    local widths      = dataset.widths
    local height      = (lineheight+linedepth)*nofrows -- - linedepth
    --
    local columns     = { }
    dataset.columns   = columns
    --
    for c=firstcolumn,lastcolumn do
        local column = cells[c]
        for r=1,nofrows do
            local cell = column[r]
            if (cell == false) or (cell == true) then
                if trace_cells then
                    column[r] = new_trace_rule(65536*2,lineheight,linedepth)
                else
                    column[r] = new_empty_rule(0,lineheight,linedepth)
                end
            end
        end
        for r=1,nofrows-1 do
            setlink(column[r],column[r+1])
        end
        columns[c] = new_vlist(column[1],widths[c],height,0) -- linedepth
    end
    --
    texsetcount("c_page_grd_first_column",firstcolumn)
    texsetcount("c_page_grd_last_column",lastcolumn)
end

function columnsets.flushcolumn(name,column)
    local dataset = data[name]
    local columns = dataset.columns
    local packed  = columns[column]
    setbox("b_page_grd_column",packed)
    columns[column] = nil
end

function columnsets.finishflush(name)
    local dataset     = data[name]
    local cells       = dataset.cells
    local firstcolumn = dataset.firstcolumn
    local lastcolumn  = dataset.lastcolumn
    local nofrows     = dataset.nofrows
    for c=firstcolumn,lastcolumn do
        local column = { }
        for r=1,nofrows do
            column[r] = false -- not used
        end
        cells[c] = column
    end
    dataset.page = dataset.page + 1
    check(dataset)
    setstate(dataset)
end

function columnsets.block(t)
    local dataset    = data[t.name]
    local cells      = dataset.cells
    local nofcolumns = dataset.nofcolumns
    local nofrows    = dataset.nofrows
    --
    local c = t.c or 0
    local r = t.r or 0
    if c == 0 or r == 0 or c > nofcolumns or r > nofrows then
        return
    end
    local nc = t.nc or 0
    local nr = t.nr or 0
    if nc == 0 then
        return
    end
    if nr == 0 then
        return
    end
    local rr = r + nr - 1
    local cc = c + nc - 1
    if rr > nofrows then
        rr = nofrows
    end
    if cc > nofcolumns then
        cc = nofcolumns
    end
    for i=c,cc do
        local column = cells[i]
        for j=r,rr do
            column[j] = true
        end
    end
end

local function here(c,r,nr,nofcolumns,nofrows,cells,width,spans)
    local rr = r + nr - 1
    if rr > nofrows then
        return false
    end
    local cc = 0
    local wd = spans[c]
    local wc = 0
    local nc = 0
    for i=c,nofcolumns do
        nc = nc + 1
        wc = wd[nc]
        if not wc then
            break
        elseif wc >= width then
            cc = i
            break
        end
    end
    if cc == 0 or cc > nofcolumns then
     -- report("needed %p, no slot free at (%i,%i)",width,c,r)
        return false
    end
    for i=c,cc do
        local column = cells[i]
        for j=r,rr do
            if column[j] then
             -- report("width %p, needed %p, checking (%i,%i) x (%i,%i), %s",width,wc,c,r,nc,nr,"quit")
                return false
            end
        end
    end
 -- report("width %p, needed %p, checking (%i,%i) x (%i,%i), %s",width,wc,c,r,nc,nr,"match")
    return c, r, nc
end

-- we use c/r as range limiters

local methods = {
    [v_here] = here,
    [v_fixed] = here,
    tblr = function(c,r,nr,nofcolumns,nofrows,cells,width,spans)
        for j=r,nofrows-nr+1 do
            for i=c,nofcolumns do
                if not cells[i][j] then
                    local c, r, cc = here(i,j,nr,nofcolumns,nofrows,cells,width,spans)
                    if c then
                        return c, r, cc
                    end
                end
            end
        end
    end,
    lrtb = function(c,r,nr,nofcolumns,nofrows,cells,width,spans)
        for i=c,nofcolumns do
            for j=r,nofrows-nr+1 do
                if not cells[i][j] then
                    local c, r, cc = here(i,j,nr,nofcolumns,nofrows,cells,width,spans)
                    if c then
                        return c, r, cc
                    end
                end
            end
        end
    end,
    tbrl = function(c,r,nr,nofcolumns,nofrows,cells,width,spans)
        for j=r,nofrows-nr+1 do
            for i=nofcolumns,c,-1 do
                if not cells[i][j] then
                    local c, r, cc = here(i,j,nr,nofcolumns,nofrows,cells,width,spans)
                    if c then
                        return c, r, cc
                    end
                end
            end
        end
    end,
    rltb = function(c,r,nr,nofcolumns,nofrows,cells,width,spans)
        for i=nofcolumns,c,-1 do
            for j=r,nofrows-nr+1 do
                if not cells[i][j] then
                    local c, r, cc = here(i,j,nr,nofcolumns,nofrows,cells,width,spans)
                    if c then
                        return c, r, cc
                    end
                end
            end
        end
    end,
    btlr = function(c,r,nr,nofcolumns,nofrows,cells,width,spans)
     -- for j=nofrows-nr+1,1,-1 do
        for j=nofrows-nr+1-r+1,1,-1 do
            for i=c,nofcolumns do
                if not cells[i][j] then
                    local c, r, cc = here(i,j,nr,nofcolumns,nofrows,cells,width,spans)
                    if c then
                        return c, r, cc
                    end
                end
            end
        end
    end,
    lrbt = function(c,r,nr,nofcolumns,nofrows,cells,width,spans)
        for i=c,nofcolumns do
         -- for j=nofrows-nr+1,1,-1 do
            for j=nofrows-nr+1-r+1,1,-1 do
                if not cells[i][j] then
                    local c, r, cc = here(i,j,nr,nofcolumns,nofrows,cells,width,spans)
                    if c then
                        return c, r, cc
                    end
                end
            end
        end
    end,
    btrl = function(c,r,nr,nofcolumns,nofrows,cells,width,spans)
     -- for j=nofrows-nr+1,1,-1 do
        for j=nofrows-nr+1-r+1,1,-1 do
            for i=nofcolumns,c,-1 do
                if not cells[i][j] then
                    local c, r, cc = here(i,j,nr,nofcolumns,nofrows,cells,width,spans)
                    if c then
                        return c, r, cc
                    end
                end
            end
        end
    end,
    rlbt = function(c,r,nr,nofcolumns,nofrows,cells,width,spans)
        for i=nofcolumns,c,-1 do
         -- for j=nofrows-nr+1,1,-1 do
            for j=nofrows-nr+1-r+1,1,-1 do
                if not cells[i][j] then
                    local c, r, cc = here(i,j,nr,nofcolumns,nofrows,cells,width,spans)
                    if c then
                        return c, r, cc
                    end
                end
            end
        end
    end,
    fxtb = function(c,r,nr,nofcolumns,nofrows,cells,width,spans)
        for i=c,nofcolumns do
            for j=r,nofrows-nr+1 do
                if not cells[i][j] then
                    local c, r, cc = here(i,j,nr,nofcolumns,nofrows,cells,width,spans)
                    if c then
                        return c, r, cc
                    end
                end
                r = 1
            end
        end
    end,
    fxbt = function(c,r,nr,nofcolumns,nofrows,cells,width,spans)
        for i=c,nofcolumns do
            for j=nofrows-nr+1,r,-1 do
                if not cells[i][j] then
                    local c, r, cc = here(i,j,nr,nofcolumns,nofrows,cells,width,spans)
                    if c then
                        return c, r, cc
                    end
                end
            end
            r = 1
        end
    end,
    [v_top] = function(c,r,nr,nofcolumns,nofrows,cells,width,spans)
        for i=c,nofcolumns do
            for j=1,nofrows-nr+1 do
                if cells[i][j] then
                    break
                else
                    local c, r, cc = here(i,j,nr,nofcolumns,nofrows,cells,width,spans)
                    if c then
                        return c, r, cc
                    end
                end
            end
        end
    end,
    [v_bottom] = function(c,r,nr,nofcolumns,nofrows,cells,width,spans)
        for i=c,nofcolumns do
            for j=1,nofrows-nr+1 do
                if cells[i][j] then
                    break
                else
                    local c, r, cc = here(i,j,nr,nofcolumns,nofrows,cells,width,spans)
                    if c then
                        return c, r, cc
                    end
                end
            end
        end
    end,
}

local threshold = 50

function columnsets.check(t)
    local dataset    = data[t.name]
    local cells      = dataset.cells
    local nofcolumns = dataset.nofcolumns
    local nofrows    = dataset.nofrows
    local widths     = dataset.widths
    local lineheight = dataset.lineheight
    local linedepth  = dataset.linedepth
    local distances  = dataset.distances
    local spans      = dataset.spans
    --
    local method     = lower(t.method or "tblr")
    local boxwidth   = t.width  or 0
    local boxheight  = t.height or 0
    local boxnumber  = t.box
    local box        = boxnumber and getbox(boxnumber)
    --
    if boxwidth > 0 and boxheight > 0 then
        -- we're ok
    elseif box then
        local wd, ht, dp = getwhd(box)
        boxwidth  = wd
        boxheight = ht + dp
    else
        report("empty box")
        return
    end
    --
    local c = t.c or 0
    local r = t.r or 0
    if c == 0 then
        c = dataset.currentcolumn
    end
    if r == 0 then
        r = dataset.currentrow
    end
    if c == 0 or r == 0 or c > nofcolumns or r > nofrows then
        texsetcount("c_page_grd_reserved_state",5)
        return
    end
 -- report("checking width %p, height %p, depth %p, slot (%i,%i)",boxwidth,boxheight,boxdepth,c,r)
    local nr = ceil(boxheight/(lineheight+linedepth))
    --
    local action = methods[method]
    local cfound = false
    local rfound = false
    local lastcolumn = dataset.lastcolumn
 -- if t.option == v_wide then
 --     lastcolumn = nofcolumns
 --     spans = dataset.spreads
 -- end
    if action then
        cfound, rfound, nc = action(c,r,nr,lastcolumn,nofrows,cells,boxwidth-threshold,spans)
    end
    if not cfound and method ~= v_here then
        cfound, rfound, nc = here(c,r,nr,lastcolumn,nofrows,cells,boxwidth-threshold,spans)
    end
    if cfound then
        local ht = nr*(lineheight+linedepth)
        local wd = spans[cfound][nc]
        dataset.reserved_ht = ht
        dataset.reserved_wd = wd
        dataset.reserved_c  = cfound
        dataset.reserved_r  = rfound
        dataset.reserved_nc = nc
        dataset.reserved_nr = nr
        texsetcount("c_page_grd_reserved_state",0)
        texsetdimen("d_page_grd_reserved_height",ht)
        texsetdimen("d_page_grd_reserved_width",wd)
     -- report("using (%i,%i) x (%i,%i) @ (%p,%p)",cfound,rfound,nc,nr,wd,ht)
    else
        dataset.reserved_ht = false
        dataset.reserved_wd = false
        dataset.reserved_c  = false
        dataset.reserved_r  = false
        dataset.reserved_nc = false
        dataset.reserved_nr = false
        texsetcount("c_page_grd_reserved_state",4)
     -- texsetdimen("d_page_grd_reserved_height",0)
     -- texsetdimen("d_page_grd_reserved_width",0)
     -- report("no slot found")
    end
end

function columnsets.put(t)
    local dataset    = data[t.name]
    local cells      = dataset.cells
    local widths     = dataset.widths
    local lineheight = dataset.lineheight
    local linedepth  = dataset.linedepth
    local boxnumber  = t.box
    local box        = boxnumber and takebox(boxnumber)
    --
    local c = t.c or dataset.reserved_c
    local r = t.r or dataset.reserved_r
    if not c or not r then
     -- report("no reserved slot (%i,%i)",c,r)
        return
    end
    local lastc = c + dataset.reserved_nc - 1
    local lastr = r + dataset.reserved_nr - 1
    --
    for i=c,lastc do
        local column = cells[i]
        for j=r,lastr do
            column[j] = true
        end
    end
    cells[c][r] = box
    setwhd(box,widths[c],lineheight,linedepth)
    dataset.reserved_c  = false
    dataset.reserved_r  = false
    dataset.reserved_nc = false
    dataset.reserved_nr = false
    --
end

local function findgap(dataset)
    local cells         = dataset.cells
    local nofcolumns    = dataset.nofcolumns
    local nofrows       = dataset.nofrows
    local currentrow    = dataset.currentrow
    local currentcolumn = dataset.currentcolumn
    --
    local foundc = 0
    local foundr = 0
    local foundn = 0
    for c=currentcolumn,dataset.lastcolumn do
        local column = cells[c]
foundn = 0
        for r=currentrow,nofrows do
            if not column[r] then
                if foundc == 0 then
                    foundc = c
                    foundr = r
                end
                foundn = foundn + 1
            elseif foundn > 0 then
                return foundc, foundr, foundn
            end
        end
        if foundn > 0 then
            return foundc, foundr, foundn
        end
        currentrow = 1
    end
end

-- we can enforce grid snapping

-- local function checkroom(head,available,row)
--     if row == 1 then
--         while head do
--             local id = getid(head)
--             if id == glue_code then
--                 head = getnext(head)
--             else
--                 break
--             end
--         end
--     end
--     local used = 0
--     local line = false
--     while head do
--         local id = getid(head)
--         if id == hlist_code or id == vlist_code or id == rule_code then -- <= rule_code
--             local wd, ht, dp = getwhd(head)
--             used = used + ht + dp
--             line = true
--         elseif id == glue_code then
--             if line then
--                 break
--             end
--             used = used + getwidth(head)
--         elseif id == kern_code then
--             used = used +  getkern(head)
--         elseif id == penalty_code then
--         end
--         if used > available then
--             break
--         end
--         head = getnext(head)
--     end
--     return line, used
-- end

local function checkroom(head,available,row)
    if row == 1 then
        while head do
            local id = getid(head)
            if id == glue_code then
                head = getnext(head)
            else
                break
            end
        end
    end
    local used = 0
    local line = false
    while head do
        local id = getid(head)
        if id == hlist_code or id == vlist_code or id == rule_code then -- <= rule_code
            local wd, ht, dp = getwhd(head)
            used = used + ht + dp
            line = true
            if used > available then
                break
            end
        elseif id == glue_code then
            if line then
                break
            end
            used = used + getwidth(head)
            if used > available then
                break
            end
        elseif id == kern_code then
            used = used + getkern(head)
            if used > available then
                break
            end
        elseif id == penalty_code then
            -- not good enough ... we need to look bakck too
            if getpenalty(head) >= 10000 then
                line = false
            else
                break
            end
        end
        head = getnext(head)
    end
    return line, used
end

-- we could preroll on a cheap copy .. in fact, a split loop normally works on
-- a copy ... then we could also stepsise make the height smaller .. slow but nice

-- local function findslice(dataset,head,available,column,row)
--     local used       = 0
--     local first      = nil
--     local last       = nil
--     local line       = false
--     local lineheight = dataset.lineheight
--     local linedepth  = dataset.linedepth
--     if row == 1 then
--         while head do
--             local id = getid(head)
--             if id == glue_code then
--                 head = removenode(head,head,true)
--             else
--                 break
--             end
--         end
--     end
--     while head do
--         -- no direction yet, if so use backend code
--         local id = getid(head)
--         local hd = 0
--         if id == hlist_code or id == vlist_code or id == rule_code then -- <= rule_code
--             local wd, ht, dp = getwhd(head)
--             hd = ht + dp
--         elseif id == glue_code then
--             hd = getwidth(head)
--         elseif id == kern_code then
--             hd = getkern(head)
--         elseif id == penalty_code then
--         end
--         if used + hd > available then
--             if first then
--                 setnext(last)
--                 setprev(head)
--                 return used, first, head
--             else
--                 return 0
--             end
--         else
--             if not first then
--                 first = head
--             end
--             used = used + hd
--             last = head
--             head = getnext(head)
--         end
--     end
--     return used, first
-- end

--  todo
--
--                 first = takelist(done)
--                 head = takelist(rest)
--                 local tail = nuts.tail(first)
--                 if false then
--                     local disc = tex.lists.split_discards_head
--                     if disc then
--                         disc = tonut(disc)
--                         setlink(tail,disc)
--                         tail = nuts.tail(disc)
--                         tex.lists.split_discards_head = nil
--                     end
--                 end
--                 setlink(tail,head)

-- We work on a copy because we need to keep properties. We can make faster copies
-- by only doing a one-level deep copy.

local function findslice(dataset,head,available,column,row)
    local first      = nil
    local lineheight = dataset.lineheight
    local linedepth  = dataset.linedepth
    local linetotal  = lineheight + linedepth
    local slack      = 65536 -- 1pt
    local copy       = copylist(head)
    local attempts   = 0
    local usedsize   = available
    while true do
        attempts = attempts + 1
        texsetbox("scratchbox",tonode(new_vlist(copy)))
        local done = splitbox("scratchbox",usedsize,"additional")
        local used = getheight(done)
        local rest = takebox("scratchbox")
        if used > (usedsize+slack) then
            if trace_details then
                report("at (%i,%i) available %p, used %p, overflow %p",column,row,usedsize,used,used-usedsize)
            end
            -- flush copy
            flushlist(takelist(done))
            flushlist(takelist(rest))
            -- check it we can try again
            usedsize = usedsize - linetotal
            if usedsize > linetotal then
                copy = copylist(head)
            else
                return 0, nil, head
            end
        else
            -- flush copied box
            flushlist(takelist(done))
            flushlist(takelist(rest))
            -- deal with real data
            texsetbox("scratchbox",tonode(new_vlist(head)))
            done  = splitbox("scratchbox",usedsize,"additional")
            rest  = takebox("scratchbox")
            used  = getheight(done)
            if attempts > 1 then
                used = available
            end
            first = takelist(done)
            head  = takelist(rest)
            -- return result
            return used, first, head
        end
    end
end

local nofcolumngaps = 0

function columnsets.add(name,box)
    local dataset       = data[name]
    local cells         = dataset.cells
    local nofcolumns    = dataset.nofcolumns
    local nofrows       = dataset.nofrows
    local currentrow    = dataset.currentrow
    local currentcolumn = dataset.currentcolumn
    local lineheight    = dataset.lineheight
    local linedepth     = dataset.linedepth
    local widths        = dataset.widths
    --
    local b = getbox(box)
    local l = getlist(b)
-- dataset.rest = l
    if l then
        setlist(b,nil)
        local hd = lineheight + linedepth
        while l do
            local foundc, foundr, foundn = findgap(dataset)
            if foundc then
                local available = foundn * hd
                local used, first, last = findslice(dataset,l,available,foundc,foundr)
                if first then
                    local v
                    if used == available or (foundr+foundn > nofrows) then
                        v = vpack(first,available,"exactly")
                    else
                        v = new_vlist(first)
                    end
                    nofcolumngaps = nofcolumngaps + 1
                    -- getmetatable(v).columngap = nofcolumngaps
                    properties[v] = { columngap = nofcolumngaps }
                 -- report("setting gap %a at (%i,%i)",nofcolumngaps,foundc,foundr)
                    setwhd(v,widths[currentcolumn],lineheight,linedepth)
                    local column = cells[foundc]
                    --
                    column[foundr] = v
                    used = used - hd
                    if used > 0 then
                        for r=foundr+1,foundr+foundn-1 do
                            used = used - hd
                            foundr = foundr + 1
                            column[r] = true
                            if used <= 0 then
                                break
                            end
                        end
                    end
                    currentcolumn = foundc
                    currentrow    = foundr
                    dataset.currentcolumn = currentcolumn
                    dataset.currentrow    = currentrow
                    l = last
                    dataset.rest = l
                else
                    local column = cells[foundc]
                    for i=foundr,foundr+foundn-1 do
                        column[i] = true
                    end
                    l = last
                end
            else
                dataset.rest = l
                return -- save and flush
            end
        end
    end
end

do

    -- A split approach is more efficient than a context(followup) inside
    -- followup itself as we need less (internal) housekeeping.

    local followup = nil
    local splitter = lpeg.splitter("*",tonumber)

    columnsets["noto"] = function(t)
        return followup()
    end

    columnsets["goto"] = function(name,target)
        local dataset    = data[name]
        local nofcolumns = dataset.nofcolumns
        if target == v_yes or target == "" then
            local currentcolumn = dataset.currentcolumn
            followup = function()
                context(dataset.currentcolumn == currentcolumn and 1 or 0)
            end
            return followup()
        end
        if target == v_first then
            if dataset.currentcolumn > 1  then
                target = v_page
            else
                return context(0)
            end
        end
        if target == v_page then
            if dataset.currentcolumn == 1 and dataset.currentrow == 1 then
                return context(0)
            else
                local currentpage = dataset.page
                followup = function()
                    context(dataset.page == currentpage and 1 or 0)
                end
                return followup()
            end
        end
        if target == v_last then
            target = dataset.nofcolumns
            if dataset.currentcolumn ~= target then
                followup = function()
                    context(dataset.currentcolumn ~= target and 1 or 0)
                end
                return followup()
            end
            return
        end
        local targetpage = tonumber(target)
        if targetpage then
            followup = function()
                context(dataset.currentcolumn ~= targetpage and 1 or 0)
            end
            return followup()
        end
        local targetcolumn, targetrow = lpeg.match(splitter,target)
        if targetcolumn and targetrow then
            if dataset.currentcolumn ~= targetcolumn and dataset.currentrow ~= targetrow then
                followup = function()
                    if dataset.currentcolumn ~= targetcolumn then
                        context(1)
                        return
                    end
                    if dataset.currentcolumn == targetcolumn then
                        context(dataset.currentrow ~= targetrow and 1 or 0)
                    else
                        context(0)
                    end
                end
                return followup()
            end
        end
    end

end

function columnsets.currentcolumn(name)
    local dataset = data[name]
    context(dataset.currentcolumn)
end

function columnsets.flushrest(name,box)
    local dataset = data[name]
    local rest    = dataset.rest
    if rest then
        dataset.rest = nil
        setbox("global",box,new_vlist(rest))
    end
end

function columnsets.setvsize(name)
    local dataset = data[name]
    local c, r, n = findgap(dataset)
    if n then
        dataset.currentcolumn = c
        dataset.currentrow    = r
    else
        dataset.currentcolumn = 1
        dataset.currentrow    = 1
        n = 0
    end
    local gap = n*(dataset.lineheight+dataset.linedepth)
    texsetdimen("d_page_grd_gap_height",gap)
    -- can be integrated
 -- report("state %a, n %a, column %a, row %a",dataset.state,n,dataset.currentcolumn,dataset.currentrow)
end

function columnsets.sethsize(name)
    local dataset = data[name]
    texsetdimen("d_page_grd_column_width",dataset.widths[dataset.currentcolumn])
end

function columnsets.sethspan(name,span)
    -- no checking if there is really space, so we assume it can be
    -- placed which makes spans a very explicit feature
    local dataset   = data[name]
    local column    = dataset.currentcolumn
    local available = dataset.lastcolumn - column + 1
    if span > available then
        span = available
    end
    local width = dataset.spans[column][span]
    texsetdimen("d_page_grd_span_width",width)
end

function columnsets.setlines(t)
    local dataset = data[t.name]
    dataset.lines[t.page][t.column] = t.value
end

function columnsets.setstart(t)
    local dataset = data[t.name]
    dataset.start[t.page][t.column] = t.value
end

function columnsets.setproperties(t)
    local dataset = data[t.name]
    local column  = t.column
    dataset.distances[column] = t.distance
    dataset.widths[column] = t.width
end

local areas = { }

function columnsets.registerarea(t)
    -- maybe metatable with values
    areas[#areas+1] = t
end

-- state : repeat | start

local ctx_page_grd_set_area = context.protected.page_grd_set_area

function columnsets.flushareas(name)
    local nofareas = #areas
    if nofareas == 0 then
        return
    end
    local dataset = data[name]
    local page    = dataset.page
    if odd(page) then
     -- report("checking %i areas",#areas)
        local kept = { }
        for i=1,nofareas do
            local area = areas[i]
         -- local page = area.page -- maybe use page counter in columnset
         -- local type = area.type
            local okay = false
            --
            local nofcolumns = area.nc
            local nofrows    = area.nr
            local column     = area.c
            local row        = area.r
            columnsets.block {
                name = name,
                c    = column,
                r    = row,
                nc   = nofcolumns,
                nr   = nofrows,
            }
            local left     = 0
            local start    = dataset.nofleft + 1
            local overflow = (column + nofcolumns - 1) - dataset.nofleft
            local height   = nofrows * (dataset.lineheight + dataset.linedepth)
            local width    = dataset.spreads[column][nofcolumns]
         -- report("span, width %p, overflow %i",width,overflow)
            if overflow > 0 then
                local used = nofcolumns - overflow
                left  = dataset.spreads[column][used] + getdimen("backspace")
            end
            ctx_page_grd_set_area(name,area.name,column,row,width,height,start,left) -- or via counters / dimens
            if area.state ~= v_repeat then
                area = nil
            end
            if area then
                kept[#kept+1] = area
            end
        end
        areas = kept
    end
end

function columnsets.setarea(t)
    local dataset = data[t.name]
    local cells   = dataset.cells
    local box     = takebox(t.box)
    local column  = t.c
    local row     = t.r
    if column and row then
        setwhd(box,dataset.widths[column],dataset.lineheight,dataset.linedepth)
        cells[column][row] = box
    end
end

-- The interface.

interfaces.implement {
    name      = "definecolumnset",
    actions   = columnsets.define,
    arguments = { {
        { "name", "string" },
    } }
}

interfaces.implement {
    name      = "resetcolumnset",
    actions   = columnsets.reset,
    arguments = { {
        { "name", "string" },
        { "nofleft", "integer" },
        { "nofright", "integer" },
        { "nofrows", "integer" },
        { "lineheight", "dimension" },
        { "linedepth", "dimension" },
        { "width", "dimension" },
        { "distance", "dimension" },
        { "maxwidth", "dimension" },
    } }
}

interfaces.implement {
    name      = "preparecolumnsetflush",
    actions   = columnsets.prepareflush,
    arguments = "string",
}

interfaces.implement {
    name      = "finishcolumnsetflush",
    actions   = columnsets.finishflush,
    arguments = "string",
}

interfaces.implement {
    name      = "flushcolumnsetcolumn",
    actions   = columnsets.flushcolumn,
    arguments = { "string" ,"integer" },
}

interfaces.implement {
    name      = "setvsizecolumnset",
    actions   = columnsets.setvsize,
    arguments = "string",
}

interfaces.implement {
    name      = "sethsizecolumnset",
    actions   = columnsets.sethsize,
    arguments = "string",
}

interfaces.implement {
    name      = "sethsizecolumnspan",
    actions   = columnsets.sethspan,
    arguments = { "string" ,"integer" },
}

interfaces.implement {
    name      = "flushcolumnsetrest",
    actions   = columnsets.flushrest,
    arguments = { "string", "integer" },
}

interfaces.implement {
    name      = "blockcolumnset",
    actions   = columnsets.block,
    arguments = { {
        { "name", "string" },
        { "c", "integer" },
        { "r", "integer" },
        { "nc", "integer" },
        { "nr", "integer" },
        { "method", "string" },
        { "box", "integer" },
    } }
}

interfaces.implement {
    name      = "checkcolumnset",
    actions   = columnsets.check,
    arguments = { {
        { "name", "string" },
        { "method", "string" },
        { "c", "integer" },
        { "r", "integer" },
        { "method", "string" },
        { "box", "integer" },
        { "width", "dimension" },
        { "height", "dimension" },
        { "option", "string" },
    } }
}

interfaces.implement {
    name      = "putincolumnset",
    actions   = columnsets.put,
    arguments = { {
        { "name", "string" },
        { "c", "integer" },
        { "r", "integer" },
        { "method", "string" },
        { "box", "integer" },
    } }
}

interfaces.implement {
    name    = "addtocolumnset",
    actions = columnsets.add,
    arguments = { "string", "integer" },
}

interfaces.implement {
    name    = "setcolumnsetlines",
    actions = columnsets.setlines,
    arguments = { {
        { "name", "string" },
        { "page", "integer" },
        { "column", "integer" },
        { "value", "integer" },
    } }
}

interfaces.implement {
    name    = "setcolumnsetstart",
    actions = columnsets.setstart,
    arguments = { {
        { "name", "string" },
        { "page", "integer" },
        { "column", "integer" },
        { "value", "integer" },
    } }
}

interfaces.implement {
    name    = "setcolumnsetproperties",
    actions = columnsets.setproperties,
    arguments = { {
        { "name", "string" },
        { "column", "integer" },
        { "distance", "dimension" },
        { "width", "dimension" },
    } }
}

interfaces.implement {
    name      = "registercolumnsetarea",
    actions   = columnsets.registerarea,
    arguments = { {
        { "name", "string" },
        { "type", "string" },
        { "page", "integer" },
        { "state", "string" },
        { "c", "integer" },
        { "r", "integer" },
        { "nc", "integer" },
        { "nr", "integer" },
    } }
}

interfaces.implement {
    name      = "flushcolumnsetareas",
    actions   = columnsets.flushareas,
    arguments = "string",
}

interfaces.implement {
    name      = "setcolumnsetarea",
    actions   = columnsets.setarea,
    arguments = { {
        { "name", "string" },
        { "c", "integer" },
        { "r", "integer" },
        { "method", "string" },
        { "box", "integer" },
    } }
}

interfaces.implement {
    name      = "columnsetgoto",
    actions   = columnsets["goto"],
    arguments = "2 strings",
}

interfaces.implement {
    name      = "columnsetnoto",
    actions   = columnsets["noto"],
}

interfaces.implement {
    name      = "columnsetcurrentcolumn",
    actions   = columnsets.currentcolumn,
    arguments = "string",
}