Created
September 20, 2023 14:34
-
-
Save naquad/e887ca637b31fe476c9ce303da217265 to your computer and use it in GitHub Desktop.
ledger-sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env lua | |
-- This is a tool to sort Ledger CLI journal file. | |
-- Implemented to be used as a filter in (Neo)VIM. | |
-- Usage (CLI): ledger-sort < ledger.txt | |
-- Usage ((Neo)VIM): :%!ledger-sort | |
-- You can also visually select the lines to be sorted. | |
local function extend(dst, src) | |
for _, v in ipairs(src) do | |
table.insert(dst, v) | |
end | |
end | |
local function ledgersort(lines) | |
local items = {} | |
local prefix = {} | |
local current = nil | |
for _, l in ipairs(lines) do | |
local date = l:match("^[0-9/-]+") | |
if date then | |
current = {date = date, header = l, prefix = prefix, suffix = {}} | |
table.insert(items, current) | |
prefix = {} | |
elseif l:match("%S") then | |
table.insert(current and current.suffix or prefix, l) | |
elseif current then | |
current = nil | |
end | |
end | |
if #items == 0 then | |
return lines | |
end | |
table.sort(items, function(a, b) | |
return a.date < b.date | |
end) | |
local newlines = {} | |
for _, i in ipairs(items) do | |
extend(newlines, i.prefix) | |
table.insert(newlines, i.header) | |
extend(newlines, i.suffix) | |
table.insert(newlines, "") | |
end | |
extend(newlines, prefix) | |
return newlines | |
end | |
local lines = {} | |
for line in io.lines() do | |
table.insert(lines, line) | |
end | |
for _, line in ipairs(ledgersort(lines)) do | |
print(line) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment