Search code examples
vimcommandeditorkeyboard-shortcuts

How to perform Ctrl+Del in Vim while in insert mode?


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.


Solution

  • 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

    1. Set the following binding on Ctrl+D in the insert mode.
    2. Add a dummy letter to deal with words that initially contain only one character.
    3. Leave the insert mode. (The cursor is on the added letter now.)
    4. Move to the beginning of the current word.
    5. 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.