nix-configs

Personal NixOS and home-manager configuration files
Log | Files | Refs

neovim-sortblock.nix (7210B)


      1 { lib, vimUtils, writeText, runCommand }:
      2 
      3 let
      4   sortblockLua = writeText "sortblock.lua" ''
      5     -- sortblock.lua
      6     -- Sort + dedupe marked blocks of text on save.
      7     --
      8     -- Wrap lines in markers:
      9     --   # sort:start
     10     --   dog
     11     --   cat
     12     --   cat
     13     --   # sort:end
     14     --
     15     --
     16     -- Also supports flags, eh: sort:start reverse nodedupe case articles
     17     --
     18     -- The "articles" flag (or ignore_articles = true in setup) sorts as if a
     19     -- leading "The", "A" or "An" were not there, so "The Beatles" sorts
     20     -- under B. Deduping still compares the full line, so "Beatles" and
     21     -- "The Beatles" are both kept.
     22     --
     23     -- Markdown bullets ("* ", "- ", "+ ") are ignored when ordering, so
     24     -- "* The Nun II (2023)" sorts under N with the articles flag on.
     25     local M = {}
     26     M.config = {
     27       start_marker = "sort:start",
     28       end_marker = "sort:end",
     29       pattern = "*",
     30       ignorecase = true,
     31       dedupe = true,
     32       reverse = false,
     33       strip_blanks = true,
     34       ignore_articles = false,
     35       articles = { "the", "a", "an" },
     36     }
     37 
     38     -- Flags accepted on the start-marker line, mapped to config overrides.
     39     local FLAGS = {
     40       case = { ignorecase = false },
     41       nocase = { ignorecase = true },
     42       reverse = { reverse = true },
     43       nodedupe = { dedupe = false },
     44       dedupe = { dedupe = true },
     45       keepblanks = { strip_blanks = false },
     46       articles = { ignore_articles = true },
     47       noarticles = { ignore_articles = false },
     48     }
     49 
     50     local function opts_for_block(base, tail)
     51       local opts = vim.tbl_extend("force", {}, base)
     52       for word in (tail or ""):gmatch("%S+") do
     53         local override = FLAGS[word:lower()]
     54         if override then opts = vim.tbl_extend("force", opts, override) end
     55       end
     56       return opts
     57     end
     58 
     59     -- Remove one leading article (matched case-insensitively) if it is
     60     -- followed by whitespace and something else. "A" on its own, or
     61     -- "Anchor", is left alone.
     62     local function strip_article(s, articles)
     63       local lower = s:lower()
     64       for _, art in ipairs(articles) do
     65         art = art:lower()
     66         local n = #art
     67         if lower:sub(1, n) == art and lower:sub(n + 1, n + 1):match("%s") then
     68           local rest = vim.trim(s:sub(n + 1))
     69           if rest ~= "" then return rest end
     70         end
     71       end
     72       return s
     73     end
     74 
     75     -- Key used for deduping: the whole line, trimmed, case-folded if asked.
     76     local function dedupe_key(line, opts)
     77       local k = vim.trim(line)
     78       if opts.ignorecase then k = k:lower() end
     79       return k
     80     end
     81 
     82     -- Key used for ordering: as above, minus any markdown bullet ("* ",
     83     -- "- ", "+ ") and, if asked, any leading article after it.
     84     local function sort_key(line, opts)
     85       local k = vim.trim(line)
     86       k = k:gsub("^[%*%-%+]%s+", "", 1)
     87       if opts.ignore_articles then k = strip_article(k, opts.articles) end
     88       if opts.ignorecase then k = k:lower() end
     89       return k
     90     end
     91 
     92     -- Take the raw lines of a block, return the sorted/deduped version.
     93     local function transform(lines, opts)
     94       local out, seen = {}, {}
     95       for _, line in ipairs(lines) do
     96         local trimmed = vim.trim(line)
     97         if not (opts.strip_blanks and trimmed == "") then
     98           local k = dedupe_key(line, opts)
     99           if not (opts.dedupe and seen[k]) then
    100             seen[k] = true
    101             out[#out + 1] = line
    102           end
    103         end
    104       end
    105 
    106       table.sort(out, function(a, b)
    107         local ka, kb = sort_key(a, opts), sort_key(b, opts)
    108         if ka == kb then
    109           -- e.g. "Beatles" vs "The Beatles": fall back to the full line
    110           local da, db = dedupe_key(a, opts), dedupe_key(b, opts)
    111           if da ~= db then return da < db end
    112           return vim.trim(a) < vim.trim(b) -- stable-ish tiebreak
    113         end
    114         if opts.reverse then return ka > kb end
    115         return ka < kb
    116       end)
    117 
    118       return out
    119     end
    120 
    121     local function same(a, b)
    122       if #a ~= #b then return false end
    123       for i = 1, #a do
    124         if a[i] ~= b[i] then return false end
    125       end
    126       return true
    127     end
    128 
    129     -- Find all blocks, returns list
    130     local function find_blocks(lines, cfg)
    131       local blocks, open, open_opts = {}, nil, nil
    132       for i, line in ipairs(lines) do
    133         local s, e = line:find(cfg.start_marker, 1, true)
    134         if s and not open then
    135           open = i
    136           open_opts = opts_for_block(cfg, line:sub(e + 1))
    137         elseif line:find(cfg.end_marker, 1, true) and open then
    138           if i > open + 1 then
    139             blocks[#blocks + 1] = { first = open, last = i - 2, opts = open_opts }
    140           end
    141           open, open_opts = nil, nil
    142         end
    143       end
    144       return blocks
    145     end
    146 
    147     function M.sort_buffer(bufnr)
    148       bufnr = (bufnr == nil or bufnr == 0) and vim.api.nvim_get_current_buf() or bufnr
    149       if not vim.api.nvim_buf_is_loaded(bufnr) then return end
    150 
    151       local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
    152       local blocks = find_blocks(lines, M.config)
    153       if #blocks == 0 then return end
    154 
    155       -- Remember cursor positions
    156       local views = {}
    157       for _, win in ipairs(vim.api.nvim_list_wins()) do
    158         if vim.api.nvim_win_get_buf(win) == bufnr then
    159           views[win] = vim.api.nvim_win_get_cursor(win)
    160         end
    161       end
    162 
    163       -- Apply backwards so line numbers are valid
    164       for i = #blocks, 1, -1 do
    165         local b = blocks[i]
    166         local original = vim.list_slice(lines, b.first + 1, b.last + 1)
    167         local sorted = transform(original, b.opts)
    168         if not same(original, sorted) then
    169           vim.api.nvim_buf_set_lines(bufnr, b.first, b.last + 1, false, sorted)
    170         end
    171       end
    172 
    173       local count = vim.api.nvim_buf_line_count(bufnr)
    174       for win, pos in pairs(views) do
    175         if vim.api.nvim_win_is_valid(win) then
    176           vim.api.nvim_win_set_cursor(win, { math.min(pos[1], count), pos[2] })
    177         end
    178       end
    179     end
    180 
    181     function M.setup(user_config)
    182       M.config = vim.tbl_extend("force", M.config, user_config or {})
    183 
    184       local group = vim.api.nvim_create_augroup("SortBlockOnSave", { clear = true })
    185       vim.api.nvim_create_autocmd("BufWritePre", {
    186         group = group,
    187         pattern = M.config.pattern,
    188         callback = function(args) M.sort_buffer(args.buf) end,
    189       })
    190 
    191       vim.api.nvim_create_user_command("SortBlocks", function()
    192         M.sort_buffer(0)
    193       end, { desc = "Sort and dedupe all marked blocks in this buffer" })
    194     end
    195 
    196     return M
    197   '';
    198 in
    199 vimUtils.buildVimPlugin {
    200   pname = "sortblock";
    201   version = "1.2.0";
    202 
    203   # buildVimPlugin expects a source tree laid out the way Neovim's
    204   # runtimepath wants it, so wrap the embedded lua string in lua/.
    205   src = runCommand "sortblock-src" { } ''
    206     mkdir -p $out/lua
    207     cp ${sortblockLua} $out/lua/sortblock.lua
    208   '';
    209 
    210   # Fails the build if `require("sortblock")` errors — catches syntax
    211   # mistakes at rebuild time instead of at startup.
    212   # Remove this if your nixpkgs is older than 24.05.
    213   nvimRequireCheck = "sortblock";
    214 
    215   meta = {
    216     description = "Sort and dedupe marked blocks of text on save";
    217     license = lib.licenses.mit;
    218     platforms = lib.platforms.all;
    219   };
    220 }