Skip to content

Instantly share code, notes, and snippets.

@voyeg3r
Last active March 30, 2022 16:14
Show Gist options
  • Save voyeg3r/223f148a115c17a02a15660cc7335f4c to your computer and use it in GitHub Desktop.
Save voyeg3r/223f148a115c17a02a15660cc7335f4c to your computer and use it in GitHub Desktop.
" 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>
@mizlan
Copy link

mizlan commented Mar 29, 2022

What are the bugs?

@anqin
Copy link

anqin commented Mar 30, 2022

@mizlan

When uncomment the lines, the indent spaces is dismissed. For example,

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

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

After uncommented,

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

if (!d) {
return -ENOMEM;
}

@mizlan
Copy link

mizlan commented Mar 30, 2022

Ah. I never addressed the uncomment portion of the original code in my diff.

Change the uncomment code to:

execute 'silent s/\v\s*\zs' . comment_leader . ' \ze//'

(i.e., change the match-any-whitespace to a match-space regex.

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