%D \module
%D   [       file=m-gnuplot,
%D        version=2020.02.10,
%D          title=\CONTEXT\ Extra Modules,
%D       subtitle=Gnuplot,
%D         author=Hans Hagen,
%D           date=\currentdate,
%D      copyright={PRAGMA ADE \& \CONTEXT\ Development Team}]
%C
%C This module is part of the \CONTEXT\ macro||package and is
%C therefore copyrighted by \PRAGMA. See mreadme.pdf for
%C details.

%D This is a variant on the \GNUPLOT\ terminal code. At some point (when there is a
%D reason) I will make a proper environment that can be used for embedded code.

\permanent\protected\def\includegnuplotsvgfile[#1]%
  {\hbox\bgroup
     \ctxlua{metapost.startsvghashing()}%
     \includesvgfile[#1]%
     \ctxlua{metapost.stopsvghashing()}%
   \egroup}

\startluacode

local modificationtime = lfs.modification
local longtostring     = string.longtostring
local formatters       = string.formatters
local expandfilename   = dir.expandname
local isfile           = lfs.isfile

local runner = sandbox.registerrunner {
    name     = "gnuplot to svg",
    program  = "gnuplot",
    template = longtostring [[
        -e "set output '%newname%'; set terminal svg"
        "%oldname%"
    ]],
    checkers = {
        oldname = "readable",
        newname = "writable",
    },
}

figures.programs.gnuplot = {
    runner = runner,
}

local function remap(specification)
    local oldname = specification.fullname
    if oldname then
        local newname = file.replacesuffix(oldname,"svg")
        local oldtime = modificationtime(oldname) or 0
        local newtime = modificationtime(newname) or 0
        if newtime == 0 or oldtime > newtime then
            runner {
                newname = expandfilename(newname),
                oldname = expandfilename(oldname),
            }
        end
        if isfile(newname) then
            local only = file.nameonly(newname)
            local name = formatters["svg-%s-inclusion"](only)
            local code = formatters["\\includegnuplotsvgfile[%s]\\resetbuffer[%s]"](newname,name)
            buffers.assign(name,code)
            specification.format   = "buffer"
            specification.fullname = name
        end
    end
    return specification
end

figures.remappers.gp = { svg = remap }

\stopluacode

\continueifinputfile{m-gnuplot.mkxl}

\startluacode
io.savedata("m-gnuplot-demo.gp", [[
set format xy "$%g$"

set title  'This is a plot of $y=\\sin(x)$'
set xlabel 'This is the $x$ axis'
set ylabel 'This is the $y$ axis'

plot [0:6.28] [0:1] sin(x)
]])
\stopluacode

\starttext

    \externalfigure[m-gnuplot-demo.gp][conversion=svg,width=4cm]

    \externalfigure[m-gnuplot-demo.gp][conversion=svg,width=8cm]

\stoptext
