Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ‘diff’ two subroutines in the same file in Vim?

Tags:

vim

diff

vimdiff

Is it possible to diff or even vimdiff two very similar subroutines occurring in the same file? If so, how?

I can think of copying the two subroutines in two separate files and then diff them, but is there a way to do it within the original file?

like image 935
Nigu Avatar asked Sep 01 '10 14:09

Nigu


People also ask

How do you get to the next difference in Vimdiff?

You can jump to the "next difference" ( ] c ), but this will jump to the next line with a difference.

What is Vimdiff in Linux?

DESCRIPTION. Vimdiff starts Vim on two (or three) files. Each file gets its own window. The differences between the files are highlighted. This is a nice way to inspect changes and to move changes from one version to another version of the same file.


2 Answers

Plugin linediff.vim : Perform an interactive diff on two blocks of text is similar to the one pointed ou by Vincent with some additional features:

  • has a command to close the opened buffer
  • seems to work without GUI
  • insert some visual indication on the original file(s) being diffed.

To use it you perform a visual selection on the first block to diff, enter command :Linediff, and repeat it to the second block. To quit, :LineDiffReset

I've found the followings maps helpful:

noremap \ldt :Linediff<CR> noremap \ldo :LinediffReset<CR> 
like image 131
mMontu Avatar answered Sep 16 '22 17:09

mMontu


You cannot do this within the original file, but you can do this without using separate files, only separate buffers. This should work if you copied one subroutine in register a (for example, with "ay typed in Visual mode) and other subroutine in register b:

enew | call setline(1, split(@a, "\n")) | diffthis | vnew | call setline(1, split(@b, "\n")) | diffthis 

To automate:

let g:diffed_buffers = []  function DiffText(a, b, diffed_buffers)     enew     setlocal buftype=nowrite     call add(a:diffed_buffers, bufnr('%'))     call setline(1, split(a:a, "\n"))     diffthis     vnew     setlocal buftype=nowrite     call add(a:diffed_buffers, bufnr('%'))     call setline(1, split(a:b, "\n"))     diffthis endfunction  function WipeOutDiffs(diffed_buffers)     for buffer in a:diffed_buffers         execute 'bwipeout! ' . buffer     endfor endfunction  nnoremap <special> <F7> :call DiffText(@a, @b, g:diffed_buffers)<CR> nnoremap <special> <F8> :call WipeOutDiffs(g:diffed_buffers) | let g:diffed_buffers=[]<CR> 

Note that you may want to set hidden option if Vim refuses to abandon changed file (see :h abandon).

like image 36
ZyX Avatar answered Sep 16 '22 17:09

ZyX