Insert vim variables into text for comment label

I have a simple goal: Ctrl-C map, a command that I don’t think I have ever used to remove vim, automatically insert the correct character (s) at the beginning of a line to comment on that line according to the file type of the file.

I decided that I could use the auto command to recognize the file type and set the vim variable to the correct comment character when the file is open. So I tried something like:

" Control C, which is NEVER used. Now comments out lines!
autocmd BufNewFile,BufRead *.c let CommentChar = "//"
autocmd BufNewFile,BufRead *.py let CommentChar = "#"
map <C-C> mwI:echo &CommentChar<Esc>`wll

This map marks my current location, goes to the beginning of the line in insert mode, echoes the comment character at this point, goes into command mode, returns to the given character and goes two characters to the right to make comments for inserted characters (subject to C style comment )

The italic part is that part with which I have problems; he is present only as the owner of the place to represent what I want to do. Can you help me figure out how to achieve this? Bonus points if you use strlen (CommentChar) to put the right number of spaces to the right! Extra bonus points for vim-master, which includes how to make block-style comments if you are in visual mode!

I'm still pretty new to vim scripts; my .vimrc is a fair 98 lines, so if you could help me by explaining any answers you provide! Thank.

+3
source share
2 answers

<C-r> :

noremap <C-c> mwI<C-r>=g:CommentChar<CR><Esc>`wll

. :h i_CTRL-R.

NERDCommenter, :

" By default, NERDCommenter uses /* ... */ comments for c code.
" Make it use // instead
let NERD_c_alt_style=1
noremap <C-c> :call NERDComment(0, "norm")<CR>

.

+5

- - . , - (), , - , .

" Set comment characters for common languages
autocmd FileType python,sh,bash,zsh,ruby,perl,muttrc let StartComment="#" | let EndComment=""
autocmd FileType html let StartComment="<!--" | let EndComment="-->"
autocmd FileType php,cpp,javascript let StartComment="//" | let EndComment=""
autocmd FileType c,css let StartComment="/*" | let EndComment="*/"
autocmd FileType vim let StartComment="\"" | let EndComment=""
autocmd FileType ini let StartComment=";" | let EndComment=""

" Toggle comments on a visual block
function! CommentLines()
    try
        execute ":s@^".g:StartComment." @\@g"
        execute ":s@ ".g:EndComment."$@@g"
    catch
        execute ":s@^@".g:StartComment." @g"
        execute ":s@$@ ".g:EndComment."@g"
    endtry
endfunction

" Comment conveniently
vmap <Leader>c :call CommentLines()<CR>
+2

Source: https://habr.com/ru/post/1768175/


All Articles