JoosepAlviste / nvim-ts-context-commentstring

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

Add option to disable default commentary mappings #42

Closed shiradofu closed 2 years ago

shiradofu commented 2 years ago

I use commentary.vim, but I don't use mappings like gcc. It would be nice if default mappings can be disabled.

JoosepAlviste commented 2 years ago

Looks good, thanks for the contribution!

Though, ideally, the mappings should be smart enough so that they would override the custom ones (but that's probably a bit difficult to do) 😄

shiradofu commented 2 years ago

I tried writing this and it seems to work well on my machine. Can I submit another PR?

local gmap = vim.api.nvim_set_keymap
local bmap = vim.api.nvim_buf_set_keymap

local M = {}

-- `maps` is user-defined config
function M.set_up_maps(maps)
  for _, mode in ipairs { 'n', 'x', 'o' } do
    gmap(
      mode,
      '<Plug>ContextCommentary',
      [[v:lua.context_commentstring.update_commentstring_and_run('Commentary')]],
      { expr = true }
    )
  end
  gmap(
    'n',
    '<Plug>ContextCommentaryLine',
    [[v:lua.context_commentstring.update_commentstring_and_run('CommentaryLine')]],
    { expr = true }
  )
  gmap(
    'n',
    '<Plug>ContextChangeCommentary',
    [[v:lua.context_commentstring.update_commentstring_and_run('ChangeCommentary')]],
    { expr = true }
  )

  maps = (maps and type(maps) == 'table') and maps or {}
  maps = vim.tbl_extend('force', {
    Commentary = 'gc',
    CommentaryLine = 'gcc',
    ChangeCommentary = 'cgc',
    CommentaryUndo = 'gcu',
  }, maps)

  if maps.Commentary then
    for _, mode in ipairs { 'n', 'x', 'o' } do
      bmap(0, mode, maps.Commentary, '<Plug>ContextCommentary', {})
    end
  end
  if maps.CommentaryLine then
    bmap(0, 'n', maps.CommentaryLine, '<Plug>ContextCommentaryLine', {})
  end
  if maps.ChangeCommentary then
    bmap(0, 'n', maps.ChangeCommentary, '<Plug>ContextChangeCommentary', {})
  end
  if maps.CommentaryUndo then
    bmap(0, 'n', maps.CommentaryUndo, '<Plug>ContextCommentary<Plug>Commentary', {})
  end
end

return M

With this impl, I'll remove disable_commentary_mappings. We can disable default mappings like this:

M.set_up_maps({ Commentary = false })
JoosepAlviste commented 2 years ago

Oh this looks pretty nice! And then the user passes in their mappings in the config without creating them themselves, right? Something like this?

require'nvim-treesitter.configs'.setup {
  context_commentstring = {
    enable = true,
    commentary_integration = {
      Commentary = 'gc',
      CommentaryLine = 'gcc',
      ChangeCommentary = 'cgc',
      CommentaryUndo = 'gcu',
    },
  }
}

I think that it is probably cleaner indeed and I don't think that it would be a breaking change, right?

I would appreciate a PR!

shiradofu commented 2 years ago

Thanks for quick reply! I created a new PR!