Skip to content
Ievgenii Shepeliuk edited this page Sep 30, 2022 · 5 revisions

Smart Comment

Bind a single key that selects between single and multiline comment styles based on the current context:

-- numToStr 2021
function _G.__toggle_contextual(vmode)
    local cfg = A.get_config()
    local range = U.get_region(vmode)
    local same_line = range.srow == range.erow

    local ctx = {
        cmode = U.cmode.toggle,
        range = range,
        cmotion = U.cmotion[vmode] or U.cmotion.line,
        ctype = same_line and U.ctype.line or U.ctype.block,
    }

    local lcs, rcs = U.parse_cstr(cfg, ctx)
    local lines = U.get_lines(range)

    local params = {
        range = range,
        lines = lines,
        cfg = cfg,
        cmode = ctx.cmode,
        lcs = lcs,
        rcs = rcs,
    }

    if same_line then
        Op.linewise(params)
    else
        Op.blockwise(params)
    end
end

map('n', '<Leader>c', '<cmd>set operatorfunc=v:lua.__toggle_contextual<CR>g@')
map('x', '<Leader>c', '<cmd>set operatorfunc=v:lua.__toggle_contextual<CR>g@')

Move cursor to the beginning of the next line after comment

require('Comment').setup {
    post_hook = function(ctx)
        local r,c = unpack(vim.api.nvim_win_get_cursor(0))
        local rc = vim.api.nvim_buf_line_count(0)
        if rc > r then
            vim.api.nvim_win_set_cursor(0, {r+1,0})
        end
    end,
}
Clone this wiki locally