How can be LuaTeX callbacks used in ConTeXt? (with LuaTeX backend)
My main concern is the usage of process_input_buffer
callback available in LuaTeX and LuaLaTeX. I am using it to altering the compiled source to reflect typografic rules customary in my country (maybe customary in general), to avoid one-letter prefixes ending the line.
Next MWEs should illustrate that:
One-letter prefix on the end of line (should be avoided):
\documentclass{article}
\usepackage{xcolor}
\begin{document}
Filling text filling text filling text filling text filling text filling text \textcolor{red}{filling V text}
\end{document}
And correct version:
\documentclass{article}
\usepackage{xcolor}
\usepackage{luacode}
\begin{luacode}
function pevnaMezera(s)
s = string.gsub(s, " V ", " V~")
return s
end
\end{luacode}
\AtBeginDocument{%
\directlua{luatexbase.add_to_callback(
"process_input_buffer", pevnaMezera , "pevnaMezera" )}
}
\begin{document}
Filling text filling text filling text filling text filling text filling text \textcolor{red}{filling V text}
\end{document}
I am aware of this question: How to register a callback in ConTeXt; Howerver, presented answer seems focused only on callback pre_linebreak_filter
, which is in ConTeXt defined as finalizer
.
I wasnt able to find anything about finalizers in general in any ConTeXt documentation or on ConTeXt Garden.
NOTE: In actual projects I am using lua regexes in function for process_input_buffer
callback, for brevity and readability I made simplier definition in MWE illustrating the problem.
EDIT3:
MWE changed according to comment of @Noone:
\startluacode
userdata = userdata or {}
function userdata.pevnaMezera(s)
s = string.gsub(s, " V ", " V~")
return s
end
process_input_buffer = userdata.pevnaMezera
\stopluacode
\starttext
Filling text filling text filling text filling text filling text filling text filling text fil V text
\stoptext
Is not adding non-breakable space. Is it correct from syntactical point of view?? I tryed to move the "assignment" to luacode block, but it did not work either.
process_input_buffer = pevnaMezera
should just work, as it is defined the engine itself, although I must recognize it isn't a very robust implementation.process_input_buffer
to search and replace text! It is close to impossible to write down a pattern that is both sufficient and exhaustive at the same time. Also the error handling scenarios are frightening, because you either get an extremely obscure error that is very hard to debug or no error at all and silently garbled output.userdata = userdata or {}
when you define Lua functions in ConTeXt, so you define your function asuserdata.myfunction
. Second, you could include the line directly in theluacode
environment, if you decide to do so. But third, Henri is right when he says you shouldn't useprocess_input_buffer
in the first place (AFAIK ConTeXt doesn't use it).