René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

Searching with VIM scripts

The following two functions both search for a regular expression.
FindRE_1 searches forward (in a case insensitive manner [/ei]) and returns the word following the found regular expression. If the regular expression was not found, it returns the empty string.
function! FindRE_1(re) 

  " Store current cursor Position
  let l:line = line(".")
  let l:col  = col (".")

  " Search for passed regular expression (a:re)
  try
    " Simulate typing '/my-regexp./ei' followed
    " by pressing enter
    execute 'normal /' . a:re . '/ei' .  nr2char(13)
  catch /E486: Pattern not found/
    " Return empty string if pattern was not found
    return ""
  endtry

  " Jump to next word...
  normal w

  " ...and store word under cursor away
  let l:return_val = expand("<cword>")

  " Restor cursor postion
  call cursor(l:line, l:col)
  
  " And return stored value
  return l:return_val
endfunction
FindRE_2 searches backwards and returns the word following the regular expression. Also, the empty string is returned if the regular expression was not found.
function FindRE_2(re)
  let l:line = line(".")
  let l:coln = col (".")

  " Store current ignore case value.
  let l:ic = &ic                       
  " and set ignore case
  let &ic = 1                          

  " search for regular expression (bw = backward, wrap around end of file)
  let l:success = search(a:re, "bW")

  " Restore ignore case setting
  let &ic = l:ic                       

  if l:success != 0                    

    " If re was found, jump to next word
    normal w

    let l:ret = expand("<cword>")

    call cursor(l:line, l:coln)

    return l:ret

  endif

  " Nothing found, return empty string
  return ""                            
endfunction