Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert character without entering insert mode?

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?

like image 956
alejandro Avatar asked Jan 17 '14 23:01

alejandro


People also ask

How do I insert a character in Vim?

Once in insert mode, typing inserts characters just like a regular text editor. You can enter it by using an insert command from normal mode. Insert commands include: i for 'insert', this immediately switches vim to insert mode.

How do you enter insert mode?

To enter Insert mode, press i . In Insert mode, you can enter text, use the Enter key to go to a new line, use the arrow keys to navigate text, and use vi as a free-form text editor. To return to Command mode, press the Esc key once. [ Free eBook: Manage your Linux environment for success. ]

How do I exit insert mode in Vim?

To exit from 'insert' mode, hit ESC (the escape key). If you want to force a quit (i.e. quit without saving) type: :q!

How do you enter insert mode and go to the beginning of the line?

Esc + i to exit insert mode and enter it again, effectively going to the beginning of line.


2 Answers

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.

like image 117
James Haigh Avatar answered Oct 03 '22 08:10

James Haigh


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>
like image 20
Wayne Avatar answered Oct 03 '22 06:10

Wayne