Search code examples
vimneovim

vim copy paste a block with different line lengths


Is there a way in vim / nvim to block copy paste a set of lines with different lengths.

I want to edit the below text from:

select 
  date
, impression_cnt
, click_cnt
, like_cnt
from table

to:

select 
  date
, sum(impression_cnt) as impression_cnt
, sum(click_cnt) as click_cnt
, sum(like_cnt) as like_cnt
from table

I know I can do two separate operations using visual line mode and doing something like

:s/^/sum(
:s/$/) as

However this won't handle the column alias at end.

In VSCode you block enter multiple cursor edit mode and block copy paste the columns, and simple <C-C> and <C-V> and type out max( and ) as in the block mode.

How can I perform this operation without a complex regex that is difficult to remember?


Solution

  • With a single, very simple substitution, assuming the cursor is on the first line to change:

    :,+2s/\w\+/sum(&) as &<CR>
    
    • The pattern, \w\+, matches one or more "keyword characters", as many as possible, it covers the column names, which are the only part of the lines that need changing,
    • the & in the replacement part reuses the whole match.

    With a manual macro, same assumption:

    :,+2norm $ciwsum(<C-v><C-R>") as <C-v><C-r>"<CR>
    
    • $ places the cursor on the last character of the line,
    • ciw cuts the word under the cursor to the default register and enters insert mode,
    • sum( is just part of the new text you type,
    • <C-R>" inserts the content of the default register (the <C-v> is used to insert a literal ^R which is needed in this case),
    • ) as is the rest of the new text you type,
    • and then you insert the column name once again.

    Bonus, with the famous "dot formula", same assumption:

    $ciwsum(<C-R>") as <C-r>"<Esc>
    j.
    j.
    

    See :help :range, :help s/\&, :help :normal, :help c, :help iw, :help i_ctrl-r, :help ..

    How can I perform this operation without a complex regex that is difficult to remember?

    Complex patterns are supposed to be composed on the fly, not remembered so that's not where the problem with complex patterns is. The problem with complex patterns is that it can take time to get them right, which can be a productivity killer.