[mini.comment] Commenting in insert mode #2308
n-crespo
started this conversation in
Show and tell
Replies: 1 comment
-
|
Thanks for sharing! I'd still think that using plain Maybe |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Here's a snippet I use for toggling comments in insert mode with (just like vsc*de):
{ "nvim-mini/mini.comment", keys = { { "<C-/>", function() local api = vim.api local cursor = api.nvim_win_get_cursor(0) local row, col = cursor[1], cursor[2] local line = api.nvim_get_current_line() -- get commentstring components local cs = require("mini.comment").get_commentstring({ row, col + 1 }) if cs == "" or not cs:find("%%s") then return end local prefix, suffix = cs:match("^(.-)%%s(.-)$") local trim_pre = prefix:gsub("%s+$", "") -- prefix without trailing space local trim_suf = suffix:gsub("^%s+", "") -- suffix without leading space -- capture leading whitespace and everything else local indent, content = line:match("^(%s*)(.*)") -- handle line that is either empty OR only contains the comment markers -- we use vim.pesc to treat markers as literal strings in the regex local pattern = "^" .. vim.pesc(prefix) .. vim.pesc(suffix) .. "$" local pattern_trimmed = "^" .. vim.pesc(trim_pre) .. vim.pesc(trim_suf) .. "$" if content == "" or content:match(pattern) or content:match(pattern_trimmed) then if content == "" then -- case: empty line -> add comment, keep indent api.nvim_set_current_line(indent .. prefix .. suffix) api.nvim_win_set_cursor(0, { row, #indent + #prefix }) else -- case: only comment markers exist -> remove markers, keep indent api.nvim_set_current_line(indent) api.nvim_win_set_cursor(0, { row, #indent }) end return end -- standard toggle logic for lines with actual content local is_commented = content:sub(1, #trim_pre) == trim_pre local offset = 0 if is_commented then local space_match = content:match("^" .. vim.pesc(trim_pre) .. "(%s?)") or "" offset = -(#trim_pre + #space_match) else local padding = prefix:find("%s$") and 1 or 0 offset = #trim_pre + padding end require("mini.comment").toggle_lines(row, row, { ref_position = { row, col + 1 } }) api.nvim_win_set_cursor(0, { row, math.max(0, col + offset) }) end, mode = "i", desc = "Toggle Comment Line", }, { "<C-/>", "gcc", mode = "n", remap = true, desc = "Toggle Comment Line", }, { "<C-/>", "gcgv", mode = "v", remap = true, desc = "Toggle Comment Line", }, }, }Beta Was this translation helpful? Give feedback.
All reactions