Metapost with LuaTeX

From LuaTeXWiki
Revision as of 22:27, 7 December 2010 by Patrick (talk | contribs) (Copied from the old bluwiki.com luatex wiki)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Writing directly some metapost code is now possible in LuaTeX, through MPLib. It only works in pdf mode.

To get it working, you will need three files: supp-mpl.lua and supp-mpl.tex (you need to copy/paste them) from the ConTeXt distribution, and a stupid .sty file:

\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{mplib}

\input supp-mpl.tex

\directlua0{dofile(kpse.find_file("formathack.lua"))}

And create a file formathack.lua containing:

local preamble = [[
input %s ; dump ;
]]
metapost.make = function (name, mem_name)
    local mpx = mplib.new {
        ini_version = true,
        find_file = metapost.finder,
        job_name =  name}
    if mpx then
        local result = mpx:execute(string.format(preamble,name))
        mpx:finish()
    end
end
function replacesuffix(filename, suffix)
  return (string.gsub(filename,"%.[%a%d]+$","")) .. "." .. suffix
end
metapost.load = function (name)
    local mpx = mplib.new {
            ini_version = false,
            mem_name = replacesuffix(name,"mem"),
            find_file = finder
        }
    local result
    if not mpx then
        metapost.make(name)
        metapost.report("creating %s.mem", name)
        mpx = mplib.new {
            ini_version = false,
            mem_name = replacesuffix(name,"mem"),
            find_file = finder
        }
    end
    if not mpx then
        result = { status = 99, error = "out of memory"}
    end
    return mpx, result
end

Once you have all four files, the following example should work:

\mplibcode
beginfig(1);
pickup pencircle xscaled 5 rotated 30;
draw unitsquare scaled 20 withcmykcolor (0.3,0.4,0.6,0);
endfig;
\endmplibcode 

as well as any metapost code.