summaryrefslogtreecommitdiff
path: root/luaextra.dtx
blob: 180a92900763aa9d57d9f7bbf9d421fadffd1c58 (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
% \iffalse meta-comment
%
% Copyright (C) 2009 by PRAGMA ADE / ConTeXt Development Team
%
% See ConTeXt's mreadme.pdf for the license.
%
% This work consists of the main source file luaextra.dtx
% and the derived file luaextra.lua.
%
% Unpacking:
%    tex luatextra.dtx
%
% Documentation:
%    pdftex luaextra.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: luaextra 2009/03/19 v0.91 Lua additional functions.}
\Msg{************************************************************************}

\keepsilent
\askforoverwritefalse

\let\MetaPrefix\relax

\preamble
This is a generated file.

Copyright (C) 2009 by PRAGMA ADE / ConTeXt Development Team

See ConTeXt's mreadme.pdf for the license.

This work consists of the main source file luaextra.dtx
and the derived file luaextra.lua.

\endpreamble

% 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{luaextra.lua}{\from{luaextra.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{*     luaextra.lua}
\Msg{*}
\Msg{* Happy TeXing!}
\Msg{*}
\Msg{************************************************************************}

\endbatchfile
%</install>
%<*ignore>
\fi
%</ignore>
%<*driver>
\NeedsTeXFormat{LaTeX2e}
\ProvidesFile{luaextra.drv}
  [2009/04/15 v0.91 Lua additional functions.]
\documentclass{ltxdoc}
\EnableCrossrefs
\CodelineIndex
\begin{document}
  \DocInput{luaextra.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{luaextra.drv}
%
% \title{The \textsf{luaextra} package}
% \date{2009/04/15 v0.91}
% \author{Elie Roux \\ \texttt{elie.roux@telecom-bretagne.eu}}
%
% \maketitle
%
% \begin{abstract}
% Additional lua functions taken from the libs of Con\TeX t. For an introduction on this package (among others), please refer to the document \texttt{luatex-reference.pdf}.
% \end{abstract}
%
% \section{Overview}
%
% Lua is a very minimal language, and it does not have a lot of built-in functions. Some functions will certainly be needed by a lot of packages. Instead of making each of them implement these functions, the aim of this file is to provide a minimal set of functions. All functions are taken from Con\TeX t libraries.
%
% There are some differences with the Con\TeX t funtions though, especially on names: for example the \texttt{file.*} funtions are renamed in \texttt{fpath.*}. It seems more logical as they deal with file paths, not files. Also the \texttt{file.is\_readable} and \texttt{file.is\_writable} are renamed \texttt{lfs.is\_readable} and \texttt{lfs.is\_writable}.
%
% If you use a function you think is missing in this file, please tell the maintainer.
%
% \texttt{Warning:} Even if the names will certainly remain the same, some implementations may differ, and some functions might appear or dissapear. As Lua\TeX\ is not stable, this file is not neither.
%
% All functions are described in this document, but the one of the functions you'll use most will certainly be \texttt{table.serialize} (also named \texttt{table.tostring}) that takes a table and returns an intented string describing the table. It describes the table so that Lua\TeX\ can read it again as a table. You can do a lot of things with this functions, like printing a table for debugging, or saving a table into a file. Functions are also converted into bytecode to be saved.
%
% \section{\texttt{luaextra.lua}}
%
% \iffalse
%<*lua>
% \fi
%
%    \begin{macrocode}
do
    local luatextra_module = {
        name          = "luaextra",
        version       = 0.91,
        date          = "2009/04/15",
        description   = "Lua additional functions.",
        author        = "Hans Hagen, PRAGMA-ADE, Hasselt NL & Elie Roux",
        copyright     = "PRAGMA ADE / ConTeXt Development Team",
        license       = "See ConTeXt's mreadme.pdf for the license",
    }

    luatextra.provides_module(luatextra_module)
end
%    \end{macrocode}
%
% \begin{macro}{string:stripspaces}
%
% A function to strip the spaces at the beginning and at the end of a string.
%
%    \begin{macrocode}

function string:stripspaces()
    return (self:gsub("^%s*(.-)%s*$", "%1"))
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{string.is boolean}
%
% If the argument is a string describing a boolean, this function returns the boolean, otherwise it retuns nil.
%
%    \begin{macrocode}

function string.is_boolean(str)
    if type(str) == "string" then
        if str == "true" or str == "yes" or str == "on" or str == "t" then
            return true
        elseif str == "false" or str == "no" or str == "off" or str == "f" then
            return false
        end
    end
    return nil
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{string.is number}
%
% Returns true if the argument string is a number.
%
%    \begin{macrocode}

function string.is_number(str)
    return str:find("^[%-%+]?[%d]-%.?[%d+]$") == 1
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{lpeg.space and lpeg.newline}
%
% Two small helpers for \texttt{lpeg}, that will certainly be widely used: spaces and newlines.
%
%    \begin{macrocode}

lpeg.space    = lpeg.S(" \t\f\v")
lpeg.newline  = lpeg.P("\r\n") + lpeg.P("\r") +lpeg.P("\n")

%    \end{macrocode}
%
% \end{macro}\begin{macro}{table.fastcopy}
%
% A function copying a table fastly.
%
%    \begin{macrocode}

if not table.fastcopy then do

    local type, pairs, getmetatable, setmetatable = type, pairs, getmetatable, setmetatable

    local function fastcopy(old) -- fast one
        if old then
            local new = { }
            for k,v in pairs(old) do
                if type(v) == "table" then
                    new[k] = fastcopy(v) -- was just table.copy
                else
                    new[k] = v
                end
            end
            local mt = getmetatable(old)
            if mt then
                setmetatable(new,mt)
            end
            return new
        else
            return { }
        end
    end

    table.fastcopy = fastcopy

end end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{table.copy}
%
% A function copying a table in more cases than fastcopy, for example when a key is a table.
%
%    \begin{macrocode}

if not table.copy then do

    local type, pairs, getmetatable, setmetatable = type, pairs, getmetatable, setmetatable

    local function copy(t, tables) -- taken from lua wiki, slightly adapted
        tables = tables or { }
        local tcopy = {}
        if not tables[t] then
            tables[t] = tcopy
        end
        for i,v in pairs(t) do -- brrr, what happens with sparse indexed
            if type(i) == "table" then
                if tables[i] then
                    i = tables[i]
                else
                    i = copy(i, tables)
                end
            end
            if type(v) ~= "table" then
                tcopy[i] = v
            elseif tables[v] then
                tcopy[i] = tables[v]
            else
                tcopy[i] = copy(v, tables)
            end
        end
        local mt = getmetatable(t)
        if mt then
            setmetatable(tcopy,mt)
        end
        return tcopy
    end

    table.copy = copy

end end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{table.serialize}
%
% A bunch of functions leading to \texttt{table.serialize}.
%
%    \begin{macrocode}

function table.sortedkeys(tab)
    local srt, kind = { }, 0 -- 0=unknown 1=string, 2=number 3=mixed
    for key,_ in pairs(tab) do
        srt[#srt+1] = key
        if kind == 3 then
            -- no further check
        else
            local tkey = type(key)
            if tkey == "string" then
            --  if kind == 2 then kind = 3 else kind = 1 end
                kind = (kind == 2 and 3) or 1
            elseif tkey == "number" then
            --  if kind == 1 then kind = 3 else kind = 2 end
                kind = (kind == 1 and 3) or 2
            else
                kind = 3
            end
        end
    end
    if kind == 0 or kind == 3 then
        table.sort(srt,function(a,b) return (tostring(a) < tostring(b)) end)
    else
        table.sort(srt)
    end
    return srt
end

do
    table.serialize_functions = true
    table.serialize_compact   = true
    table.serialize_inline    = true

    local function key(k)
        if type(k) == "number" then -- or k:find("^%d+$") then
            return "["..k.."]"
        elseif noquotes and k:find("^%a[%a%d%_]*$") then
            return k
        else
            return '["'..k..'"]'
        end
    end

    local function simple_table(t)
        if #t > 0 then
            local n = 0
            for _,v in pairs(t) do
                n = n + 1
            end
            if n == #t then
                local tt = { }
                for i=1,#t do
                    local v = t[i]
                    local tv = type(v)
                    if tv == "number" or tv == "boolean" then
                        tt[#tt+1] = tostring(v)
                    elseif tv == "string" then
                        tt[#tt+1] = ("%q"):format(v)
                    else
                        tt = nil
                        break
                    end
                end
                return tt
            end
        end
        return nil
    end

    local function serialize(root,name,handle,depth,level,reduce,noquotes,indexed)
        handle = handle or print
        reduce = reduce or false
        if depth then
            depth = depth .. " "
            if indexed then
                handle(("%s{"):format(depth))
            else
                handle(("%s%s={"):format(depth,key(name)))
            end
        else
            depth = ""
            local tname = type(name)
            if tname == "string" then
                if name == "return" then
                    handle("return {")
                else
                    handle(name .. "={")
                end
            elseif tname == "number" then
                handle("[" .. name .. "]={")
            elseif tname == "boolean" then
                if name then
                    handle("return {")
                else
                    handle("{")
                end
            else
                handle("t={")
            end
        end
        if root and next(root) then
            local compact = table.serialize_compact
            local inline  = compact and table.serialize_inline
            local first, last = nil, 0 -- #root cannot be trusted here
            if compact then
              for k,v in ipairs(root) do -- NOT: for k=1,#root do (why)
                    if not first then first = k end
                    last = last + 1
                end
            end
            for _,k in pairs(table.sortedkeys(root)) do
                local v = root[k]
                local t = type(v)
                if compact and first and type(k) == "number" and k >= first and k <= last then
                    if t == "number" then
                        handle(("%s %s,"):format(depth,v))
                    elseif t == "string" then
                        if reduce and (v:find("^[%-%+]?[%d]-%.?[%d+]$") == 1) then
                            handle(("%s %s,"):format(depth,v))
                        else
                            handle(("%s %q,"):format(depth,v))
                        end
                    elseif t == "table" then
                        if not next(v) then
                            handle(("%s {},"):format(depth))
                        elseif inline then
                            local st = simple_table(v)
                            if st then
                                handle(("%s { %s },"):format(depth,table.concat(st,", ")))
                            else
                                serialize(v,k,handle,depth,level+1,reduce,noquotes,true)
                            end
                        else
                            serialize(v,k,handle,depth,level+1,reduce,noquotes,true)
                        end
                    elseif t == "boolean" then
                        handle(("%s %s,"):format(depth,tostring(v)))
                    elseif t == "function" then
                        if table.serialize_functions then
                            handle(('%s loadstring(%q),'):format(depth,string.dump(v)))
                        else
                            handle(('%s "function",'):format(depth))
                        end
                    else
                        handle(("%s %q,"):format(depth,tostring(v)))
                    end
                elseif k == "__p__" then -- parent
                    if false then
                        handle(("%s __p__=nil,"):format(depth))
                    end
                elseif t == "number" then
                    handle(("%s %s=%s,"):format(depth,key(k),v))
                elseif t == "string" then
                    if reduce and (v:find("^[%-%+]?[%d]-%.?[%d+]$") == 1) then
                        handle(("%s %s=%s,"):format(depth,key(k),v))
                    else
                        handle(("%s %s=%q,"):format(depth,key(k),v))
                    end
                elseif t == "table" then
                    if not next(v) then
                        handle(("%s %s={},"):format(depth,key(k)))
                    elseif inline then
                        local st = simple_table(v)
                        if st then
                            handle(("%s %s={ %s },"):format(depth,key(k),table.concat(st,", ")))
                        else
                            serialize(v,k,handle,depth,level+1,reduce,noquotes)
                        end
                    else
                        serialize(v,k,handle,depth,level+1,reduce,noquotes)
                    end
                elseif t == "boolean" then
                    handle(("%s %s=%s,"):format(depth,key(k),tostring(v)))
                elseif t == "function" then
                    if table.serialize_functions then
                        handle(('%s %s=loadstring(%q),'):format(depth,key(k),string.dump(v)))
                    else
                        handle(('%s %s="function",'):format(depth,key(k)))
                    end
                else
                    handle(("%s %s=%q,"):format(depth,key(k),tostring(v)))
                --  handle(('%s %s=loadstring(%q),'):format(depth,key(k),string.dump(function() return v end)))
                end
            end
            if level > 0 then
                handle(("%s},"):format(depth))
            else
                handle(("%s}"):format(depth))
            end
        else
            handle(("%s}"):format(depth))
        end
    end

    function table.serialize(root,name,reduce,noquotes)
        local t = { }
        local function flush(s)
            t[#t+1] = s
        end
        serialize(root, name, flush, nil, 0, reduce, noquotes)
        return table.concat(t,"\n")
    end

    function table.tostring(t, name)
        return table.serialize(t, name)
    end

    function table.tohandle(handle,root,name,reduce,noquotes)
        serialize(root, name, handle, nil, 0, reduce, noquotes)
    end

    -- sometimes tables are real use (zapfino extra pro is some 85M) in which
    -- case a stepwise serialization is nice; actually, we could consider:
    --
    -- for line in table.serializer(root,name,reduce,noquotes) do
    --    ...(line)
    -- end
    --
    -- so this is on the todo list

    table.tofile_maxtab = 2*1024

    function table.tofile(filename,root,name,reduce,noquotes)
        local f = io.open(filename,'w')
        if f then
            local concat = table.concat
            local maxtab = table.tofile_maxtab
            if maxtab > 1 then
                local t = { }
                local function flush(s)
                    t[#t+1] = s
                    if #t > maxtab then
                        f:write(concat(t,"\n"),"\n") -- hm, write(sometable) should be nice
                        t = { }
                    end
                end
                serialize(root, name, flush, nil, 0, reduce, noquotes)
                f:write(concat(t,"\n"),"\n")
            else
                local function flush(s)
                    f:write(s,"\n")
                end
                serialize(root, name, flush, nil, 0, reduce, noquotes)
            end
            f:close()
        end
    end

end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{table.tohash}
%
% Returning a table with all values of the argument table as keys, and \texttt{false} as values. This is what we will call a hash.
%
%    \begin{macrocode}

function table.tohash(t)
    local h = { }
    for _, v in pairs(t) do -- no ipairs here
        h[v] = true
    end
    return h
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{table.fromhash}
%
% Returning a table built from a hash, with simple integer keys.
%
%    \begin{macrocode}

function table.fromhash(t)
    local h = { }
    for k, v in pairs(t) do -- no ipairs here
        if v then h[#h+1] = k end
    end
    return h
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{table.contains value}
%
% A function returning true if the value \texttt{val} is in the table \texttt{t}.
%
%    \begin{macrocode}

function table.contains_value(t, val)
    if t then
        for k, v in pairs(t) do
            if v==val then
                return true
            end
        end
    end
    return false
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{table.contains key}
%
% A function returning true if the key \texttt{key} is in the table \texttt{t}
%
%    \begin{macrocode}

function table.contains_key(t, key)
    if t then
        for k, v in pairs(t) do
            if k==key then
                return true
            end
        end
    end
    return false
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{table.value position}
%
% A function returning the position of a value in a table. This will be important to be able to remove a value.
%
%    \begin{macrocode}

function table.value_position(t, val)
    if t then
        local i=1
        for k, v in pairs(t) do
            if v==val then
                return i
            end
            i=i+1
        end
    end
    return 0
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{table.key position}
%
% A function returning the position of a key in a table.
%
%    \begin{macrocode}

function table.key_position(t, key)
    if t then
        local i=1
        for k,v in pairs(t) do
            if k==key then
                return i
            end
            i = i+1
        end
    end
    return -1
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{table.remove value}
%
% Removes the first occurence of a value from a table.
%
%    \begin{macrocode}

function table.remove_value(t, v)
    local p = table.value_position(t,v)
    if p ~= -1 then
        table.remove(t, table.value_position(t,v))
    end
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{table.remove key}
%
% Removing a key from a table.
%
%    \begin{macrocode}

function table.remove_key(t, k)
    local p = table.key_position(t,k)
    if p ~= -1 then
        table.remove(t, table.key_position(t,k))
    end
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{table.is empty}
%
% Returns true if a table is empty.
%
%    \begin{macrocode}

function table.is_empty(t)
    return not t or not next(t)
end

%    \end{macrocode}
%
%  \texttt{fpath} will contain all the file path manipulation functions. Some functions certainly need a little update or cleanup...
%
%    \begin{macrocode}

fpath = { }

%    \end{macrocode}
%
% \end{macro}\begin{macro}{fpath.removesuffix}
%
% A function to remove the suffix (extention) of a filename.
%
%    \begin{macrocode}

function fpath.removesuffix(filename)
    return filename:gsub("%.[%a%d]+$", "")
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{fpath.addsuffix}
%
% A function adding a suffix to a filename, except if it already has one.
%
%    \begin{macrocode}

function fpath.addsuffix(filename, suffix)
    if not filename:find("%.[%a%d]+$") then
        return filename .. "." .. suffix
    else
        return filename
    end
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{fpath.replacesuffix}
%
% A function replacing a suffix by a new one.
%
%    \begin{macrocode}

function fpath.replacesuffix(filename, suffix)
    if not filename:find("%.[%a%d]+$") then
        return filename .. "." .. suffix
    else
        return (filename:gsub("%.[%a%d]+$","."..suffix))
    end
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{fpath.dirname}
%
% A function returning the directory of a file path.
%
%    \begin{macrocode}

function fpath.dirname(name)
    return name:match("^(.+)[/\\].-$") or ""
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{fpath.basename}
%
% A function returning the basename (the name of the file, without the directories) of a file path.
%
%    \begin{macrocode}

function fpath.basename(fname)
    if not fname then
        return nil
    end
    return fname:match("^.+[/\\](.-)$") or fname
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{fpath.nameonly}
%
% Returning the basename of a file without the suffix.
%
%    \begin{macrocode}

function fpath.nameonly(name)
    return ((name:match("^.+[/\\](.-)$") or name):gsub("%..*$",""))
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{fpath.suffix}
%
% Returns the suffix of a file name.
%
%    \begin{macrocode}

function fpath.suffix(name)
    return name:match("^.+%.([^/\\]-)$") or  ""
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{fpath.join}
%
% A function joining any number of arguments into a complete path.
%
%    \begin{macrocode}

function fpath.join(...)
    local pth = table.concat({...},"/")
    pth = pth:gsub("\\","/")
    local a, b = pth:match("^(.*://)(.*)$")
    if a and b then
        return a .. b:gsub("//+","/")
    end
    a, b = pth:match("^(//)(.*)$")
    if a and b then
        return a .. b:gsub("//+","/")
    end
    return (pth:gsub("//+","/"))
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{fpath.split}
%
% A function returning a table with all directories from a filename.
%
%    \begin{macrocode}

function fpath.split(str)
    local t = { }
    str = str:gsub("\\", "/")
    str = str:gsub("(%a):([;/])", "%1\001%2")
    for name in str:gmatch("([^;:]+)") do
        if name ~= "" then
            name = name:gsub("\001",":")
            t[#t+1] = name
        end
    end
    return t
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{fpath.normalize sep}
%
% A function to change directory separators to canonical ones (\texttt{/}).
%
%    \begin{macrocode}

function fpath.normalize_sep(str)
    return str:gsub("\\", "/")
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{fpath.localize sep}
%
% A function changing directory separators into local ones (\texttt{/} on Unix, |\| on Windows).
%
%    \begin{macrocode}

function fpath.localize_sep(str)
    if os.type == 'windows' or type == 'msdos' then
        return str:gsub("/", "\\")
    else
        return str:gsub("\\", "/")
    end
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{lfs.is writable}
%
% Returns true if a file is writable. This function and the following ones are a bit too expensive, they should be made with |lfs.attributes|.
%
%    \begin{macrocode}

function lfs.is_writable(name)
    local f = io.open(name, 'w')
    if f then
        f:close()
        return true
    else
        return false
    end
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{lfs.is readable}
%
% Returns true if a file is readable.
%
%    \begin{macrocode}

function lfs.is_readable(name)
    local f = io.open(name,'r')
    if f then
        f:close()
        return true
    else
        return false
    end
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{math.round}
%
% Returns the closest integer.
%
%    \begin{macrocode}

if not math.round then
    function math.round(x)
        return math.floor(x + 0.5)
    end
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{math.div}
%
% Returns the quotient of the euclidian division of n by m.
%
%    \begin{macrocode}

if not math.div then
    function math.div(n,m)
        return floor(n/m)
    end
end

%    \end{macrocode}
%
% \end{macro}\begin{macro}{math.mod}
%
% Returns the remainder of the euclidian division of n by m.
%
%    \begin{macrocode}

if not math.mod then
    function math.mod(n,m)
        return n % m
    end
end

%    \end{macrocode}
%
% \end{macro}
%
% \iffalse
%</lua>
% \fi
% \Finale
\endinput