https://wiki.luatex.org/index.php?title=Typeset_non-TeX_files_by_converting_them_using_Lua_code&feed=atom&action=historyTypeset non-TeX files by converting them using Lua code - Revision history2024-03-29T08:28:34ZRevision history for this page on the wikiMediaWiki 1.31.1https://wiki.luatex.org/index.php?title=Typeset_non-TeX_files_by_converting_them_using_Lua_code&diff=31&oldid=prevPatrick: Copied from the old bluwiki.com luatex wiki2010-12-07T21:21:16Z<p>Copied from the old bluwiki.com luatex wiki</p>
<p><b>New page</b></p><div>The following code example demonstrates how to use the file reading callback and coroutines to convert a non-TeX file into TeX code which is then typeset.<br />
<br />
<br />
First the Lua code ("Preprocessor.lua"):<br />
<br />
local function readFile(fn)<br />
local file = assert(io.open(fn, "r"))<br />
local contents = file:read("*a")<br />
file:close()<br />
return contents<br />
end<br />
<br />
<br />
local function processInputFile(contents)<br />
-- Preamble<br />
coroutine.yield("\\pdfoutput=1 ")<br />
<br />
-- Process the file: Return each line<br />
for line in contents:gmatch("(.-)[\n\r]") do<br />
coroutine.yield(line)<br />
end<br />
<br />
-- Postamble<br />
coroutine.yield("\\bye")<br />
<br />
-- Done<br />
coroutine.yield(nil)<br />
end<br />
<br />
<br />
callback.register("open_read_file", function(fileName)<br />
local contents = readFile(fileName)<br />
return {<br />
reader = coroutine.wrap(function()<br />
processInputFile(contents .. "\n")<br />
end)<br />
}<br />
end)<br />
<br />
Then a small test file ("Preprocessor.txt"):<br />
<br />
Hello World1<br />
<br />
Hello World2<br />
<br />
Paragraph 3,<br />
continuing right now<br />
and going on over<br />
four lines<br />
<br />
And finally the bash shell script to tie everything together ("Preprocessor.sh"):<br />
<br />
luatex -fmt=luatex --jobname=Preprocessor '\directlua0{dofile("Preprocessor.lua")}\input Preprocessor.txt'<br />
<br />
As you can see, the file to be converted is simply read using "\input" and then converted<br />
in the Lua function "processInputFile". By using coroutines, we can pretend to convert the file<br />
in one go, when really we are supplying it line by line to LuaTeX.<br />
<br />
It would of course be possible to check the file type/extension inside the "open_read_file" callback and perform different conversions (or none at all if a TeX file) depending on the<br />
file type, i.e. to typeset source code.</div>Patrick