Recent versions of pandoc allow to do this with a short Lua filter:
pandoc --lua-filter extract-bib.lua --to=biblatex paper.Rmd -o paper.bib
where paper.Rmd
is your Markdown input, and extract-bib.lua
contains
function Pandoc(d)
d.meta.references = pandoc.utils.references(d)
d.meta.bibliography = nil
return d
end
This is the quickest, easiest, and cleanest method, but requires pandoc 2.17 or later.
There is also Robert Winkler's perl-based mdbibexport:
mdbibexport.pl extracts the cited references of a pandoc Markdown document and writes a BibTeX database for this document. The keys are extracted from the Markdown file and written into an auxiliary file, which is used by BibTool to find the references in the bibtex (.bib) data base and to write them into a new file.
As a third option, it's possible to combine re-implement the ideas used in mdbibexport with a pandoc Lua writer. E.g., the following will write the reduced bib-file to bibexport.bib
. Safe the script below to a file bibexport.lua
and call pandoc normally, but use bibexport.lua as the target format: pandoc --to bibexport.lua …
local citation_ids = {}
function Doc(body, meta, vars)
local citations = {};
for cid, _ in pairs(citation_ids) do
citations[#citations + 1] = cid
end
-- create a dummy .aux file
local aux = '\\bibstyle{alpha}\n' ..
'\\bibdata{' .. meta.bibliography .. '}\n' ..
'\\citation{' .. table.concat(citations, ',') .. '}\n'
local auxfile_name = meta.auxfile or 'bibexport.aux'
local auxfile = io.open(auxfile_name, 'w')
auxfile:write(aux)
auxfile:close()
os.execute('bibexport bibexport.aux')
return 'Output written to bibexport.bib, aux to ' .. auxfile_name
end
function Cite(c, cs)
for i = 1, #cs do citation_ids[cs[i].citationId] = true end
return ''
end
function Str(s) return s end
setmetatable(_G, {__index = function() return function() return "" end end})
This should work even with old pandoc versions, but has the bibexport
tool as an additional dependency.
Best Answer
Pandoc
can use a number file formats (.bib, .ris, etc.) to generate your bibliography. Have a look at the documentation here. You need to put a header like:# References #
into your .md document and your references need to look like:
[^ref1]: See @Author1, p. 20
.As noted in the comments, you also need to include
--filter pandoc-citeproc
to generate the bibliography.