Wikia

Vim Tips Wiki

Quick insert character at end-of-line

Talk0
1,612pages on
this wiki
Tip 936 Printable Monobook Previous Next

created 2005 · complexity basic · author Gerald Lai · version 5.7


This inserts the next character typed at the end of a line and operation continues where the cursor was. Useful for adding trailing '"', ';' and ')' without moving around too much.

To use, hit <F2> in insert mode and type the end character.

"place in vimrc
imap <silent><F2> <Esc>v`^me<Esc>gi<C-o>:call Ender()<CR>
function Ender()
  let endchar = nr2char(getchar())
  execute "normal \<End>a".endchar
  normal `e
endfunction

CommentsEdit

The goal is to first record the INSERT cursor position (A), insert the end character (B) and then come back to the recorded cursor position (C). The function Ender() takes care of steps (B) and (C).

I'll break up the imap into three parts to explain step (A):

<Esc>v`^me<Esc>

This is the best way I found that would mark an INSERT cursor position. After pressing first <Esc>, the INSERT cursor position would be recorded into marker '^. However, since we are doing *another* insert at the end-of-line, we cannot rely on '^ and must mark it somewhere else. I chose 'e.

We have to get into visual mode v to get to marker '^. Note that jumping to marker '^ while in normal mode would NOT work (e.g., for one-character lines, when insert cursor is at the end-of-line, etc.) This is an inherent limitation of Vim which arises from how a cursor is defined in normal and insert modes. Normal mode cursor is over-a-character, insert mode cursor is in-between-characters.

After jumping to marker '^, mark it as marker 'e and get back to normal mode <Esc>.

gi

Returns to insert mode with last INSERT cursor position. "i" instead of "gi" would work here too.

<C-o>:call Ender()<CR>

Call function Ender() from insert mode.


Around Wikia's network

Random Wiki