Movatterモバイル変換


[0]ホーム

URL:


Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq
Go to keyword (shortcut:k)
Site search (shortcut:s)
diff.txt  ForVim version 9.2.  Last change: 2026 Feb 14VIM REFERENCE MANUAL  by Bram Moolenaardiffvimdiffgvimdiffdiff-modeThis file describes the+diff feature: Showing differences between two toeight versions of the same file.The basics are explained insection08.7 of the user manual.1. Startingdiff modestart-vimdiff2. Viewing diffsview-diffs3. Jumping to diffsjumpto-diffs4. Copying diffscopy-diffs5. Diff anchorsdiff-anchors6. Diffoptionsdiff-options==============================================================================1. Startingdiff modestart-vimdiffThe easiest way to start editing indiff modeis with the "vimdiff" command.This starts Vimas usual, and additionally sets up for viewing the differencesbetween the arguments.vimdiff file1 file2 [file3 [file4]]Thisis equivalent to:vim -d file1 file2 [file3 [file4]]You may also use "gvimdiff" or "vim-d-g".  TheGUIis started then.You may also use "viewdiff" or "gviewdiff".  Vim starts in readonly mode then."r" may be prepended for restricted mode (see-Z).The second and following arguments may also bea directory name.  Vim willthen append the file name of the first argument to the directory name to findthe file.By default an internaldiff library will be used.  When'diffopt' or'diffexpr' has been set an external "diff" command will be used.  This onlyworks when suchadiff programis available.Diffs are local to the currenttab pagetab-page.  You can't see diffs withawindow in anothertab page.  This does makeit possible to have severaldiffsat the same time, each in their owntab page.What happensis that Vim opensawindow for each of the files.  Thisis likeusing the-O argument.  This uses vertical splits.  If you prefer horizontalsplits add the-o argument:vimdiff -o file1 file2 [file3 [file4]]If you always prefer horizontal splits include "horizontal" in'diffopt'.In each of the edited files theseoptions are set:'diff'on'scrollbind'on'cursorbind'on'scrollopt'includes "hor"'wrap'off, or leave as-is if'diffopt' includes "followwrap"'foldmethod'"diff"'foldcolumn'value from'diffopt', defaultis 2Theseoptions are set local to the window.  When editing another file they arereset to the global value.Theoptions can still be overruled fromamodeline when re-editing the file.However,'foldmethod' and'wrap' won't be set fromamodeline when'diff'isset.See:diffoff for aneasy way to revert the options.The differences shown are actually the differences in the buffer.  Thus if youmake changes after loadinga file, these will be included in the displayeddiffs.  You might have todo ":diffupdate" now and then, not all changes areimmediately taken into account, especially when using an externaldiffcommand.In your.vimrc file you coulddo something special when Vim was started indiff mode.  You could usea construct like this:if &diff   setup for diff modeelse   setup for non-diff modeendifWhile already in Vim you can startdiff mode in three ways.E98:diffs[plit]{filename}:diffs:diffsplitOpena newwindow on the file{filename}.  Theoptions are setas for "vimdiff" for the current and the newly opened window.Also see'diffexpr'.:difft:diffthis:difft[his]Make the currentwindow part of thediff windows.  This setstheoptions like for "vimdiff".:diffp[atch]{patchfile}E816:diffp:diffpatchUse the current buffer, patchit with thediff found in{patchfile} and opena buffer on the result.  Theoptions aresetas for "vimdiff".{patchfile} can be in any format that the "patch" programunderstands or'patchexpr' can handle.Note that{patchfile} should only containadiff for one file,the current file.  If{patchfile} contains diffs for otherfilesas well, the results are unpredictable.  Vim changesdirectory to /tmp to avoid files in the current directoryaccidentally being patched.  Butit may still result invarious ".rej" files to be created.  And when absolute pathnames are present these files may get patched anyway.Using the "patch" commandis not allowed inrestricted-mode.To make these commands usea vertical split, prepend:vertical.  Examples::vert diffsplit main.c~:vert diffpatch /tmp/diffIf you always prefera vertical split include "vertical" in'diffopt'.E96There can be up to eightbuffers with'diff' set.Since the option values are remembered with the buffer, you can edit anotherfile fora moment and come back to the same file and be indiff mode again.:diffo:diffoff:diffo[ff]Switch offdiff mode for the current window.  Resets relatedoptions also when'diff' was not set.:diffo[ff]!Switch offdiff mode for the currentwindow and in allwindowsin the currenttab page where'diff'is set.  Resettingrelatedoptions only happens inawindow that has'diff' set,if the currentwindow does not have'diff' set then nooptionsinit are changed.Hiddenbuffers are also removed from thelist of diff'edbuffers.The:diffoff command resets the relevantoptions to the values they had whenusing:diffsplit,:diffpatch,:diffthis, orstarting Vim indiff mode.When using:diffoff twice the last saved values are restored.Otherwise they are set to their default value:'diff'off'scrollbind'off'cursorbind'off'scrollopt'without "hor"'wrap'on, or leave as-is if'diffopt' includes "followwrap"'foldmethod'"manual"'foldcolumn'0'foldenable' will most-likely be reset to off.  Thatis when'foldmethod'isis restored to "manual".  Thefolds themselves are not cleared but they shouldnot show up, resetting'foldenable'is the best way todo that.==============================================================================2. Viewing diffsview-diffsThe effectis that thediffwindows show the same text, with the differenceshighlighted.  Whenscrolling the text, the'scrollbind' option will make thetext in otherwindows to be scrolledas well.  With vertical splits the textshould be aligned properly.The alignment of text willgo wrong when:-'wrap'is on, some lines will be wrapped and occupy two or more screen  lines-folds are open in onewindow but not another-'scrollbind'is off- changes have been made to the text- "filler"is not present in'diffopt', deleted/inserted lines makes the  alignmentgo wrongAll thebuffers edited inawindow where the'diff' optionis set will join inthe diff.  Thisis also possible for hidden buffers.  Theymust have beenedited inawindow first for this to be possible.  To get rid of the hiddenbuffers use:diffoff!.:DiffOrigdiff-original-fileSince'diff'isa window-local option, it's possible toview the same bufferindiff mode in onewindow and "normal" in another window.  Itis alsopossible toview the changes you have made toa buffer since the file wasloaded.  Since Vim doesn't allow having twobuffers for the same file, youneed another buffer.  This commandis useful: command DiffOrig vert new | set bt=nofile | r ++edit # | 0d_\ | diffthis | wincmd p | diffthis(thisis indefaults.vim).  Use ":DiffOrig" to see the differences betweenthe current buffer and the fileit was loaded from.A buffer thatis unloaded cannot be used for the diff.  Butit does work forhidden buffers.  You can use ":hide" to closeawindow without unloading thebuffer.  If you don't wanta buffer to remain used for thediffdo ":setnodiff" before hiding it.:dif:diff:diffupdate:dif[fupdate][!]Update thediff highlighting and folds.Vim attempts to keep the differences updated when you make changes to thetext.  This mostly takes care of inserted and deleted lines.  Changes withinaline and more complicated changesdo not cause the differences to be updated.To force the differences to be updated use::diffupdateIf the!is included Vim will check if the file was changed externally andneeds to be reloaded.  It will prompt for each changed file, like:checktimewas used.Vim will show filler lines for lines that are missing in onewindow but arepresent in another.  These lines were inserted in another file or deleted inthis file.  Removing "filler" from the'diffopt' option will make Vim notdisplay these filler lines.Folds are used to hide the text that wasn't changed.  Seefolding for allthe commands that can be used with folds.The context of lines abovea difference that are not included in the fold canbe set with the'diffopt' option.  For example, to set the context to threelines::set diffopt=filler,context:3The diffs are highlighted with these groups:hl-DiffAdd  DiffAddAdded (inserted) lines.  These lines exist inthis buffer but not in another.hl-DiffChange  DiffChangeChanged lines.hl-DiffText  DiffTextChanged text insidea Changed line.  Exactbehavior depends on theinline: setting in'diffopt'.Withinline: set to "simple", Vim finds thefirst character thatis different, and thelast character thatis different (searchingfrom theend of the line).  The text inbetweenis highlighted.  This means that partsin the middle that are still the same arehighlighted anyway.  The'diffopt' flags"iwhite" and "icase" are used here.Withinline: set to "char" or "word", Vimuses the internaldiff library to performadetaileddiff between the changed blocks andhighlight the exact difference between thetwo.  Will respect any'diffopt' flag thataffects internal diff.Not used wheninline:is set to "none".hl-DiffTextAdd  DiffTextAdd  Added text insidea Changed line.  Similar toDiffText, but used when thereis nocorresponding text in other buffers.  Not usedwheninline:is set to "simple" or "none".hl-DiffDelete  DiffDeleteDeleted lines.  Also called filler lines,because they don't really exist in thisbuffer.==============================================================================3. Jumping to diffsjumpto-diffsTwo commands can be used to jump to diffs:[c[cJump backwards to the previous start ofa change.Whenacountis used,doit that many times.]c]cJump forwards to the next start ofa change.Whenacountis used,doit that many times.Itis an error if thereis no change for the cursor to move to.==============================================================================4. Diffcopyingcopy-diffsE99E100E101E102E103mergeThere are two commands to copy text from one buffer to another.  The resultisthat thebuffers will be equal within the specified range.:diffg:diffget:[range]diffg[et][bufspec]Modify the current buffer toundo difference with anotherbuffer.  If[bufspec]is given, that bufferis used.  If[bufspec] refers to the current buffer then nothing happens.Otherwise this only works if thereis one other buffer indiffmode.See below for[range].:diffpu:diffputE793:[range]diffpu[t][bufspec]Modify another buffer toundo difference with the currentbuffer.  Just like ":diffget" but the other bufferis modifiedinstead of the current one.When[bufspec]is omitted and thereis more than one otherbuffer indiff mode where'modifiable'is set this fails.See below for[range].do[count]doSameas ":diffget" without range.  The "o" stands for "obtain"("dg" can't be used,it could be the start of "dgg"!).Note:this doesn't work inVisual mode.If you givea[count],itis usedas the[bufspec] argumentfor ":diffget".dp[count]dpSameas ":diffput" without range.Note: this doesn't work inVisual mode.If you givea[count],itis usedas the[bufspec] argumentfor ":diffput".When no[range]is given, thediffat the cursor position or just aboveitisaffected.  There can be deleted lines below the last line of the buffer.  Whenthe cursoris on the last line in the buffer and thereis nodiff above thisline, and no[range]is given, thediff below the cursor position will be usedinstead.When[range]is used, Vim tries to onlyput or get the specified lines.  Whenthere are deleted lines, they will be used if they are between the linesspecified by[range].To be able toput or get those lines to/from another buffer ina[range] it'sallowed to use0 and the last line number plus one.  This command gets alldiffs from the other buffer::0,$+1diffgetNote that deleted lines are displayed, but not countedas text lines.  Youcan't move the cursor into them.  To fill the deleted lines with the linesfrom another buffer use ":diffget" on the line below them.E787When the buffer thatis about to be modifiedis read-only and theautocommandthatis triggered byFileChangedRO changesbuffers the command will fail.Theautocommandmust not change buffers.The[bufspec] argument above can bea buffer number,apattern fora buffername ora part ofa buffer name.  Examples::diffgetUse the other buffer whichis indiff mode:diffget 3Use buffer 3:diffget v2Use the buffer which matches "v2" andis indiff mode (e.g., "file.c.v2")==============================================================================5. Diff anchorsdiff-anchorsDiff anchors allow you tocontrol where thediff algorithm aligns andsynchronize text across files.  Each anchor matches each other in each file,allowing you tocontrol the output ofa diff.Thisis useful whena change involves complicated edits.  For example, ifafunction was moved to another location and further edited.  By default, thealgorithm aims to create the smallest diff, which results in that entirefunction being considered to be deleted and added on the other side, makingithard to see what the actual edit onit was.  You can usediff anchors to pinthat function so thediff algorithm will align based on it.To use it, set anchors using'diffanchors' whichisa comma-separatedlist of{address} in each file, and then add "anchor" to'diffopt'.  Internally, Vimsplits each file up into sections split by the anchors.  It performs thediffon each pair of sections separately before merging the results back.Setting'diffanchors' will update thediff immediately.  If an anchoris tiedtoa mark, and you change what themarkis pointed to, you need to manuallycall:diffupdate afterwards to get the updateddiff results.Example:Let's say we have the following files, side-by-side.  We are interested in thechange that happened to the functionfoo(), which was both edited and moved.File A:int foo() {    int n = 1;    return n;}int g = 1;int bar(int a) {    a *= 2;    a += 3;    return a;}File B:int bar(int a) {    a *= 2;    a += 3;    return a;}int foo() {    int n = 999;    return n;}int g = 1;A normaldiff will usually align thediff resultas such:int foo() {     |----------------    int n = 1;  |----------------    return n;   |----------------}               |----------------                |----------------int g = 1;      |----------------                |----------------int bar(int a) {|int bar(int a) {    a *= 2;     |    a *= 2;    a += 3;     |    a += 3;    return a;   |    return a;}               |}----------------|----------------|int foo() {----------------|    int n = 999;----------------|    return n;----------------|}----------------|----------------|int g = 1;What we wantis to instead ask thediff to align onfoo():----------------|int bar(int a) {----------------|    a *= 2;----------------|    a += 3;----------------|    return a;----------------|}----------------|int foo() {     |int foo() {    int n = 1;  |    int n = 999;    return n;   |    return n;}               |}                |int g = 1;      |int g = 1;                |----------------int bar(int a) {|----------------    a *= 2;     |----------------    a += 3;     |----------------    return a;   |----------------}               |----------------Below are some ways of settingdiff anchors to get the above result.  In eachexample,'diffopt' needs to haveanchor set for this to take effect.Marks: Set the'amark on the `int foo()` lines in each file first beforesetting the anchors:set diffanchors='aPattern: Specify the anchor usingapattern (see:/).  Here, we make sureto always start search from line 1 for consistency:set diffanchors=1/int\ foo(/Selection: Use visual mode to select the entirefoo() function body in eachfile.  Here, we use two anchors.  This doesa betterjob of making sure onlythe function bodies are anchored against each other but not the lines afterit.Note the'>+1 below.  The "+1"is necessaryas we want the split tohappen below the last line of the function, not above:set diffanchors='<,'>+1Manually set two anchors using line numbers via buffer-local options:setlocal diffanchors=1,5wincmd wsetlocal diffanchors=7,11==============================================================================6. Diffoptionsdiff-optionsAlso see'diffopt' and the "diff" item of'fillchars'.diff-slowdiff_translationsFor very long lines, thediffsyntax highlighting might be slow, especiallysinceit tries to match all different kind of localisations.  To disablelocalisations and speed up thesyntax highlighting, set the global variableg:diff_translations to zero:    let g:diff_translations = 0After setting this variable,reload thesyntax script:    set syntax=diffFINDING THE DIFFERENCESdiff-diffexprThe'diffexpr' option can be set to use something else than the internaldiffsupport or the standard "diff" program to compare two files and find thedifferences.E959When'diffexpr'is empty, Vim uses this command to find the differencesbetween file1 and file2:diff file1 file2 > outfileThe ">"is replaced with the value of'shellredir'.The output of "diff"must bea normal "ed" stylediff ora unified diff.Acontextdiff will NOT work.  Fora unifieddiff no context lines can be used.Using "diff-u" will NOT work, use "diff -U0".This example explains the format that Vim expects for the "ed" style diff:1a2> bbb4d4< 1117c7< GGG---> gggThe "1a2" item appends the line "bbb".The "4d4" item deletes the line "111".The "7c7" item replaces the line "GGG" with "ggg".When'diffexpr'is not empty, Vim evaluatesit to obtainadiff file in theformat mentioned.  Thesevariables are set to the file names used:v:fname_inoriginal filev:fname_newnew version of the same filev:fname_outwhere to write the resultingdiff fileAdditionally,'diffexpr' should take care of "icase" and "iwhite" in the'diffopt' option.'diffexpr' cannot change the value of'lines' and'columns'.The advantage of usinga function call without argumentsis thatitis faster,seeexpr-option-function.Example (this does almost the sameas'diffexpr' being empty):set diffexpr=MyDiff()function MyDiff()   let opt = ""   if &diffopt =~ "icase"     let opt = opt .. "-i "   endif   if &diffopt =~ "iwhite"     let opt = opt .. "-b "   endif   silent execute "!diff -a --binary " .. opt .. v:fname_in .. " " .. v:fname_new ..\  " > " .. v:fname_out   redraw!endfunctionThe "-a" argumentis used to force comparing the filesas text, comparingasbinaries isn't useful.  The "--binary" argument makes the files read in binarymode, so thataCTRL-Z doesn'tend the text on DOS.Theredraw! command may not be needed, depending on whether executingashell command shows something on the display or not.If the'diffexpr'expression starts with s: or<SID>, thenitis replacedwith thescript ID(local-function).  Example:set diffexpr=s:MyDiffExpr()set diffexpr=<SID>SomeDiffExpr()Otherwise, theexpressionis evaluated in the context of thescript where theoption was set, thusscript-local items are available.E810E97Vim willdoa test if thediff output looks alright.  Ifit doesn't, you willget an error message.  Possible causes:-  The "diff" program cannot be executed.-  The "diff" program doesn't produce normal "ed" style diffs (see above).-  The'shell' and associatedoptions are not set correctly.  Try if filtering   works witha command like ":!sort".-  You are using'diffexpr' andit doesn't work.If it's not clear what the problemis set the'verbose' option to one or moreto see more messages.The self-installing Vim forMS-Windows includesadiff program.  If you don'thaveit you might want todownloada diff.exe.  For example fromhttp://gnuwin32.sourceforge.net/packages/diffutils.htm.USING PATCHESdiff-patchexprThe'patchexpr' option can be set to use something else than the standard"patch" program.When'patchexpr'is empty, Vim will call the "patch" program like this:patch -o outfile origfile < patchfileThis should work fine with most versions of the "patch" program.Note thataCR in the middle ofa line may cause problems,itis seenasa line break.If the default doesn't work for you, set the'patchexpr' to anexpression thatwill have the same effect.  Thesevariables are set to the file names used:v:fname_inoriginal filev:fname_diffpatch filev:fname_outresulting patched fileThe advantage of usinga function call without argumentsis thatitis faster,seeexpr-option-function.Example (this does the sameas'patchexpr' being empty):set patchexpr=MyPatch()function MyPatch()   :call system("patch -o " .. v:fname_out .. " " .. v:fname_in ..   \  " < " .. v:fname_diff)endfunctionMake sure that using the "patch" program doesn't have unwanted side effects.For example, watch out for additionally generated files, which should bedeleted.  It should just patch the file and nothing else.   Vim will change directory to "/tmp" or another temp directory beforeevaluating'patchexpr'.  This hopefully avoids that files in the currentdirectory are accidentally patched.  Vim will also delete filesstarting withv:fname_in and ending in ".rej" and ".orig".If the'patchexpr'expression starts with s: or<SID>, thenitis replacedwith thescript ID(local-function).  Example:set patchexpr=s:MyPatchExpr()set patchexpr=<SID>SomePatchExpr()Otherwise, theexpressionis evaluated in the context of thescript where theoption was set, thusscript-local items are available.DIFF FUNCTION EXAMPLESdiff-func-examplesSome examples for using thediff() function to compute thediff indicesbetween twoLists of strings are below.  " some lines are changed  :echo diff(['abc', 'def', 'ghi'], ['abx', 'rrr', 'xhi'], {'output': 'indices'})   [{'from_idx': 0, 'from_count': 3, 'to_idx': 0, 'to_count': 3}]  " few lines added at the beginning  :echo diff(['ghi'], ['abc', 'def', 'ghi'], {'output': 'indices'})   [{'from_idx': 0, 'from_count': 0, 'to_idx': 0, 'to_count': 2}]  " few lines removed from the beginning  :echo diff(['abc', 'def', 'ghi'], ['ghi'], {'output': 'indices'})   [{'from_idx': 0, 'from_count': 2, 'to_idx': 0, 'to_count': 0}]  " few lines added in the middle  :echo diff(['abc', 'jkl'], ['abc', 'def', 'ghi', 'jkl'], {'output': 'indices'})   [{'from_idx': 1, 'from_count': 0, 'to_idx': 1, 'to_count': 2}]  " few lines removed in the middle  :echo diff(['abc', 'def', 'ghi', 'jkl'], ['abc', 'jkl'], {'output': 'indices'})   [{'from_idx': 1, 'from_count': 2, 'to_idx': 1, 'to_count': 0}]  " few lines added at the end  :echo diff(['abc'], ['abc', 'def', 'ghi'], {'output': 'indices'})   [{'from_idx': 1, 'from_count': 0, 'to_idx': 1, 'to_count': 2}]  " few lines removed from the end  :echo diff(['abc', 'def', 'ghi'], ['abc'], {'output': 'indices'})   [{'from_idx': 1, 'from_count': 2, 'to_idx': 1, 'to_count': 0}]  " disjointed changes  :echo diff(['ab', 'def', 'ghi', 'jkl'], ['abc', 'def', 'ghi', 'jk'], {'output': 'indices', 'context': 0})   [{'from_idx': 0, 'from_count': 1, 'to_idx': 0, 'to_count': 1},    {'from_idx': 3, 'from_count': 1, 'to_idx': 3, 'to_count': 1}]  " disjointed changes with context length 1  :echo diff(['ab', 'def', 'ghi', 'jkl'], ['abc', 'def', 'ghi', 'jk'], {'output': 'indices', 'context': 1})   [{'from_idx': 0, 'from_count': 4, 'to_idx': 0, 'to_count': 4}] vim:tw=78:ts=8:noet:ft=help:norl:

Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq


[8]ページ先頭

©2009-2026 Movatter.jp