summaryrefslogtreecommitdiff
path: root/macros/luatex/generic/nodetree/nodetree.lua
blob: 666413578df6b7f268d2986c26b3225d6003f20a (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
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
--- The nodetree package.
--
-- Nodetree uses [LDoc](https://github.com/stevedonovan/ldoc) for the
--  source code documentation. The supported tags are described on in
--  the [wiki](https://github.com/stevedonovan/LDoc/wiki).
--
-- Nodes in LuaTeX are connected. The nodetree view distinguishs
-- between the `list` and `field` connections.
--
-- * `list`: Nodes, which are double connected by `next` and
--   `previous` fields.
-- * `field`: Connections to nodes by other fields than `next` and
--   `previous` fields, e. g. `head`, `pre`.
-- @module nodetree

-- luacheck: globals node tex luatexbase lfs callback os unicode status modules

if not modules then modules = { } end modules ['nodetree'] = {
  version   = '2.0',
  comment   = 'nodetree',
  author    = 'Josef Friedrich',
  copyright = 'Josef Friedrich',
  license   = 'The LaTeX Project Public License Version 1.3c 2008-05-04'
}

--- A counter for the compiled TeX examples. Some TeX code snippets
-- a written into file, wrapped with some TeX boilerplate code.
-- This written files are compiled.
local example_counter = 0

--- The default options
local default_options = {
  callback = 'post_linebreak_filter',
  channel = 'term',
  color = 'colored',
  decimalplaces = 2,
  engine = 'luatex', -- Required for the callback registration
  unit = 'pt',
  verbosity = 1,
}

--- The current options
-- They are changed very often.
local options = {}
for key, value in pairs(default_options) do
  options[key] = value
end

if arg[0] == 'lualatex' then
  options.engine = 'lualatex'
end

--- File descriptor
local output_file

--- The lua table named `tree_state` holds state values of the current
-- tree item.
--
-- `tree_state`:
--
-- * `1` (level):
--   * `list`: `continue`
--   * `field`: `stop`
-- * `2`:
--   * `list`: `continue`
--   * `field`: `stop`
-- @table
local tree_state = {}

--- Format functions.
--
-- Low level template functions.
--
-- @section format

local format = {
  ---
  -- @treturn string
  underscore = function(string)
    if options.channel == 'tex' then
      return string.gsub(string, '_', '\\_')
    else
      return string
    end
  end,

  ---
  -- @treturn string
  escape = function(string)
    if options.channel == 'tex' then
      return string.gsub(string, [[\]], [[\string\]])
    else
      return string
    end
  end,

  -- @treturn number
  number = function(number)
    local mult = 10^(options.decimalplaces or 0)
    return math.floor(number * mult + 0.5) / mult
  end,

  ---
  -- @treturn string
  whitespace = function(count)
    local whitespace
    local output = ''
    if options.channel == 'tex' then
      whitespace = '\\hspace{0.5em}'
    else
      whitespace = ' '
    end
    if not count then
      count = 1
    end
    for _ = 1, count do
      output = output .. whitespace
    end
    return output
  end,

  ---
  -- @treturn string
  color_code = function(code)
    return string.char(27) .. '[' .. tostring(code) .. 'm'
  end,

  ---
  -- @treturn string
  color_tex = function(color, mode)
    if not mode then mode = '' end
    return 'NTE' .. color .. mode
  end,

  ---
  -- @treturn string
  node_begin = function()
    if options.channel == 'tex' then
      return '\\mbox{'
    else
      return ''
    end
  end,

  ---
  -- @treturn string
  node_end = function()
    if options.channel == 'tex' then
      return '}'
    else
      return ''
    end
  end,

  ---
  -- @treturn string
  new_line = function(count)
    local output = ''
    if not count then
      count = 1
    end
    local new_line
    if options.channel == 'tex' then
      new_line = '\\par{}'
    else
      new_line = '\n'
    end

    for _ = 1, count do
      output = output .. new_line
    end
    return output
  end,

  ---
  -- @treturn string
  type_id = function(id)
    return '[' .. tostring(id) .. ']'
  end
}

--- Print the output to stdout or write it into a file (`output_file`).
-- New text is appended.
--
-- @tparam string text A text string.
--
local function nodetree_print(text)
  if options.channel == 'log' or options.channel == 'tex' then
    output_file:write(text)
  else
    io.write(text)
  end
end

--- Template functions.
-- @section template

local template = {
  node_colors = {
    hlist = {'red', 'bright'},
    vlist = {'green', 'bright'},
    rule = {'blue', 'bright'},
    ins = {'blue'},
    mark = {'magenta'},
    adjust = {'cyan'},
    boundary = {'red', 'bright'},
    disc = {'green', 'bright'},
    whatsit = {'yellow', 'bright'},
    local_par = {'blue', 'bright'},
    dir = {'magenta', 'bright'},
    math = {'cyan', 'bright'},
    glue = {'magenta', 'bright'},
    kern = {'green', 'bright'},
    penalty = {'yellow', 'bright'},
    unset = {'blue'},
    style = {'magenta'},
    choice = {'cyan'},
    noad = {'red'},
    radical = {'green'},
    fraction = {'yellow'},
    accent = {'blue'},
    fence = {'magenta'},
    math_char = {'cyan'},
    sub_box = {'red', 'bright'},
    sub_mlist = {'green', 'bright'},
    math_text_char = {'yellow', 'bright'},
    delim = {'blue', 'bright'},
    margin_kern = {'magenta', 'bright'},
    glyph = {'cyan', 'bright'},
    align_record = {'red'},
    pseudo_file = {'green'},
    pseudo_line = {'yellow'},
    page_insert = {'blue'},
    split_insert = {'magenta'},
    expr_stack = {'cyan'},
    nested_list = {'red'},
    span = {'green'},
    attribute = {'yellow'},
    glue_spec = {'magenta'},
    attribute_list = {'cyan'},
    temp = {'magenta'},
    align_stack = {'red', 'bright'},
    movement_stack = {'green', 'bright'},
    if_stack = {'yellow', 'bright'},
    unhyphenated = {'magenta', 'bright'},
    hyphenated = {'cyan', 'bright'},
    delta = {'red'},
    passive = {'green'},
    shape = {'yellow'},
  },

  ---
  -- [SGR (Select Graphic Rendition) Parameters](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters)
  --
  -- __attributes__
  --
  -- | color      |code|
  -- |------------|----|
  -- | reset      |  0 |
  -- | clear      |  0 |
  -- | bright     |  1 |
  -- | dim        |  2 |
  -- | underscore |  4 |
  -- | blink      |  5 |
  -- | reverse    |  7 |
  -- | hidden     |  8 |
  --
  -- __foreground__
  --
  -- | color      |code|
  -- |------------|----|
  -- | black      | 30 |
  -- | red        | 31 |
  -- | green      | 32 |
  -- | yellow     | 33 |
  -- | blue       | 34 |
  -- | magenta    | 35 |
  -- | cyan       | 36 |
  -- | white      | 37 |
  --
  -- __background__
  --
  -- | color      |code|
  -- |------------|----|
  -- | onblack    | 40 |
  -- | onred      | 41 |
  -- | ongreen    | 42 |
  -- | onyellow   | 43 |
  -- | onblue     | 44 |
  -- | onmagenta  | 45 |
  -- | oncyan     | 46 |
  -- | onwhite    | 47 |
  --
  -- @tparam string color A color name (`black`, `red`, `green`,
  --   `yellow`, `blue`, `magenta`, `cyan`, `white`).
  -- @tparam string mode `bright` or `dim`.
  -- @tparam boolean background Colorize the background not the text.
  --
  -- @treturn string
  color = function(color, mode, background)
    if options.color ~= 'colored' then
      return ''
    end

    local output = ''
    local code

    if mode == 'bright' then
      output = format.color_code(1)
    elseif mode == 'dim' then
      output = format.color_code(2)
    end

    if not background then
      if color == 'reset' then code = 0
      elseif color == 'red' then code = 31
      elseif color == 'green' then code = 32
      elseif color == 'yellow' then code = 33
      elseif color == 'blue' then code = 34
      elseif color == 'magenta' then code = 35
      elseif color == 'cyan' then code = 36
      else code = 37 end
    else
      if color == 'black' then code = 40
      elseif color == 'red' then code = 41
      elseif color == 'green' then code = 42
      elseif color == 'yellow' then code = 43
      elseif color == 'blue' then code = 44
      elseif color == 'magenta' then code = 45
      elseif color == 'cyan' then code = 46
      elseif color == 'white' then code = 47
      else code = 40 end
    end
    return output .. format.color_code(code)
  end,

  --- Format a single unicode character.
  --
  -- @tparam string char A single input character.
  --
  -- @treturn string
  char = function(char)
    char = string.format('%s', unicode.utf8.char(char))
    char = '\'' .. char .. '\''
    if options.channel == 'tex' then
      char = format.escape(char)
    end
    return char
  end,

  ---
  -- @treturn string
  line = function(length)
    local output
    if length == 'long' then
      output = '------------------------------------------'
    else
      output = '-----------------------'
    end
      return output .. format.new_line()
  end,

  ---
  -- @treturn string
  branch = function(connection_type, connection_state, last)
    local c = connection_type
    local s = connection_state
    local l = last
    if c == 'list' and s == 'stop' and l == false then
      return format.whitespace(2)
    elseif c == 'field' and s == 'stop' and l == false then
      return format.whitespace(2)
    elseif c == 'list' and s == 'continue' and l == false then
      return '│' .. format.whitespace()
    elseif c == 'field' and s == 'continue' and l == false then
      return '║' .. format.whitespace()
    elseif c == 'list' and s == 'continue' and l == true then
      return '├─'
    elseif c == 'field' and s == 'continue' and l == true then
      return '╠═'
    elseif c == 'list' and s == 'stop' and l == true then
      return '└─'
    elseif c == 'field' and s == 'stop' and l == true then
      return '╚═'
    end
    return ''
  end,
}

---
-- @treturn string
function template.fill(number, order, field)
  local output
  if order ~= nil and order ~= 0 then
    if field == 'stretch' then
      output = '+'
    else
      output = '-'
    end
    return output .. string.format(
      '%g%s', number / 2^16,
      template.colored_string(
        'fi' .. string.rep('l', order - 1),
        'white',
        'dim'
      )
    )
  else
    return template.length(number)
  end
end

--- Colorize a text string.
--
-- @tparam string text A text string.
-- @tparam string color A color name (`black`, `red`, `green`,
--   `yellow`, `blue`, `magenta`, `cyan`, `white`).
-- @tparam string mode `bright` or `dim`.
-- @tparam boolean background Colorize the background not the text.
--
-- @treturn string
function template.colored_string(text, color, mode, background)
  if options.channel == 'tex' then
    if mode == 'dim' then
      mode = ''
    end
    return '\\textcolor{' ..
      format.color_tex(color, mode) ..
      '}{' ..
      text ..
      '}'
  else
   return template.color(color, mode, background) .. text .. template.color('reset')
  end
end

--- Format a scaled point input value into dimension string (`12pt`,
--  `1cm`)
--
-- @tparam number input
--
-- @treturn string
function template.length (input)
  input = tonumber(input)
  input = input / tex.sp('1' .. options.unit)
  return string.format(
    '%g%s',
    format.number(input),
    template.colored_string(options.unit, 'white', 'dim')
  )
end

--- Convert a Lua table into a format string.
--
-- @tparam table table A table to generate a inline view of.
--
-- @treturn string
function template.table_inline(table)
  local tex_escape = ''
  if options.channel == 'tex' then
    tex_escape = '\\'
  end
  if type(table) == 'table' then
    local output = tex_escape .. '{'
    local kv_list = ''
    for key, value in pairs(table) do
        if type(key) ~= 'numbers' then
          key = '\'' ..
            template.colored_string(key, 'cyan', 'dim') .. '\''
        end
        kv_list = kv_list .. '[' .. key .. '] = ' ..
          template.table_inline(value) .. ', '
    end
    output = output .. kv_list:gsub(', $', '')
    return output .. tex_escape .. '}'
  else
    return tostring(table)
  end
end

--- Format a key value pair (`key: value, `).
--
-- @tparam string key A key
-- @tparam string|number value A value
-- @tparam string color A color name (`black`, `red`, `green`,
--   `yellow`, `blue`, `magenta`, `cyan`, `white`).
--
-- @treturn string
function template.key_value(key, value, color)
  if type(color) ~= 'string' then
    color = 'yellow'
  end
  if options.channel == 'tex' then
    key = format.underscore(key)
  end
  local output = template.colored_string(key .. ':', color)
  if value then
    output = output .. ' ' .. value .. ', '
  end
  return output
end

---
-- @treturn string
function template.type(type, id)
  local output
  if options.channel == 'tex' then
    output = format.underscore(type)
  else
    output = type
  end
  output = string.upper(output)
  if options.verbosity > 1 then
    output = output .. format.type_id(id)
  end
  return template.colored_string(
    output .. format.whitespace(),
    template.node_colors[type][1],
    template.node_colors[type][2]
  )
end

---
-- @treturn string
function template.callback(callback_name, variables)
  nodetree_print(
    format.new_line(2) ..
    'Callback: ' ..
    template.colored_string(format.underscore(callback_name), 'red', '', true) ..
    format.new_line()
  )
  if variables then
    for name, value in pairs(variables) do
      if value ~= nil and value ~= '' then
        nodetree_print(
          '- ' ..
          format.underscore(name) ..
          ': ' ..
          tostring(value) ..
          format.new_line()
        )
      end
    end
  end
  nodetree_print(template.line('long'))
end

---
-- @treturn string
function template.branches(level, connection_type)
  local output = ''
  for i = 1, level - 1  do
    output = output .. template.branch('list', tree_state[i]['list'], false)
    output = output .. template.branch('field', tree_state[i]['field'], false)
  end
-- Format the last branches
  if connection_type == 'list' then
    output = output .. template.branch('list', tree_state[level]['list'], true)
  else
    output = output .. template.branch('list', tree_state[level]['list'], false)
    output = output .. template.branch('field', tree_state[level]['field'], true)
  end
  return output
end

--- Extend the node library
-- @section node_extended

local node_extended = {}

--- Get the ID of a node.
--
-- We have to convert the node into a string and than have to extract
-- the ID from this string using a regular expression. If you convert a
-- node into a string it looks like: `<node    nil <    172 >    nil :
-- hlist 2>`.
--
-- @tparam node n A node.
--
-- @treturn string
function node_extended.node_id(n)
  return string.gsub(tostring(n), '^<node%s+%S+%s+<%s+(%d+).*', '%1')
end

--- A table of all node subtype names.
--
-- __Nodes without subtypes:__
--
-- * `ins` (3)
-- * `mark` (4)
-- * `whatsit` (8)
-- * `local_par` (9)
-- * `dir` (10)
-- * `penalty` (14)
-- * `unset` (15)
-- * `style` (16)
-- * `choice` (17)
-- * `fraction` (20)
-- * `math_char` (23)
-- * `sub_box` (24)
-- * `sub_mlist` (25)
-- * `math_text_char` (26)
-- * `delim` (27)
-- * `margin_kern` (28)
-- * `align_record` (30)
-- * `pseudo_file` (31)
-- * `pseudo_line` (32)
-- * `page_insert` (33)
-- * `split_insert` (34)
-- * `expr_stack` (35)
-- * `nested_list` (36)
-- * `span` (37)
-- * `attribute` (38)
-- * `glue_spec` (39)
-- * `attribute_list` (40)
-- * `temp` (41)
-- * `align_stack` (42)
-- * `movement_stack` (43)
-- * `if_stack` (44)
-- * `unhyphenated` (45)
-- * `hyphenated` (46)
-- * `delta` (47)
-- * `passive` (48)
-- * `shape` (49)
--
-- @treturn table
local function get_node_subtypes ()
    local subtypes = {
    -- hlist (0)
    hlist = {
      [0] = 'unknown',
      [1] = 'line',
      [2] = 'box',
      [3] = 'indent',
      [4] = 'alignment',
      [5] = 'cell',
      [6] = 'equation',
      [7] = 'equationnumber',
      [8] = 'math',
      [9] = 'mathchar',
      [10] = 'hextensible',
      [11] = 'vextensible',
      [12] = 'hdelimiter',
      [13] = 'vdelimiter',
      [14] = 'overdelimiter',
      [15] = 'underdelimiter',
      [16] = 'numerator',
      [17] = 'denominator',
      [18] = 'limits',
      [19] = 'fraction',
      [20] = 'nucleus',
      [21] = 'sup',
      [22] = 'sub',
      [23] = 'degree',
      [24] = 'scripts',
      [25] = 'over',
      [26] = 'under',
      [27] = 'accent',
      [28] = 'radical',
    },
    -- vlist (1)
    vlist = {
      [0] = 'unknown',
      [4] = 'alignment',
      [5] = 'cell',
    },
    -- rule (2)
    rule = {
      [0] = 'normal',
      [1] = 'box',
      [2] = 'image',
      [3] = 'empty',
      [4] = 'user',
      [5] = 'over',
      [6] = 'under',
      [7] = 'fraction',
      [8] = 'radical',
      [9] = 'outline',
    },
    -- adjust (5)
    adjust = {
      [0] = 'normal',
      [1] = 'pre',
    },
    -- boundary (6)
    boundary = {
      [0] = 'cancel',
      [1] = 'user',
      [2] = 'protrusion',
      [3] = 'word',
    },
    -- disc (7)
    disc  = {
      [0] = 'discretionary',
      [1] = 'explicit',
      [2] = 'automatic',
      [3] = 'regular',
      [4] = 'first',
      [5] = 'second',
    },
    -- math (11)
    math = {
      [0] = 'beginmath',
      [1] = 'endmath',
    },
    -- glue (12)
    glue = {
      [0]   = 'userskip',
      [1]   = 'lineskip',
      [2]   = 'baselineskip',
      [3]   = 'parskip',
      [4]   = 'abovedisplayskip',
      [5]   = 'belowdisplayskip',
      [6]   = 'abovedisplayshortskip',
      [7]   = 'belowdisplayshortskip',
      [8]   = 'leftskip',
      [9]   = 'rightskip',
      [10]  = 'topskip',
      [11]  = 'splittopskip',
      [12]  = 'tabskip',
      [13]  = 'spaceskip',
      [14]  = 'xspaceskip',
      [15]  = 'parfillskip',
      [16]  = 'mathskip',
      [17]  = 'thinmuskip',
      [18]  = 'medmuskip',
      [19]  = 'thickmuskip',
      [98]  = 'conditionalmathskip',
      [99]  = 'muglue',
      [100] = 'leaders',
      [101] = 'cleaders',
      [102] = 'xleaders',
      [103] = 'gleaders',
    },
    -- kern (13)
    kern = {
      [0] = 'fontkern',
      [1] = 'userkern',
      [2] = 'accentkern',
      [3] = 'italiccorrection',
    },
    -- penalty (14)
    penalty = {
      [0] = 'userpenalty',
      [1] = 'linebreakpenalty',
      [2] = 'linepenalty',
      [3] = 'wordpenalty',
      [4] = 'finalpenalty',
      [5] = 'noadpenalty',
      [6] = 'beforedisplaypenalty',
      [7] = 'afterdisplaypenalty',
      [8] = 'equationnumberpenalty',
    },
    noad = {
      [0] = 'ord',
      [1] = 'opdisplaylimits',
      [2] = 'oplimits',
      [3] = 'opnolimits',
      [4] = 'bin',
      [5] = 'rel',
      [6] = 'open',
      [7] = 'close',
      [8] = 'punct',
      [9] = 'inner',
      [10] = 'under',
      [11] = 'over',
      [12] = 'vcenter',
    },
    -- radical (19)
    radical = {
      [0] = 'radical',
      [1] = 'uradical',
      [2] = 'uroot',
      [3] = 'uunderdelimiter',
      [4] = 'uoverdelimiter',
      [5] = 'udelimiterunder',
      [6] = 'udelimiterover',
    },
    -- accent (21)
    accent = {
      [0] = 'bothflexible',
      [1] = 'fixedtop',
      [2] = 'fixedbottom',
      [3] = 'fixedboth',
    },
    -- fence (22)
    fence = {
      [0] = 'unset',
      [1] = 'left',
      [2] = 'middle',
      [3] = 'right',
      [4] = 'no',
    },
    -- margin_kern (28)
    margin_kern = {
      [0] = 'left',
      [1] = 'right',
    },
    -- glyph (29)
    glyph = {
      [0] = 'character',
      [1] = 'ligature',
      [2] = 'ghost',
      [3] = 'left',
      [4] = 'right',
    },
  }
  subtypes.whatsit = node.whatsits()
  return subtypes
end

---
-- @treturn string
function node_extended.subtype(n)
  local typ = node.type(n.id)
  local subtypes = get_node_subtypes()

  local output
  if subtypes[typ] and subtypes[typ][n.subtype] then
    output = subtypes[typ][n.subtype]
    if options.verbosity > 1 then
      output = output .. format.type_id(n.subtype)
    end
    return output
  else
    return tostring(n.subtype)
  end
end

--- Build the node tree.
-- @section tree

local tree = {}

---
-- @tparam node head
-- @tparam string field
--
-- @treturn string
function tree.format_field(head, field)
  local output
-- Character "0" should be printed in a tree, because in TeX fonts the
-- 0 slot usually has a symbol.
  if not head[field] or (head[field] == 0 and field ~= "char") then
    return ''
  end

  if options.verbosity < 2 and
    -- glyph
    field == 'font' or
    field == 'left' or
    field == 'right' or
    field == 'uchyph' or
    -- hlist
    field == 'dir' or
    field == 'glue_order' or
    field == 'glue_sign' or
    field == 'glue_set' or
    -- glue
    field == 'stretch_order' then
    return ''
  elseif options.verbosity < 3 and
    field == 'prev' or
    field == 'next' or
    field == 'id'
  then
    return ''
  end

  if field == 'prev' or field == 'next' then
    output = node_extended.node_id(head[field])
  elseif field == 'subtype' then
    output = format.underscore(node_extended.subtype(head))
  elseif
    field == 'width' or
    field == 'height' or
    field == 'depth' or
    field == 'kern' or
    field == 'shift' then
    output = template.length(head[field])
  elseif field == 'char' then
    output = template.char(head[field])
  elseif field == 'glue_set' then
    output = format.number(head[field])
  elseif field == 'stretch' or field == 'shrink' then
    output = template.fill(head[field], head[field .. '_order'], field)
  else
    output = tostring(head[field])
  end

  return template.key_value(field, output)
end

---
-- Attributes are key/value number pairs. They are printed as an inline
-- list. The attribute `0` with the value `0` is skipped because this
-- attribute is in every node by default.
--
-- @tparam node head
--
-- @treturn string
function tree.format_attributes(head)
  if not head then
    return ''
  end
  local output = ''
  local attr = head.next
  while attr do
    if attr.number ~= 0 or (attr.number == 0 and attr.value ~= 0) then
      output = output .. tostring(attr.number) .. '=' .. tostring(attr.value) .. ' '
    end
    attr = attr.next
  end
  return output
end

---
-- @tparam number level `level` is a integer beginning with 1.
-- @tparam number connection_type The variable `connection_type`
--   is a string, which can be either `list` or `field`.
-- @tparam connection_state `connection_state` is a string, which can
--   be either `continue` or `stop`.
function tree.set_state(level, connection_type, connection_state)
  if not tree_state[level] then
    tree_state[level] = {}
  end
  tree_state[level][connection_type] = connection_state
end

---
-- @tparam table fields
-- @tparam number level
function tree.analyze_fields(fields, level)
  local max = 0
  local connection_state
  for _ in pairs(fields) do
    max = max + 1
  end
  local count = 0
  for field_name, recursion_node in pairs(fields) do
    count = count + 1
    if count == max then
      connection_state = 'stop'
    else
      connection_state = 'continue'
    end
    tree.set_state(level, 'field', connection_state)
    nodetree_print(
      format.node_begin() ..
      template.branches(level, 'field') ..
      template.key_value(field_name) ..
      format.node_end() ..
      format.new_line()
    )
    tree.analyze_list(recursion_node, level + 1)
  end
end

---
-- @tparam node head
-- @tparam number level
function tree.analyze_node(head, level)
  local connection_state
  local output
  if head.next then
    connection_state = 'continue'
  else
    connection_state = 'stop'
  end
  tree.set_state(level, 'list', connection_state)
  output = template.branches(level, 'list')
    .. template.type(node.type(head.id), head.id)
  if options.verbosity > 1 then
    output = output .. template.key_value('no', node_extended.node_id(head))
  end

  -- We store the attributes output to append it to the field list.
  local attributes

  -- We store fields which are nodes for later treatment.
  local fields = {}

  -- Inline fields, for example: char: 'm', width: 25pt, height: 13.33pt,
  local output_fields = ''
  for _, field_name in pairs(node.fields(head.id, head.subtype)) do
    if field_name == 'attr' then
      attributes = tree.format_attributes(head.attr)
    elseif field_name ~= 'next' and field_name ~= 'prev' and
      node.is_node(head[field_name]) then
      fields[field_name] = head[field_name]
    else
      output_fields = output_fields .. tree.format_field(head, field_name)
    end
  end
  if output_fields ~= '' then
    output = output .. output_fields
  end

  -- Append the attributes output if available
  if attributes ~= '' then
    output = output .. template.key_value('attr', attributes, 'blue')
  end

  output = output:gsub(', $', '')

  nodetree_print(
    format.node_begin() ..
    output ..
    format.node_end() ..
    format.new_line()
  )

  local property = node.getproperty(head)
  if property then
    nodetree_print(
      format.node_begin() ..
      template.branches(level, 'field') ..
      '  ' ..
      template.colored_string('properties:', 'blue') .. ' ' ..
      template.table_inline(property) ..
      format.node_end() ..
      format.new_line()
    )
  end

  tree.analyze_fields(fields, level)
end

---
-- @tparam node head
-- @tparam number level
function tree.analyze_list(head, level)
  while head do
    tree.analyze_node(head, level)
    head = head.next
  end
end

---
-- @tparam node head
function tree.analyze_callback(head)
  tree.analyze_list(head, 1)
  nodetree_print(template.line('short') .. format.new_line())
end

--- Callback wrapper.
-- @section callbacks

local callbacks = {

  ---
  -- @tparam string extrainfo
  contribute_filter = function(extrainfo)
    template.callback('contribute_filter', {extrainfo = extrainfo})
    return true
  end,

  ---
  -- @tparam string extrainfo
  buildpage_filter = function(extrainfo)
    template.callback('buildpage_filter', {extrainfo = extrainfo})
    return true
  end,

  ---
  -- @tparam string n
  -- @tparam string i
  build_page_insert = function(n, i)
    print('lol')
    template.callback('build_page_insert', {n = n, i = i})
    return 0
  end,

  ---
  -- @tparam node head
  -- @tparam string groupcode
  pre_linebreak_filter = function(head, groupcode)
    template.callback('pre_linebreak_filter', {groupcode = groupcode})
    tree.analyze_callback(head)
    return true
  end,

  ---
  -- @tparam node head
  -- @tparam boolean is_display
  linebreak_filter = function(head, is_display)
    template.callback('linebreak_filter', {is_display = is_display})
    tree.analyze_callback(head)
    return true
  end,

  ---
  -- @tparam node box
  -- @tparam string locationcode
  -- @tparam number prevdepth
  -- @tparam boolean mirrored
  append_to_vlist_filter = function(box, locationcode, prevdepth, mirrored)
    local variables = {
      locationcode = locationcode,
      prevdepth = prevdepth,
      mirrored = mirrored,
    }
    template.callback('append_to_vlist_filter', variables)
    tree.analyze_callback(box)
    return box
  end,

  ---
  -- @tparam node head
  -- @tparam string groupcode
  post_linebreak_filter = function(head, groupcode)
    template.callback('post_linebreak_filter', {groupcode = groupcode})
    tree.analyze_callback(head)
    return true
  end,

  ---
  -- @tparam node head
  -- @tparam string groupcode
  -- @tparam number size
  -- @tparam string packtype
  -- @tparam string direction
  -- @tparam node attributelist
  hpack_filter = function(head, groupcode, size, packtype, direction, attributelist)
    local variables = {
      groupcode = groupcode,
      size = size,
      packtype = packtype,
      direction = direction,
      attributelist = attributelist,
    }
    template.callback('hpack_filter', variables)
    tree.analyze_callback(head)
    return true
  end,

  ---
  -- @tparam node head
  -- @tparam string groupcode
  -- @tparam number size
  -- @tparam string packtype
  -- @tparam number maxdepth
  -- @tparam string direction
  -- @tparam node attributelist
  vpack_filter = function(head, groupcode, size, packtype, maxdepth, direction, attributelist)
    local variables = {
      groupcode = groupcode,
      size = size,
      packtype = packtype,
      maxdepth = template.length(maxdepth),
      direction = direction,
      attributelist = attributelist,
    }
    template.callback('vpack_filter', variables)
    tree.analyze_callback(head)
    return true
  end,

  ---
  -- @tparam string incident
  -- @tparam number detail
  -- @tparam node head
  -- @tparam number first
  -- @tparam number last
  hpack_quality = function(incident, detail, head, first, last)
    local variables = {
      incident = incident,
      detail = detail,
      first = first,
      last = last,
    }
    template.callback('hpack_quality', variables)
    tree.analyze_callback(head)
  end,

  ---
  -- @tparam string incident
  -- @tparam number detail
  -- @tparam node head
  -- @tparam number first
  -- @tparam number last
  vpack_quality = function(incident, detail, head, first, last)
    local variables = {
      incident = incident,
      detail = detail,
      first = first,
      last = last,
    }
    template.callback('vpack_quality', variables)
    tree.analyze_callback(head)
  end,

  ---
  -- @tparam node head
  -- @tparam number width
  -- @tparam number height
  process_rule = function(head, width, height)
    local variables = {
      width = width,
      height = height,
    }
    template.callback('process_rule', variables)
    tree.analyze_callback(head)
    return true
  end,

  ---
  -- @tparam node head
  -- @tparam string groupcode
  -- @tparam number size
  -- @tparam string packtype
  -- @tparam number maxdepth
  -- @tparam string direction
  pre_output_filter = function(head, groupcode, size, packtype, maxdepth, direction)
    local variables = {
      groupcode = groupcode,
      size = size,
      packtype = packtype,
      maxdepth = maxdepth,
      direction = direction,
    }
    template.callback('pre_output_filter', variables)
    tree.analyze_callback(head)
    return true
  end,

  ---
  -- @tparam node head
  -- @tparam node tail
  hyphenate = function(head, tail)
    template.callback('hyphenate')
    nodetree_print('head:')
    tree.analyze_callback(head)
    nodetree_print('tail:')
    tree.analyze_callback(tail)
  end,

  ---
  -- @tparam node head
  -- @tparam node tail
  ligaturing = function(head, tail)
    template.callback('ligaturing')
    nodetree_print('head:')
    tree.analyze_callback(head)
    nodetree_print('tail:')
    tree.analyze_callback(tail)
  end,

  ---
  -- @tparam node head
  -- @tparam node tail
  kerning = function(head, tail)
    template.callback('kerning')
    nodetree_print('head:')
    tree.analyze_callback(head)
    nodetree_print('tail:')
    tree.analyze_callback(tail)
  end,

  ---
  -- @tparam node local_par
  -- @tparam string location
  insert_local_par = function(local_par, location)
    template.callback('insert_local_par', {location = location})
    tree.analyze_callback(local_par)
    return true
  end,

  ---
  -- @tparam node head
  -- @tparam string display_type
  -- @tparam boolean need_penalties
  mlist_to_hlist = function(head, display_type, need_penalties)
    local variables = {
      display_type = display_type,
      need_penalties = need_penalties,
    }
    template.callback('mlist_to_hlist', variables)
    tree.analyze_callback(head)
    return node.mlist_to_hlist(head, display_type, need_penalties)
  end,
}

--- Set a single option key value pair.
--
-- @tparam string key The key of the option pair.
-- @tparam number|string value The value of the option pair.
local function set_option(key, value)
  if not options then
    options = {}
  end
  if key == 'verbosity' or key == 'decimalplaces' then
    options[key] = tonumber(value)
  else
    options[key] = value
  end
end

--- Set multiple key value pairs using a table.
--
-- @tparam table opts Options
local function set_options(opts)
  if not options then
    options = {}
  end
  for key, value in pairs(opts) do
    set_option(key, value)
  end
end

--- Check if the given callback name exists.
--
-- Throw an error if it doen’t.
--
-- @tparam string callback_name The name of a callback to check.
--
-- @treturn string The unchanged input of the function.
local function check_callback_name(callback_name)
  local info = callback.list()
  if info[callback_name] == nil then
    tex.error(
      'Package "nodetree": Unkown callback name or callback alias: "' ..
      callback_name ..
      '"'
    )
  end
  return callback_name
end

--- Get the real callback name from an alias string.
--
-- @tparam string alias The alias of a callback name or the callback
-- name itself.
--
-- @treturn string The real callback name.
local function get_callback_name(alias)
  local callback_name
  -- Listed as in the LuaTeX reference manual.
  if alias == 'contribute' or alias == 'contributefilter' then
    callback_name = 'contribute_filter'

  -- Formerly called buildpage, now there is a build_page_insert.
  elseif alias == 'buildfilter' or alias == 'buildpagefilter' then
    callback_name = 'buildpage_filter'

  -- Untested: I don’t know how to invoke this filter.
  elseif alias == 'buildinsert' or alias == 'buildpageinsert' then
    callback_name = 'build_page_insert'

  elseif alias == 'preline' or alias == 'prelinebreakfilter' then
    callback_name = 'pre_linebreak_filter'

  elseif alias == 'line' or alias == 'linebreakfilter' then
    callback_name = 'linebreak_filter'

  elseif alias == 'append' or alias == 'appendtovlistfilter' then
    callback_name = 'append_to_vlist_filter'

  -- postlinebreak is not documented.
  elseif alias == 'postline' or alias == 'postlinebreak' or alias == 'postlinebreakfilter' then
    callback_name = 'post_linebreak_filter'

  elseif alias == 'hpack' or alias == 'hpackfilter' then
    callback_name = 'hpack_filter'

  elseif alias == 'vpack' or alias == 'vpackfilter' then
    callback_name = 'vpack_filter'

  elseif alias == 'hpackq' or alias == 'hpackquality' then
    callback_name = 'hpack_quality'

  elseif alias == 'vpackq' or alias == 'vpackquality' then
    callback_name = 'vpack_quality'

  elseif alias == 'process' or alias == 'processrule' then
    callback_name = 'process_rule'

  elseif alias == 'preout' or alias == 'preoutputfilter' then
    callback_name = 'pre_output_filter'

  elseif alias == 'hyph' or alias == 'hyphenate' then
    callback_name = 'hyphenate'

  elseif alias == 'liga' or alias == 'ligaturing' then
    callback_name = 'ligaturing'

  elseif alias == 'kern' or alias == 'kerning' then
    callback_name = 'kerning'

  elseif alias == 'insert' or alias == 'insertlocalpar' then
    callback_name = 'insert_local_par'

  elseif alias == 'mhlist' or alias == 'mlisttohlist' then
    callback_name = 'mlist_to_hlist'

  else
    callback_name = alias
  end
  return check_callback_name(callback_name)
end

--- Register a callback.
--
-- @tparam string cb The name of a callback.
local function register_callback(cb)
  if options.engine == 'lualatex' then
    luatexbase.add_to_callback(cb, callbacks[cb], 'nodetree')
  else
    callback.register(cb, callbacks[cb])
  end
end

--- Unregister a callback.
--
-- @tparam string cb The name of a callback.
local function unregister_callback(cb)
  if options.engine == 'lualatex' then
    luatexbase.remove_from_callback(cb, 'nodetree')
  else
    register_callback(cb, nil)
  end
end

--- Exported functions.
-- @section export

local export = {
  set_option = set_option,
  set_options = set_options,

  ---
  register_callbacks = function()
    if options.channel == 'log' or options.channel == 'tex' then
      -- nt = nodetree
      -- jobname.nttex
      -- jobname.ntlog
      local file_name = tex.jobname .. '.nt' .. options.channel
      io.open(file_name, 'w'):close() -- Clear former content
      output_file = io.open(file_name, 'a')
    end
    for alias in string.gmatch(options.callback, '([^,]+)') do
      register_callback(get_callback_name(alias))
    end
  end,

  ---
  unregister_callbacks = function()
    for alias in string.gmatch(options.callback, '([^,]+)') do
      unregister_callback(get_callback_name(alias))
    end
  end,

  --- Compile a TeX snippet.
  --
  -- Write some TeX snippets into a temporary LaTeX file, compile this
  -- file using `latexmk` and read the generated `*.nttex` file and
  -- return its content.
  --
  -- @tparam string tex_markup
  --
  -- @treturn string
  compile_include = function(tex_markup)
    -- Generate a subfolder for all tempory files: _nodetree-jobname.
    local parent_path = lfs.currentdir() .. '/' .. '_nodetree-' .. tex.jobname
    lfs.mkdir(parent_path)

    -- Generate the temporary LuaTeX or LuaLaTeX file.
    example_counter = example_counter + 1
    local filename_tex = example_counter .. '.tex'
    local absolute_path_tex = parent_path .. '/' .. filename_tex
    output_file = io.open(absolute_path_tex, 'w')

    local format_option = function (key, value)
      return '\\NodetreeSetOption[' .. key .. ']{' .. value .. '}' .. '\n'
    end

    -- Process the options
    local options =
      format_option('channel', 'tex') ..
      format_option('verbosity', options.verbosity) ..
      format_option('unit', options.unit) ..
      format_option('decimalplaces', options.decimalplaces) ..
      '\\NodetreeUnregisterCallback{post_linebreak_filter}'  .. '\n' ..
      '\\NodetreeRegisterCallback{' .. options.callback .. '}'

    local prefix = '%!TEX program = lualatex\n' ..
                  '\\documentclass{article}\n' ..
                  '\\usepackage{nodetree}\n' ..
                  options .. '\n' ..
                  '\\begin{document}\n'
    local suffix = '\n\\end{document}'
    output_file:write(prefix .. tex_markup .. suffix)
    output_file:close()

    -- Compile the temporary LuaTeX or LuaLaTeX file.
    os.spawn({ 'latexmk', '-cd', '-pdflua', absolute_path_tex })
    local include_file = assert(io.open(parent_path .. '/' .. example_counter .. '.nttex', 'rb'))
    local include_content = include_file:read("*all")
    include_file:close()
    include_content = include_content:gsub('[\r\n]', '')
    tex.print(include_content)
  end,

  --- Check for `--shell-escape`
  --
  check_shell_escape = function()
    local info = status.list()
    if info.shell_escape == 0 then
      tex.error('Package "nodetree-embed": You have to use the --shell-escape option')
    end
  end,

  --- Print a node tree.
  ---
  -- @tparam node head The head node of a node list.
  -- @tparam table opts Options as a table.
  print = function(head, opts)
    if opts and type(opts) == 'table' then
      set_options(opts)
    end
    nodetree_print(format.new_line())
    tree.analyze_list(head, 1)
  end,

  --- Format a scaled point value into a formated string.
  --
  -- @tparam number sp A scaled point value
  --
  -- @treturn string
  format_dim = function(sp)
    return template.length(sp)
  end,

  --- Get a default option that is not changed.
  -- @tparam string key The key of the option.
  --
  -- @treturn string|number|boolean
  get_default_option = function(key)
    return default_options[key]
  end
}

--- Use export.print
-- @tparam node head
export.analyze = export.print

return export