Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paste a block while creating the necessary lines to give room for the block solely?

Tags:

vim

In VIM, text block yanking in Visual Mode, and pasting the block afterwards, paste it after the desired column given by the cursor, but pastes in-place, overwriting contents of the current and following lines.

Sometimes I don't want this, what I want is to paste a block with the indentation given by the cursor position, but pasting inside new empty lines, without overwriting text.

Is there a way to do that?

Currently, to achieve this, I create a good amount of empty lines, and then paste the block, eliminating the remaining empty lines after (not very clever... ).

Note: I use set virtualedit=all to be able to paste at any column in the said empty lines.

like image 271
pepper_chico Avatar asked Oct 05 '22 01:10

pepper_chico


1 Answers

You can try something like the following. Block-wise yank something, position the cursor and hit <Leader>p, whatever your leader key is.

function! FancyPaste()
    let paste = split(@", '\n')
    let spaces = repeat(' ', col('.')-1)
    call map(paste, 'spaces . v:val')
    call append(line('.'), paste)
endfunction

nnoremap <Leader>p :call FancyPaste()<CR>

You can of course change the mapping to be anything you want; it's just a suggestion.

Update: Here's a version that accepts an argument. This let's you e.g. paste from the system clipboard instead. It also uses virtcol() instead of col() to take account for the possible use of 'virtualedit':

function! FancyPaste(reg)
    let paste = split(getreg(a:reg), '\n')
    let spaces = repeat(' ', virtcol('.')-1)
    call map(paste, 'spaces . v:val')
    call append(line('.'), paste)
endfunction

nnoremap <Leader>p  :call FancyPaste('"')<CR>
nnoremap <Leader>cp :call FancyPaste('+')<CR>

Keep in mind it will only indent with spaces, not tabs. Indenting with the appropriate amount of tabs (and spaces if needed) would require some extra lines of code, but is quite doable.

like image 92
Øsse Avatar answered Oct 16 '22 08:10

Øsse