| 1 |
TeXStringBuffer = {content={}, finished=false} |
| 2 |
|
| 3 |
function TeXStringBuffer:new() |
| 4 |
o = {} |
| 5 |
setmetatable(o, self) |
| 6 |
self.__index = self |
| 7 |
return o |
| 8 |
end |
| 9 |
|
| 10 |
function TeXStringBuffer:clear() |
| 11 |
while #self.content ~= 0 do rawset(self.content, #self.content, nil) end |
| 12 |
end |
| 13 |
|
| 14 |
function TeXStringBuffer:content_to_string() |
| 15 |
return table.concat(self.content, "") |
| 16 |
end |
| 17 |
|
| 18 |
function TeXStringBuffer:show() |
| 19 |
tex.write(self:content_to_string()) |
| 20 |
end |
| 21 |
|
| 22 |
function TeXStringBuffer:append(data) |
| 23 |
table.insert(self.content, data) |
| 24 |
end |
| 25 |
|
| 26 |
function TeXStringBuffer:append_carriage_return(data) |
| 27 |
self:append("\r") |
| 28 |
end |
| 29 |
|
| 30 |
function _tex_buffer_remove_callback(name, description) |
| 31 |
for k, v in pairs(luatexbase.callback_descriptions(name)) do |
| 32 |
if v == description then |
| 33 |
texio.write("\nsafely removing callback " .. name .. " : " .. description) |
| 34 |
luatexbase.remove_from_callback(name, description) |
| 35 |
end |
| 36 |
end |
| 37 |
end |
| 38 |
|
| 39 |
function tex_buffer_remove_callback() |
| 40 |
_tex_buffer_remove_callback("find_read_file", "tex_file_buffer_find") |
| 41 |
_tex_buffer_remove_callback("open_read_file", "tex_file_buffer_read") |
| 42 |
end |
| 43 |
|
| 44 |
function tex_file_buffer_reader(env) |
| 45 |
local ret = nil |
| 46 |
if not env["finished"] then |
| 47 |
ret = env["content"] |
| 48 |
env["finished"] = true |
| 49 |
-- remove callback immediately |
| 50 |
tex_buffer_remove_callback() |
| 51 |
end |
| 52 |
return ret |
| 53 |
end |
| 54 |
|
| 55 |
function tex_file_buffer_find(id_number, asked_name) |
| 56 |
-- arguments and return value doesn't matter |
| 57 |
texio.write("\nTeXStringBuffer tries to find ".. asked_name .. " id=" .. id_number) |
| 58 |
return asked_name |
| 59 |
end |
| 60 |
|
| 61 |
function TeXStringBuffer:register_callback() |
| 62 |
tex_file_buffer_read = function (filename) |
| 63 |
local env = {} |
| 64 |
texio.write("\nTeXStringBuffer opens ".. filename) |
| 65 |
env["finished"] = false |
| 66 |
env["content"] = self:content_to_string() |
| 67 |
env["reader"] = tex_file_buffer_reader |
| 68 |
return env |
| 69 |
end |
| 70 |
|
| 71 |
-- register callback |
| 72 |
luatexbase.add_to_callback("find_read_file", tex_file_buffer_find, "tex_file_buffer_find") |
| 73 |
luatexbase.add_to_callback("open_read_file", tex_file_buffer_read, "tex_file_buffer_read") |
| 74 |
end |