Comparing two files in Vim
Is it possible to view two files side-by-side in Vim? If so, how can I set up my editor to do this, and is there a way to
diff between the two files within Vim?
I am aware of the
:prev commands, but this is not what I’m after. It would really be nice to view the two files in tandem.
Open the side by side view:
Change between them:
Ctrl+w h or l
You can then open another file for comparison in one side by entering a command such as:
Checkout the vimdiff command, part of the vim package, if you want a diff-like view, e.g.:
vimdiff file1.txt file2.txt
You can also open vim in split-screen mode, with the
vim -O file1 [file2 ...]
To then turn on diff mode, you need to run the
:diffthis command in each pane.
Another use-case scenario, is if you’ve already got one file open in vim, and you want to open and compare it against another. Then you can use the following vim commands:-
:vs otherfile (open otherfile in vertical split screen)
:diffthis (turn on diff mode in original file)
Ctrl+w l (swap to newly opened file)
:diffthis (turn on diff mode in opened file)
You can then turn off diff mode in each pane with the vim command
And the other standard one that hasn’t been mentioned:-
vim -d file1 [file2 ...]
This is equivalent to calling
Or just open the first file in VIM, then
:vert diffsplit file2 makes it split the screen vertically.
diffsplit does a diff, and splits the files and scrolls locks them.
While it has already been answered how to start the diff, it’s also important how to stop it in all windows. For completeness, I repeat the comment from @Bernhard.
Start and Stop Diff of two files opened in 2 Windows (works in both, vertical and horizontal split):
this can be shortened to either
Be aware that opened windows for showing plugin content lead to issues. So close stuff like NERDtree, minibufexplorer++ etc before.
To ease up things you can add custom commands to your
command! Difft [ClosePluginWindow |] windo diffthis
command! Diffo windo diffoff
[ClosePluginWindow |] being optional to close plugin windows you usually use. For NERDtree e.g. this would be
For those of you using neovim:
nvim -d file1 file2 [file3 [file4]]