vim: diff two sections in two files, but not the entire file?
I upgraded a system from Nagios 2 to Nagios 3, and now I am comparing some differences in the old and new configuration files.
There are significant changes to the configuration files, and I do not want to perform a diff on the entire file because vimdiff is showing me too many irrelevant differences and has trouble dealing with #
comments at the beginning of lines, etc.
Can I use vim, or a vimdiff-like functionality to perform a diff on two particular sections in two different files?
For example, I want to diff only the lines which look something like this:
# Define a service to check the load on the local machine.
define service{
use local-service ; Name of service template to use
host_name localhost
service_description Blah Blah
check_command Blah Blah
}
It sounds like linediff.vim might be what you want: “Perform an interactive diff on two blocks of text”.
You specify each block (line range) with its :Linediff
command (e.g. :4,10Linediff
, or do a visual selection first, then type :Linediff
(which comes out as :'<,'>LineDiff
)).
The ranges can be from the same file/buffer or different ones.
Once you have specified two ranges, it opens a new tab that has two new, diff-mode buffers (in a split) for the specified ranges.
You can edit and :w
in either of these buffers to update the original ranges.
When you are done, :q
out of the diff buffers and :LinediffReset
to get rid of the range specifiers in the original buffers.
The Stackoverflow answer where I first learned of linediff.vim also suggests a couple of mappings. Other answers on that question also mention a custom solution and another plugin that can address this same issue.
I haven't found a really straightforward way to do this, but I've had pretty good success with the NrrwRgn (Narrow Region) plugin, http://www.vim.org/scripts/script.php?script_id=3075. It lets you select a region of a buffer and open that region in a new buffer. You can edit that new buffer and when you close it, the plugin automatically copies your edited text back to the region it came from in the original file. You can also copy different regions of one or more files into new buffers, then diff those new buffers. That's how I usually use the plugin--to check differences between similar functions defined in one file.
In your case, you can open both files in Vim, then use V
to select the section of interest in the first file and type \nr
to copy that section to a new buffer. Repeat for the similar section in the other file. Then in each of the two new buffers, execute :diffthis
.