How to uncomment several lines when some of these lines are not comments? #496
Unanswered
gaoqiangks
asked this question in
Q&A
Replies: 1 comment
-
I ran into this myself...I couldn't find much in the world of configuration to do this trivially. That said, I did a bit of silly business in my personal config that pulls in from the utils portion of the plugin. local uncommentLine = function()
local utils = require("Comment.utils")
local mode = vim.api.nvim_get_mode().mode
-- Leave visual mode if active
if mode == "v" or mode == "V" then
local escapeKey = vim.api.nvim_replace_termcodes("<esc>", true, false, true)
vim.api.nvim_feedkeys(escapeKey, "nx", false)
else
mode = "line" -- Convert to Comment.nvim's expected format
end
local range = utils.get_region(mode)
local lines = utils.get_lines(range)
-- Recreate internal API to construct the "comment context"
-- > https://github.com/numToStr/Comment.nvim/blob/master/lua/Comment/opfunc.lua#L46
local left_cs, right_cs = utils.parse_cstr({}, {
cmode = utils.cmode.uncomment,
cmotion = "line",
ctype = utils.ctype.linewise,
range = range,
})
-- Closures to perform the uncomment operation
-- > Boolean params enable padding
local check = utils.is_commented(left_cs, right_cs, true)
local uncomment = utils.uncommenter(left_cs, right_cs, true)
local changes = false
for idx, line in pairs(lines) do
if check(line) then
lines[idx] = uncomment(line)
changes = true
end
end
-- TODO: Currently, nvim_buf_set_lines has a bug where all marks that are
-- > within the changed content region are cleared
-- > Currently only in the nightly builds is the vim._with function, which
-- > should resolve this bug
-- > https://github.com/neovim/neovim/pull/29168
-- Call nvim api to update the buffer
-- vim._with({ lockmarks = true }, function()
if changes then
vim.api.nvim_buf_set_lines(0, range.srow - 1, range.erow, false, lines)
else
vim.notify("Nothing to uncomment!", vim.log.levels.WARN)
end
-- end)
-- Re-enter previous visual mode selection
-- if mode == "v" or mode == "V" then
-- vim.api.nvim_feedkeys("gv", "nx", false)
-- end
end And then I bound this as it's own keymap (in the same file) I pulled this straight from my config so forgive the silly todo comments :) |
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
-
For example, I have three lines, the first and the third are comments, while the second is not.
When visually select these three lines and type
gc
, it will becomeI want it to become
Beta Was this translation helpful? Give feedback.
All reactions