VIM如何替换文件名的一部分,类似于ZSH cd命令?

5

我最近开始使用VIM。我需要处理同一个代码的多个分支,因此经常会出现两个文件具有非常相似的路径(例如:/home/user/turkey/code/helloworld.cpp),我希望在另一个分支中比较相同的文件(例如:/home/user/kangaroo/code/helloworld.cpp)。

ZSH有cd命令,可以直接输入cd turkey kangaroo来更改路径。我想在我的vimrc中找到/创建类似的东西(例如:diffsplit vert turkey kangaroo)。您有什么建议吗?

我知道当前文件的完整路径存储在expand('%:p')中,但是不确定如何更改其内容。似乎vim的替换功能只能用于编辑文件而不是寄存器。我希望在内存中完成这个任务,而不是让它编辑一个文件。


路径中是否可以多次出现 turkey?例如 /home/usr/turkey/turkey(需要替换)/turkeyCode/foo.file,而分支是 /home/usr/turkey/kanaroo/turkeyCode/foo.file - Kent
1个回答

1
将以下代码添加到您的vimrc文件中:
let s:branches=['/foo/','/bar/']
function! ShowDiff()
    let other = expand('%:p')
    let do_diff = 0
    if match(other, s:branches[0])>0
        let other = substitute(other, s:branches[0], s:branches[1],'')
        let do_diff = 1
    elseif match(other, s:branches[1])>0
        let other = substitute(other, s:branches[1], s:branches[0],'')
        let do_diff = 1
    endif
    if do_diff
        exec 'vert diffsplit '. other
    endif
endfunction
nnoremap <F5> :call ShowDiff()<cr>

然后在普通模式下按下<f5>,将会在垂直分割的窗口中以diff模式打开相应分支(目录)中的同一文件。

例如:现在你正在编辑

/home/whatever/foo/code/foo.txt

按下 <F5> 将垂直分割并进行差异比较:
/home/whatever/bar/code/foo.txt

它搜索完整的目录名称,例如/foo//bar/,您可以更改s:branches以满足您的需求。例如let s:branches=['/turkey/','/kangaroo/'] 一个小演示:enter image description here

非常感谢你,肯特!那正是我需要的!我改了一些东西来自动创建目录,但是很大程度上依赖于你的代码。这是我的最终结果: function! ShowDiff() let filePath = expand('%:p') call inputsave() let newStream = input("New stream name: ") call inputrestore() let filePath = substitute(filePath, $USER."[a-zA-Z0-9]*", $USER."_".newStream, '') if filereadable(filePath) exec 'vert diffsplit ' . filePath else echo "File doesn't exist in same location for other branch" endif endfunction nnoremap <F5> :call ShowDiff()<cr> - user3147860

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接