Vim; Shortcut to add comment at beginning of line

1

When I code, I tend to execute the following manually a lot after having selected multiple lines of code.

:'<,'>s/^/#/

I want to add this to my .vimrc but I am having troubles making it work. The intention is to be able to select a set of lines and then press mapleader c and vim will add an extra # at the beginning of all selected lines.

1 " Key mapping.                                                                                                                                                      
2 let mapleader = ","
...
141 nmap <silent> <leader>c :<'>'s/^/#/<CR>

Line 141 seems to just delete the selected lines and I am having troubles seeing why this is. Any ideas what I am doing wrong or what I can change to get this to work?

Mogget

Posted 2015-09-27T18:30:00.873

Reputation: 1 186

1

You could also consider the NerdCommenter plugin btw., which can do this and more: https://github.com/scrooloose/nerdcommenter

– miyalys – 2015-09-27T18:32:30.170

1@miyalys, I am quite satisfied with the setup I have a this very moment and I wish only to add that specific option. I feel that adding a feature rich plugin just to get me this is a bit overkill. Thank you for the suggestion though. – Mogget – 2015-09-27T18:40:30.740

3Alright, I'm not sure why you're using an nmap if you want to select the lines in visual mode first, but if you still want to select the lines first in visual mode I have a suggestion for vimrc, however it seems I can't get it to work with <leader>c for some reason (maybe <leader>c will work for you): vmap <silent> t :s/^/#/<CR>:let @/ = ""<CR>. If this solves your problem okay I'll write it up as an answer. – miyalys – 2015-09-27T18:58:53.560

1@Mogget, in line 141 <'>' should be '<,'> (wrong order and missin ","); also define it for visual mode (vmap ...) – JJoao – 2015-10-05T16:02:12.137

Answers

0

This is an exact replica of the line @miyalys gave in a comment and it work exactly as I want it to.

vmap <silent> t :s/^/#/<CR>:let @/ = ""<CR>

He says he could not get it to work with c, but I got it to work with that character.

Thanks.

Mogget

Posted 2015-09-27T18:30:00.873

Reputation: 1 186

2

Try this: it does a block insert while in visual mode

vmap <silent> <leader>c :norm i#<ESC>

Isaac Hanson

Posted 2015-09-27T18:30:00.873

Reputation: 553