@c-*-texinfo-*-@cThisispartoftheGNUEmacsLispReferenceManual.@cCopyright(C)1990,1991,1992,1993,1994FreeSoftwareFoundation,Inc.@cSeethefileelisp.texiforcopyingconditions.@setfilename../info/backups@nodeBackupsandAuto-Saving,Buffers,Files,Top@chapterBackupsandAuto-SavingBackupfilesandauto-savefilesaretwomethodsbywhichEmacstriestoprotecttheuserfromtheconsequencesofcrashesoroftheuser'sownerrors.Auto-savingpreservesthetextfromearlierinthecurrenteditingsession;backupfilespreservefilecontentspriortothecurrentsession.@menu*BackupFiles::Howbackupfilesaremade;howtheirnamesarechosen.*Auto-Saving::Howauto-savefilesaremade;howtheirnamesarechosen.*Reverting::@code{revert-buffer},andhowtocustomizewhatitdoes.@endmenu@nodeBackupFiles@sectionBackupFiles@cindexbackupfileA@dfn{backupfile}isacopyoftheoldcontentsofafileyouareediting.Emacsmakesabackupfilethefirsttimeyousaveabufferintoitsvisitedfile.Normally,thismeansthatthebackupfilecontainsthecontentsofthefileasitwasbeforethecurrenteditingsession.Thecontentsofthebackupfilenormallyremainunchangedonceitexists.Backupsareusuallymadebyrenamingthevisitedfiletoanewname.Optionally,youcanspecifythatbackupfilesshouldbemadebycopyingthevisitedfile.Thischoicemakesadifferenceforfileswithmultiplenames;italsocanaffectwhethertheeditedfileremainsownedbytheoriginalownerorbecomesownedbytheusereditingit.Bydefault,Emacsmakesasinglebackupfileforeachfileedited.Youcanalternativelyrequestnumberedbackups;theneachnewbackupfilegetsanewname.Youcandeleteoldnumberedbackupswhenyoudon'twantthemanymore,orEmacscandeletethemautomatically.@menu*MakingBackups::HowEmacsmakesbackupfiles,andwhen.*RenameorCopy::Twoalternatives:renamingtheoldfileorcopyingit.*NumberedBackups::Keepingmultiplebackupsforeachsourcefile.*BackupNames::Howbackupfilenamesarecomputed;customization.@endmenu@nodeMakingBackups@subsectionMakingBackupFiles@defunbackup-bufferThisfunctionmakesabackupofthefilevisitedbythecurrentbuffer,ifappropriate.Itiscalledby@code{save-buffer}beforesavingthebufferthefirsttime.@enddefun@defvarbuffer-backed-upThisbuffer-localvariableindicateswhetherthisbuffer'sfilehasbeenbackeduponaccountofthisbuffer.Ifitisnon-@code{nil},thenthebackupfilehasbeenwritten.Otherwise,thefileshouldbebackedupwhenitisnextsaved(ifbackupsareenabled).Thisisapermanentlocal;@code{kill-local-variables}doesnotalterit.@enddefvar@defoptmake-backup-filesThisvariabledetermineswhetherornottomakebackupfiles.Ifitisnon-@code{nil},thenEmacscreatesabackupofeachfilewhenitissavedforthefirsttime---providedthat@code{backup-inhibited}is@code{nil}(seebelow).Thefollowingexampleshowshowtochangethe@code{make-backup-files}variableonlyinthe@file{RMAIL}bufferandnotelsewhere.Settingit@code{nil}stopsEmacsfrommakingbackupsofthe@file{RMAIL}file,whichmaysavediskspace.(Youwouldputthiscodeinyour@file{.emacs}file.)@smallexample@group(add-hook'rmail-mode-hook(function(lambda()(make-local-variable'make-backup-files)(setqmake-backup-filesnil))))@endgroup@endsmallexample@enddefopt@defvarbackup-enable-predicateThisvariable'svalueisafunctiontobecalledoncertainoccasionstodecidewhetherafileshouldhavebackupfiles.Thefunctionreceivesoneargument,afilenametoconsider.Ifthefunctionreturns@code{nil},backupsaredisabledforthatfile.Otherwise,theothervariablesinthissectionsaywhetherandhowtomakebackups.Thedefaultvalueisthis:@example(lambda(name)(or(<(lengthname)5)(not(string-equal"/tmp/"(substringname05)))))@endexample@enddefvar@defvarbackup-inhibitedIfthisvariableisnon-@code{nil},backupsareinhibited.Itrecordstheresultoftesting@code{backup-enable-predicate}onthevisitedfilename.Itcanalsocoherentlybeusedbyothermechanismsthatinhibitbackupsbasedonwhichfileisvisited.Forexample,VCsetsthisvariablenon-@code{nil}topreventmakingbackupsforfilesmanagedwithaversioncontrolsystem.Thisisapermanentlocal,sothatchangingthemajormodedoesnotloseitsvalue.Majormodesshouldnotsetthisvariable---theyshouldset@code{make-backup-files}instead.@enddefvar@nodeRenameorCopy@subsectionBackupbyRenamingorbyCopying?@cindexbackupfiles,howtomakethemTherearetwowaysthatEmacscanmakeabackupfile:@itemize@bullet@itemEmacscanrenametheoriginalfilesothatitbecomesabackupfile,andthenwritethebufferbeingsavedintoanewfile.Afterthisprocedure,anyothernames(i.e.,hardlinks)oftheoriginalfilenowrefertothebackupfile.Thenewfileisownedbytheuserdoingtheediting,anditsgroupisthedefaultfornewfileswrittenbytheuserinthatdirectory.@itemEmacscancopytheoriginalfileintoabackupfile,andthenoverwritetheoriginalfilewithnewcontents.Afterthisprocedure,anyothernames(i.e.,hardlinks)oftheoriginalfilestillrefertothecurrentversionofthefile.Thefile'sownerandgroupwillbeunchanged.@enditemizeThefirstmethod,renaming,isthedefault.Thevariable@code{backup-by-copying},ifnon-@code{nil},saystousethesecondmethod,whichistocopytheoriginalfileandoverwriteitwiththenewbuffercontents.Thevariable@code{file-precious-flag},ifnon-@code{nil},alsohasthiseffect(asasidelineofitsmainsignificance).@xref{SavingBuffers}.@defvarbackup-by-copyingIfthisvariableisnon-@code{nil},Emacsalwaysmakesbackupfilesbycopying.@enddefvarThefollowingtwovariables,whennon-@code{nil},causethesecondmethodtobeusedincertainspecialcases.Theyhavenoeffectonthetreatmentoffilesthatdon'tfallintothespecialcases.@defvarbackup-by-copying-when-linkedIfthisvariableisnon-@code{nil},Emacsmakesbackupsbycopyingforfileswithmultiplenames(hardlinks).Thisvariableissignificantonlyif@code{backup-by-copying}is@code{nil},sincecopyingisalwaysusedwhenthatvariableisnon-@code{nil}.@enddefvar@defvarbackup-by-copying-when-mismatchIfthisvariableisnon-@code{nil},Emacsmakesbackupsbycopyingincaseswhererenamingwouldchangeeithertheownerorthegroupofthefile.Thevaluehasnoeffectwhenrenamingwouldnotaltertheownerorgroupofthefile;thatis,forfileswhichareownedbytheuserandwhosegroupmatchesthedefaultforanewfilecreatedtherebytheuser.Thisvariableissignificantonlyif@code{backup-by-copying}is@code{nil},sincecopyingisalwaysusedwhenthatvariableisnon-@code{nil}.@enddefvar@nodeNumberedBackups@subsectionMakingandDeletingNumberedBackupFilesIfafile'snameis@file{foo},thenamesofitsnumberedbackupversionsare@file{foo.~@var{v}~},forvariousintegers@var{v},likethis:@file{foo.~1~},@file{foo.~2~},@file{foo.~3~},@dots{},@file{foo.~259~},andsoon.@defoptversion-controlThisvariablecontrolswhethertomakeasinglenon-numberedbackupfileormultiplenumberedbackups.@table@asis@item@code{nil}Makenumberedbackupsifthevisitedfilealreadyhasnumberedbackups;otherwise,donot.@item@code{never}Donotmakenumberedbackups.@item@var{anythingelse}Makenumberedbackups.@endtable@enddefoptTheuseofnumberedbackupsultimatelyleadstoalargenumberofbackupversions,whichmustthenbedeleted.Emacscandothisautomaticallyoritcanasktheuserwhethertodeletethem.@defoptkept-new-versionsThevalueofthisvariableisthenumberofnewestversionstokeepwhenanewnumberedbackupismade.Thenewlymadebackupisincludedinthecount.Thedefaultvalueis2.@enddefopt@defoptkept-old-versionsThevalueofthisvariableisthenumberofoldestversionstokeepwhenanewnumberedbackupismade.Thedefaultvalueis2.@enddefoptIftherearebackupsnumbered1,2,3,5,and7,andbothofthesevariableshavethevalue2,thenthebackupsnumbered1and2arekeptasoldversionsandthosenumbered5and7arekeptasnewversions;backupversion3isexcess.Thefunction@code{find-backup-file-name}(@pxref{BackupNames})isresponsiblefordeterminingwhichbackupversionstodelete,butdoesnotdeletethemitself.@defopttrim-versions-without-askingIfthisvariableisnon-@code{nil},thensavingafiledeletesexcessbackupversionssilently.Otherwise,itaskstheuserwhethertodeletethem.@enddefopt@defoptdired-kept-versionsThisvariablespecifieshowmanyofthenewestbackupversionstokeepintheDiredcommand@kbd{.}(@code{dired-clean-directory}).That'sthesamething@code{kept-new-versions}specifieswhenyoumakeanewbackupfile.Thedefaultvalueis2.@enddefopt@nodeBackupNames@subsectionNamingBackupFilesThefunctionsinthissectionaredocumentedmainlybecauseyoucancustomizethenamingconventionsforbackupfilesbyredefiningthem.Ifyouchangeone,youprobablyneedtochangetherest.@defunbackup-file-name-pfilenameThisfunctionreturnsanon-@code{nil}valueif@var{filename}isapossiblenameforabackupfile.Afilewiththename@var{filename}neednotexist;thefunctionjustchecksthename.@smallexample@group(backup-file-name-p"foo")@result{}nil@endgroup@group(backup-file-name-p"foo~")@result{}3@endgroup@endsmallexampleThestandarddefinitionofthisfunctionisasfollows:@smallexample@group(defunbackup-file-name-p(file)"Return non-nil if FILE is a backup file \name (numeric or not)..."(string-match"~$"file))@endgroup@endsmallexample@noindentThus,thefunctionreturnsanon-@code{nil}valueifthefilenameendswitha@samp{~}.(Weuseabackslashtosplitthedocumentationstring'sfirstlineintotwolinesinthetext,butproducejustonelineinthestringitself.)Thissimpleexpressionisplacedinaseparatefunctiontomakeiteasytoredefineforcustomization.@enddefun@defunmake-backup-file-namefilenameThisfunctionreturnsastringthatisthenametouseforanon-numberedbackupfileforfile@var{filename}.OnUnix,thisisjust@var{filename}withatildeappended.Thestandarddefinitionofthisfunctionisasfollows:@smallexample@group(defunmake-backup-file-name(file)"Create the non-numeric backup file name for FILE.@dots{}"(concatfile"~"))@endgroup@endsmallexampleYoucanchangethebackup-filenamingconventionbyredefiningthisfunction.Thefollowingexampleredefines@code{make-backup-file-name}toprependa@samp{.}inadditiontoappendingatilde:@smallexample@group(defunmake-backup-file-name(filename)(concat"."filename"~"))@endgroup@group(make-backup-file-name"backups.texi")@result{}".backups.texi~"@endgroup@endsmallexample@enddefun@defunfind-backup-file-namefilenameThisfunctioncomputesthefilenameforanewbackupfilefor@var{filename}.Itmayalsoproposecertainexistingbackupfilesfordeletion.@code{find-backup-file-name}returnsalistwhose@sc{car}isthenameforthenewbackupfileandwhose@sc{cdr}isalistofbackupfileswhosedeletionisproposed.Twovariables,@code{kept-old-versions}and@code{kept-new-versions},determinewhichbackupversionsshouldbekept.Thisfunctionkeepsthoseversionsbyexcludingthemfromthe@sc{cdr}ofthevalue.@xref{NumberedBackups}.Inthisexample,thevaluesaysthat@file{~rms/foo.~5~}isthenametouseforthenewbackupfile,and@file{~rms/foo.~3~}isan``excess''versionthatthecallershouldconsiderdeletingnow.@smallexample@group(find-backup-file-name"~rms/foo")@result{}("~rms/foo.~5~""~rms/foo.~3~")@endgroup@endsmallexample@enddefun@cEmacs19feature@defunfile-newest-backupfilenameThisfunctionreturnsthenameofthemostrecentbackupfilefor@var{filename},or@code{nil}ifthatfilehasnobackupfiles.Somefilecomparisoncommandsusethisfunctionsothattheycanautomaticallycompareafilewithitsmostrecentbackup.@enddefun@nodeAuto-Saving@sectionAuto-Saving@cindexauto-savingEmacsperiodicallysavesallfilesthatyouarevisiting;thisiscalled@dfn{auto-saving}.Auto-savingpreventsyoufromlosingmorethanalimitedamountofworkifthesystemcrashes.Bydefault,auto-saveshappenevery300keystrokes,orafteraround30secondsofidletime.@xref{Auto-Save,Auto-Save,Auto-Saving:ProtectionAgainstDisasters,emacs,TheGNUEmacsManual},forinformationonauto-saveforusers.Herewedescribethefunctionsusedtoimplementauto-savingandthevariablesthatcontrolthem.@defvarbuffer-auto-save-file-nameThisbuffer-localvariableisthenameofthefileusedforauto-savingthecurrentbuffer.Itis@code{nil}ifthebuffershouldnotbeauto-saved.@example@groupbuffer-auto-save-file-name=>"/xcssun/users/rms/lewis/#files.texi#"@endgroup@endexample@enddefvar@deffnCommandauto-save-modeargWhenusedinteractivelywithoutanargument,thiscommandisatoggleswitch:itturnsonauto-savingofthecurrentbufferifitisoff,andvice-versa.Withanargument@var{arg},thecommandturnsauto-savingonifthevalueof@var{arg}is@code{t},anonemptylist,orapositiveinteger.Otherwise,itturnsauto-savingoff.@enddeffn@defunauto-save-file-name-pfilenameThisfunctionreturnsanon-@code{nil}valueif@var{filename}isastringthatcouldbethenameofanauto-savefile.Itworksbasedonknowledgeofthenamingconventionforauto-savefiles:anamethatbeginsandendswithhashmarks(@samp{#})isapossibleauto-savefilename.Theargument@var{filename}shouldnotcontainadirectorypart.@example@group(make-auto-save-file-name)@result{}"/xcssun/users/rms/lewis/#files.texi#"@endgroup@group(auto-save-file-name-p"#files.texi#")@result{}0@endgroup@group(auto-save-file-name-p"files.texi")@result{}nil@endgroup@endexampleThestandarddefinitionofthisfunctionisasfollows:@example@group(defunauto-save-file-name-p(filename)"Return non-nil if FILENAME can be yielded by..."(string-match"^#.*#$"filename))@endgroup@endexampleThisfunctionexistssothatyoucancustomizeitifyouwishtochangethenamingconventionforauto-savefiles.Ifyouredefineit,besuretoredefinethefunction@code{make-auto-save-file-name}correspondingly.@enddefun@defunmake-auto-save-file-nameThisfunctionreturnsthefilenametouseforauto-savingthecurrentbuffer.Thisisjustthefilenamewithhashmarks(@samp{#})appendedandprependedtoit.Thisfunctiondoesnotlookatthevariable@code{auto-save-visited-file-name}(describedbelow);youshouldcheckthatbeforecallingthisfunction.@example@group(make-auto-save-file-name)@result{}"/xcssun/users/rms/lewis/#backup.texi#"@endgroup@endexampleThestandarddefinitionofthisfunctionisasfollows:@example@group(defunmake-auto-save-file-name()"Return file name to use for auto-saves \of current buffer.@dots{}"(ifbuffer-file-name@endgroup@group(concat(file-name-directorybuffer-file-name)"#"(file-name-nondirectorybuffer-file-name)"#")(expand-file-name(concat"#%"(buffer-name)"#"))))@endgroup@endexampleThisexistsasaseparatefunctionsothatyoucanredefineittocustomizethenamingconventionforauto-savefiles.Besuretochange@code{auto-save-file-name-p}inacorrespondingway.@enddefun@defvarauto-save-visited-file-nameIfthisvariableisnon-@code{nil},Emacsauto-savesbuffersinthefilestheyarevisiting.Thatis,theauto-saveisdoneinthesamefilethatyouareediting.Normally,thisvariableis@code{nil},soauto-savefileshavedistinctnamesthatarecreatedby@code{make-auto-save-file-name}.Whenyouchangethevalueofthisvariable,thevaluedoesnottakeeffectuntilthenexttimeauto-savemodeisreenabledinanygivenbuffer.Ifauto-savemodeisalreadyenabled,auto-savescontinuetogointhesamefilenameuntil@code{auto-save-mode}iscalledagain.@enddefvar@defunrecent-auto-save-pThisfunctionreturns@code{t}ifthecurrentbufferhasbeenauto-savedsincethelasttimeitwasreadinorsaved.@enddefun@defunset-buffer-auto-savedThisfunctionmarksthecurrentbufferasauto-saved.Thebufferwillnotbeauto-savedagainuntilthebuffertextischangedagain.Thefunctionreturns@code{nil}.@enddefun@defoptauto-save-intervalThevalueofthisvariableisthenumberofcharactersthatEmacsreadsfromthekeyboardbetweenauto-saves.Eachtimethismanymorecharactersareread,auto-savingisdoneforallbuffersinwhichitisenabled.@enddefopt@defoptauto-save-timeoutThevalueofthisvariableisthenumberofsecondsofidletimethatshouldcauseauto-saving.Eachtimetheuserpausesforthislong,Emacsauto-savesanybuffersthatneedit.(Actually,thespecifiedtimeoutismultipliedbyafactordependingonthesizeofthecurrentbuffer.)@enddefopt@defvarauto-save-hookThisnormalhookisrunwheneveranauto-saveisabouttohappen.@enddefvar@defoptauto-save-defaultIfthisvariableisnon-@code{nil},buffersthatarevisitingfileshaveauto-savingenabledbydefault.Otherwise,theydonot.@enddefopt@deffnCommanddo-auto-save&optionalno-messagecurrent-onlyThisfunctionauto-savesallbuffersthatneedtobeauto-saved.Itsavesallbuffersforwhichauto-savingisenabledandthathavebeenchangedsincethepreviousauto-save.Normally,ifanybuffersareauto-saved,amessagethatsays@samp{Auto-saving...}isdisplayedintheechoareawhileauto-savingisgoingon.However,if@var{no-message}isnon-@code{nil},themessageisinhibited.If@var{current-only}isnon-@code{nil},onlythecurrentbufferisauto-saved.@enddeffn@defundelete-auto-save-file-if-necessaryThisfunctiondeletesthecurrentbuffer'sauto-savefileif@code{delete-auto-save-files}isnon-@code{nil}.Itiscalledeverytimeabufferissaved.@enddefun@defvardelete-auto-save-filesThisvariableisusedbythefunction@code{delete-auto-save-file-if-necessary}.Ifitisnon-@code{nil},Emacsdeletesauto-savefileswhenatruesaveisdone(inthevisitedfile).Thissavesdiskspaceanduncluttersyourdirectory.@enddefvar@defunrename-auto-save-fileThisfunctionadjuststhecurrentbuffer'sauto-savefilenameifthevisitedfilenamehaschanged.Italsorenamesanexistingauto-savefile.Ifthevisitedfilenamehasnotchanged,thisfunctiondoesnothing.@enddefun@defvarbuffer-saved-sizeThevalueofthisbuffer-localvariableisthelengthofthecurrentbufferasofthelasttimeitwasreadin,saved,orauto-saved.Thisisusedtodetectasubstantialdecreaseinsize,andturnoffauto-savinginresponse.Ifitis-1,thatmeansauto-savingistemporarilyshutoffinthisbufferduetoasubstantialdeletion.Explicitlysavingthebufferstoresapositivevalueinthisvariable,thusreenablingauto-saving.Turningauto-savemodeofforonalsoaltersthisvariable.@enddefvar@defvarauto-save-list-file-nameThisvariable(ifnon-@code{nil})specifiesafileforrecordingthenamesofalltheauto-savefiles.EachtimeEmacsdoesauto-saving,itwritestwolinesintothisfileforeachbufferthathasauto-savingenabled.Thefirstlinegivesthenameofthevisitedfile(it'semptyifthebufferhasnone),andthesecondgivesthenameoftheauto-savefile.IfEmacsexitsnormally,itdeletesthisfile.IfEmacscrashes,youcanlookinthefiletofindalltheauto-savefilesthatmightcontainworkthatwasotherwiselost.The@code{recover-session}commandusesthesefiles.Thedefaultnameforthisfileisinyourhomedirectoryandstartswith@samp{.saves-}.ItalsocontainstheEmacsprocess@sc{id}andthehostname.@enddefvar@nodeReverting@sectionRevertingIfyouhavemadeextensivechangestoafileandthenchangeyourmindaboutthem,youcangetridofthembyreadinginthepreviousversionofthefilewiththe@code{revert-buffer}command.@xref{Reverting,,RevertingaBuffer,emacs,TheGNUEmacsManual}.@deffnCommandrevert-buffer&optionalcheck-auto-savenoconfirmThiscommandreplacesthebuffertextwiththetextofthevisitedfileondisk.Thisactionundoesallchangessincethefilewasvisitedorsaved.Iftheargument@var{check-auto-save}isnon-@code{nil},andthelatestauto-savefileismorerecentthanthevisitedfile,@code{revert-buffer}askstheuserwhethertousethatinstead.Otherwise,italwaysusesthetextofthevisitedfileitself.Interactively,@var{check-auto-save}issetifthereisanumericprefixargument.Normally,@code{revert-buffer}asksforconfirmationbeforeitchangesthebuffer;butiftheargument@var{noconfirm}isnon-@code{nil},@code{revert-buffer}doesnotaskforconfirmation.Revertingtriestopreservemarkerpositionsinthebufferbyusingthereplacementfeatureof@code{insert-file-contents}.Ifthebuffercontentsandthefilecontentsareidenticalbeforetherevertoperation,revertingpreservesallthemarkers.Iftheyarenotidentical,revertingdoeschangethebuffer;thenitpreservesthemarkersintheunchangedtext(ifany)atthebeginningandendofthebuffer.Preservinganyadditionalmarkerswouldbeproblematical.@enddeffnYoucancustomizehow@code{revert-buffer}doesitsworkbysettingthesevariables---typically,asbuffer-localvariables.@defvarrevert-buffer-functionThevalueofthisvariableisthefunctiontousetorevertthisbuffer.Ifnon-@code{nil},itiscalledasafunctionwithnoargumentstodotheworkofreverting.Ifthevalueis@code{nil},revertingworkstheusualway.ModessuchasDiredmode,inwhichthetextbeingediteddoesnotconsistofafile'scontentsbutcanberegeneratedinsomeotherfashion,givethisvariableabuffer-localvaluethatisafunctiontoregeneratethecontents.@enddefvar@defvarrevert-buffer-insert-file-contents-functionThevalueofthisvariable,ifnon-@code{nil},isthefunctiontousetoinserttheupdatedcontentswhenrevertingthisbuffer.Thefunctionreceivestwoarguments:firstthefilenametouse;second,@code{t}iftheuserhasaskedtoreadtheauto-savefile.@enddefvar@defvarbefore-revert-hookThisnormalhookisrunby@code{revert-buffer}beforeactuallyinsertingthemodifiedcontents---butonlyif@code{revert-buffer-function}is@code{nil}.FontLockmodeusesthishooktorecordthatthebuffercontentsarenolongerfontified.@enddefvar@defvarafter-revert-hookThisnormalhookisrunby@code{revert-buffer}afteractuallyinsertingthemodifiedcontents---butonlyif@code{revert-buffer-function}is@code{nil}.FontLockmodeusesthishooktorecomputethefontsfortheupdatedbuffercontents.@enddefvar