Question

Sometimes I want to insert a # to comment out a line and test it quickly. Currently I do:

i#ESC:w

Is there something shorter I can do?

Was it helpful?

Solution

Although I agree with others that there are better ways to comment and uncomment code, it seems that people have gotten distracted and forgotten to actually answer the question.

This is my approach to inserting a single character:

:noremap <key> i <Esc>r

I tend to find that I need to replace, remove, or add single characters very often if I'm correcting typos, so (resp.) r, x, and whatever is chosen for <key> in the above become very handy.

Note that . is also particularly handy for this sort of task. It repeats the previous action.

Personally though, I only map this function to a valuable key when I'm doing a task where I use it frequently enough to justify occupying a prime spot on the keyboard (such as correcting typos), because really, it only saves one keystroke per use and that's only when <key> is not a combination, which of course limits availability.

OTHER TIPS

I map a couple of things to my <leader> key (\ by default):

" # comment the current line
nnoremap <leader>d I#<ESC>

" block comment in visual mode
vnoremap <leader>c <ESC>'<O/*<ESC>'>o*/<ESC>V'<k

If you want to add a # to the start of a group of lines, then do this:

  1. <ctl-v>
  2. j (as many times as necessary
  3. I#
  4. <esc>

You could use a recording. From normal mode, type:

qlml0i#<press escape>`lq

Then to comment out a line, just press @l

Mapping in vim is so easy that I might do something like

:nmap CC I#<Esc>:w<CR>

on the fly. If I get used to it, then I will add it to my vimrc file.

:help key-mapping
:help usr_40.txt

Actually there is a plugin you might wanna take a look at:

http://www.vim.org/scripts/script.php?script_id=1218

It is specifically designed for that purpose.

I'm particularly fond of the tComment plugin. gcc to comment a line, repeat to uncomment, multiple lines, motions, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top