I am looking for a way to comment on individual lines (single-line comments) in source codes both in visual mode and in insert mode, but I would like to do a simple editing of .vimrc without additional plugins. I am sure that this is possible, so please indicate what could be pushed away from.

1 answer 1

As a starting point you can do, for example, as follows.

function! GetCommentStyleByFileType() let file_name = buffer_name('%') if file_name =~ '\(\.\|_\)vim' return ["\"", ''] elseif file_name =~ '\.\(bat\|cmd\)' return ['::', ''] elseif file_name =~ '\.\(c\|cpp\|cs\|js\|php\)' return ['//', ''] elseif file_name =~ '\.\(ht\|x\)ml$' return ['<!--', '-->'] elseif file_name =~ '\.\(lua\|sql\)' return ['--', ''] elseif file_name =~ '\.\(vb\|vbs\)' return ["'", ''] endif return ['#', ''] endfunction au BufEnter * let b:comment = GetCommentStyleByFileType() function! CommentLine() let stsymbol = b:comment[0] let endsymbol = b:comment[1] exe ":sil! norm 0i" . stsymbol . "\<Esc>A" . endsymbol . "\<Esc>" endfunction function! UnCommentLine() let file_name = buffer_name('%') let stsymbol = b:comment[0] if file_name =~ '\.\(c\|cpp\|cs\|js\|php\)' let stsymbol = '\/\/' endif let endsymbol = b:comment[1] exe ":sil! norm :s/^\s*" . stsymbol . "//\<CR>" exe ":sil! norm :s/\s*" . endsymbol . "\s*$//\<CR>" endfunction exe "set <Mc>=\ec" nnoremap <Mc> :call CommentLine()<CR> inoremap <Mc> <Esc>:call CommentLine()<CR>i vmap <Mc> :call CommentLine()<CR> exe "set <Mu>=\eu" nnoremap <Mu> :call UnCommentLine()<CR> inoremap <Mu> <Esc>:call UnCommentLine()<CR>i vmap <Mu> :call UnCommentLine()<CR> 

So, to comment out the line you need to press Alt+C to remove the comment from the line - Alt+U You can bind on another keyboard shortcut, using Alt+некая_клавиша for an example here, just like the functions themselves - experiment, maybe you will do something convenient and useful not only for yourself.