rnso
rnso

Reputation: 24545

How to get variable's value in this loop in vim

I am trying to filter for multiple words using a loop but following is not working:

function! Myfilter (...)
   for s in a:000
     v/s/d 
   endfor
endfunction

It deletes all lines that do not contain the letter s rather than the value of s. How can I get value of s in statement v/s/d?

Upvotes: 0

Views: 83

Answers (3)

Jim U
Jim U

Reputation: 3366

Deletes all lines other than those that contain all of the function's arguments

function! Myfilter0 (...)
  exec 'v/\(.*' . join(a:000, '\)\@=\(.*') . '\)\@=/d'
endfunction

Example buffer

word1 beta word2
a word1 b word2 c
a word2 b word1 c word3 d
a word2 b word3 c word1 d
word1 delta
epsilon

Example function call

:call Myfilter("word1", "word2", "word3")

Example result

a word2 b word1 c word3 d
a word2 b word3 c word1 d

Note

Uses regex lookahead to match words in any order. This is what the example regex looks like after substitution and without the escape characters for clarity:

:v/(.*word1)@=(.*word2)@=(.*word3)@=/d

Upvotes: 1

Luc Hermitte
Luc Hermitte

Reputation: 32946

A much more efficient solution would be to compose a regex from your parameters, and to use it to remove non matching lines.

exe 'v/\('.join(a:000, '\|').'\)/d_'

Upvotes: 0

sidyll
sidyll

Reputation: 59287

The :execute command is designed precisely for this task of evaluating an expression and executing it as an Ex command:

exec 'v/' . s . '/d'

Upvotes: 0

Related Questions