Vim Tips Wiki
Register
Advertisement
Tip 1593 Printable Monobook Previous Next

created 2008 · complexity basic · version 7.0


Here is a mapping that provides a "smart paste" to insert the system clipboard and automatically indent the pasted text. This is useful when pasting code from another application into the program you are working on. You could put the following lines in your vimrc:

:nnoremap <C-v> "+P=']
:inoremap <C-v> <C-o>"+P<C-o>=']

Example[]

Copy the following three lines to the clipboard (for example, you could use your web browser to copy the lines from this tip).

if (y==1){
printf("y=1");
}

In Vim, put the cursor on the closing brace '}' in the following. Then press Ctrl-v.

if (x==1){
    printf("x=1");
}

The above mapping will insert the clipboard and indent it, with result:

if (x==1){
    printf("x=1");
    if (y==1){
        printf("y=1");
    }
}

Explanation[]

The command "+P pastes the system clipboard before the cursor position. The pasted text becomes the "last change" which sets mark '[ to the beginning of the pasted text, and mark '] to the end. After the P command, the cursor is at the '[ mark, and the command ='] applies the = filter to the pasted text (all lines from the cursor line to the line with the '] mark, inclusive). Assuming the defaults, the = command applies the indent rules for the C language, or for the language of the current buffer, if your syntax rules have defined an indent expression. In insert mode, Ctrl-o (<c-o>) executes one normal-mode command, then returns to insert mode.

References[]

Comments[]

Advertisement