ConTeXt and Lua programming/LuaTeX callbacks

From Wiki
Jump to navigation Jump to search

The callback system from LuaTeX has been disabled. Instead, Context defines actions that must be registered through an offical mechanism. Then they can be toggled on and off at will, as long as it makes sense.

This page is dedicated to collecting all available information on how to achieve in Context when you would resort to callbacks to do the same in plain LuaTeX.

File reading callbacks / open_read_file

The functionality provided by the open_read_file callback can be accessed through a string filter that is hooked into the textfileactions processor (data-tex.lua, cf. luat-fio.lua)

Hans demonstrated the canonical way on the mailing list [1]:

\startluacode

  function document.MyCharacterMess(str,filename)
    if file.nameonly(filename) == "ward" then
      str = table.concat(string.totable(str,"."), " + ")
    end
    return str
  end

  local textfileactions = resolvers.openers.helpers.textfileactions
  utilities.sequencers.appendaction(textfileactions,"system","document.MyCharacterMess")

\stopluacode

\starttext
  \input ward
  \input knuth
\stoptext

Register Post-Run Functions

In LuaTeX, it is possible to register a callback function that gets executed at the end of a run. Like so:

id, err = callback.register('stop_run', new_stop_run_function)

But ConTeXt doesn't allow stop_run callbacks to be registered. If you attempt to, err will be set to "callback 'stop_run' is frozen (actions performed at the end of a run)".

Instead, ConTeXt provides two methods for executing actions at the end of a run, depending on the purpose of the action.

For actions whose primary purpose is to display a message or report some statistic, use:

statistics.register("banner",function() return "text" end)

The function passed in should return either a string to be reported, or false (or nil) which will not show the statistic. (The latter makes sense if there there ends up being nothing useful to report.)

For actions whose primary purpose is to perform some post-run processing, use:

luatex.registerstopactions(yourfunction)

Further Information