18

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)

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

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

1 Answer 1

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.

2
  • 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. Aug 13, 2015 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, 2017 at 8:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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