Does anyone know how to delete the word in front of the cursor while in insert mode in Vim? Most systems use Ctrl+Del
to do this.
I know to delete the word behind the cursor in Vim is Ctrl+w
while in insert mode, but I don't know how to delete forward.
Add this to your ~/.vimrc
(for VIM or GVIM):
imap <C-D> X<Esc>lbce
; 1 2 3 4 5 ; just a comment for the further description
(In GVIM, <C-Del>
also works.)
Description
- Set the following binding on
Ctrl+D
in the insert mode.
- Add a dummy letter to deal with words that initially contain only one character.
- Leave the insert mode. (The cursor is on the added letter now.)
- Move to the beginning of the current word.
- Remove characters from the current position to the next end-of-word (i.e., from the first character of the current word to its last character). Then enter the insert mode again.
Behavior
- If the cursor was on a character of a word or immediately after the last character of a word (but not at the end of the current line), then this word will be removed.
- Otherwise, if there's a word to the left (on the same line), then it will be removed (without any blank characters).
- Otherwise (when there's no next word) the behavior is undefined. (Feel free to update the answer to cover these cases too.)
If a word is removed, then the cursor will be at the same position as the first character of the word was.