Insert character without entering insert mode?
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:
<ctl-v>
-
j
(as many times as necessary I#
<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
Related videos on Youtube
alejandro
Updated on June 04, 2022Comments
-
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 over 10 yearspossible duplicate of What's a quick way to comment/uncomment lines in Vim?
-
Peter Rincker over 10 yearsThere are many comment scripts. I use commentary.vim: github.com/tpope/vim-commentary
-
Pandu over 10 yearsAs 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.
-