diff options
| author | Robert Günzler <r@gnzler.io> | 2022-07-01 16:58:50 +0200 |
|---|---|---|
| committer | Robert Günzler <r@gnzler.io> | 2022-08-02 22:13:49 +0200 |
| commit | e54f2e4830eedb0930ccb3b5fdb8cffe8b9e8dbf (patch) | |
| tree | 31f7b13f96dda8f13925313be1917588729a30b5 /.vim/lua/misc.lua | |
| parent | dd31339e49c28b9c719b60425c5f7ae31a0e45f4 (diff) | |
vim: implement inccomand for sortline
Diffstat (limited to '.vim/lua/misc.lua')
| -rw-r--r-- | .vim/lua/misc.lua | 54 |
1 files changed, 38 insertions, 16 deletions
diff --git a/.vim/lua/misc.lua b/.vim/lua/misc.lua index 457aa3c..7d4fa31 100644 --- a/.vim/lua/misc.lua +++ b/.vim/lua/misc.lua @@ -47,28 +47,50 @@ function M.open_under_cursor(cmd, detect_cmd) end local function get_visual_selection() - local pos1 = vim.fn.getpos("'<") - local ln1, col1 = pos1[2], pos1[3] - local pos2 = vim.fn.getpos("'>") - local ln2, col2 = pos2[2], pos2[3] - local lines = vim.fn.getline(ln1, ln2) + local top = vim.fn.getpos("'<") + top = { ln = top[2], col = top[3] } + local bot = vim.fn.getpos("'>") + bot = { ln = bot[2], col = bot[3] } + local lines = vim.api.nvim_buf_get_lines(0, (top.ln - 1), bot.ln, false) if vim.opt.selection:get() == 'inclusive' then - lines[#lines] = lines[#lines]:sub(1,col2) + lines[#lines] = lines[#lines]:sub(1, bot.col) else - lines[#lines] = lines[#lines]:sub(1,col2-1) + lines[#lines] = lines[#lines]:sub(1, (bot.col -1)) end - lines[1] = lines[1]:sub(col1) - return pos1, pos2, lines + lines[1] = lines[1]:sub(top.col) + return top, bot, lines end -function M.sort_line() - local fn = vim.fn - local pos1, _, lines = get_visual_selection() +function M.sort_lines(_, preview_ns, preview_bufnr) + local bufnr = vim.api.nvim_get_current_buf() + + local top, bot, lines = get_visual_selection() for i=1, #lines do - local ln = pos1[2] + (i-1) - local line = fn.join(fn.sort(fn.split(lines[i], " "))) - line = fn.substitute(fn.getline(ln), lines[i], line, "") - vim.fn.setline(ln, line) + lines[i] = vim.fn.join(vim.fn.sort(vim.fn.split(lines[i], " "))) + end + + if not preview_ns then + vim.api.nvim_buf_set_lines(bufnr, top.ln-1, bot.ln, false, lines) + vim.notify('no preview') + return 0 + end + + -- inccommand preview + if preview_ns ~= nil then + for i, line in ipairs(lines) do + vim.api.nvim_buf_set_extmark(bufnr, preview_ns, top.ln+i - 2, 0, { + hl_mode = 'combine', + virt_text_pos = 'overlay', + virt_text = {{line, 'Substitute'}}, + }) + + if preview_bufnr ~= nil then + local prefix = string.format('|%d| ', top.ln + i - 1) + vim.api.nvim_buf_set_lines(preview_bufnr, i-1, -1, false, { prefix .. line }) + vim.api.nvim_buf_add_highlight(preview_bufnr, preview_ns, 'Substitute', i, #prefix, #prefix+#line) + end + end + return (#lines > 1 and 2 or 1) end end |