Sebastián Grignoli
Sebastián Grignoli

Reputation: 33462

Vim: expanding lines with a custom pattern

Recording macros is fine, but I have this in my .vimrc, and I find it very useful:

""""""""""""""""""""""""""""""""""""""""""""""""
" ,p prepares and ,a applies a pattern
"    $x = array("@@@"=>"@@@");        (type ,p here)
"    text                             (type ,a here)
" gives you: 
"    $x = array("text"=>"text");
" and moves to the next line to repeat
""""""""""""""""""""""""""""""""""""""""""""""""
nnoremap ,p "ryy
nnoremap ,a "edd"rPV:s/@@@/<C-r>e<Backspace>/g<CR>j

Once you are used to this, it's a lot faster (for me at least) than recording a macro.

My question is:

Could this be changed to recognize different parameters? The current replace recognizes only one (the whole current line) and places it where the @@@ are.

I would like to improve it to something like this:

$x = array("{{1}}"=>"{{2}}"); // {{3}}    (type ,p here)
key, value, some explanation              (type ,a here)

And using that, obtain something like:

$x = array("key"=>"value"); // some explanation

I'm not very fluent in vimscript or a regex so dynamic (I mean, capturing a variable number or strings). Could someone point me out in the right direction?

Upvotes: 0

Views: 125

Answers (1)

Kent
Kent

Reputation: 195209

this one line map works, but there should be more elegant solution:

nnoremap ,a :let li=split(getline('.'),', ')<cr><esc>dd"rP:s/{{1}}/\=li[0]/g\|s/{{2}}/\=li[1]/g\|s/{{3}}/\=li[2]/g<cr>

the ,p mapping doesn't need to be changed.

enter image description here

EDIT

got sometime just now, this should work for your requirement:

you could put it in your .vimrc

function! Doit4u(vline)
    let o = @r
    let vlist = split(a:vline, ', ')
    for v in vlist
        let n = '{{'.(1+index(vlist,v)) .'}}'
        let o = substitute(o,n,v,'g')
    endfor  
    call setline(line("."),o)
endfunction 
nnoremap ,p "ryy
nnoremap ,a :call Doit4u(getline('.'))<cr>

Upvotes: 2

Related Questions