summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/source/luatex/luatextra/luatextra.dtx
blob: 62c763d8484863ab4389109a9f0616a0534d32ae (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
% \iffalse meta-comment
%
% Copyright (C) 2009 by Elie Roux <elie.roux@telecom-bretagne.eu>
%
% This work is under the CC0 license.
%
% This work consists of the main source file luamcallbacks.dtx
% and the derived files
%    luatextra.sty, luatextra.lua, luatextra-latex.tex, luatextra.pdf.
%
% Unpacking:
%    tex luatextra.dtx
%
% Documentation:
%    pdflatex luatextra.dtx
%
%    The class ltxdoc loads the configuration file ltxdoc.cfg
%    if available. Here you can specify further options, e.g.
%    use A4 as paper format:
%       \PassOptionsToClass{a4paper}{article}
%
%
%
%<*ignore>
\begingroup
  \def\x{LaTeX2e}%
\expandafter\endgroup
\ifcase 0\ifx\install y1\fi\expandafter
         \ifx\csname processbatchFile\endcsname\relax\else1\fi
         \ifx\fmtname\x\else 1\fi\relax
\else\csname fi\endcsname
%</ignore>
%<*install>
\input docstrip.tex
\Msg{************************************************************************}
\Msg{* Installation}
\Msg{* Package: luatextra 2009/04/15 v0.93 Additional low level functions for LuaTeX}
\Msg{************************************************************************}

\keepsilent
\askforoverwritefalse

\let\MetaPrefix\relax

\preamble
This is a generated file.

Copyright (C) 2009 by Elie Roux <elie.roux@telecom-bretagne.eu>

This work is under the CC0 license.

This work consists of the main source file luainputenc.dtx
and the derived files
    luatextra.sty, luatextra.lua, luatextra-latex.tex, luatextra.pdf

\endpreamble

\let\MetaPrefix\DoubleperCent


\generate{%
  \usedir{tex/luatex/luatextra}%
  \file{luatextra.sty}{\from{luatextra.dtx}{package}}%
  \file{luatextra-latex.tex}{\from{luatextra.dtx}{latex}}%
}

% The following hacks are to generate a lua file with lua comments starting by -- instead of %%

\def\MetaPrefix{-- }

\def\luapostamble{%
  \MetaPrefix^^J%
  \MetaPrefix\space End of File `\outFileName'.%
}

\def\currentpostamble{\luapostamble}%

\generate{%
  \usedir{tex/luatex/luatextra}%
  \file{luatextra.lua}{\from{luatextra.dtx}{lua}}%%
}

\obeyspaces
\Msg{************************************************************************}
\Msg{*}
\Msg{* To finish the installation you have to move the following}
\Msg{* files into a directory searched by TeX:}
\Msg{*}
\Msg{*     luatextra.sty luatextra-latex.tex luatextra.lua}
\Msg{*}
\Msg{* Happy TeXing!}
\Msg{*}
\Msg{************************************************************************}

\endbatchfile
%</install>
%<*ignore>
\fi
%</ignore>
%<*driver>
\NeedsTeXFormat{LaTeX2e}
\ProvidesFile{luaminimalotf.drv}%
  [2009/04/15 v0.93 LuaTeX extra low-level macros.]%
\documentclass{ltxdoc}
\EnableCrossrefs
\CodelineIndex
\begin{document}
  \DocInput{luatextra.dtx}%
\end{document}
%</driver>
% \fi
%
% \CheckSum{0}
%
% \CharacterTable
%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%   Digits        \0\1\2\3\4\5\6\7\8\9
%   Exclamation   \!     Double quote  \"     Hash (number) \#
%   Dollar        \$     Percent       \%     Ampersand     \&
%   Acute accent  \'     Left paren    \(     Right paren   \)
%   Asterisk      \*     Plus          \+     Comma         \,
%   Minus         \-     Point         \.     Solidus       \/
%   Colon         \:     Semicolon     \;     Less than     \<
%   Equals        \=     Greater than  \>     Question mark \?
%   Commercial at \@     Left bracket  \[     Backslash     \\
%   Right bracket \]     Circumflex    \^     Underscore    \_
%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%   Right brace   \}     Tilde         \~}
%
% \GetFileInfo{luatextra.drv}
%
% \title{The \textsf{luatextra} package}
% \date{2009/04/15 v0.93}
% \author{Elie Roux \\ \texttt{elie.roux@telecom-bretagne.eu}}
%
% \maketitle
%
% \begin{abstract}
% \textsf{luatextra} provides low-level addition to the formats Plain and \LaTeX\ to be used with the engine Lua\TeX.
% \end{abstract}
%
% \tableofcontents
%
% \section{Documentation}
%
% \subsection{Preamble}
%
% This document is made for people wanting to understand how the package was made. For an introduction to the use of Lua\TeX\ with the formats Plain and \LaTeX , please read the document \texttt{luatextra-reference.pdf} that you can find in your \TeX\ distribution (\TeX Live from version 2009) or on the CTAN.
% 
% \subsection{History of formats and engines}
% 
% To understand this package, one must fist understand some historical choices in the \TeX\ world.
%
% A \TeX\ engine is a binary executable that provides some very low-level primitives, for example \texttt{\string\count} to set a counter to a certain value. A \TeX\ format is a macro package that provides higher-level macros for the user and the package developer, for example \texttt{\string\newcount} that allocates a new counter and gives it a name. Examples of engines are the old \TeX\ 82, $\varepsilon$-\TeX, pdf\TeX, Omega/Aleph, Lua\TeX\ and Xe\TeX. Examples of formats are Plain, \LaTeX\ and Con\TeX t. 
% 
% This distinction is hard to make as only one command is invoked, for example when you call the command \texttt{tex}, you often have no idea that the engine \TeX\ 82 is invoked with the format Plain.
%
% Evolution is also something confusing in the \TeX\ world: engines often evolve, and new engines have always appeared, when most formats are frozen: the Plain and \LaTeX\ formats do not accept any new code to cope with the new engines. In theory, this package shouldn't exist, or at least shouldn't be a package, but its code should be integrated into a format. But as Plain and \LaTeX\ are frozen, people wanting to take advantage of the new engines have to use a package. 
%
% This package is really necessary to take advantage of Lua\TeX\ as it provides things users are expecting a macro package to provide, for example \texttt{\string\newluaattribute} that acts like \texttt{\string\newcount} for lua attributes. It also enables all Lua\TeX\ primitives, that are disabled by default.
%
% \subsection{choices made in this package}
%
% In the very long term, it is higly possible that Lua\TeX\ will replace pdf\TeX\ as the default \LaTeX\ engine, so it is necessary to keep backward compatibility. This lead us to the decision of renaming Lua\TeX -only primitives so that they all start by \texttt{lua}, like the pdf\TeX -only primitives start by \texttt{pdf}. Thus attributes become luaattributes, \texttt{\string\directlua} becomes \texttt{\string\luadirect}, etc. This also allows primitives to keep having the same name, even if their name is changed later at the engine level.
%
% \subsection{registers allocation scheme}
%
% The default register allocation scheme of \LaTeX\ is old and limited (like the one of \TeX 82) to 256 values. The engine $\varepsilon$-\TeX allows more different registers (up to 32768), and Lua\TeX\ allows even 65536 ones. These new limits were not acknowledged by \LaTeX . A package \textsf{etex} was created for \LaTeX\ to extends the allocation scheme. \textsf{luatextra} loads \textsf{etex}, and overrides somes values to extend the allocation max number to 65536.
%
% \subsection{attributes}
% 
% Attributes are a new concept in Lua\TeX\ (see the Lua\TeX\ documentation for details). As the macro \texttt{\string\attribute} is certainly very common in the user's documents, they are renamed \texttt{luaattribute}s. This package provides a simple way to allocate new attributes, with the macro \texttt{\string\newluaattribute}. For more informations about attribute handling in lua, please read section \ref{sub:attr}.
% 
% \subsection{Module system}
%
% Lua has some embedded module management, with the functions \texttt{module} and \texttt{require}. With this package we try get more control on the module system, by implementing something close to the \LaTeX 's \texttt{\string\usepackage} and \texttt{\string\RequirePackage} macros: the \texttt{\string\luaUseModule} and \texttt{\string\luaRequireModule} that act like them, but for lua files. The functions \texttt{module} and \texttt{require} should not be used, in profit of the lua functions \texttt{luatextra.provides\_module} and \texttt{luatextra.use\_module} or \texttt{luatextra.require\_module}.
%
% \subsection{Multiple callbacks handling}
%
% Lua\TeX\ has no way to register multiple functions in a callback. This package loads \textsf{luamcallbacks} that provides a safe way to do so. But the \textsf{luamcallbacks} package can't register several functions in some callbacks, like \texttt{open\_read\_file} and \texttt{define\_font}. This package takes advantage of the callback creation possibilities of \textsf{luamcallbacks} to split these callbacks into several ones that can agregate several functions. Thus it allows several packages to safely use the callbacks. See section \ref{sub:orf} for more details.
%
% 
% \section{\texttt{luatextra.lua}}
%
% \subsection{Initialization and internal functions}
%
% \iffalse
%<*lua>
% \fi
%
% \TeX\ always prints the names of the files that are input. Unfortunatly it can't do so with lua files called with \texttt{dofile}. We will fix it with the \texttt{luatextra.use\_module} function, but in the meantime we print this information for the \texttt{luatextra.lua} file.
%
% A change compared to usual filename printings is the fact that Lua\TeX\ does not print the \texttt{./} for files in the current directory. We keep this convention for lua filename printings.
%
%    \begin{macrocode}
do
    local luatextrapath = kpse.find_file("luatextra.lua")
    if luatextrapath then
        if luatextrapath:sub(1,2) == "./" then
            luatextrapath = luatextrapath:sub(3)
        end
        texio.write(' ('..luatextrapath) 
    end
end

%    \end{macrocode}
%
% We create the \texttt{luatextra} table that will contain all the functions and variables, and we register it as a normal lua module.
%
%    \begin{macrocode}

luatextra = {}

module("luatextra", package.seeall)

%    \end{macrocode}
%
% We initiate the modules table that will contain informations about the loaded modules. And we register the \texttt{luatextra} module. The informations contained in the table describing the module are always the same, it can be taken as a template. See \texttt{luatextra.provides\_module} for more details.
%
%    \begin{macrocode}

luatextra.modules = {}

luatextra.modules['luatextra'] = {
    version     = 0.93,
    name        = "luatextra",
    date        = "2009/04/15",
    description = "Additional low level functions for LuaTeX",
    author      = "Elie Roux",
    copyright   = "Elie Roux, 2009",
    license     = "CC0",
}

local format = string.format

%    \end{macrocode}
%
% Here we define the warning and error functions specific to \texttt{luatextra}.
%
%    \begin{macrocode}

luatextra.internal_warning_spaces = "                   "

function luatextra.internal_warning(msg)
    if not msg then return end
    texio.write_nl(format("\nLuaTeXtra Warning: %s\n\n", msg))
end

luatextra.internal_error_spaces = "                 "

function luatextra.internal_error(msg)
    if not msg then return end
    tex.sprint(format("\\immediate\\write16{}\\errmessage{LuaTeXtra error: %s^^J^^J}", msg))
end

%    \end{macrocode}
%
% \subsection{Error, warning and info function for modules}
%
% Some module printing functions are provided, they have the same philosophy as the \LaTeX 's \texttt{\string\PackageError} and \texttt{\string\PackageWarning} macros: their first argument is the name of the module, and the second is the message. These functions are meant to be used by lua module writers.
%
%    \begin{macrocode}

function luatextra.module_error(package, msg, helpmsg)
    if not package or not msg then
        return
    end
    if helpmsg then
        tex.sprint(format("\\errhelp{%s}", helpmsg))
    end
    tex.sprint(format("\\luaModuleError{%s}{%s}", package, msg))
end

function luatextra.module_warning(modulename, msg)
    if not modulename or not msg then
        return
    end
    texio.write_nl(format("\nModule %s Warning: %s\n\n", modulename, msg))
end

function luatextra.module_log(modulename, msg)
    if not modulename or not msg then
        return
    end
    texio.write_nl('log', format("%s: %s", modulename, msg))
end

function luatextra.module_term(modulename, msg)
    if not modulename or not msg then
        return
    end
    texio.write_nl('term', format("%s: %s", modulename, msg))
end

function luatextra.module_info(modulename, msg)
    if not modulename or not msg then
        return
    end
    texio.write_nl(format("%s: %s\n", modulename, msg))
end

%    \end{macrocode}
%
% \subsection{module loading and providing functions}
%
% A small function to find a lua module file according to its name, with or without the \texttt{.lua} at the end of the filename.
%
%    \begin{macrocode}

function luatextra.find_module_file(name)
    if string.sub(name, -4) ~= '.lua' then
        name = name..'.lua'
    end
    path = kpse.find_file(name, 'tex')
    if not path then
      path = kpse.find_file(name, 'texmfscripts')
    end
    return path, name
end

%    \end{macrocode}
%
% A small patch, for the \texttt{module} function to work in this file. I can't understand why it doens't otherwise.
%
%    \begin{macrocode}

luatextra.module = module

%    \end{macrocode}
%
% \begin{macro}{luatextra.use module}
%
% This macro is the one used to simply load a lua module file. It does not reload it if it's already loaded, and prints the filename in the terminal and the log. A lua module must call the macro \texttt{luatextra.provides\_module}.
%
%    \begin{macrocode}


function luatextra.use_module(name)
    if not name or luatextra.modules[name] then
        return
    end
    local path, filename = luatextra.find_module_file(name)
    if not path then
        luatextra.internal_error(format("unable to find lua module %s", name))
    else
        if path:sub(1,2) == "./" then
            path = path:sub(3)
        end
        texio.write(' ('..path)
        dofile(path)
        if not luatextra.modules[name] then
            luatextra.internal_warning(format("You have requested module `%s',\n%s but the file %s does not provide it.", name, luatextra.internal_warning_spaces, filename))
        end
        if not package.loaded[name] then
            luatextra.module(name, package.seeall)
        end
        texio.write(')')
    end
end

%    \end{macrocode}
%
% \end{macro}
%
% Some internal functions to convert a date into a number, and to determine if a string is a date. It is useful for \texttt{luatextra.require\_package} to understand if a user asks a version with a date or a version number.
%
%    \begin{macrocode}

function luatextra.datetonumber(date)
    numbers = string.gsub(date, "(%d+)/(%d+)/(%d+)", "%1%2%3")
    return tonumber(numbers)
end

function luatextra.isdate(date)
    for _, _ in string.gmatch(date, "%d+/%d+/%d+") do
        return true
    end
    return false
end

local date, number = 1, 2

function luatextra.versiontonumber(version)
    if luatextra.isdate(version) then
        return {type = date, version = luatextra.datetonumber(version), orig = version}
    else
        return {type = number, version = tonumber(version), orig = version}
    end
end

luatextra.requiredversions = {}

%    \end{macrocode}
%
% \begin{macro}{luatextra.require module}
%
% This function is like the \texttt{luatextra.use\_module} function, but can accept a second argument that checks for the version of the module. The version can be a number or a date (format yyyy/mm/dd).
%
%    \begin{macrocode}

function luatextra.require_module(name, version)
    if not name then
        return
    end
    if not version then
        return luatextra.use_module(name)
    end
    luaversion = luatextra.versiontonumber(version)
    if luatextra.modules[name] then
        if luaversion.type == date then
            if luatextra.datetonumber(luatextra.modules[name].date) < luaversion.version then
                luatextra.internal_error(format("found module `%s' loaded in version %s, but version %s was required", name, luatextra.modules[name].date, version))
            end
        else
            if luatextra.modules[name].version < luaversion.version then
                luatextra.internal_error(format("found module `%s' loaded in version %.02f, but version %s was required", name, luatextra.modules[name].version, version))
            end
        end
    else
        luatextra.requiredversions[name] = luaversion
        luatextra.use_module(name)
    end
end

%    \end{macrocode}
%
% \end{macro}
%
% \begin{macro}{luatextra.provides module}
%
% This macro is the one that must be called in the module files. It takes a table as argument. You can put any information you want in this table, but the mandatory ones are \texttt{name} (a string), \texttt{version} (a number), \texttt{date} (a string) and \texttt{description} (a string). Other fields are usually \texttt{copyright}, \texttt{author} and \texttt{license}.
%
% This function logs informations about the module the same way \LaTeX\ does for informations about packages.
%
%    \begin{macrocode}

function luatextra.provides_module(mod)
    if not mod then
        luatextra.internal_error('cannot provide nil module')
        return
    end
    if not mod.version or not mod.name or not mod.date or not mod.description then
        luatextra.internal_error('invalid module registered, fields name, version, date and description are mandatory')
        return
    end
    requiredversion = luatextra.requiredversions[mod.name]
    if requiredversion then
        if requiredversion.type == date and requiredversion.version > luatextra.datetonumber(mod.date) then
            luatextra.internal_error(format("loading module %s in version %s, but version %s was required", mod.name, mod.date, requiredversion.orig))
        elseif requiredversion.type == number and requiredversion.version > mod.version then
            luatextra.internal_error(format("loading module %s in version %.02f, but version %s was required", mod.name, mod.version, requiredversion.orig))
        end
    end
    luatextra.modules[mod.name] = module
    texio.write_nl('log', format("Lua module: %s %s v%.02f %s\n", mod.name, mod.date, mod.version, mod.description))
end

%    \end{macrocode}
%
% \end{macro}
%
% Here we load the \textsf{luaextra} module, that contains a bunch of very useful functions. See the documentation of \textsf{luaextra} for more details.
%
%    \begin{macrocode}

luatextra.use_module('luaextra')

%    \end{macrocode}
%
% \texttt{luatextra.kpse\_module\_loader} finds a module with the \texttt{kpse} library. This function is then registered in the table of the functions used by the lua function \texttt{require} to look for modules.
%
%    \begin{macrocode}

function luatextra.kpse_module_loader(mod)
  local file = luatextra.find_module_file(mod)
  if file then
    local loader, error = loadfile(file)
    if loader then
      texio.write_nl("(" .. file .. ")")
      return loader
    end
    return "\n\t[luatextra.kpse_module_loader] Loading error:\n\t"
           .. error
  end
  return "\n\t[luatextra.kpse_module_loader] Search failed"
end

table.insert(package.loaders, luatextra.kpse_module_loader)

%    \end{macrocode}
%
% \subsection{Attributes handling\label{sub:attr}}
%
% Attribute allocation is done mainly in the \texttt{sty} file, but there is also a lua addition for attribute handling: Lua\TeX\ is by default unable to tell the attribute number corresponding to an attribute name. This attribute number is necessary for functions such as \texttt{node.has\_attribute}, which is used very often. The solution until now was to give a chosen attribute number to each attribute, and pray that someone else didn't use it before. With this method it was easy to know the number of an attribute, as it was chosen. Now with the \texttt{\string\newluaattribute} macro, it's impossible to know the number of an attribute. To fix it, when \texttt{\string\newluaattribute} is called, it calls \texttt{luatextra.attributedef\_from\_tex}. This function registers the number in the table \texttt{tex.attributenumber}. For example to get the number of the attribute \texttt{myattribute} registered with \texttt{\string\newluaattribute\string\myattribute}, you can simply call \texttt{tex.attributenumber[myattribute]}.
%
%    \begin{macrocode}

luatextra.attributes = {}

tex.attributenumber = luatextra.attributes

function luatextra.attributedef_from_tex(name, number)
    truename = name:gsub('[\\ ]', '')
    luatextra.attributes[truename] = tonumber(number)
end

%    \end{macrocode}
%
% \subsection{Catcodetables handling}
%
% In the same way, the table \texttt{tex.catcodetablenumber} contains the numbers of the catcodetables registered with \texttt{\string\newluacatcodetable}.
%
%    \begin{macrocode}

luatextra.catcodetables = {}

tex.catcodetablenumber = luatextra.catcodetables

function luatextra.catcodetabledef_from_tex(name, number)
    truename = name:gsub('[\\ ]', '')
    luatextra.catcodetables[truename] = tonumber(number)
end

%    \end{macrocode}
%
% \subsection{Multiple callbacks on the \texttt{open\_read\_file} callback\label{sub:orf}}
%
% The luamcallbacks (see documentation for details) cannot really provide a simple and reliable way of registering multiple functions in some callbacks. To be able to do so, the solution we implemented is to register one function in these callbacks, and to create "sub-callbacks" that can accept several functions. That's what we do here for the callback \texttt{open\_read\_file}.
%
% \begin{macro}{luatextra.open read file}
%
% This function is the one that will be registered in the callback. It calls new callbacks, that will be created later. These callbacks are:
%
%\begin{itemize}
% \item \texttt{pre\_read\_file} in which you can register a function with the signature \texttt{pre\_read\_file(env)}, with \texttt{env} being a table containing the fields \texttt{filename} which is the argument of the callback \texttt{open\_read\_file}, and \texttt{path} which is the result of \texttt{kpse.find\_file}. You can put any field you want in the \texttt{env} table, you can even override the existing fields. This function is called at the very beginning of the callback, it allows for instance to register functions in the other callbacks. It is useless to add a field \texttt{reader} or \texttt{close}, as they will be overriden.
% \item \texttt{file\_reader} is automatically registered in the \texttt{reader} callback for every file, it has the same signature.
% \item \texttt{file\_close} is registered in the \texttt{close} callback for every file, and has the same signature.
%\end{itemize}
%
%    \begin{macrocode}

function luatextra.open_read_file(filename)
    local path = kpse.find_file(filename)
    local env = {
      ['filename'] = filename,
      ['path'] = path,
    }
    luamcallbacks.call('pre_read_file', env)
    path = env.path
    if not path then
        return
    end
    local f = env.file
    if not f then
        f = io.open(path)
        env.file = f
    end
    if not f then
        return
    end
    env.reader = luatextra.reader
    env.close = luatextra.close
    return env
end

%    \end{macrocode}
%
% \end{macro}
%
% The two next functions are the one called in the \texttt{open\_read\_file} callback.
%
%    \begin{macrocode}


function luatextra.reader(env)
    local line = (env.file):read()
    line = luamcallbacks.call('file_reader', env, line)
    return line
end

function luatextra.close(env)
    (env.file):close()
    luamcallbacks.call('file_close', env)
end

%    \end{macrocode}
%
% In the callback creation process we need to have default behaviours. Here they are. These are called only when no function is registered in the created callback. See the documentation of \texttt{luamcallbacks} for more details.
%
%    \begin{macrocode}


function luatextra.default_reader(env, line)
    return line
end

function luatextra.default_close(env)
    return
end

function luatextra.default_pre_read(env)
    return env
end

%    \end{macrocode}
%
% \subsection{Multiple callbacks on the \texttt{define\_font} callback\label{sub:df}}
%
% The same principle is applied to the \texttt{define\_font} callback. The main difference is that this mechanism is not applied by default. The reason is that the callback most people will register in the \texttt{define\_font} callback is the one from Con\TeX t allowing the use of OT fonts. When the code will be more adapted (not so soon certainly), this mechanism will certainly be used, as it allows more flexibility in the font syntax, the OT font load mechanism, etc.
%
% The callbacks we register here are the following ones:
%
% \begin{itemize}
% \item \texttt{font\_syntax} that takes a table with the fields \texttt{asked\_name}, \texttt{name} and \texttt{size}, and modifies this table to add more information. It must add at least a \texttt{path} field. The structure of the final table is not precisely defined, as it can vary from one syntax to another.
% \item \texttt{open\_otf\_font} takes the previous table, and must return a valid font structure as described in the Lua\TeX\ manual.
% \item \texttt{post\_font\_opening} takes the final font table and can modify it, before this table is returned to the \texttt{define\_font} callback.
% \end{itemize}
%
% But first, we acknowledge the fact that \texttt{fontforge} has been renamed to \texttt{fontloader}. This check allows older versions of Lua\TeX\ to use \texttt{fontloader}.
%
% As this mechanism is not loaded by default and certainly won't be until version 1.0 of Lua\TeX , we don't document it further. See the documentation of \texttt{luatextra.sty} (macro \texttt{\string\ltxtra\string@RegisterFontCallback}) to know how to load this mechanism anyway.
%
%    \begin{macrocode}

do
  if tex.luatexversion < 36 then
      fontloader = fontforge
  end
end

function luatextra.find_font(name)
    local types = {'ofm', 'ovf', 'opentype fonts', 'truetype fonts'}
    local path = kpse.find_file(name)
    if path then return path end
    for _,t in pairs(types) do
        path = kpse.find_file(name, t)
        if path then return path end
    end
    return nil
end

function luatextra.font_load_error(error)
    luatextra.module_warning('luatextra', string.format('%s\nloading lmr10 instead...', error))
end

function luatextra.load_default_font(size)
    return font.read_tfm("lmr10", size)
end

function luatextra.define_font(name, size)
    if (size < 0) then size = (- 655.36) * size end
    local fontinfos = {
        asked_name = name,
        name = name,
        size = size
        }
    callback.call('font_syntax', fontinfos)
    name = fontinfos.name
    local path = fontinfos.path
    if not path then
        path = luatextra.find_font(name)
        fontinfos.path = luatextra.find_font(name)
    end
    if not path then
        luatextra.font_load_error("unable to find font "..name)
        return luatextra.load_default_font(size)
    end
    if not fontinfos.filename then
        fontinfos.filename = fpath.basename(path)
    end
    local ext = fpath.suffix(path)
    local f
    if ext == 'tfm' or ext == 'ofm' then
        f =  font.read_tfm(name, size)
    elseif ext == 'vf' or ext == 'ovf' then
        f =  font.read_vf(name, size)
    elseif ext == 'ttf' or ext == 'otf' or ext == 'ttc' then
        f = callback.call('open_otf_font', fontinfos)
    else
        luatextra.font_load_error("unable to determine the type of font "..name)
        f = luatextra.load_default_font(size)
    end
    if not f then
        luatextra.font_load_error("unable to load font "..name)
        f = luatextra.load_default_font(size)
    end
    callback.call('post_font_opening', f, fontinfos)
    return f
end

function luatextra.default_font_syntax(fontinfos)
    return
end

function luatextra.default_open_otf(fontinfos)
    return nil
end

function luatextra.default_post_font(f, fontinfos)
    return true
end

function luatextra.register_font_callback()
    callback.add('define_font', luatextra.define_font, 'luatextra.define_font')
end

do
    luatextra.use_module('luamcallbacks')
    callback.create('pre_read_file', 'simple', luatextra.default_pre_read)
    callback.create('file_reader', 'data', luatextra.default_reader)
    callback.create('file_close', 'simple', luatextra.default_close)
    callback.add('open_read_file', luatextra.open_read_file, 'luatextra.open_read_file')
    callback.create('font_syntax', 'simple', luatextra.default_font_syntax)
    callback.create('open_otf_font', 'first', luatextra.default_open_otf)
    callback.create('post_font_opening', 'simple', luatextra.default_post_font)

    if luatextrapath then
        texio.write(')')
    end
end
%    \end{macrocode}
% \iffalse
%</lua>
% \fi
%
% \section{\texttt{luatextra.sty}}
%
% \iffalse
%<*package>
% \fi
%
% \subsection{Initializations}
%
% First we prevent multiple loads of the file (useful for plain-\TeX ).
%
%    \begin{macrocode}
\csname ifluatextraloaded\endcsname
\let\ifluatextraloaded\endinput

%    \end{macrocode}
%
% Then we load \textsf{ifluatex}.
%
%    \begin{macrocode}

\expandafter\ifx\csname ProvidesPackage\endcsname\relax
  \expandafter\ifx\csname ifluatex\endcsname\relax
    \input ifluatex.sty
  \fi
\else
  \RequirePackage{ifluatex}
\fi

\expandafter\ifx\csname ProvidesPackage\endcsname\relax
%    \end{macrocode}
%
% If the package is loaded with Plain, we raise an error if the package is called with a non-Lua\TeX\ engine, and we define \texttt{\string\luaRequireModule} with two mandatory arguments.
%
%    \begin{macrocode}
  \ifluatex\else
    \immediate\write16{}
    \errmessage{Package luatextra Error: This package must be used with LuaTeX}
  \fi
  \def\luaRequireModule#1#2{\luadirect{luatextra.require_module([[#1]], [[#2]])}}
\else
%    \end{macrocode}
%
% If the package is loaded with \LaTeX , we also print the error message, and we define \texttt{\string\luaRequireModule} with one mandatory argument (the name of the package) and one optional (the version or the date). We also define the environment \texttt{luacode}.
%
%    \begin{macrocode}
  \ifluatex\else
    \PackageError{luatextra}{This package must be used with LuaTeX.}
  \fi
  \NeedsTeXFormat{LaTeX2e}
  \ProvidesPackage{luatextra}
    [2009/04/15 v0.93 LuaTeX extra low-level macros]
  \RequirePackage{environ}
  \NewEnviron{luacode}{\luadirect{\BODY}}
  \newcommand\luaRequireModule[2][0]{\luadirect{luatextra.require_module([[#2]], [[#1]])}}
%    \end{macrocode}
%
% We also require the package \textsf{etex} to be loaded. The \texttt{\string\input} is a hack that modifies some values in the register attribution scheme of $\varepsilon$-\TeX\ and remaps \texttt{\string\newcount} to \textsf{etex}'s \texttt{\string\globcount}. We have to do such a remapping in a separate file that Plain doesn't see, otherwise it outputs an error if we try to change \texttt{\string\newcount} (because it is an \texttt{\string\outer} macro). See section \ref{sub:latex} for the file content.
%
%    \begin{macrocode}
  \RequirePackage{etex}[1998/03/26]%
  \input luatextra-latex.tex
\fi

%    \end{macrocode}
%
% The two macros \texttt{\string\LuaTeX} and \texttt{\string\LuaLaTeX} are defined to Lua\TeX\ and Lua\LaTeX , because that's the way it's written in the Lua\TeX 's manual (not in small capitals).
%
%    \begin{macrocode}

\def\LuaTeX{Lua\TeX }
\def\LuaLaTeX{Lua\LaTeX }

%    \end{macrocode}
%
% \subsection{Primitives renaming}
%
% Here we differenciate two very different cases: Lua\TeX\ version < 0.36 has no \texttt{tex.enableprimitives} function, and has support for multiple lua states, and for versions > 0.35, the \texttt{tex.enableprimitives} is provided, and the old \texttt{\string\directlua} syntax prints a warning.
%
%    \begin{macrocode}

\ifnum\luatexversion<36
%    \end{macrocode}
%
% For old versions, we simply rename the primitives. You can note that \texttt{\string\attribute} (and also others) have no \texttt{\string\primitive} before them, because it would make users unable to call \texttt{\string\global\string\luaattribute}, which is a strong restriction. With this method, we can call it, but if \texttt{\string\attribute} was defined before, this means that \texttt{\string\luaattribute} will get its meaning, which is dangerous. Note also that you cannot use multiple states.
%
%    \begin{macrocode}
  \def\directlua{\pdfprimitive\directlua0}
  \def\latelua{\pdfprimitive\latelua0}
  \def\luadirect{\pdfprimitive\directlua0}
  \def\lualate{\pdfprimitive\latelua0}
  \def\luaattribute{\attribute}
  \def\luaattributedef{\attributedef}
  \def\luaclearmarks{\pdfprimitive\luaclearmarks}
  \def\luaformatname{\pdfprimitive\formatname}
  \def\luascantexttokens{\pdfprimitive\scantexttokens}
  \def\luacatcodetable{\catcodetable}
\else
%    \end{macrocode}
%
% For newer versions, we first enable all primitives with their default name. Then we add a prefix to some. Note that with this method, \texttt{\string\luaattribute} will always have the good meaning (except, of course, if it was defined before, but I think we can call it perversion...).
%
%    \begin{macrocode}
  \directlua{tex.enableprimitives('lua', {'attribute'})}
  \directlua{tex.enableprimitives('lua', {'attributedef'})}
  \directlua{tex.enableprimitives('lua', {'clearmarks'})}
  \directlua{tex.enableprimitives('lua', {'formatname'})}
  \directlua{tex.enableprimitives('lua', {'scantexttokens'})}
  \directlua{tex.enableprimitives('lua', {'catcodetable'})}
  \def\luadirect{\pdfprimitive\directlua}
  \def\lualate{\pdfprimitive\latelua}
\fi

%    \end{macrocode}
%
% Finally we add some common definitions that have lua inside their name, or that must remove their suffix.
%
%    \begin{macrocode}
\def\initluacatcodetable{\pdfprimitive\initcatcodetable}
\def\saveluacatcodetable{\pdfprimitive\savecatcodetable}
\def\luaclose{\pdfprimitive\closelua}

%    \end{macrocode}
%
% We load the \texttt{lua} file.
%
%    \begin{macrocode}

\luadirect{dofile(kpse.find_file("luatextra.lua"))}

%    \end{macrocode}
%
% A small macro to register the \texttt{define\_font} callback from \textsf{luatextra}. See section \ref{sub:df} for more details.
%
%    \begin{macrocode}

\def\ltxtra@RegisterFontCallback{
  \luadirect{luatextra.register_font_callback()}
}

%    \end{macrocode}
%
% \subsection{Module handling}
%
% The \texttt{\string\luaModuleError} macro is called by the lua function \texttt{luatextra.module\_error}. It is necessary because we can't call directly \texttt{\string\errmessage} in lua.
%
%    \begin{macrocode}

%    \end{macrocode}
%
% \subsection{Module handling}
%
% The \texttt{\string\luaModuleError} macro is called by the lua function \texttt{luatextra.module\_error}. It is necessary because we can't call directly \texttt{\string\errmessage} in lua. Then we define \texttt{\string\luaUseModule} that simply calls \texttt{luatextra.use\_module}. Remember that \texttt{\string\luaRequireModule} is defined at the beginning of this file.
%
%    \begin{macrocode}


\def\luaModuleError#1#2{%
  \errorcontextlines=0\relax
  \immediate\write16{}%
  \errmessage{Module #1 error: #2^^J^^J%
See the module #1 documentation for explanation.^^J ...^^J}%
}

\def\luaUseModule#1{\luadirect{luatextra.use_module([[#1]])}}

%    \end{macrocode}
%
% \subsection{Attributes handling}
%
% The most important macro here is \texttt{\string\newluaattribute} that allocates a new attribute, and adds it in the \texttt{tex.attributename} table (see \texttt{luatextra.attributedef\_from\_tex} for more details. It works just like the other \texttt{\string\new*} macros, we can allocate up to 65536 different attributes.
%
%    \begin{macrocode}


\newcount\luaattdefcounter
\luaattdefcounter = 1

\def\newluaattribute#1{%
  \ifnum\luaattdefcounter<65535\relax %
    \global\advance\luaattdefcounter by 1\relax %
    \allocationnumber\luaattdefcounter %
    \ifluatex %
      \global\luaattributedef#1=\allocationnumber %
    \fi %
    \wlog{\string#1=\string\attribute\the\allocationnumber}%
    \luadirect{%
      luatextra.attributedef_from_tex([[\noexpand#1]], '\number\allocationnumber')}%
  \else %
    \errmessage{No room for a new \string\attribute}%
  \fi %
}

%    \end{macrocode}
%
% Two convenient macros, one to set an attribute (basically just a wrapper), and another one to uset it. Unsetting attributes with this function is important, as the \texttt{unset} value may change, as it already has in the 0.37 version.
%
%    \begin{macrocode}

\def\setluaattribute#1#2{%
  #1=\numexpr#2\relax %
}

\def\unsetluaattribute#1{%
  \ifnum\luatexversion<37\relax %
    #1=-1\relax %
  \else %
    #1=-"7FFFFFFF\relax %
  \fi %
}

%    \end{macrocode}
%
% \subsection{Catcodetables handling}
%
% Here we allocate catcodetables the same way we handle attributes.
%
%    \begin{macrocode}

\newcount\luacatcodetabledefcounter

\luacatcodetabledefcounter = 1

\def\newluacatcodetable#1{%
  \ifnum\luacatcodetabledefcounter<1114110\relax % 0x10FFFF is maximal \chardef
    \global\advance\luacatcodetabledefcounter by 1\relax %
    \allocationnumber=\luacatcodetabledefcounter %
    \global\chardef#1=\allocationnumber %
    \luadirect{%
      luatextra.catcodetabledef_from_tex([[\noexpand#1]], '\number\allocationnumber')}%
    \wlog{\string#1=\string\catcodetable\the\allocationnumber}%
  \else %
    \errmessage{No room for a new \string\catcodetable}%
  \fi %
}

%    \end{macrocode}
%
% A small patch to manage the catcode of \@ in Plain, and to get two new counters in Plain too.
%
%    \begin{macrocode}

\expandafter\edef\csname ltxtra@AtEnd\endcsname{%
  \catcode64 \the\catcode64\relax
}

\catcode 64=11\relax

\expandafter\ifx\csname @tempcnta\endcsname\relax
  \csname newcount\endcsname\@tempcnta
\fi
\expandafter\ifx\csname @tempcntb\endcsname\relax
  \csname newcount\endcsname\@tempcntb
\fi

%    \end{macrocode}
%
% A macro that sets the catcode of a range of characters. The first parameter is the character number of the first character of the range, the second parameter is one for the last character, and the third parameter is the catcode we want them to have. 
%
%    \begin{macrocode}

\def\luasetcatcoderange#1#2#3{%
  \edef\luaSCR@temp{%
    \noexpand\@tempcnta=\the\@tempcnta
    \noexpand\@tempcntb=\the\@tempcntb
    \noexpand\count@=\the\count@
    \relax
  }%
  \@tempcnta=#1\relax
  \@tempcntb=#2\relax
  \count@=#3\relax
  \loop\unless\ifnum\@tempcnta>\@tempcntb
    \catcode\@tempcnta=\count@
    \advance\@tempcnta by 1\relax
  \repeat
  \luaSCR@temp
}

%    \end{macrocode}
%
% Finally we create several catcodetables that may be used by the user. These are:
%
% \begin{itemize}
% \item \texttt{\string\CatcodeTableIniTeX}: the base \TeX\ catcodes
% \item \texttt{\string\CatcodeTableString}: almost all characters have catcode 12
% \item \texttt{\string\CatcodeTableOther}: all characters have catcode 12 (even space)
% \item \texttt{\string\CatcodeTableLaTeX}: the \LaTeX\ classical catcodes
% \end{itemize}
%
%    \begin{macrocode}

\newluacatcodetable\CatcodeTableIniTeX
\newluacatcodetable\CatcodeTableString
\newluacatcodetable\CatcodeTableOther
\newluacatcodetable\CatcodeTableLaTeX
\initluacatcodetable\CatcodeTableIniTeX

\expandafter\ifx\csname @firstofone\endcsname\relax
  \long\def\@firstofone#1{#1}%
\fi

\begingroup
  \def\@makeother#1{\catcode#1=12\relax}%
  \@firstofone{%
    \luacatcodetable\CatcodeTableIniTeX
    \begingroup
      \luasetcatcoderange{0}{8}{15}%
      \catcode9=10  % tab
      \catcode11=15 %
      \catcode12=13 % form feed
      \luasetcatcoderange{14}{31}{15}%
      \catcode35=6 % hash
      \catcode36=3 % dollar
      \catcode38=4 % ampersand
      \catcode94=7 % circumflex
      \catcode95=8 % underscore
      \catcode123=1 % brace left
      \catcode125=2 % brace right
      \catcode126=13 % tilde
      \catcode127=15 %
      \saveluacatcodetable\CatcodeTableLaTeX
    \endgroup
    \@makeother{0}% nul
    \@makeother{13}% carriage return
    \@makeother{37}% percent
    \@makeother{92}% backslash
    \@makeother{127}%
    \luasetcatcoderange{65}{90}{12}% A-Z
    \luasetcatcoderange{97}{122}{12}% a-z
    \saveluacatcodetable\CatcodeTableString
    \@makeother{32}% space
    \saveluacatcodetable\CatcodeTableOther
  \endgroup
}

%    \end{macrocode}
%
% We load \textsf{luaotfload}. 
%
%    \begin{macrocode}

\expandafter\ifx\csname ProvidesPackage\endcsname\relax
  \input luaotfload.sty
\else
  \RequirePackage{luaotfload}
\fi

\ltxtra@AtEnd
%    \end{macrocode}
% \iffalse
%</package>
% \fi
%
% \section{\texttt{luatextra-latex.tex}\label{sub:latex}}
%
% This file is very small, it just changes the maximum values of allowed registers from 32768 to 65536, and remaps \texttt{\string\newcount} (and friends) to \textsf{etex}'s \texttt{\string\globcount}.
%
% \iffalse
%<*latex>
% \fi
%    \begin{macrocode}
\def\ltxtra@temp#1{%
\ifnum\count27#1=32768 %
  \count27#1=65536 %
\fi
}%
\ltxtra@temp0%
\ltxtra@temp1%
\ltxtra@temp2%
\ltxtra@temp3%
\ltxtra@temp4%
\ltxtra@temp5%
\ltxtra@temp6%
\let\newcount\globcount
\let\newdimen\globdimen
\let\newskip\globskip
\let\newbox\globbox
%    \end{macrocode}
% \iffalse
%</latex>
% \fi
%
% 
% \Finale
\endinput