What is the easiest / most elegant way to iterate over matches in vim script / function?

I am looking for an elegant solution (within a vim script) to iterate over all matches the regular expression in the buffer. It will be something like

fu! DoSpecialThingsWithMatchedLines()

  for matched_line_no in (GetMatchedPositions("/foo\\>.*\\<bar"))
      let line = getline(matched_line_no)
      call DoItPlease(line)
  end for

endfu

Is there something similar? I'm not necessarily looking for a complete solution, any pointer directing me in the right direction will do.

Thanks / Renee

+3
source share
2 answers

In most cases, I use michael's solution with :global

You can also play with filter(getline('1','$'), 'v:val =~ "foo\\>.*\\<bar"')if you really want to use :for.

Otherwise, you can just call search()in a loop.

+3
source

you can use: he: global for example.

 :%g/foo\\>.*\\<bar/call DoItPlease(getline("."))

Vimscript example:

fun! Doit(line)
    echo a:line
endfun


fun! MyDo()
    %g/foo/call Doit(getline("."))
endfun

:call MyDo()
+4
source

Source: https://habr.com/ru/post/1725137/


All Articles