Reputation: 23216
I am trying to write a function in Vim that searches the current buffer for a certain pattern and returns it. But, I'm failing horribly. Basically, what I want is a function that returns the (PHP) namespace of the file I am working in. The namespace is defined in the file itself:
namespace Foo\Bar;
What I would like is a function that returns the Foo\Bar
part as a string. I.e. something that searches like /namespace\s\([^;]\+\)
and returns the first submatch.
Edit: Here's the function I build thanks to the help I got:
func! PhpNamespace()
let l:lnr = 0
while l:lnr < line('$')
let l:str = matchstr(getline(l:lnr), '^\s*namespace\s\+[^;]\+')
if len(l:str)
return substitute(l:str, '^\s*namespace\s\+', '', '')
endif
let l:lnr = l:lnr + 1
endwhile
return ''
endfunc
Upvotes: 1
Views: 786
Reputation: 172768
One option is to use searchpos()
, which gets you the start position; you then need to extract the text yourself. This is fast and easy, especially if you need to search forward / backward from the cursor position. With the 'n'
flag, the cursor position will not change. Otherwise, you have to save and restore the cursor position (getpos('.')
, setpos('.', saved_cursor)
).
For your problem, it looks like the namespace declaration is likely at the beginning of the file, and is limited to a single line. Then, you could also get individual lines with getline(lnum)
in a loop and extract the text with matchstr()
, and break out of the loop once you have it.
Upvotes: 4