-- deckblatt.lua
-- Lua part of the LaTeX package deckblatt: reads a BibTeX/biblatex file and
-- provides the data of one entry for the cover page (loaded by deckblatt.sty).
--
-- Copyright (C) 2026 Daniel Tibi
--
-- This work may be distributed and/or modified under the conditions of the
-- LaTeX Project Public License, either version 1.3c of this license or (at
-- your option) any later version. The latest version of this license is in
--   https://www.latex-project.org/lppl.txt
-- and version 1.3c or later is part of all distributions of LaTeX version
-- 2008 or later.
--
-- This work has the LPPL maintenance status `maintained'.
-- The Current Maintainer of this work is Daniel Tibi.
--
-- This work consists of the files deckblatt.sty and deckblatt.lua.

local M = {}
M.version = "1.0"
M.entries = {}     -- key -> entry
M.lower   = {}     -- lowercased key -> entry
M.current = nil    -- selected entry
M.lang    = "de"   -- "de" or "en"
M.request = nil    -- last requested key (avoids repeated error messages)
M.split   = true   -- split the title into main title and subtitle

-- Code is written with the LaTeX catcodes and @ as a letter, so that the
-- internal commands of deckblatt.sty can be used. Plain strings (field values
-- that must not be interpreted) are written with catcode table -2.
local cct = luatexbase.registernumber("catcodetable@atletter")

local function out(s)    tex.sprint(cct, s) end
local function outstr(s) tex.sprint(-2, s) end

local function yes() out("\\@firstoftwo") end
local function no()  out("\\@secondoftwo") end

local function err(text)
  tex.error("Package deckblatt Error: " .. text)
end

------------------------------------------------------------------------
-- Language dependent strings
------------------------------------------------------------------------

local strings = {
  de = {
    and_ = " und ", etal = " u.\\,a.", ed = "Hrsg.", eds = "Hrsg.",
    in_ = "in", page = "S.~", pages = "S.~", issue = "H.~",
    transl = "übers. von", slash = true,
    q1 = { "„", "“" }, q2 = { "‚", "‘" },
    months = { "Januar", "Februar", "März", "April", "Mai", "Juni", "Juli",
               "August", "September", "Oktober", "November", "Dezember" },
  },
  en = {
    and_ = " and ", etal = " et al.", ed = "ed.", eds = "eds.",
    in_ = "in", page = "p.~", pages = "pp.~", issue = "no.~",
    transl = "trans. by", slash = false,
    q1 = { "“", "”" }, q2 = { "‘", "’" },
    months = { "January", "February", "March", "April", "May", "June", "July",
               "August", "September", "October", "November", "December" },
  },
}

local function S() return strings[M.lang] or strings.en end

function M.setlang(l)
  if strings[l] then M.lang = l end
end

function M.setsplit(b)
  M.split = b
end

------------------------------------------------------------------------
-- Helpers
------------------------------------------------------------------------

local function trim(s)
  return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end

local function oneline(s)
  return trim((s:gsub("%s+", " ")))
end

-- Reads a field value starting at position i ({...}, (...), "..." or a bare
-- number/macro). Returns the value without the outer delimiters and the
-- position after it.
local function read_value(s, i)
  local c = s:sub(i, i)
  if c == "{" or c == "(" then
    local open, close = c, (c == "{") and "}" or ")"
    local depth, j = 0, i
    while j <= #s do
      local ch = s:sub(j, j)
      if ch == "\\" then
        j = j + 1
      elseif ch == open then
        depth = depth + 1
      elseif ch == close then
        depth = depth - 1
        if depth == 0 then return s:sub(i + 1, j - 1), j + 1 end
      end
      j = j + 1
    end
    return nil, #s + 1
  elseif c == '"' then
    local depth, j = 0, i + 1
    while j <= #s do
      local ch = s:sub(j, j)
      if ch == "\\" then
        j = j + 1
      elseif ch == "{" then
        depth = depth + 1
      elseif ch == "}" then
        depth = depth - 1
      elseif ch == '"' and depth == 0 then
        return s:sub(i + 1, j - 1), j + 1
      end
      j = j + 1
    end
    return nil, #s + 1
  else
    local w, j = s:match("^([^,%s}%)]+)()", i)
    return w, j or i + 1
  end
end

-- Splits a name list at "and" (top brace level only).
local function split_and(s)
  local parts, depth, start, i = {}, 0, 1, 1
  while i <= #s do
    local ch = s:sub(i, i)
    if ch == "{" then
      depth = depth + 1
      i = i + 1
    elseif ch == "}" then
      depth = depth - 1
      i = i + 1
    elseif depth == 0 then
      local a, e = s:find("^%s+and%s+", i)
      if a then
        table.insert(parts, trim(s:sub(start, i - 1)))
        i = e + 1
        start = i
      else
        i = i + 1
      end
    else
      i = i + 1
    end
  end
  table.insert(parts, trim(s:sub(start)))
  return parts
end

-- Splits text at a separator pattern (top brace level only).
local function split_top(s, sep)
  local parts, depth, buf = {}, 0, {}
  for _, cp in utf8.codes(s) do
    local ch = utf8.char(cp)
    if ch == "{" then depth = depth + 1 elseif ch == "}" then depth = depth - 1 end
    if depth == 0 and ch:match(sep) then
      if #buf > 0 then table.insert(parts, table.concat(buf)) end
      buf = {}
    else
      table.insert(buf, ch)
    end
  end
  if #buf > 0 then table.insert(parts, table.concat(buf)) end
  return parts
end

local function strip_braces(s)
  if s:find("\\") then return s end   -- do not damage macros
  return (s:gsub("[{}]", ""))
end

-- "First Last" or "Last, First" -> first, last
local function name_parts(n)
  n = oneline(n)
  local comma = split_top(n, ",")
  if #comma >= 2 then
    return strip_braces(trim(comma[2])), strip_braces(trim(comma[1]))
  end
  local w = split_top(n, "%s")
  if #w == 1 then return "", strip_braces(w[1]) end
  local last = table.remove(w)
  return strip_braces(table.concat(w, " ")), strip_braces(last)
end

local function name_plain(n)
  local f, l = name_parts(n)
  if f == "" then return l end
  return f .. " " .. l
end

-- Last name in small caps (\dbsc replaces missing small caps of the font)
local function sc(s)
  return "\\dbsc{" .. s .. "}"
end

local function name_sc(n)
  local f, l = name_parts(n)
  if f == "" then return sc(l) end
  return f .. " " .. sc(l)
end

-- Joins names; style "plain" or "sc" (A, B and C) or "cite"
-- (German: A~/ B~/ C; English: as "plain")
local function join(names, style)
  local s, n = S(), #names
  if n == 0 then return "" end
  if style == "cite" and s.slash then return table.concat(names, "~/ ") end
  if n == 1 then return names[1] end
  if n == 2 then return names[1] .. s.and_ .. names[2] end
  local head = table.concat(names, ", ", 1, n - 1)
  if M.lang == "en" then return head .. "," .. s.and_ .. names[n] end
  return head .. s.and_ .. names[n]
end

-- Formats a name list. Returns the string and the number of names
-- ("others" counts as one more name).
local function namelist(field, style)
  if not field then return nil, 0 end
  local names, others = {}, false
  for _, n in ipairs(split_and(field)) do
    if n == "others" then
      others = true
    elseif n ~= "" then
      table.insert(names, (style == "cite" or style == "sc") and name_sc(n) or name_plain(n))
    end
  end
  if #names == 0 then return nil, 0 end
  local s = join(names, style)
  if others then s = s .. S().etal end
  return s, #names + (others and 1 or 0)
end

local function ed_label(count)
  return (count > 1) and S().eds or S().ed
end

local function has(e, name)
  local w = e.f[name]
  return w ~= nil and trim(w) ~= ""
end

local function value(e, name)
  if has(e, name) then return oneline(e.f[name]) end
  return nil
end

local function year(e)
  local d = e.f.date or e.f.year or ""
  return d:match("^%s*(%d%d%d%d)") or trim(d)
end

local function date_long(e)
  local d = e.f.date
  if not d then return year(e) end
  local months = S().months
  local y, m, t = d:match("^%s*(%d%d%d%d)%-(%d%d)%-(%d%d)")
  if y and months[tonumber(m)] then
    if M.lang == "de" then
      return tonumber(t) .. ".~" .. months[tonumber(m)] .. " " .. y
    end
    return tonumber(t) .. "~" .. months[tonumber(m)] .. " " .. y
  end
  y, m = d:match("^%s*(%d%d%d%d)%-(%d%d)")
  if y and months[tonumber(m)] then return months[tonumber(m)] .. " " .. y end
  return year(e)
end

local function doi_of(e)
  local d = value(e, "doi")
  if not d then return nil end
  d = d:gsub("^https?://dx%.doi%.org/", ""):gsub("^https?://doi%.org/", "")
       :gsub("^[Dd][Oo][Ii]:%s*", "")
  return d
end

-- Words after which a full stop does not start a subtitle
local abbreviations = {}
for w in ([[
  c cc can St Hl hl Hrsg hrsg Bd Bde Nr vgl Vgl Abs Art Dr Prof fr P Jh Jhd
  ca bzw usw etc ders dies Mt Mk Lk Joh Apg Röm Kor Gal Eph Phil Kol Hebr
  Offb Ps Gen Ex Lev Dtn Jes
  vs cf Vol vol No no pp ed eds Mr Mrs Ms Jr Sr Fr
]]):gmatch("%S+") do abbreviations[w] = true end

-- Splits the title into main title and subtitle (at the first ". ", "? "
-- or "! " outside braces, otherwise at the first ": "), unless a subtitle
-- field exists.
local function split_title(e)
  local t = value(e, "title") or ""
  if has(e, "subtitle") then return t, value(e, "subtitle") end
  if not M.split then return t, nil end
  for _, p in ipairs({ { "^(Rezension) zu:%s*(.+)$" }, { "^(Rezension):%s*(.+)$" },
                       { "^(Review) of:%s*(.+)$" }, { "^(Review):%s*(.+)$" } }) do
    local word, rest = t:match(p[1])
    if word then return word, rest end
  end
  if t:match("^Rezension") or t:match("^Review") then return t, nil end
  local depth = 0
  for i = 1, #t - 1 do
    local ch = t:sub(i, i)
    if ch == "{" then
      depth = depth + 1
    elseif ch == "}" then
      depth = depth - 1
    elseif depth == 0 and (ch == "." or ch == "?" or ch == "!")
           and t:sub(i + 1, i + 1) == " " then
      local before = t:sub(1, i - 1)
      local word = before:match("([%a\128-\255]+)$")
      local ok = true
      if ch == "." then
        if before:match("%d$") then ok = false end
        if word and (abbreviations[word] or utf8.len(word) == 1) then ok = false end
      end
      if ok then
        local main = (ch == ".") and before or t:sub(1, i)
        return trim(main), trim(t:sub(i + 2))
      end
    end
  end
  depth = 0
  for i = 1, #t - 1 do
    local ch = t:sub(i, i)
    if ch == "{" then
      depth = depth + 1
    elseif ch == "}" then
      depth = depth - 1
    elseif depth == 0 and ch == ":" and t:sub(i + 1, i + 1) == " " then
      return trim(t:sub(1, i - 1)), trim(t:sub(i + 2))
    end
  end
  return t, nil
end

-- Plain text (for the PDF metadata)
local function plaintext(s)
  if not s then return "" end
  local old
  local level = 0
  local q1, q2 = S().q1, S().q2
  repeat
    -- outer level q1, inner level q2
    old = s
    level = level + 1
    local open, close = q1[1], q1[2]
    if level % 2 == 0 then open, close = q2[1], q2[2] end
    s = s:gsub("\\enquote%*?%s*(%b{})", function(b) return open .. b:sub(2, -2) .. close end)
  until s == old
  repeat
    old = s
    s = s:gsub("\\%a+%*?%s*(%b{})", function(b) return b:sub(2, -2) end)
  until s == old
  s = s:gsub("\\S", "§"):gsub("\\[,;:! ]", " "):gsub("\\%a+%s*", "")
  s = s:gsub("~", " "):gsub("%-%-%-", "—"):gsub("%-%-", "–"):gsub("[{}]", "")
  return oneline(s)
end

local function pages(p)
  local s = S()
  if p:find("-", 1, true) or p:find("–", 1, true) or p:find("—", 1, true)
     or p:find(",", 1, true) then
    return s.pages .. p
  end
  return s.page .. p
end

local function ordinal(n)
  n = tonumber(n)
  local suffix = "th"
  if n % 100 < 11 or n % 100 > 13 then
    local d = n % 10
    if d == 1 then suffix = "st" elseif d == 2 then suffix = "nd" elseif d == 3 then suffix = "rd" end
  end
  return n .. suffix
end

-- Place: Publisher
local function place_publisher(e)
  local place = value(e, "address") or value(e, "location")
  local publisher = value(e, "publisher")
  if place then place = table.concat(split_and(place), "~/ ") end
  if place and publisher then return place .. ": " .. publisher end
  return place or publisher
end

-- Place: Publisher, Year (with edition)
local function imprint(e)
  local s = place_publisher(e) or ""
  local y = year(e)
  local ed = value(e, "edition")
  local numbered = ed and ed:match("^%d+$") and ed ~= "1"
  if numbered and M.lang == "de" then y = "\\textsuperscript{" .. ed .. "}" .. y end
  if s ~= "" then s = s .. ", " end
  s = s .. y
  if numbered and M.lang ~= "de" then s = ordinal(ed) .. " ed., " .. s end
  return s
end

local function series(e)
  local r = value(e, "series")
  if not r then return "" end
  local n = value(e, "number")
  return " (" .. r .. (n and (" " .. n) or "") .. ")"
end

local function etype(e)
  return e.type:lower()
end

local function is_article(e)
  local t = etype(e)
  return t == "article" or t == "periodical"
         or ((has(e, "journaltitle") or has(e, "journal")) and not has(e, "booktitle"))
end

local function is_contribution(e)
  return has(e, "booktitle")
end

local function journal(e)
  return value(e, "journaltitle") or value(e, "journal") or ""
end

-- Source without "in:"; style "plain" or "cite"
local function source(e, style)
  if is_article(e) then
    local s = "\\emph{" .. journal(e) .. "}"
    local v = value(e, "volume")
    if v then s = s .. " " .. v end
    s = s .. " (" .. year(e) .. ")"
    local n = value(e, "number") or value(e, "issue")
    if n then s = s .. ", " .. S().issue .. n end
    local p = value(e, "pages")
    if p then s = s .. ", " .. pages(p) end
    return s
  elseif is_contribution(e) then
    local s = ""
    local eds, count = namelist(value(e, "editor"), style)
    if eds then s = eds .. " (" .. ed_label(count) .. "): " end
    s = s .. "\\emph{" .. value(e, "booktitle") .. "}" .. series(e) .. ", " .. imprint(e)
    local p = value(e, "pages")
    if p then s = s .. ", " .. pages(p) end
    return s
  else
    return imprint(e)
  end
end

local function creators(e, style)
  local a = namelist(value(e, "author"), style)
  if a then return a end
  local eds, count = namelist(value(e, "editor"), style)
  if eds then return eds .. " (" .. ed_label(count) .. ")" end
  return nil
end

local function citation(e)
  local s = ""
  local c = creators(e, "cite")
  if c then s = c .. ": " end
  local t = value(e, "title") or ""
  if is_article(e) or is_contribution(e) then
    s = s .. "\\enquote{" .. t .. "}, " .. S().in_ .. ": " .. source(e, "cite")
  else
    s = s .. "\\emph{" .. t .. "}" .. series(e)
    local tr = namelist(value(e, "translator"), "plain")
    if tr and has(e, "author") then s = s .. ", " .. S().transl .. " " .. tr end
    s = s .. ", " .. source(e, "cite")
  end
  if doi_of(e) then s = s .. ", DOI: \\dbdoi" end
  return s .. "."
end

------------------------------------------------------------------------
-- Reading the bibliography
------------------------------------------------------------------------

function M.load(file)
  local path = kpse.find_file(file) or file
  local f = io.open(path, "r")
  if not f then
    err("bibliography file '" .. file .. "' not found")
    return
  end
  local s = f:read("*a")
  f:close()
  s = s:gsub("\r\n", "\n")
  local i = 1
  while true do
    local a, typename, b = s:match("()@%s*([%a]+)%s*[{(]()", i)
    if not a then break end
    local t = typename:lower()
    if t == "comment" or t == "preamble" or t == "string" then
      local _, next_pos = read_value(s, b - 1)
      i = next_pos
    else
      local key, j = s:match("^%s*([^,%s]+)%s*,()", b)
      if not key then
        i = b
      else
        local e = { type = typename, key = key, f = {}, list = {} }
        while true do
          local name, p = s:match("^%s*([%w_%-%.:]+)%s*=%s*()", j)
          if not name then break end
          local w, q = read_value(s, p)
          if w == nil then break end
          e.f[name:lower()] = w
          table.insert(e.list, { name = name, value = w })
          local comma, r = s:match("^%s*(,?)()", q)
          j = r
          if comma == "" then break end
        end
        local stop = s:match("^%s*[})]()", j)
        i = stop or j
        M.entries[key] = e
        M.lower[key:lower()] = e
      end
    end
  end
end

-- Selects an entry. If usejob is true and the job name is a key of the
-- bibliography, the job name wins.
function M.select(key, jobname, usejob)
  local k = key or ""
  if jobname then jobname = jobname:gsub('^"(.*)"$', "%1") end
  if usejob and jobname and M.entries[jobname] then k = jobname end
  if k == "" then return end
  local e = M.entries[k] or M.lower[k:lower()]
  if e then
    M.current = e
    M.request = nil
  elseif M.request ~= k then
    M.request = k
    err("entry '" .. k .. "' not found in the bibliography")
  end
end

function M.ifselected()
  if M.current then yes() else no() end
end

-- PDF metadata. Title and subject get an additional pair of braces because
-- the XMP metadata would otherwise read commas as list separators. Several
-- authors are passed as a list (one dc:creator each).
function M.metadata()
  local e = M.current
  if not e then return end
  out("\\hypersetup{pdftitle={{")
  outstr(plaintext(value(e, "title")))
  out("}},pdfauthor={")
  local field = value(e, "author") or value(e, "editor")
  local first = true
  if field then
    for _, n in ipairs(split_and(field)) do
      if n ~= "others" and n ~= "" then
        if not first then out(", ") end
        out("{")
        outstr(plaintext(name_plain(n)))
        out("}")
        first = false
      end
    end
  end
  out("},pdfsubject={{")
  outstr(plaintext((citation(e):gsub(", DOI: \\dbdoi", ""))))
  out("}}}")
end

local function cur()
  if not M.current then
    err("no bibliography entry selected (use \\deckblattsetup{key=...})")
    return nil
  end
  return M.current
end

------------------------------------------------------------------------
-- Output to TeX
------------------------------------------------------------------------

function M.field(name)
  local e = cur(); if not e then return end
  local w = value(e, name:lower())
  if w then out(w) end
end

function M.rawfield(name)
  local e = cur(); if not e then return end
  local w = value(e, name:lower())
  if w then outstr(w) end
end

function M.iffield(name)
  local e = M.current
  if e and has(e, name:lower()) then yes() else no() end
end

function M.iftype(names)
  local e = M.current
  local t = e and etype(e) or ""
  for n in names:gmatch("[^,%s]+") do
    if n:lower() == t then yes() return end
  end
  no()
end

function M.ifarticle()
  local e = M.current
  if e and is_article(e) then yes() else no() end
end

function M.ifsubtitle()
  local e = M.current
  local u = nil
  if e then _, u = split_title(e) end
  if u then yes() else no() end
end

-- Is the entry part of a larger work (article or contribution)?
function M.ifpart()
  local e = M.current
  if e and (is_article(e) or is_contribution(e)) then yes() else no() end
end

function M.ifdoi()
  local e = M.current
  if e and doi_of(e) then yes() else no() end
end

function M.iffulldate()
  local e = M.current
  local d = e and e.f.date
  if d and d:match("^%s*%d%d%d%d%-%d%d") then yes() else no() end
end

function M.ifpublisher()
  local e = M.current
  if e and (has(e, "publisher") or has(e, "address") or has(e, "location")) then
    yes() else no()
  end
end

function M.type()
  local e = cur(); if e then outstr(etype(e)) end
end

function M.key()
  local e = cur(); if e then outstr(e.key) end
end

function M.authors()
  local e = cur(); if not e then return end
  local c = creators(e, "plain")
  if c then out(c) end
end

function M.authorssc()
  local e = cur(); if not e then return end
  local c = creators(e, "sc")
  if c then out(c) end
end

function M.authorscite()
  local e = cur(); if not e then return end
  local c = creators(e, "cite")
  if c then out(c) end
end

function M.title()
  local e = cur(); if not e then return end
  local t = split_title(e)
  out(t)
end

function M.subtitle()
  local e = cur(); if not e then return end
  local _, u = split_title(e)
  if u then out(u) end
end

function M.year()
  local e = cur(); if e then out(year(e)) end
end

function M.date()
  local e = cur(); if e then out(date_long(e)) end
end

function M.journal()
  local e = cur(); if not e then return end
  if is_article(e) then
    out("\\emph{" .. journal(e) .. "}")
  elseif is_contribution(e) then
    out("\\emph{" .. value(e, "booktitle") .. "}")
  end
end

function M.source()
  local e = cur(); if e then out(source(e, "plain")) end
end

-- Collection: Editors (ed.): Book title (Series)
function M.collection()
  local e = cur(); if not e or not is_contribution(e) then return end
  local s = ""
  local eds, count = namelist(value(e, "editor"), "sc")
  if eds then s = eds .. " (" .. ed_label(count) .. "): " end
  out(s .. "\\emph{" .. value(e, "booktitle") .. "}" .. series(e))
end

-- Place: Publisher
function M.publisher()
  local e = cur(); if not e then return end
  local s = place_publisher(e)
  if s then out(s) end
end

function M.citation()
  local e = cur(); if e then out(citation(e)) end
end

-- Fallback small caps for fonts without real small caps: lowercase letters
-- are set as reduced uppercase letters (\deckblatt@scsmall), uppercase
-- letters and all other characters stay as they are.
local upper = (unicode and unicode.utf8 and unicode.utf8.upper) or function(z)
  local map = { ["ä"] = "Ä", ["ö"] = "Ö", ["ü"] = "Ü" }
  return map[z] or z:upper()
end

function M.scfallback(s)
  if s:find("[\\{}]") then
    -- contains TeX code: do not split into characters
    out("{\\deckblatt@scsmall\\MakeUppercase{" .. s .. "}}")
    return
  end
  local run = {}
  local function flush()
    if #run > 0 then
      out("{\\deckblatt@scsmall ")
      outstr(table.concat(run))
      out("}")
      run = {}
    end
  end
  for _, c in utf8.codes(s) do
    local z = utf8.char(c)
    local up = (z == "ß") and "SS" or upper(z)
    if up ~= z then
      table.insert(run, up)
    else
      flush()
      if z == "~" then out("~") else outstr(z) end
    end
  end
  flush()
end

-- DOI as a link; kind = "doi" (DOI only) or "url" (https://doi.org/...)
function M.doi(kind)
  local e = cur(); if not e then return end
  local d = doi_of(e)
  if not d then return end
  local url = "https://doi.org/" .. d
  out("\\href{")
  outstr(url)
  out("}{\\deckblatt@doifont\\nolinkurl{")
  outstr(kind == "url" and url or d)
  out("}}")
end

function M.doiqr(options)
  local e = cur(); if not e then return end
  local d = doi_of(e)
  if not d then return end
  out("\\qrcode[" .. options .. "]{")
  outstr("https://doi.org/" .. d)
  out("}")
end

-- BibTeX code of the entry (fields in their original order, white space
-- normalised). If an unbreakable line is too wide, the font is reduced.
function M.bibtex(linewidth, charwidth, size)
  local e = cur(); if not e then return end
  local width = 0
  for _, p in ipairs(e.list) do width = math.max(width, utf8.len(p.name)) end
  -- longest unbreakable line in characters: head line or longest word of a field
  local needed = utf8.len("@" .. e.type .. "{" .. e.key .. ",")
  for _, p in ipairs(e.list) do
    local words = {}
    for w in oneline(p.value):gmatch("%S+") do table.insert(words, w) end
    local first = words[1] and utf8.len(words[1]) or 0
    local longest = 0
    for _, w in ipairs(words) do longest = math.max(longest, utf8.len(w)) end
    needed = math.max(needed, 2 + width + 4 + math.max(first, longest) + 2)
  end
  if linewidth and charwidth and charwidth > 0 and needed * charwidth > linewidth then
    local new = tonumber(size) * linewidth / (needed * charwidth) * 0.99
    out(string.format("\\fontsize{%.2f}{%.2f}\\selectfont"
      .. "\\settowidth\\deckblatt@ch{0}\\setlength\\deckblatt@indent{2\\deckblatt@ch}",
      new, new * 1.3))
  end
  out("\\deckblatt@namewidth=" .. width .. "\\deckblatt@ch")
  out("\\deckblatt@bibhead{")
  outstr("@" .. e.type)
  out("}{")
  outstr(e.key)
  out("}")
  for i, p in ipairs(e.list) do
    out("\\deckblatt@bibfield{")
    outstr(p.name)
    out("}{")
    outstr(oneline(p.value))
    out("}{" .. (i < #e.list and "," or "") .. "}")
  end
  out("\\deckblatt@bibend")
end

return M
