phinz
phinz

Reputation: 1459

VIM check for search pattern match in vim script

I just started with vim script and try make translation of opencart language files easier. I want to have a function that looks for a given search pattern and selects it. If there is no match left in the file, it shall open the next file for editing. What I have so far:

function! Nextmatch()
    normal /\(= *'\)\@<=.\{-\}\('\)\@=/
    normal v//e
endfunction

function! Nextfile()
   if !exists("s:filecounter")
        execute "!find -iname *.php > files.txt"
        normal <CR>
        let s:filecounter=0
   endif
   let s:lines= system("wc -l < files.txt")
   if s:filecounter<s:lines
        w
        let s:filecounter += 1
        let s:sedcommand="sed '".s:filecounter."!d' files.txt"
        let s:selectedfile=system(s:sedcommand)
        execute 'edit' s:selectedfile
   else
        wq
   endif
endfunction

How can I achieve that Nextfile() is called in Nextmatch() if the search pattern is not found between the cursor and the end of the current file? And is there something that you consider to be bad style in my snippet?

Upvotes: 1

Views: 2224

Answers (2)

yolenoyer
yolenoyer

Reputation: 9445

Quickfix commands are powerful and well integrated with some external plugins, but if you really need to use your own script, and if you need to check a match in an if statement, just do:

if search("=\\s*'\\zs[^']*\\ze", 'W') == 0
     echo 'No match until the end of the buffer'
endif

See :h search(), and please note :

  • the double backslashes, due to the double quotes
  • the 'W' flag which forbids wrapping around the end of file
  • I simplified the pattern you gave

Upvotes: 2

yolenoyer
yolenoyer

Reputation: 9445

You could simply use the :vim command to get rid of all your script.

I think the following should do quite what you're expecting:

:noremap <f8> <esc>:cn<cr>gn
/\(= *'\)\@<=.\{-\}\('\)\@=
:vim //g *.php

Then, to go to the next pattern in all files while selecting it, you just have to press the F8 key.

In the noremap line, gn let you select the next actual search.

You may need to do:

:set nohidden

to let you navigate threw modified buffers (but don't forget to save them with :wa, or list them with :ls)

About your script:

  • It's a good habit in scripts to always use :normal! instead of :normal (unless you deliberately need it) : thus, your personnal mappings won't interfer in your scripts.

Upvotes: 1

Related Questions