LuaTeXについて4(MPlib)

今回はMPlibについて。 LuaTeXの機能としてあげられている、MetaPostのサポート。 実際にはMPlibというMetaPostを外部ライブラリ化して、 Luaインターフェイスを追加したライブラリを通して行うらしい。 MetaPostとはTeXでよく使われるコマンド型の描画ツールです。 (奥村本、付録Fより) METAFONTでグラフとかを書いてepsにできるようにしたものらしい。 多分有名な物なので、詳細は略。 LaTeXで使える描画ツールとしては TeXWikiで紹介されているようにたくさんあるわけだが、 LuaTeXではMetaPostをそのまま使える様にすることを選んだ。 MPlibの開発に関していくつか資料を見つけた。 MPlib: MetaPost as a reusable component MetaPost developments: MPlib project report ようは現代的に、外部ライブラリ化してLuaからよびたかったらしい。 apiのリファレンスはこちら。 と前置きはこんな感じ。使ってみる。 texliveでluatexが入っている環境ではluamplibは既にインストール済みだったので、 特にインストール作業はなし。
\documentclass{article}
\usepackage{luamplib}
\begin{document}
\begin{mplibcode}
prologues := 1;
beginfig(1);
draw (0,0)--(100,0)--(100,100)--(0,100)--cycle;
label("some text",(50,50));
endfig;
\end{mplibcode}
\end{document}
パッケージluamplibを使う様に指定して、 MetaPostのコードをmplibcode環境で囲めばいい。 この例では四角形のなかに"some text"と表示される。 そのままだと日本語は通らない。 Luaから使う場合。How to use mplib directly from lua?から拝借。
\documentclass{article}
\usepackage{luamplib}
\begin{document}
\directlua{dofile('test.lua')}
\directlua{ StartMP() }
\end{document}
local mpkpse = kpse.new("luatex", "mpost")

local function finder(name, mode, ftype)
    if mode == "w" then
    return name
    else
    return mpkpse:find_file(name,ftype)
    end
end

function StartMP()
  local mplib = require('mplib')
  local mpx=mplib.new({find_file=finder,ini_version=true})
  local result = mpx:execute('input plain;')
  result=mpx:execute('beginfig(1); draw fullcircle scaled 20 withcolor red; endfig;')
  local t,e,l = result.term,result.error,result.log
  if result.status>0 then
    tex.print([[Result of mplib execute is unsuccessfull.]])
  else
    if result.fig then
      tex.sprint('Converted something: \\vrule\\vbox{\\hrule')
      local converted=luamplib.convert(result)
      tex.sprint('\\hrule}\\vrule')
    else
      tex.print([[No figure output.]])
      tex.print([[Log:]])
      tex.print(l)
    end
  end
  mpx:finish()
end
急に長くなったが、基本的には require('mplib")で読み込み、 mpx = mplib.new(...)でMetaPostのインタプリタを用意し、 result = mpx:execute('...')でMetaPostを図に変換している。 あとはエラー処理のコードと、 mplib.newの引数に渡すfind_file関数を用意している。 この関数がないと動かない。 これはapiリファレンスにデフォルトでローカルのファイルしか探さないから と書いてあるが、だからなぜ使えないかわからなかった(苦)。 kpseとはLuaTeXのパッケージの一つで、 公式のリファレンスにのっているのでそちらを参考に。 普通に使う分にはmplibcode環境で大体事足りそうなので、 とりあえず使えるようになったことにして、まとめた事にする。 日本語の対応の関連は日本語対応版のjmpostあたりの話をそのうち探ってみることにする。