vim search or match pattern with variables

为君一笑 提交于 2020-02-08 05:50:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/31022184/vim-search-or-match-pattern-with-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!