Neovim - Setup comment symbol, different symbols for different languages

Written by Lyoneel on in neovim
 1 min

Define comment_symbol without extra plugins for different languages

I’m migrating part of my workflow to Neovim, I stumbled upon this problem, and I solved it with the following:

 1vim.api.nvim_exec([[
 2augroup visual_commenting
 3    autocmd!
 4    autocmd FileType c,cpp,java,rust,go,kt,kts,zig      let b:comment_symbol = '//'
 5    autocmd FileType vim                                let b:comment_symbol = '"'
 6    autocmd FileType sh,python,yaml,yml,nix             let b:comment_symbol = '#'
 7    autocmd FileType tex                                let b:comment_symbol = '%'
 8    autocmd FileType lua                                let b:comment_symbol = '--'
 9    autocmd BufEnter * silent! vnoremap <silent> <C-_> :<C-u>keepp '<,'>s@^@\=b:comment_symbol<CR>
10    autocmd BufEnter * silent! exec 'vnoremap <silent> <C-?> :<C-u>keepp ''<,''>s@^' . b:comment_symbol . '@<CR>'
11augroup END
12]], false)

This solution solves only comments that start with the defined symbol, does not cover block comments, for my use-case is enough.

You can add as 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 there 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.