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)
undo.txt      ForVim version 9.1.  Last change: 2024 Nov 09VIM REFERENCE MANUAL    by Bram MoolenaarUndo andredoundo-redoThe basics are explained insection02.5 of the user manual.1. Undo andredo commandsundo-commands2. Two ways ofundoundo-two-ways3. Undo blocksundo-blocks4. Undo branchesundo-branches5. Undo persistenceundo-persistence6. Remarks aboutundoundo-remarks==============================================================================1. Undo andredo commandsundo-commands<Undo>orundo<Undo>uuUndo[count] changes.:u:un:undo:u[ndo]Undo one change.E830:u[ndo]{N}Jump to after change number{N}.  Seeundo-branchesfor the meaning of{N}.CTRL-RCTRL-RRedo[count] changes which were undone.:red:redoredo:red[o]Redo one change which was undone.UUUndo all latest changes on one line, the line wherethe latest change was made.U itself also countsasa change, and thusU undoesa previousU.The last changes are remembered.  You can use theundo andredo commands aboveto revert the text to howit was before each change.  You can also apply thechanges again, getting back the text before the undo.The "U" commandis treated by undo/redo just like any other command.  Thusa"u" command undoesa "U" command anda 'CTRL-R' command redoesit again.  Whenmixing "U", "u" and 'CTRL-R' you will notice that the "U" command willrestore the situation ofa line to before the previous "U" command.  This maybe confusing.  Tryit out to get used to it.The "U" command will alwaysmark the bufferas changed.  When "U" changes thebuffer back to howit was without changes,itis still considered changed.Use "u" toundo changes until the buffer becomes unchanged.==============================================================================2. Two ways ofundoundo-two-waysHowundo andredo commands work depends on the 'u' flag in'cpoptions'.Thereis the Vim way ('u' excluded) and the Vi-compatible way ('u' included).In the Vim way, "uu" undoes two changes.  In the Vi-compatible way, "uu" doesnothing (undoes an undo).'u' excluded, the Vim way:You cango back in time with theundo command.  You can thengo forward againwith theredo command.  If you makea new change after theundo command,theredo will not be possible anymore.'u' included, the Vi-compatible way:Theundo command undoes the previous change, and also the previousundocommand.  Theredo command repeats the previousundo command.  It does NOTrepeata change command, use "." for that.ExamplesVim wayVi-compatible way"uu"two timesundono-op"uCTRL-R"no-optwo timesundoRationale:Nvi uses the "." command instead ofCTRL-R.  Unfortunately, thisis notVi compatible.  For example "dwdwu." inVi deletes two    words, inNviit does nothing.==============================================================================3. Undo blocksundo-blocksOneundo command normally undoesa typed command, no matter how many changesthat command makes.  This sequence of undo-able changes forms anundo block.Thus if the typed key(s) calla function, all the commands in the function areundone together.If you want to writea function orscript that doesn't createa new undoablechange but joins in with the previous change use this command::undoj:undojoinE790:undoj[oin]Join further changes with the previousundo block.Warning: Use with care,it may prevent the user fromproperly undoing changes.  Don't use this afterundoor redo.Thisis most useful when you need to prompt the user halfway througha change.For example ina function that callsgetchar().  Do make sure that there wasa related change before this that youmust join with.This doesn't work by itself, because the next key press will starta newchange again.  But you cando something like this::undojoin | deleteAfter thisa "u" command willundo the delete command and the previouschange.undo-breakundo-close-blockTodo the opposite, usea newundo block for the next change, inInsert modeuseCTRL-G u.  Thisis useful if you want aninsert command to be undoable inparts.  E.g., for each sentence.i_CTRL-G_uSetting the value of'undolevels' also closes theundo block.  Even when thenew valueis equal to the old value.  Useg:undolevels to explicitly readand write only the global value of'undolevels'. InVim9 script:&g:undolevels = &g:undolevelsIn legacy script:let &g:undolevels = &g:undolevelsNote that the similar-looking assignment `let &undolevels=&undolevels` does notpreserve the global option value of'undolevels' in the event that the localoption has been set toa different value.  For example:" Start with different global and local values for 'undolevels'.let &g:undolevels = 1000let &l:undolevels = 2000" This assignment changes the global option to 2000:let &undolevels = &undolevels==============================================================================4. Undo branchesundo-branchesundo-treeAbove we only discussed one line of undo/redo.  Butitis also possible tobranch off.  This happens when youundoa few changes and then makea newchange.  The undone changes becomea branch.  You cango to that branch withthe following commands.Thisis explained in the user manual:usr_32.txt.:undol:undolist:undol[ist]List the leafs in the tree of changes.  Example:   number changes  when               saved       88      88  2010/01/04 14:25:53      108     107  08/07 12:47:51      136      46  13:33:01             7      166     164  3 seconds agoThe "number" columnis the change number.  This numbercontinuously increases and can be used to identifyaspecific undo-able change, see:undo.The "changes" columnis the number of changes to thisleaf from the root of the tree.The "when" columnis the date and time when thischange was made.  The four possible formats are:N seconds ago    HH:MM:SS             hour, minute, seconds    MM/DD HH:MM:SS       idem, with month and day    YYYY/MM/DD HH:MM:SS  idem, with yearThe "saved" column specifies, if this change waswritten to disk and which file writeit was. This canbe used with the:later and:earlier commands.For more details use theundotree() function.g-g-Go to older text state.  Withacount repeat that manytimes.:ea:earlier:ea[rlier]{count}Go to older text state{count} times.:ea[rlier]{N}sGo to older text state about{N} seconds before.:ea[rlier]{N}mGo to older text state about{N} minutes before.:ea[rlier]{N}hGo to older text state about{N} hours before.:ea[rlier]{N}dGo to older text state about{N} days before.:ea[rlier]{N}fGo to older text state{N} file writes before.When changes were made since the last write":earlier 1f" will revert the text to the state whenit was written.  Otherwiseit willgo to the writebefore that.Whenat the state of the first file write, or whenthe file was not written, ":earlier 1f" willgo tobefore the first change.g+g+Go to newer text state.  Withacount repeat that manytimes.:lat:later:lat[er]{count}Go to newer text state{count} times.:lat[er]{N}sGo to newer text state about{N} seconds later.:lat[er]{N}mGo to newer text state about{N} minutes later.:lat[er]{N}hGo to newer text state about{N} hours later.:lat[er]{N}dGo to newer text state about{N} days later.:lat[er]{N}fGo to newer text state{N} file writes later.Whenat the state of the last file write, ":later 1f"willgo to the newest text state.Note that text states will become unreachable whenundo informationis clearedfor'undolevels'.Don't be surprised when moving through time shows multiple changes to takeplaceata time.  This happens when moving through theundo tree and thenmakinga new change.EXAMPLEStart with this text:one two threeDelete the firstword by pressing "x" three times:ne two threee two three two threeNowundo that by pressing "u" three times:e two threene two threeone two threeDelete the secondword by pressing "x" three times:one wo threeone o threeone  threeNowundo that by using "g-" three times:one o threeone wo three two threeYou are now back in the firstundo branch, afterdeleting "one".  Repeating"g-" will now bring you back to the original text:e two threene two threeone two threeJump to the last change with ":later 1h":one  threeAnd back to the start again with ":earlier 1h":one two threeNote that using "u" andCTRL-R will not get you to all possible text stateswhilerepeating "g-" and "g+" does.==============================================================================5. Undo persistenceundo-persistencepersistent-undoWhen unloadinga buffer Vim normally destroys the tree of undos created forthat buffer.  By setting the'undofile' option, Vim will automatically saveyourundohistory when you writea file and restoreundohistory when you editthe file again.The'undofile' optionis checked afterwritinga file, before theBufWritePostautocommands.  If you want tocontrol what files to writeundo informationfor, you can useaBufWritePre autocommand:au BufWritePre /tmp/* setlocal noundofileVim savesundo trees ina separateundo file, one for each edited file, usinga simple scheme that maps filesystem paths directly toundo files. Vim willdetect if anundo fileis no longer synchronized with the fileit was writtenfor (witha hash of the file contents) and ignoreit when the file was changedafter theundo file was written, to prevent corruption.  Anundo fileis alsoignored if its owner differs from the owner of the edited file, except whenthe owner of theundo fileis the current user.  Set'verbose' to getamessage about that when openinga file.Undo files are normally saved in the same directoryas the file.  This can bechanged with the'undodir' option.When the fileis encrypted, the text in theundo fileis also encrypted.  Thesame key andmethodis used.encryptionNote that text properties are not stored in theundo file.  You can restoretext properties so longasa bufferis loaded, but you cannot restore themfrom anundo file.  Rationale: It would require the associated text propertytypes to be defined in exactly the same wasas before, which cannot beguaranteed.You can also save and restoreundo histories by using ":wundo" and ":rundo"respectively::wundo:rundo:wundo[!]{file}Writeundohistory to{file}.When{file} exists andit does not look like anundo file(the magic numberat the start of the fileis wrong), thenthis fails, unless the! was added.Ifit exists and does look like anundo fileitisoverwritten. If thereis no undo-history, nothing will bewritten.Implementation detail: Overwriting happens by firstdeletingthe existing file and then creatinga new file with the samename. Soitis not possible to overwrite an existing undofileina write-protected directory.:rundo{file}Readundohistory from{file}.You can use these inautocommands to explicitly specify the name of thehistory file.  E.g.:au BufReadPost * call ReadUndo()au BufWritePost * call WriteUndo()func ReadUndo()  if filereadable(expand('%:h') .. '/UNDO/' .. expand('%:t'))    rundo %:h/UNDO/%:t  endifendfuncfunc WriteUndo()  let dirname = expand('%:h') .. '/UNDO'  if !isdirectory(dirname)    call mkdir(dirname)  endif  wundo %:h/UNDO/%:tendfuncYou should keep'undofile' off, otherwise youend up with twoundo files forevery write.You can use theundofile() function to find out the file name that Vim woulduse.Note that while reading/writing files and'undofile'is set mosterrors willbe silent, unless'verbose'is set.  With:wundo and:rundo you will get moreerror messages, e.g., when the file cannot be read or written.NOTE:undo files are never deleted by Vim.  You need to delete them yourself.Reading an existingundo file may fail for several reasons:E822  It cannot be opened, because the file permissions don't allow it.E823  The magic numberat the start of the file doesn't match.  This usuallymeansitis not anundo file.E824  The version number of theundo file indicates that it's written byanewer version of Vim.  You need that newer version to open it.  Don'twrite the buffer if you want to keep theundo info in the file."File contents changed, cannot useundo info"The file text differs from when theundo file was written.  This meanstheundo file cannot be used,it would corrupt the text.  This alsohappens when'encoding' differs from when theundo file was written.E825  Theundo file does not contain valid contents and cannot be used.E826  Theundo fileis encrypted but decryption failed.E827  Theundo fileis encrypted but this version of Vim does not supportencryption.  Open the file with another Vim.E832  Theundo fileis encrypted but'key'is not set, the text fileis notencrypted.  This would happen if the text file was written by Vimencryptedat first, and later overwritten by not encrypted text.You probably want to delete thisundo file."Not readingundo file, owner differs"Theundo fileis owned by someone else than the owner of the textfile.  For safety theundo fileis not used.Writing anundo file may fail for these reasons:E828  The file to be written cannot be created.  Perhaps youdo not havewrite permissions in the directory."Cannot writeundo file in any directory in'undodir'"None of the directories in'undodir' can be used."Will not overwrite withundo file, cannot read"A file exists with the name of theundo file to be written, butitcannot be read.  You may want to delete this file or rename it."Will not overwrite, thisis not anundo file"A file exists with the name of theundo file to be written, butitdoes not start with the right magic number.  You may want to deletethis file or rename it."Skippingundo file write, nothing toundo"Thereis noundo information to be written, nothing has been changedor'undolevels'is negative.E829  An error occurred whilewriting theundo file.  You may want to tryagain.==============================================================================6. Remarks aboutundoundo-remarksThe number of changes that are rememberedis set with the'undolevels' option.Ifitis zero, the Vi-compatible wayis always used.  Ifitis negative noundois possible.  Use this if you are running out of memory.clear-undoWhen you set'undolevels' to -1 theundo informationis not immediatelycleared, this happensat the next change.  To force clearing theundoinformation you can use these commands::let old_undolevels = &l:undolevels:setlocal undolevels=-1:exe "normal a \<BS>\<Esc>":let &l:undolevels = old_undolevels:unlet old_undolevelsNote use of&l:undolevels to explicitly read the local value of'undolevels'and the use of:setlocal to change only the local option (which takesprecedence over the corresponding global option value).  Saving the option valuevia the use of&undolevelsis unpredictable;it reads either the local value(if one has been set) or the global value (otherwise).  Also, ifa local valuehas been set,changing the option via `:set undolevels` will change both theglobal and local values, requiring extra work to save and restore both values.Marks for the buffer ('a to 'z) are also saved and restored, together with thetext.When all changes have been undone, the bufferis not considered to be changed.Itis then possible to exit Vim with ":q" instead of ":q!".Notethat thisis relative to the last write of the file.  Typing "u" after ":w"actually changes the buffer, compared to what was written, so the bufferisconsidered changed then.When manualfoldingis being used, thefolds are not saved and restored.Only changes completely withina fold will keep the foldasit was, becausethe first and last line of the fold don't change.The numberedregisters can also be used for undoing deletes.  Each time youdelete text,itisput intoregister "1.  The contents ofregister "1 areshifted to "2, etc.  The contents ofregister "9 are lost.  You can now getback the most recent deleted text with theput command:'"1P'.  (also, if thedeleted text was the result of the last delete or copy operation, 'P' or 'p'also worksas this puts the contents of the unnamed register).  You can getback the text of three deletes ago with'"3P'.redo-registerIf you want to get back more than one part of deleted text, you can useaspecial feature of the repeat command ".".  It will increase the number of theregister used.  So if you firstdo'"1P', the following "." will result ina'"2P'.  Repeating this will result in all numberedregisters being inserted.Example:If you deleted text with 'dd....'it can be restored with'"1P....'.If you don't know in whichregister the deleted text is, you can use the:display command.  An alternativeis to try the firstregister with'"1P', andifitis not what you wantdo 'u.'.  This will remove the contents of thefirst put, and repeat theput command for the second register.  Repeat the'u.' until you got what you want. vim:tw=78:ts=8:noet:ft=help:norl:

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


[8]ページ先頭

©2009-2025 Movatter.jp