Define comment_symbol without extra plugins for different languages
Im migrating part of my workflow to Neovim, I stumble upon this problem, and I solved it with the following:
I know there are plugins
that does what I am doing
here, and better, but, I
prefer as few plugins as
possible
vim.api.nvim_exec([[
augroup visual_commenting
autocmd!
autocmd FileType c,cpp,java,rust,go,kt,kts,zig let b:comment_symbol = '//'
autocmd FileType vim let b:comment_symbol = '"'
autocmd FileType sh,python,yaml,yml,nix let b:comment_symbol = '#'
autocmd FileType tex let b:comment_symbol = '%'
autocmd FileType lua let b:comment_symbol = '--'
autocmd BufEnter * silent! vnoremap <silent> <C-_> :<C-u>keepp '<,'>s@^@\=b:comment_symbol<CR>
autocmd BufEnter * silent! exec 'vnoremap <silent> <C-?> :<C-u>keepp ''<,''>s@^' . b:comment_symbol . '@<CR>'
augroup END
]], false)
This solution solves only comments that starts with the defined symbol, does not cover block comments, for my usecase is enough.
You can add many lines as you need for more obscure languages and symbols.
If the file is not recognized, or not listed Neovim will show the message comment_symbol is not recognized
.
I’m sure should be a way to do it more in the “Neovim” way but, this just works.
This is based on this Vi’s StackExchange response and adapted for Lua.