%D \module
%D   [       file=s-phy-01,
%D        version=2011-11-24,
%D          title=\CONTEXT\ Modules,
%D       subtitle=Units Tables,
%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.

\unprotect

% todo: better breaks of head line

\startluacode
moduledata.units = moduledata.units or { }

local tables    = physics.units.tables
local units     = tables.units
local shortcuts = tables.shortcuts

local HL = context.HL
local NC = context.NC
local NR = context.NR

local function typeset(list,followup,name,category)
    if list then
        if followup then
            context.TB()
        end
        if category then
            HL()
            NC()
            context.rlap(category .. ":" .. name)
            NC()
            NC()
            NR()
            HL()
        end
        for k, v in table.sortedhash(list) do
            NC()
            context(k)
            NC()
            if isunit then
                context(v)
            else
                context.type(v)
            end
            NC()
            if name == "units" or name == "symbols" or name == "packaged" then
                context.unittext(v)
            elseif name == "prefixes" then
                context.prefixtext(v)
            elseif name == "operators" then
                context.operatortext(v)
            elseif name == "suffixes" then
                context.suffixtext(v)
            end
            NC()
            NR()
        end
        if category and name then
            HL()
        end
    end
end

function moduledata.units.show_table(name)
    context.starttabulate { "|lT|l|c|" }
    if name and name ~= "" then
        local first, second = string.match(name,"(.-):(.-)") -- [units|shortcuts]:[units|...]
        if first then
            typeset(tables[first] and tables[first][second],false)
        else
            typeset(units[name],false)
            typeset(shortcuts[name],true)
        end
    else
        local done = false
        for what, list in table.sortedhash(units) do
            typeset(list,done,what,"units")
            done = true
        end
        for what, list in table.sortedhash(shortcuts) do
            typeset(list,done,what,"shortcuts")
            done = true
        end
    end
    context.stoptabulate()
end

\stopluacode

\unexpanded\def\ShowUnitsTable
  {\dosingleempty\Show_Units_Table}

\def\Show_Units_Table[#1]%
  {\ctxlua{moduledata.units.show_table("#1")}}

\protect

\continueifinputfile{s-phy-01.mkiv}

\usemodule[art-01]

\starttext
    \ShowUnitsTable
\stoptext
