How can I write a function to get the content between mark 1
and mark 2
for further processing? mark
can be a string, or a function call, it doesn't matter.
mark 1
foo1
foo2
foo3
mark 2
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communitySee :h getbufline()
:
getbufline({expr}, {lnum} [, {end}])
Return a List with the lines starting from {lnum} to {end} (inclusive) in the buffer {expr}. If {end} is omitted, a List with only the line {lnum} is returned.
To get the line numbers you're looking for you can use :search()
for example. See :h search()
.
For example in this file:
mark 1
foo1
foo2
foo3
mark 2
The command:
echo getbufline(bufnr('%'), 1, 7)
Will return the following list:
['mark 1', '', 'foo1', 'foo2', 'foo3', '', 'mark 2']
You might even want to wrap it in a function:
function! SearchForLines(pattern1, pattern2)
let line1 = search(a:pattern1)
let line2 = search(a:pattern2)
return getbufline(bufnr('%'), line1, line2)
endfunction
This way to get the list of the lines between mark 1
and mark 2
you can simply do:
:echo SearchForLines('mark 1', 'mark 2')
Edit Note that as @Christian Brabandt noted in the comments, the function getline()
can also be used and in some circumstances may be easier to use. See :h getline()
.