Skip to content

Instantly share code, notes, and snippets.

@scythe
Created March 31, 2021 17:41
Show Gist options
  • Save scythe/7cea80364bacf1f1ce6a67786bcbc577 to your computer and use it in GitHub Desktop.
Save scythe/7cea80364bacf1f1ce6a67786bcbc577 to your computer and use it in GitHub Desktop.
Fix the dumb LaTeX bibliography
-- This script attempts to automatically sort the \bibitem{}s in the bibliography of a .tex file according to occurrences of \cite{}.
-- Pretty much everyone wants this, but LaTeX you to use extra files or sort by hand. This is annoying for small projects which only
-- need to use a single .tex file.
-- Assumptions: all \cite{} and \bibitem{} occurrences are in one file; only one \bibitem{} on each line; string.lower() works with
-- your citation handles.
tfile = [==[ PASTE .tex FILE HERE ]==] -- or use file i/o and io:lines() instead of the first call to gmatch()
local orders, count, lines = {}, 1, {}
for line in tfile:gmatch"[^\r\n]+" do
for val in line:gmatch"\\cite{([^}]+)}" do
for v in val:gmatch"[^, ]+" do -- handle multiple citations in one \cite{...}
v = v:lower()
if not orders[v] then
orders[v] = count
count = count + 1
end
end
end
local bib = line:match"\\bibitem{([^}]+)}"
if bib then
print(bib)
lines[bib:lower()] = line
end
end
local items = {}
for item, order in pairs(orders) do items[order] = item end
for order, item in ipairs(items) do print(lines[item]) end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment