terrortylor / nvim-comment

A comment toggler for Neovim, written in Lua
MIT License
479 stars 23 forks source link

Whitespace trim doesn't work on indented blocks as expected #59

Open darthdeus opened 11 months ago

darthdeus commented 11 months ago

I have comment_empty_trim_whitespace = true but doing a simple comment/uncomment on something like this leaves the middle line with spaces when only the inner block is selected

if true then
  local foo = 1   -- visual mode from here

  foo = foo + 1  -- to here
end

If I select the whole top level statement it works, but if I comment out the middle part it does not, and leaves as many spaces as it was initially indented. This is undesirable, because at least in my experience one does not want whitespace on empty lines in indented code.

I dug into the code a bit and found that the pattern is matched, but the replacement seems wrong

function M.uncomment_line(l, left, right, comment_empty_trim_whitespace)
  local line = l
  if right and right ~= "" then
    line = line:gsub(vim.pesc(right) .. "$", "")
    return line:gsub(vim.pesc(left), "", 1)
  end

  if comment_empty_trim_whitespace and left:match("%s+$") then
    local left_nw = left:match("^(%S+)%s+$")
    if line:match("^%s*" .. left_nw .. "$") then
      print("THIS GETS PRINTED EXACTLY ONCE, BUT NO REPLACEMENT")
      return line:gsub(vim.pesc(left_nw), "", 1)
    end
  end

  return line:gsub(vim.pesc(left), "", 1)
end

Replacing

      return line:gsub(vim.pesc(left_nw), "", 1)

with

      return line:gsub("^%s*" .. vim.pesc(left_nw) .. "%s*", "", 1)

fixes it for me. I don't know much about neovim's APIs, so not sure if this is the best way to do it, but it does seem to work. Testing it even on some bigger code seems to produce the expected results.