JoosepAlviste / nvim-ts-context-commentstring

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

Add support for requesting multi-line comments #26

Closed JoosepAlviste closed 3 years ago

JoosepAlviste commented 3 years ago

This is useful if a commenting plugin enables commenting a region that is not the full line. Currently, only Comment.nvim seems to support this.

For example, typing gciw in a TypeScript file here:

hello world!
        ^ cursor

Would result in this:

hello /* world */!

And not this:

// hello world!

The way we support it is to allow each commentstring configuration value to be a table with custom keys. Afterwards, the custom key can be passed to update_commentstring so that the commentstring returned matches the requested one if possible.

require'nvim-treesitter.configs'.setup {
  context_commentstring = {
    enable = true,
    config = {
      typescript = { __default = '// %s', __multiline = '/* %s */' }
    }
  }
}

Later, the __multiline comment is returned (if available) with:

require('ts_context_commentstring.internal').update_commentstring({
  key = '__multiline',
})

Here is how it can be configured with Comment.nvim:

require('Comment').setup {
  pre_hook = function(ctx)
    local U = require 'Comment.utils'
    local type = ctx.ctype == U.ctype.line and '__default' or '__multiline'
    return require('ts_context_commentstring.internal').calculate_commentstring {
      key = type,
    }
  end,
}

This feature was requested in https://github.com/numToStr/Comment.nvim/issues/10