diff --git a/config/plugin/keymap.insertsection.lua b/config/plugin/keymap.insertsection.lua index 8da4b56..7d331eb 100644 --- a/config/plugin/keymap.insertsection.lua +++ b/config/plugin/keymap.insertsection.lua @@ -1,23 +1,38 @@ -- https://github.com/echasnovski/nvim/blob/0a87022921d2e2a95fb987c4f11fc4804b57d6f9/plugin/21_functions.lua#L23 vim.keymap.set("n", "(ivy-insert-section)", function() + local lnum = vim.fn.line(".") local symbol = "=" local total_width = vim.o.textwidth > 0 and vim.o.textwidth or 79 - -- Insert template: 'commentstring' but with '%s' replaced by section symbols - local comment_string = vim.bo.commentstring - local comment_str_len = #comment_string:format("") - local content = string.rep(symbol, total_width - comment_str_len) - local section_template = comment_string:format(content) - local okn = vim.fn.append(vim.fn.line("."), { section_template }) - if okn == 1 then + local indent = vim.fn.indent(lnum) + if indent == -1 then return end + -- on empty lines: inherit indent of previous non-empty line + local lnum_ = lnum + while + indent == 0 + and #vim.api.nvim_buf_get_lines(0, lnum_ - 1, lnum_, true)[1] == 0 + and lnum_ > 0 + do + lnum_ = lnum_ - 1 + indent = vim.fn.indent(lnum_) + end + local indent_str = string.rep(" ", indent) + + -- use 'commentstring' with '%s' replaced by section symbols and prepended + -- with indent_str + local comment_string = vim.bo.commentstring + local comment_str_len = #comment_string:format("") + local content = string.rep(symbol, total_width - indent - comment_str_len) + local section_template = indent_str .. comment_string:format(content) + vim.api.nvim_buf_set_lines(0, lnum - 1, lnum, true, { section_template }) - -- Enable Replace mode in appropriate place - local inner_start = comment_string:find("%%s") - vim.fn.cursor(vim.fn.line(".") + 1, inner_start) - vim.cmd([[startreplace]]) + -- start replace mode at inner start + local inner_start = comment_string:find("%%s") + indent + vim.fn.cursor(lnum, inner_start) + vim.cmd.startreplace() end) vim.keymap.set("n", "is", "(ivy-insert-section)")