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 okay 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.
Step 1: Go to the the first column of the first line you want to comment.
Step 2: Press: Ctrl+v and select the lines you want to comment:
Step 3:Shift–I#space (Enter Insert-at-left mode, type chars to insert. The selection will disappear, but all lines within it will be modified after Step 4.)
Comment the selected block out with: :norm i# (lower case i)
To uncomment, highlight your block again, and uncomment with: :norm ^x
The :norm command performs an action for every selected line. Commenting will insert a # at the start of every line, and uncommenting will delete that #.
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:
Frankly I use a tcomment plugin for that link. It can handle almost every syntax. It defines nice movements, using it with some text block matchers specific for python makes it a powerful tool.
NERDcommenter is an excellent plugin for commenting which automatically detects a number of filetypes and their associated comment characters. Ridiculously easy to install using Pathogen.
Comment with <leader>cc. Uncomment with <leader>cu. And toggle comments with <leader>c<space>.
There’s a lot of comment plugins for vim – a number of which are multi-language – not just python. If you use a plugin manager like Vundle then you can search for them (once you’ve installed Vundle) using e.g.: