BaRud
BaRud

Reputation: 3218

vim search or match pattern with variables

In my last question, python code in vim script, lcd047 provided me a beautiful vimscript. I was trying to make it more general, so, I replaced the fixed search word "Program" to a:arg:

function! FixName(arg)
    let [buf, l, c, off] = getpos('.')
    call cursor([1, 1, 0])

    :let lnum = search('\v\c^" . a:arg ."\s+', 'cnW')
    if !lnum
        call cursor(l, c, off)
        return
    endif

    "let parts = matchlist(getline(lnum), '\v\c^Program\s+(\S*)\s*$')
    :let parts = matchlist(getline(lnum),'\v\c^" . a:arg ."\s+(\S*)\s*', 'cnW')
    if len(parts) < 2
        call cursor(l, c, off)
        return
    endif

    let lnum = search('\v\c^End\s+Program\s+', 'cnW')
    call cursor(l, c, off)
    if !lnum
        return
    endif

    call setline(lnum, substitute(getline(lnum), '\v\c^End\s+Program\s+\zs.*', parts[1], ''))
endfunction

and it is not working. No error, no change, as intended by the substitute.

I would also like to have it case insensitive.

Upvotes: 0

Views: 658

Answers (1)

Birei
Birei

Reputation: 36262

Just replace every Program word with a:word, like:

function! FixName(word)
    let [buf, l, c, off] = getpos('.')
    call cursor([1, 1, 0]) 

    let lnum = search('\v\c^' . a:word . '\s+', 'cnW')
    if !lnum
        call cursor(l, c, off)
        return
    endif

    let parts = matchlist(getline(lnum), '\v\c^' . a:word . '\s+(\S*)\s*$')
    if len(parts) < 2 
        call cursor(l, c, off)
        return
    endif

    let lnum = search('\v\c^End\s+' . a:word . '\s+', 'cnW')
    call cursor(l, c, off)
    if !lnum
        return
    endif

    call setline(lnum, substitute(getline(lnum), '\v\c^End\s+' . a:word . '\s+\zs.*', parts[1], ''))
endfunction

And lcd047 solution already matches ignoring case because of \c atom at the beginning of each search.

Upvotes: 2

Related Questions