2016-02-08 20 views
0

我寫了一個函數,它爲我打開相應的文件。vimscript替代上次發生(用於打開相應的測試/ spec文件)

我在我的編碼項目中有一個約定,即將測試文件保存在與原始文件相同的子文件夾中 - 以進行測試 - 其中一個。

例如:

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

所以,如果我編輯test/test_spec.js並調用OpenCorrespondingFile()然後SRC/test.js應該被打開,反之亦然。

現在我寫了如下功能:

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> 

存在的問題是,如果我有測試/或SRC /多於一個在其時間的路徑,則路徑的錯誤部分被替換。

所以我需要知道,我可以如何替換模式的最後一次出現。

let l:correspondingFilePath = SUBSTITUTE_LAST_OCCURRENCE(l:path, "src/", "test/", "") 

thx提前!

UPDATE:reafactored功能

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 
    only 
    execute "split " . correspondingFilePath 
endfunction 
:nnoremap <leader>oc :call OpenCorrespondingFile()<cr> 
+0

簡而言之,您是否想將字符串'blafooxfooyfoobar'換成'blafooxfooy ### bar'(last'foo' - >'###')? – Kent

+0

yes,Lucs評論解決了它 – divramod

回答

2

搜索'.*\zssrc/'

  • .*消耗一切,
  • \zs,以紀念在比賽的開始。
+0

hmm,找不到src /的路徑,當我嘗試你的解決方案 – divramod

+0

'''let l:correspondingFilePath = substitute(l:path,「。* \ zssrc /」,「test /」 ,「」)''' – divramod

+0

避免雙引號,它們需要雙反斜線。在處理正則表達式時使用單引號。除非你需要搜索一些特殊的字符/序列。 –

相關問題