Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
darthdeus opened this issue Nov 24, 2023 · 0 comments
Open

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

darthdeus opened this issue Nov 24, 2023 · 0 comments

Comments

@darthdeus
Copy link

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.

@darthdeus darthdeus changed the title Whitespace trim doesn't work Whitespace trim doesn't work on indented blocks as expected Nov 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant