javascript - vimscript substitute last occurence (for opening corresponding test/spec-file) -


i wrote function, opens corresponding file me.

i have convention in coding projects, save test-files in same subfolderstructure original - tested - one.

for example:

project_dir/ |-->src/ |   |-->test.js |-->test/     |-->test_spec.js 

so, if editing test/test_spec.js , call opencorrespondingfile() src/test.js should opened , vice-versa.

now wrote following function:

function! opencorrespondingfile()   let l:filename=expand('%:t')   let l:path=expand('%:p')   if l:path =~ "/src/"     let l:correspondingfilepath = substitute(l:path, "src/", "test/", "")     let l:correspondingfilepath = substitute(l:correspondingfilepath, ".js", "_spec.js", "")   elseif l:path =~ "/test/"     let l:correspondingfilepath = substitute(l:path, "test/", "src/", "")     let l:correspondingfilepath = substitute(l:correspondingfilepath, "_spec", "", "")   endif   execute "only"   execute "split"   execute "edit " . l:correspondingfilepath   execute "wincmd j"   execute "edit " . l:path endfunction :nnoremap <leader>oc :call opencorrespondingfile()<cr> 

the problem is, if have path test/ or src/ more 1 time in it, wrong part of path substituted.

so need know, how can substitute last occurrence of pattern.

let l:correspondingfilepath = substitute_last_occurrence(l:path, "src/", "test/", "") 

thx in advance!

update: reafactored function

function! opencorrespondingfile()   let filename=expand('%:t')   let path=expand('%:p')   if path =~ '/src/'     let correspondingfilepath = substitute(path, '.*\zssrc/', 'test/', '')     let correspondingfilepath = substitute(correspondingfilepath, '.js', '_spec.js', '')   elseif path =~ '/test/'     let correspondingfilepath = substitute(path, '.*\zstest/', 'src/', '')     let correspondingfilepath = substitute(correspondingfilepath, '_spec', '', '')   endif     execute "split " . correspondingfilepath endfunction :nnoremap <leader>oc :call opencorrespondingfile()<cr> 

search '.*\zssrc/'.

  • .* consume everything,
  • and \zs mark start of match.

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -