Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM replace part of filename with something else similar to ZSH cd

Tags:

vim

zsh

I have recently switched to using VIM. I work on multiple branches of the same code so often two files will have very similar paths (example: /home/user/turkey/code/helloworld.cpp) and I would like to diff the same file in another branch (example: /home/user/kangaroo/code/helloworld.cpp).

ZSH has cd command where one can just say cd turkey kangaroo to change the path. I would like to find/create something similar in my vimrc (example: diffsplit vert turkey kangaroo). Any suggestions on how to go about this?

I know that the full path to the current file is stored in expand('%:p') but am not sure how I would go about changing the contents of this. It seems like the vim replace is limited to editing files rather than registers. I would like to do this in memory instead of having it edit a file.

like image 717
user3147860 Avatar asked Nov 11 '22 15:11

user3147860


1 Answers

add this codes in your 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>

then press <f5> in normal mode will open the same file in corresponding branch (dir) in vert split and in diff mode.

e.g. now you are editing

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

Pressing <F5> will vert-split and diff:

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

it searches the complete directory name, like /foo/ or /bar/ you can change the s:branches to match your needs. like let s:branches=['/turkey/','/kangaroo/']

A small demo:enter image description here

like image 85
Kent Avatar answered Nov 15 '22 05:11

Kent