JoosepAlviste / nvim-ts-context-commentstring

Neovim treesitter plugin for setting the commentstring based on the cursor location in a file.
MIT License
1.18k stars 35 forks source link

Incorrect commentstring inside <?php ?> tags #112

Open nipunlakshank opened 6 months ago

nipunlakshank commented 6 months ago

Minimal reproducible full config

-- Install lazy.nvim automatically
local lazypath = vim.fn.stdpath 'data' .. '/lazy/lazy.nvim'
if not vim.loop.fs_stat(lazypath) then
  vim.fn.system {
    'git',
    'clone',
    '--filter=blob:none',
    'https://github.com/folke/lazy.nvim.git',
    '--branch=stable', -- latest stable release
    lazypath,
  }
end
vim.opt.rtp:prepend(lazypath)

-- Or some other small value (Vim default is 4000)
vim.opt.updatetime = 200

require('lazy').setup {
  {
    'nvim-treesitter/nvim-treesitter',
    build = ':TSUpdate',
    config = function()
      require('nvim-treesitter.configs').setup {
        ensure_installed = { 'vim', 'lua', 'php' },
        highlight = {
          enable = true,
        },
      }
    end,
  },`
`  {
    'numToStr/Comment.nvim',
    lazy = true,
    event = { "BufReadPre", "BufNewFile" },
    dependencies = {
          'JoosepAlviste/nvim-ts-context-commentstring',
    }
    config = function()
      require('Comment').setup {
          pre_hook = require("ts_context_commentstring.integrations.comment_nvim").create_pre_hook(),
      }
    end,
  },
}

Description

In php files commenting inside a <php ?> tag that is inside an html tag results in adding a html commentstring instead of php commentstring Ex:

<html>
<?php
for ($i = 0; $i < 10; $i++) {
    print_r($i);
}
?>
... more html or php
</html>

Steps to reproduce

Ex:

<html>
<?php
for ($i = 0; $i < 10; $i++) {
    // try commenting below line
    print_r($i);
}
?>
</html>

Expected behavior

<html>
<?php
for ($i = 0; $i < 10; $i++) {
    // after commenting below line
    // print_r($i);
}
?>
</html>

Actual behavior

<html>
<?php
for ($i = 0; $i < 10; $i++) {
    // after commenting below line
    <!-- print_r($i); -->
}
?>
</html>

Additional context

No response

JoosepAlviste commented 6 months ago

Hey! It looks like this is indeed a problem. I think that it's because the PHP treesitter parser is kinda weird. The PHP and HTML trees both cover the entire buffer and aren't nested inside each other. When we're looping over the language trees here, we first see PHP and then HTML. This means that the HTML tree will always overwrite the PHP one.

I'm not sure what the best solution would be, we might need to add a special case for PHP in that function (something like "if previous tree PHP and new tree HTML, then don't overwrite"), though that might break the cases if we actually do want to use the HTML commentstring inside the PHP parts.

Will need to play around with this a little bit since there isn't an obvious solution to this 😕