2

I'm using a modified version of https://stackoverflow.com/a/1676672/618584

autocmd FileType php,styl,javascript let b:comment_leader = '// '
noremap <C-\> :<C-B>silent <C-E>s/^/<C-R>=escape(b:comment_leader,'\/')<CR>/<CR>:nohlsearch<CR>
"noremap <C-\> :<C-B>silent <C-E>s/^\V<C-R>=escape(b:comment_leader,'\/')<CR>//e<CR>:nohlsearch<CR>

I want to remove comments using the same command (see commented out line above). What I need to do is check if the line begins with '//' and if so, map the to removing the comment.

Any idea how to do this?

I was previously using tpope's commentary plugin, and to achieve what I wnt with that, I'd do:

" comments toggle
autocmd FileType php setlocal commentstring=\/\/\ %s
nmap <C-\> gcc
xmap <C-\> gcugin I'd do:

But again, I do not want to use a plugin because I only code in JS and PHP.

ditto
  • 5,917
  • 10
  • 51
  • 88

1 Answers1

0

First, I would build abstractions via a custom function. Adding a custom command would make sense, too:

function! CommentToggle() range
    silent execute a:firstline . ',' . a:lastline . 's/^/' . escape(b:comment_leader, '\/') . '/e'
    "silent execute a:firstline . ',' . a:lastline . 's/^\V' . escape(b:comment_leader, '\/') . '//e'
endfunction
command! -range CT <line1>,<line2>call CommentToggle()|nohlsearch

noremap <C-\> :CT<CR>

With this, toggling just means checking (let's say the first line determines the on/off for all lines, i.e. you only operate on all-comments or nothing-commented) the line:

function! CommentToggle() range
    if getline(a:firstline) =~ '^\V' . escape(b:comment_leader, '\')
        silent execute a:firstline . ',' . a:lastline . 's/^\V' . escape(b:comment_leader, '\/') . '//e'
    else
        silent execute a:firstline . ',' . a:lastline . 's/^/' . escape(b:comment_leader, '\/') . '/e'
    endif
endfunction
Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
  • Getting a bunch of undefined variable: b:comment_leader errors. – ditto Jun 02 '17 at 16:14
  • You need to keep your original `autocmd`, I didn't duplicate it. – Ingo Karkat Jun 02 '17 at 18:24
  • Similar [comment toggle](https://gist.github.com/PeterRincker/13bde011c01b7fc188c5) method I experimented with for this question: [set filetype and comment key map with .s file](https://stackoverflow.com/q/41755704/438329) – Peter Rincker Jun 06 '17 at 15:36