tags:

views:

749

answers:

5

I was wondering if there was any key mapping in VIM to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or n lines above/below current cursor position).

So basically something that converts the following

def my_fun(x, y):
    return x + y

to

#def my_fun(x, y):
#    return x + y

I am ok with using either # or """ for commenting out the relevant lines. Ideally, I would also like the same keymapping to uncomment the lines if the given lines have been commented out.

Thanks

+2  A: 

one way manually

:set number
:10,12s/^/#
ghostdog74
+14  A: 
Ctrl+v

Select The first column of the lines you want to comment.

VISUAL BLOCK

Shift-I # <Esc>

Shift-I #

Shift-I #

<Esc>

<Esc>

TheOsp
Commenting the lines this way works great. Is there some way to uncomment these lines? `Shift-I # <ESC>` didn't work (maybe I'm doing it wrong).
Rishabh Manocha
@rishabh-manocha: use visual block (Ctrl-V) to select all the added # and type x to delete them.
TheOsp
@TheOsp - duh!! Should have thought of that :). Thx.
Rishabh Manocha
You gotta remember that Shift-I means "insert at the first non-blank in the line", so it can't be used to delete. Doing a visual selection with Ctrl-V marks the characters to modify, then "x" deletes one character in the selected area, ending up deleting the '#' characters. See ":h I" and ":h CTRL-V" in vim for more information.
Greg
+3  A: 

There are some good plugins to help comment/uncomment lines. For example The NERD Commenter.

Geoff Reedy
A: 

I usually sweep out a visual block (<C-V>), then search and replace the first character with:

:'<,'>s/^/#

(Entering command mode with a visual block selected automatically places '<,'> on the command line) I can then uncomment the block by sweeping out the same visual block and:

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

I have the following lines in my .vimrc:

" comment line, selection with Ctrl-N,Ctrl-N
au BufEnter *.py nnoremap  <C-N><C-N>    mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>`n
au BufEnter *.py inoremap  <C-N><C-N>    <C-O>mn<C-O>:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap  <C-N><C-N>    mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>gv`n

" uncomment line, selection with Ctrl-N,N
au BufEnter *.py nnoremap  <C-N>n     mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>:s/^#$//ge<CR>:noh<CR>`n
au BufEnter *.py inoremap  <C-N>n     <C-O>mn<C-O>:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR><C-O>:s/^#$//ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap  <C-N>n     mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>gv:s/#\n/\r/ge<CR>:noh<CR>gv`n

The shortcuts preserve your cursor position and your comments as long as they start with # (there is space after #). For example:

# variable x
x = 0

After commenting:

# variable x
#x = 0

After uncomennting:

# variable x
x = 0
Lukas Cenovsky