created May 26, 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
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):
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>.
Returns to insert mode with last INSERT cursor position. "i" instead of "gi" would work here too.
Call function Ender() from insert mode.