summaryrefslogtreecommitdiff
path: root/paper/lua-filters/bibexport/bibexport.lua
blob: 9174e694b1593983a0cff297e293f50f29a53e03 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
local utils = require 'pandoc.utils'
local List = require 'pandoc.List'

local citation_id_set = {}

-- Collect all citation IDs.
function Cite (c)
  local cs = c.citations
  for i = 1, #cs do
    citation_id_set[cs[i].id or cs[i].citationId] = true
  end
end

--- Return a list of citation IDs
function citation_ids ()
  local citations = {};
  for cid, _ in pairs(citation_id_set) do
    citations[#citations + 1] = cid
  end
  return citations
end

function bibdata (bibliography)
  function bibname (bibitem)
    if type(bibitem) == 'string' then
      return bibitem:gsub('%.bib$', '')
    else
      -- bibitem is assumed to be a list of inlines
      return utils.stringify(pandoc.Span(bibitem)):gsub('%.bib$', '')
    end
  end

  local bibs = bibliography.t == 'MetaList'
    and List.map(bibliography, bibname)
    or {bibname(bibliography)}
  return table.concat(bibs, ',')
end

function aux_content(bibliography)
  local cites = citation_ids()
  table.sort(cites)
  local citations = table.concat(cites, ',')
  return table.concat(
    {
      '\\bibstyle{alpha}',
      '\\bibdata{' .. bibdata(bibliography) .. '}',
      '\\citation{' .. citations .. '}',
      '',
    },
    '\n'
  )
end

function write_dummy_aux (bibliography, auxfile)
  local filename
  if type(auxfile) == 'string' then
    filename = auxfile
  elseif type(auxfile) == 'table' then
    -- assume list of inlines
    filename = utils.stringify(pandoc.Span(auxfile))
  else
    filename = 'bibexport.aux'
  end
  local fh = io.open(filename, 'w')
  fh:write(aux_content(bibliography))
  fh:close()
  io.stdout:write('Aux written to ' .. filename .. '\n')
  return filename
end

function Pandoc (doc)
  local meta = doc.meta
  if not meta.bibliography then
    return nil
  else
    -- create a dummy .aux file
    local auxfile_name = write_dummy_aux(meta.bibliography, meta.auxfile)
    os.execute('bibexport ' .. auxfile_name)
    io.stdout:write('Output written to bibexport.bib\n')
    return nil
  end
end