Technology
 

Insert a single character

From Vim Tips Wiki

(Redirected from VimTip270)

Tip 270 Previous Next created June 29, 2002 · complexity basic · author Mikko Pulkkinen · version 6.0


Using insert mode to insert a single character feels clumsy (you need three keypresses for one character), so here's a slightly easier way:

:nmap <Space> i_<Esc>r

Now, when in normal mode, just press space followed by what it is you want to insert.

Bug: Repeating the insertion with . doesn't work.

[edit] Comments

I prefer <C-I> as a {lhs}. It is unused and fits better to the insert logic of Vim, although it saves less key strokes.


I use

:map gt i_<Esc>r
:map gb a_<Esc>r

The author was looking for a way to save a keystroke. Both solutions are 3 keystrokes long. A solution that also moves the cursor to the right would be better.


I consider this a better solution:

:nnoremap s :exec "normal i".nr2char(getchar())."\e"<CR>
:nnoremap S :exec "normal a".nr2char(getchar())."\e"<CR>

Such inserts can be repeated with '.' thus making this command worthy (it's not a big problem to make an additional keypress but imagine you need to manually put some spaces or other separators).

PS. 's' and 'S' were chosen because:

  • They remind of 'single'.
  • If they are used occasionally, one can use synonyms 'cl' and 'cc' instead.
What is the "\e" for?
The built-in s command is very useful, but that's a choice for the user. JohnBeckett 22:56, 15 June 2009 (UTC)