Neovim - Setup comment symbol, different symbols for different languages

Written by Lyoneel on in neovim
 1 min

Neovim - Setup comment symbol, different symbols for different languages

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:

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.