1

I am moving the first steps in scripting and I am facing this issue. Say that I have a test like the one below

1 bla bla bla
2
3
..
13 SOME KEYWORK
14 blah blah blah
15
..
..
21 SOME KEYWORK
22 whatever
..
29 SOME KEYWORD
30 yet another Section
..
..
..
42 this is the last line of the file.

I am trying to write a function that, given the current cursor positions, returns the lines corresponding to ?SOME\ KEYWORK and to /SOME\ KEYWORK , respectively. This, because I would like to create a range from ?SOME\ KEYWORK to /SOME\ KEYWORK.

For example, if I the cursor is at line 18, such function shall return [13,21]; if the cursor is at line 24, then such a function shall return [21,29] and so on.

The exception happen at the beginning and end of the file. For example, if the cursor is on any line number less than 5, then my function shall return [0,13] or if it is on any line number greater than 29, then it shall return [29,42].

What I learned is that I can get the current line with line("."), but unfortunately syntax like line("/SOME\ KEYWORD") or line("?SOME\ KEYWORD") are not allowed according to the documentation.

2
  • Is there a reason you can't directly work with a range represented by searches themselves?
    – Maxim Kim
    Oct 2, 2022 at 12:17
  • I could, but I don't know how to get such a range.
    – Barzi2001
    Oct 2, 2022 at 12:25

1 Answer 1

2

operate on a range given by a searches

This would delete everything in range defined by 2 searches

:?SOME KEYWORK?;/SOME KEYWORK/d

use range in function

This function if called with a range, will return it (this probably doesn't make sense, but still).

func! MyRange() range
    return [a:firstline, a:lastline]
endfunc

With this function if called as :?SOME KEYWORK?;/SOME KEYWORK/call MyRange() would print all lines in range.

func! MyRange() range
    for linenr in range(a:firstline, a:lastline)
        echo getline(linenr)
    endfor
endfunc
2
  • I was not aware of that syntax for range selection! Thanks! Regarding the example in reality I wish achieve the following: when the cursor is in a range delimited by two consecutive SOME KEYWORD I wish to change the editor background color only in that specific range; when the cursor move to another range (still delimited by two consecutive SOME KEYWORD), I with to restore the bg color in the previous range and change the editor bg color it in the new range. Automatically.:-) But perhaps this is a broader question …
    – Barzi2001
    Oct 2, 2022 at 13:14
  • @Barzi2001 you can check limelight.vim plugin for inspiration
    – Maxim Kim
    Oct 2, 2022 at 15:30

Your Answer

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

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