16

In a vimscript-function, I need to assign a matched string to a variable l:matched after calling search() and I am wondering if there is a shorter way than what I am currently doing:

let l:pattern   = '\v^Foo: \zs.*'
let l:line      = search(l:pattern)
let l:line_text = getline(l:line)
let l:matched   = matchstr(l:line, l:pattern)

Ideally, I'd want something like

let l:matched = search_text(l:pattern)

withouth resorting to getline(). Is there such a vim function that I seem unable to find?

  • 1
    Sadly, the answer is no. – Sato Katsura Aug 13 '15 at 19:07
  • 2
    protip: local variables are the default inside of functions so you can probably forgo the l: namespace declaration. – Peter Rincker Aug 13 '15 at 20:39
  • 2
    in a function you can probably do: :let @/="pattern" | norm! ygn and have the content in register 0 available. – Christian Brabandt Aug 9 '17 at 6:05
8

Since the cursor is placed on the 1st letter of the match, you could probably do a :normal! y$ after the search, and get the register content in your local variable.

Another approach, which I think would work here very well, would be to use :substitute with the n flag (i.e. without an actual substitution):

function! ActOn(match)
    " do something with the match
    echo a:match
    " [...]
endfunction

function! FindAndCall(regex, func_name)
    execute ':keeppatterns %s/' . a:regex . '/\=' . a:func_name. '(submatch(0))/gn'
endfunction

... and which you call like this:

:call FindAndCall('^Foo: \zs.*', 'ActOn')

This practically makes ActOn a callback function - it will be evaluated for each match.

| improve this answer | |
  • 1
    Note: :s with a sub-replace-expression and the n flag is only available since Vim 7.3.627+. Otherwise you need to do an actually substitution (lame as this will mark the buffer as modified). You probably also want to save and restore the search register, @/, or use :keeppatterns. – Peter Rincker Aug 13 '15 at 20:43
  • 3
    Please fix the typo: keeppaterns -> keeppatterns. It is causing E488: Trailing characters which is rather tricky to trace back to the cause. Thanks! – artemave Aug 8 '17 at 8:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.