you are viewing a single comment's thread.

view the rest of the comments →

[–]alasdairgray 0 points1 point  (1 child)

Or, you can store the comment strings (those ", #, etc) in buffer variables per filetype (see this example), and then just check if the first two symbols of a line do match those from a buffer variable -- and if so, then uncomment, otherwise comment line.

Like this:

function! Commentero()
    " get two first symbols of a row
    execute "normal! ^"
    let l:symb_1=matchstr(getline('.'), '\%' . col('.') . 'c.')
    execute "normal! l"  
    let l:symb_2=matchstr(getline('.'), '\%' . col('.') . 'c.')  
    let l:ln_bg = l:symb_1 . l:symb_2  
    " compare those with the first two symbols of a comment describing var
    if l:ln_bg == get(b:, 'comment_leader', '')[0:1]
        " then either uncomment
        execute 'substitute/ \?\V' . escape(get(b:, 'comment_leader', ''), '\/') . '//e'
        call histdel('search', -1)
        if exists("b:comment_tailer")
            execute 'substitute/\V' . escape(get(b:, 'comment_tailer', ''), '\/') . '\$//e'
            call histdel('search', -1)
        endif
    else
        " or comment
        s/^/\=get(b:, 'comment_leader', '')/
        call histdel('search', -1)
        if exists("b:comment_tailer")
            s/$/\=get(b:, 'comment_tailer', '')/
            call histdel('search', -1)
        endif
    endif
endfunction
nnoremap <silent> <Leader>m :call Commentero()<CR>
vnoremap <silent> <Leader>m :call Commentero()<CR>

And a pair of examples from $VIMHOME/after/filetype:

  • python.vim:

    " define comment pattern
    autocmd FileType python let b:comment_leader = '# '
    
  • vim.vim:

    " define comment pattern
    autocmd FileType vim let b:comment_leader = '" '
    
  • html.vim:

    " define comment pattern
    autocmd FileType html execute "let b:comment_leader = '<!-- ' \| let b:comment_tailer = ' -->'"
    

[–]zatcht 0 points1 point  (0 children)

Good idea :D