Insert character without entering insert mode?

11,244

Solution 1

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.

Solution 2

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>

Solution 3

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
Share:
11,244

Related videos on Youtube

alejandro
Author by

alejandro

Updated on June 04, 2022

Comments

  • alejandro
    alejandro almost 2 years

    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?

    • ben
      ben over 10 years
    • Peter Rincker
      Peter Rincker over 10 years
      There are many comment scripts. I use commentary.vim: github.com/tpope/vim-commentary
    • Pandu
      Pandu over 10 years
      As others have said, you might want to try a plugin for comments. More generally, though, if you have a simple action that you need to do often or repetitively, you can easily create a mapping or macro.