divramod February 2016

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

i wrote a function, which opens a corresponding file for me.

I have a convention in my coding projects, that i save test-files in the same subfolderstructure like the original - to be tested - one.

for example:

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

so, if i am editing test/test_spec.js and call OpenCorrespondingFile() then src/test.js should be opened and vice-versa.

now i wrote the 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, that if i have a path with test/ or src/ more than one time in it, the wrong part of the path is substituted.

So i need to know, how i can substitute the last occurrence of a 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        

Answers


Luc Hermitte February 2016

Search for '.*\zssrc/'.

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

Post Status

Asked in February 2016
Viewed 2,537 times
Voted 5
Answered 1 times

Search




Leave an answer