Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
" source: https://stackoverflow.com/a/24046914/2571881
let s:comment_map = {
\ "c": '\/\/',
\ "cpp": '\/\/',
\ "go": '\/\/',
\ "java": '\/\/',
\ "javascript": '\/\/',
\ "lua": '--',
\ "scala": '\/\/',
\ "php": '\/\/',
\ "python": '#',
\ "ruby": '#',
\ "rust": '\/\/',
\ "sh": '#',
\ "desktop": '#',
\ "fstab": '#',
\ "conf": '#',
\ "profile": '#',
\ "bashrc": '#',
\ "bash_profile": '#',
\ "mail": '>',
\ "eml": '>',
\ "bat": 'REM',
\ "ahk": ';',
\ "vim": '"',
\ "tex": '%',
\ }
function! ToggleComment()
if has_key(s:comment_map, &filetype)
let comment_leader = s:comment_map[&filetype]
if getline('.') =~ '^\s*$'
" Skip empty line
return
endif
if getline('.') =~ '^\s*' . comment_leader
" Uncomment the line
execute 'silent s/\v\s*\zs' . comment_leader . '\s*\ze//'
else
" Comment the line
execute 'silent s/\v^(\s*)/\1' . comment_leader . ' /'
endif
else
echo "No comment leader found for filetype"
endif
endfunction
nnoremap <Leader>t :call ToggleComment()<CR>
vnoremap <Leader>t :call ToggleComment()<CR>
@dave-kennedy
Copy link

dave-kennedy commented Mar 30, 2018

I edited this to skip empty lines. Also removed the \v from the regex comparison as it is unnecessary, and added a missing comment.

See https://gist.github.com/dave-kennedy/2188b3dd839ac4f73fe298799bb15f3b.

Feel free to merge!

@TLogiviere
Copy link

TLogiviere commented Apr 30, 2019

Nice, thank you ! 😃

@backermanbd
Copy link

backermanbd commented Jun 30, 2021

@voyeg3r @dave-kennedy Could you please configure your script to put comment out signs at the first of each line?
For example: like this cpp code

//#include <iostream>
//      using namespace std;

//    int main() {
//    cout << "hello world";
//   }

Other Alternative Solution:

  1. I found this in stackoverflow.. this code comments out sign at the first of each line
function! CommentToggle()
    execute ':silent! s/\([^ ]\)/\/\/ \1/'
    execute ':silent! s/^\( *\)\/\/ \/\/ /\1/'
endfunction
map <C-C> :call CommentToggle()<CR>
  1. https://stackoverflow.com/a/22246318/15770124
autocmd FileType c,cpp,java,scala let b:comment_leader = '//'
autocmd FileType sh,ruby,python   let b:comment_leader = '#'
autocmd FileType conf,fstab       let b:comment_leader = '#'
autocmd FileType tex              let b:comment_leader = '%'
autocmd FileType mail             let b:comment_leader = '>'
autocmd FileType vim              let b:comment_leader = '"'
function! CommentToggle()
    execute ':silent! s/\([^ ]\)/' . escape(b:comment_leader,'\/') . ' \1/'
    execute ':silent! s/^\( *\)' . escape(b:comment_leader,'\/') . ' \?' . escape(b:comment_leader,'\/') . ' \?/\1/'
endfunction
map <F7> :call CommentToggle()<CR>

@mizlan
Copy link

mizlan commented Jul 13, 2021

I believe the following change should work for putting the comment sign flush at the start of each line:

diff --git a/a.vim b/b.vim
index 17be639..d3c6330 100644
--- a/a.vim
+++ b/b.vim
@@ -37,7 +37,7 @@ function! ToggleComment()
             execute 'silent s/\v\s*\zs' . comment_leader . '\s*\ze//'
         else
             " Comment the line
-            execute 'silent s/\v^(\s*)/\1' . comment_leader . ' /'
+            execute 'silent s/\v^(\s*)/' . comment_leader . '\1 /'
         endif
     else
         echo "No comment leader found for filetype"

@dave-kennedy
Copy link

dave-kennedy commented Jul 18, 2021

@backermanbd both alternatives you copied from SO have the same behavior as the original script, i.e. they add the comment leader to the beginning of each line, regardless of previous lines. Just curious, what do you not like about vim-commentary?

@backermanbd
Copy link

backermanbd commented Jul 19, 2021

the alternatives don't work as expected.. my 1st alternative was only for cpp //
it doesn't support multiple languages comment out feature

vim-commentary doesn't put comment out signs at the start of each line

PS: i preferred this gist. because it's minimal.. has the three feature i need.
only missing feature is to make it add comment out signs at the start of each line

@dave-kennedy
Copy link

dave-kennedy commented Jul 19, 2021

@backermanbd I hear ya, I prefer minimal plugins as well. vim-commentary meets my criteria for minimalism: Striving for minimalism, it weighs in at under 100 lines of code.

Give it another try. It puts the comment leader where you want - aligning it with the beginning of the first line in the range.

Example before:

class Foo:
    def foo(items: list):
        for item in items:
            print(item)

After copying that into a buffer, then hitting gcG:

# class Foo:
#     def foo(items: list):
#         for item in items:
#             print(item)

ujgcG:

class Foo:
    # def foo(items: list):
    #     for item in items:
    #         print(item)

ujgc<CR>:

class Foo:
    def foo(items: list):
        # for item in items:
        #     print(item)

You get the idea.

@backermanbd
Copy link

backermanbd commented Jul 20, 2021

@dave-kennedy I tried..

  1. if you comment out whole file or in a block of lines, there's a line which first char is from the start of line
    vim-commentary puts comment out signs at the start of each line.
    otherwise it doesn't
  2. but if you comment out single lines, comment out signs doesn't go to the start of each line

PS: i couldn't make the commentstring // of cpp file
tried this //\ from this issue
still no luck

@dave-kennedy
Copy link

dave-kennedy commented Jul 23, 2021

@backermanbd I think I understand your first point. If I have this code:

static int do_something() {
    struct dir* d = malloc(sizeof(*d));

    if (!d) {
        return -ENOMEM;
    }

And I put my cursor on line 3 and do gc}, this is the result:

static int do_something() {
    struct dir* d = malloc(sizeof(*d));

//     if (!d) {
//         return -ENOMEM;
//     }

For comparison, if I put my cursor on on line 4:

static int do_something() {
    struct dir* d = malloc(sizeof(*d));

    // if (!d) {
    //     return -ENOMEM;
    // }

You want it to behave like the second result regardless of whether you had your cursor on line 3 or 4.

If I were you I'd create an issue here: https://github.com/tpope/vim-commentary/issues. Chances are good you're not the only person who finds this behavior irksome. You'll probably get more traction there. Maybe I'll even take a poke at it. Or you can fix it yourself and help everybody. This is the strength of open source software.

As for your second point, try putting this in your .vimrc:

autocmd BufEnter *.c,*.cpp setlocal commentstring=//\ %s

Or create a file under ~/.vim/after/ftplugin/c.vim with these contents:

setlocal commentstring=//\ %s

Make sure it's exactly like that, including the %s at the end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment