cld-files.tex /size: 2231 b    last modification: 2021-10-28 13:50
1% language=us runpath=texruns:manuals/cld
2
3\startcomponent cld-macros
4
5\environment cld-environment
6
7\startchapter[title=Files]
8
9\startsection[title={Preprocessing}]
10
11Although this option must be used with care, it is possible to preprocess files
12before they enter \TEX. The following example shows this.
13
14\starttyping
15local function showline(str,filename,linenumber,noflines)
16    logs.simple("[lc] file: %s, line: %s of %s, length: %s",
17        file.basename(filename),linenumber,noflines,#str)
18end
19
20local function showfile(str,filename)
21    logs.simple("[fc] file: %s, length: %s",
22        file.basename(filename),#str)
23end
24
25resolvers.installinputlinehandler(showline)
26resolvers.installinputfilehandler(showfile)
27\stoptyping
28
29Preprocessors like this are rather innocent. If you want to manipulate the
30content you need to be aware of the fact that modules and such also pass your
31code, and manipulating them can give unexpected side effects. So, the following
32code will not make \CONTEXT\ happy.
33
34\starttyping
35local function foo()
36    return "bar"
37end
38
39resolvers.installinputlinehandler(foo)
40\stoptyping
41
42But, as we pass the filename, you can base your preprocessing on names.
43
44There can be multiple handlers active at the same time, and although more
45detailed control is possible, the current interface does not provide that, simply
46because having too many handlers active is asking for trouble anyway. What you
47can do, is putting your handler in front or after the built in handlers.
48
49\starttyping
50resolvers.installinputlinehandler("before",showline)
51resolvers.installinputfilehandler("after", showfile)
52\stoptyping
53
54Of course you can also preprocess files outside this mechanism, which in most
55cases might be a better idea. However, the following example code is quite
56efficient and robust.
57
58\starttyping
59local function MyHandler(str,filename)
60    if file.suffix(filename) == "veryspecial" then
61        logs.simple("preprocessing file '%s',filename)
62        return MyConverter(str)
63    else
64        return str
65    end
66end
67
68resolvers.installinputfilehandler("before",MyHandler)
69\stoptyping
70
71In this case only files that have a suffix \type {.veryspecial} will get an extra
72treatment.
73
74\stopsection
75
76\stopchapter
77
78\stopcomponent
79