editing.txt ForVim version 9.1. Last change: 2025 Apr 03VIM REFERENCE MANUAL by Bram MoolenaarEditing filesedit-files1. Introductionedit-intro2. Editinga fileedit-a-file3. The argumentlistargument-list4. Writingwriting5. Writing and quittingwrite-quit6. Dialogsedit-dialogs7. The current directorycurrent-directory8. Editing binary filesedit-binary9. Encryptionencryption10. Timestampstimestamps11. File Searchingfile-searching==============================================================================1. Introductionedit-introEditinga file with Vim means:1. reading the file intoa buffer2.changing the buffer with editor commands3.writing the buffer intoa filecurrent-fileAs longas you don't write the buffer, the original file remains unchanged.If you start editinga file (reada file into the buffer), the file nameisrememberedas the "current file name". Thisis also knownas the name of thecurrent buffer. It can be used with "%" on the command line:_%.alternate-fileIf there already wasa current file name, then that one becomes the alternatefile name. It can be used with "#" on the command line:_# and you can usetheCTRL-^ command totoggle between the current and the alternate file.However, the alternate file nameis not changed when:keepaltis used.An alternate file nameis remembered for each window.:keepalt:keepa:keepalt{cmd}Execute{cmd} while keeping the current alternate filename.Note that commands invoked indirectly (e.g.,witha function) may still set the alternate filename.All file names are remembered in the buffer list. When you entera file name,for editing (e.g., with ":e filename") orwriting (e.g., with ":w filename"),the file nameis added to the list. You can use the bufferlist to rememberwhich files you edited and to quickly switch from one file to another (e.g.,to copy text) with theCTRL-^ command. First type the number of the fileand then hitCTRL-^.CTRL-GorCTRL-G:f:fi:file:f[ile]Prints the current file name (as typed, unless ":cd"was used), the cursor position (unless the'ruler'optionis set), and the file status (readonly,modified, read errors, new file). See the'shortmess'option about how to make this message shorter.:f[ile]!like:file, but don't truncate the name even when'shortmess' indicates this.{count}CTRL-GLikeCTRL-G, but prints the current file name withfull path. If thecountis higher than 1 the currentbuffer numberis also given.g_CTRL-Gword-countbyte-countgCTRL-GPrints the current position of the cursor in fiveways: Column, Line, Word, Character and Byte. If thenumber of Characters and Bytesis the same then theCharacter positionis omitted.If there are characters in the line that take morethan one position on the screen (<Tab> or specialcharacter), or characters using more than one byte percolumn (characters above 0x7F when'encoding'isutf-8), both the byte column and the screen column areshown, separated bya dash.Also see the'ruler' option and thewordcount()function.v_g_CTRL-G{Visual}gCTRL-GSimilar to "gCTRL-G", but Word, Character, Line, andByte counts for the visually selected region aredisplayed.In Blockwise mode, Columncountis also shown. (For{Visual} seeVisual-mode.):file_f:f[ile][!]{name}Sets the current file name to{name}. The optional!avoids truncating the message,as with:file.If the buffer did havea name, that name becomes thealternate-file name. An unlisted bufferis createdto hold the old name.:0file:0f[ile][!]Remove the name of the current buffer. The optional!avoids truncating the message,as with:file.:buffers:files:lsList all the currently known file names. Seewindows.txt:files:buffers:ls.Vim will remember the full path name ofa file name that you enter. In mostcases when the file nameis displayed only the name you typedis shown, butthe full path nameis being used if you used the ":cd" command:cd.home-replaceIf the environment variable$HOMEis set, and the file name starts with thatstring,itis often displayed with HOME replaced with "~". This was done tokeep file names short. When reading orwriting files the full nameis stillused, the "~"is only used when displaying file names. Whenreplacing thefile name would result in just "~", "~/"is used instead (to avoid confusionbetweenoptions set to$HOME with'backupext' set to "~").Whenwriting the buffer, the defaultis to use the current file name. Thuswhen you give the "ZZ" or ":wq" command, the original file will beoverwritten. If youdo not want this, the buffer can be written into anotherfile by givinga file name argument to the ":write" command. For example:vim testfile[change the buffer with editor commands]:w newfile:qThis will createa file "newfile", thatisa modified copy of "testfile".The file "testfile" will remain unchanged. Anyway, if the'backup' optionisset, Vim renames or copies the original file beforeit will be overwritten.You can use this file if you discover that you need the original file. Seealso the'patchmode' option. The name of thebackup fileis normally the sameas the original file with'backupext' appended. The default "~"isa bitstrange to avoid accidentally overwriting existing files. If you prefer ".bak"change the'backupext' option. Extra dots are replaced with '_' onMS-Windowsmachines, when Vim has detected that an MS-DOS-like filesystemis being used(e.g., messydos or crossdos) or when the'shortname' optionis on. Thebackup file can be placed in another directory by setting'backupdir'.auto-shortnameTechnical: On theAmiga you can use 30 characters fora file name. But on an MS-DOS-compatible filesystem only 8 plus 3 characters are available. Vim tries to detect the type of filesystem whenitis creating the .swp file. If an MS-DOS-like filesystemis suspected,a flagis set that has the same effectas setting the'shortname' option. This flag will be resetas soonas you start editinga new file. The flag will be used when making the file name for the ".swp" and ".~" files for the current file. But when you are editinga file ina normal filesystem and write to an MS-DOS-like filesystem the flag will not have been set. In thatcase the creation of the ".~" file may fail and you will get an error message. Use the'shortname' option in this case.When you started editing without givinga file name, "No File"is displayed inmessages. If the ":write" commandis used witha file name argument, the filename for the current fileis set to that file name. This only happens whenthe 'F' flagis included in'cpoptions' (by defaultitis included)cpo-F.Thisis useful when entering text in an empty buffer and thenwritingit toafile. If'cpoptions' contains the 'f' flag (by defaultitis NOT included)cpo-f the file nameis set for the ":read file" command. Thisis usefulwhenstarting Vim without an argument and then doing ":read file" to starteditinga file.When the file name was set and'filetype'is empty thefiletype detectionautocommands will be triggered.not-editedBecause the file name was set without reallystarting to edit that file, youare protected from overwriting that file. Thisis done by setting the"notedited" flag. You can see if this flagis set with theCTRL-G or ":file"command. It will include "[Not edited]" when the "notedited" flagis set.Whenwriting the buffer to the current file name (with ":w!"), the "notedited"flagis reset.abandonVim remembers whether you have changed the buffer. You are protected fromlosing the changes you made. If you try to quit without writing, or want tostart editing another file, Vim will refuse this. In order to overrule thisprotection, adda '!' to the command. The changes will then be lost. Forexample: ":q" will not work if the buffer was changed, but ":q!" will. To seewhether the buffer was changed use the "CTRL-G" command. The message includesthestring "[Modified]" if the buffer has been changed, or "+" if the 'm' flagis in'shortmess'.If you want to automatically save the changes without asking, switch on the'autowriteall' option.'autowrite'is the associated Vi-compatible optionthat does not work for all commands.If you want to keep the changed buffer without saving it, switch on the'hidden' option. Seehidden-buffer. Some commands work like this even when'hidden'is not set, check thehelp for the command.==============================================================================2. Editinga fileedit-a-file:e:editreload:e[dit][++opt][+cmd]Edit the current file. Thisis useful to re-edit thecurrent file, whenit has been changed outside of Vim.This fails when changes have been made to the currentbuffer and'autowriteall' isn't set or the file can'tbe written.Also see++opt and+cmd.:edit!discard:e[dit]![++opt][+cmd]Edit the current file always. Discard any changes tothe current buffer. Thisis useful if you want tostart all over again.Also see++opt and+cmd.:edit_f:e[dit][++opt][+cmd]{file}Edit{file}.This fails when changes have been made to the currentbuffer, unless'hidden'is set or'autowriteall'isset and the file can be written.Also see++opt and+cmd.:edit!_f:e[dit]![++opt][+cmd]{file}Edit{file} always. Discard any changes to thecurrent buffer.Also see++opt and+cmd.:edit_#:e#:e[dit][++opt][+cmd] #[count]Edit the[count]th buffer (as shown by:files).This command does the sameas[count]CTRL-^. But ":e#" doesn't work if the alternate buffer doesn't haveafile name, whileCTRL-^ still works then.Also see++opt and+cmd.:ene:enew:ene[w]Edita new, unnamed buffer. This fails when changeshave been made to the current buffer, unless'hidden'is set or'autowriteall'is set and the file can bewritten.If'fileformats'is not empty, the first format givenwill be used for the new buffer. If'fileformats'isempty, the'fileformat' of the current bufferis used.:ene!:enew!:ene[w]!Edita new, unnamed buffer. Discard any changes tothe current buffer.Set'fileformat' like:enew.:fin:find:fin[d][!][++opt][+cmd]{file}Find{file} in'path' and then:edit it.:{count}fin[d][!][++opt][+cmd]{file}Just like ":find", but use the{count} match in'path'. Thus ":2find file" will find the second"file" found in'path'. When there are fewer matchesfor the file in'path' than asked for, you get anerror message.:ex:ex[++opt][+cmd][file]Sameas:edit.:vi:visual:vi[sual][!][++opt][+cmd][file]When used inEx mode: LeaveEx-mode,go back toNormal mode. Otherwise sameas:edit.:vie:view:vie[w][!][++opt][+cmd] fileWhen used inEx mode: LeaveEx-mode,go back toNormal mode. Otherwise sameas:edit, but set'readonly' option for this buffer.CTRL-^CTRL-6CTRL-^Edit the alternate file. Mostly the alternate fileisthe previously edited file. Thisisa quick way totoggle between two files. Itis equivalent to ":e#",except thatit also works when thereis no file name.If the'autowrite' or'autowriteall' optionis on andthe buffer was changed, write it.Mostly the^ characteris positioned on the 6 key,pressing CTRL and 6 then gets you what we callCTRL-^.But on some non-US keyboardsCTRL-^is produced inanother way.{count}CTRL-^Edit[count]th file in the bufferlist (equivalent to":e #[count]"). Thisisa quick way to switch betweenfiles.SeeCTRL-^ above for further details.[count]]f]f[f[count][fSameas "gf". Deprecated.gfE446E447[count]gfEdit the file whose nameis under or after the cursor.Mnemonic: "goto file".Uses the'isfname' option to find out which charactersare supposed to be ina file name. Trailingpunctuation characters ".,:;!" are ignored. Escapedspaces "\ " are reduced toa single space.Uses the'path' optionasalist of directory names tolook for the file. See the'path' option for detailsabout relative directories and wildcards.Uses the'suffixesadd' option to check for file nameswitha suffix added.If the file can't be found,'includeexpr'is used tomodify the name and another attemptis done.Ifa[count]is given, the count'th file thatis foundin the'path'is edited.This command fails if Vim refuses toabandon thecurrent file.If you want to edit the file ina newwindow useCTRL-W_CTRL-F.If youdo want to edita new file, use::e <cfile>To makegf always work like that::map gf :e <cfile><CR>If the nameisa hypertext link, that looks like"type://machine/path", you need thenetrw plugin.ForUnix the '~' characteris expanded, like in"~user/file". Environmentvariables are expanded tooexpand-env.v_gf{Visual}[count]gfSameas "gf", but the highlighted textis usedas thename of the file to edit.'isfname'is ignored.Leading blanks are skipped, otherwise all blanks andspecial characters are included in the file name.(For{Visual} seeVisual-mode.)gF[count]gFSameas "gf", except ifa number follows the filename, then the cursoris positioned on that line inthe file.The file name and the numbermust be separated byanon-filename (see'isfname') and non-numericcharacter. " line "is also recognized, likeitisused in the output of `:verbose command UserCmd`Whitespace between the filename, the separator andthe number are ignored.Examples:eval.c:10eval.c @ 20eval.c (30)eval.c 40v_gF{Visual}[count]gFSameas "v_gf".These commands are used to start editinga single file. This means that thefileis read into the buffer and the current file nameis set. The file thatis opened depends on the current directory, see:cd.Seeread-messages for an explanation of the message thatis given after thefile has been read.You can use the ":e!" command if you messed up the buffer and want to startall over again. The ":e" commandis only useful if you have changed thecurrent file name.:filename{file}Besides the things mentioned here, more special items for wherea filenameisexpected are mentionedatcmdline-special.Note for systems other than Unix: When usinga command that acceptsa singlefile name (like ":edit file") spaces in the file name are allowed, buttrailing spaces are ignored. Thisis useful on systems that regularly embedspaces in file names (likeMS-Windows and the Amiga). Example: The command":e Long File Name " will edit the file "Long File Name". When usingacommand that accepts more than one file name (like ":next file1 file2")embedded spacesmust be escaped witha backslash.wildcardwildcardsWildcards in{file} are expanded, butas with file completion,'wildignore'and'suffixes' apply. Whichwildcards are supported depends on the system.These are the common ones:?matches one character*matches anything, including nothing**matches anything, including nothing, recurses into directories[abc]match 'a', 'b' or 'c'To avoid the special meaning of thewildcards prependa backslash. However,onMS-Windows thebackslashisa path separator and "path\[abc]"is still seenasawildcard when "["is in the'isfname' option.A simple way to avoid thisis to use "path\[[]abc]", this matches the file "path\[abc]".starstar-wildcardExpanding "**"is possible on Unix, Win32, macOS anda few other systems (butit may depend on your'shell' setting onUnix and macOS. It's known to workcorrectly for zsh; for bash this requiresat least bash version >= 4.X).This allows searchinga directory tree. This goes up to 100 directories deep.Note there are some commands where this works slightly differently, seefile-searching.Example::n **/*.txtFinds files:aaa.txtsubdir/bbb.txta/b/c/d/ccc.txtWhen non-wildcard characters are used right before or after "**" these areonly matched in the top directory. They are not used for directories furtherdown in the tree. For example::n /usr/inc**/types.hFinds files:/usr/include/types.h/usr/include/sys/types.h/usr/inc/old/types.hNote that the path with "/sys"is included becauseit does not need to match"/inc". Thus it's like matching "/usr/inc*/*/*...", not"/usr/inc*/inc*/inc*".backtick-expansion`-expansionOnUnix anda few other systems you can also use backticks for the file nameargument, for example::next `find . -name ver\\*.c -print`:view `ls -t *.patch \| head -n1`Vim will run the command in backticks using the'shell' and use the standardoutputas argument for the given Vim command (errormessages from the shellcommand will be discarded).To see what shell command Vimis running, set the'verbose' option to 4. Whenthe shell command returnsa non-zero exit code, an error message will bedisplayed and the Vim command will be aborted. To avoid this make the shellalways return zero like so: :next `find . -name ver\\*.c -print \|\| true`The backslashes before thestar are required to prevent the shell fromexpanding "ver*.c" prior to execution of the find program. Thebackslashbefore the shell pipe symbol "|" prevents Vim from parsingitas commandtermination.This also works for most other systems, with the restriction that thebackticksmust be around the whole item. Itis not possible to have textdirectly before the first or just after the last backtick.`=E1083You can have the backticks expandedasa Vim expression, instead ofas anexternal command, by putting an equal sign right after the first backtick,e.g.::e `=tempname()`Theexpression can contain just about anything, thus this can also be used toavoid the special meaning of'"','|', '%' and '#'. However,'wildignore'does apply like to other wildcards.Environmentvariables in theexpression are expanded when evaluating theexpression, thus this works::e `=$HOME .. '/.vimrc'`This uses$HOME insideastring andit will be used literally, most likely notwhat you intended::e `='$HOME' .. '/.vimrc'`If theexpression returnsastring then names are to be separated with linebreaks. When the resultisaList then each itemis usedasa name. Linebreaks also separate names.Note that such expressions are only supported in places wherea filenameisexpectedas an argument to an Ex-command.++opt[++opt]The[++opt] argument can be used to force the value of'fileformat','fileencoding' or'binary' toa value for one command, and to specify thebehavior for bad characters. The form is:++{optname}Or:++{optname}={value}Where{optname}is one of:++ff++enc++bin++nobin++edit ff or fileformat overrides'fileformat' enc or encoding overrides'fileencoding' bin or binary sets'binary' nobin or nobinary resets'binary' badspecifies behavior for bad characters edit for:read only: keep option valuesas if editinga file{value} cannot contain white space. It can be any valid value for theseoptions. Examples::e ++ff=unixThis edits the same file again with'fileformat' set to "unix".:w ++enc=latin1 newfileThis writes the current buffer to "newfile" in latin1 format.The message given whenwritinga file will show "[converted]" when'fileencoding' or the value specified with++enc differs from'encoding'.There may be several++opt arguments, separated by white space. Theymust allappear before any+cmd argument.++badThe argument of "++bad="specifies what happens with characters that can't beconverted and illegal bytes. It can be one of three things: ++bad=XA single-byte character that replaces each bad character. ++bad=keep Keep bad characters without conversion.Note that this may result in illegal bytes in your text! ++bad=drop Remove the bad characters.The defaultis like "++bad=?":Replace each bad character witha questionmark. In some places an inverted questionmarkis used (0xBF).Note that not all commands use the++bad argument, even though theydo notgive an error when you add it. E.g.:write.Note that when reading, the'fileformat' and'fileencoding'options will beset to the used format. Whenwriting this doesn't happen, thusa next writewill use the old value of the option. Same for the'binary' option.+cmd[+cmd]The[+cmd] argument can be used to position the cursor in the newly openedfile, or execute any other command:+Startat the last line.+{num}Startat line{num}.+/{pat}Startat first line containing{pat}.+{command}Execute{command} after opening the new file.{command}is anyEx command.To includea whitespace in the{pat} or{command}, precedeit withabackslash. Double the number of backslashes.:edit +/The\ book file:edit +/dir\ dirname\\ file:edit +set\ dir=c:\\\\temp fileNote that in the last example the number of backslashesis halved twice: Oncefor the "+cmd" argument and once for the ":set" command.file-formatsThe'fileformat' option sets the<EOL> style fora file:'fileformat' characters name "dos"<CR><NL> or<NL>DOS formatDOS-format "unix"<NL>Unix formatUnix-format "mac"<CR>Mac formatMac-formatPreviously'textmode' was used. Itis obsolete now.When readinga file, the mentioned characters are interpretedas the<EOL>.InDOS format (default for Win32),<CR><NL> and<NL> are both interpretedasthe<EOL>.Note that whenwriting the file inDOS format,<CR> characterswill be added for each single<NL>. Also seefile-read.Whenwritinga file, the mentioned characters are used for<EOL>. ForDOSformat<CR><NL>is used. Also seeDOS-format-write.You can reada file inDOS format and writeit inUnix format. This willreplace all<CR><NL> pairs by<NL> (assuming'fileformats' includes "dos")::e file:set fileformat=unix:wIf you reada file inUnix format and write withDOS format, all<NL>characters will be replaced with<CR><NL> (assuming'fileformats' includes"unix")::e file:set fileformat=dos:wIf you start editinga new file and the'fileformats' optionis not empty(whichis the default), Vim will try to detect whether the lines in the fileare separated by the specified formats. When set to "unix,dos", Vim willcheck for lines witha single<NL> (as used onUnix and Amiga) or bya<CR><NL> pair (MS-Windows). Only when ALL linesend in<CR><NL>,'fileformat'isset to "dos", otherwiseitis set to "unix". When'fileformats' includes"mac", and no<NL> characters are found in the file,'fileformat'is set to"mac".If the'fileformat' optionis set to "dos" on non-MS-Windows systems themessage "[dos format]"is shown to remind you that something unusualishappening. OnMS-Windows systems you get the message "[unix format]" if'fileformat'is set to "unix". On all systems but theMacintosh you get themessage "[mac format]" if'fileformat'is set to "mac".If the'fileformats' optionis empty andDOS formatis used, but while readinga file some lines did notend in<CR><NL>, "[CR missing]" will be included inthe file message.If the'fileformats' optionis empty andMac formatis used, but while readinga filea<NL> was found, "[NL missing]" will be included in the file message.If the new file does not exist, the'fileformat' of the current bufferis usedwhen'fileformats'is empty. Otherwise the first format from'fileformats'isused for the new file.Before editing binary, executable or Vimscript files you should set the'binary' option.A simple way todo thisis bystarting Vim with the "-b"option. This will avoid the use of'fileformat'. Without this you risk thatsingle<NL> characters are unexpectedly replaced with<CR><NL>.You can encrypt files that are written by setting the'key' option. Thisprovides some security against others reading your files.encryptionEND OF LINE AND END OF FILEeol-and-eofVim has severaloptions tocontrol the file format:'fileformat'the<EOL> style: Unix, DOS,Mac'endofline'whether the last line ends witha<EOL>'endoffile'whether the file ends withaCTRL-Z'fixendofline'whether to fix eol and eofThe first three values are normally detected automatically when reading thefile and are used whenwriting the text toa file. While editing the bufferit looks like every line hasa line ending and theCTRL-Z isn't there (anexceptionis when'binary'is set,it works differently then).The'fixendofline' option can be used to choose what to write. You can alsochange the option values to write the file differently than howit was read.Here are some examples how to use them.If you want files inUnix format (every line NL terminated):setl ff=unix fixeolYou should probablydo this on any Unix-like system. Also modernMS-Windowssystems tend to work well with this. Itis recommended to always use thisformat for Vim scripts.If you want to use an oldMS-DOS file ina modern environment, fixing lineendings and droppingCTRL-Z, but keeping the<CR><NL> style<EOL>:setl ff=dos fixeolThisis useful for manyMS-Windows programs, they regularly expect the<CR><NL> line endings.If you want to drop the final<EOL> and adda finalCTRL-Z (e.g. for an oldsystem like CP/M):setl ff=dos nofixeol noeol eofIf you want to preserve the fileformat exactly as-is, including any final<EOL> and finalCTRL-Z:setl nofixeol==============================================================================3. The argumentlistargument-listarglistIf you give more than one file name whenstarting Vim, thislistis rememberedas the argument list. You can jump to each file in this list.Do not confuse this with the buffer list, which you can see with the:buffers command. The argumentlist was already present in Vi, the bufferlistis new in Vim. Every file name in the argumentlist will also be presentin the bufferlist (unlessit was deleted with:bdel or:bwipe). But it'scommon that names in the bufferlist are not in the argument list.This subjectis introduced insection07.2 of the user manual.Thereis one global argument list, whichis used for allwindows by default.Itis possible to createa new argumentlist local toa window, see:arglocal.You can use the argumentlist with the following commands, and with theexpressionfunctionsargc() andargv(). These all work on the argumentlist of the current window.:ar:arg:args:ar[gs]Print the argument list, with the current file insquare brackets.:ar[gs][++opt][+cmd]{arglist}:args_fDefine{arglist}as the new argumentlist and editthe first one. This fails when changes have been madeand Vim does not want toabandon the current buffer.Also see++opt and+cmd.:ar[gs]![++opt][+cmd]{arglist}:args_f!Define{arglist}as the new argumentlist and editthe first one. Discard any changes to the currentbuffer.Also see++opt and+cmd.:[count]arge[dit][!][++opt][+cmd]{name} ..:arge:argeditAdd{name}s to the argumentlist and edit it.Thereis no check for duplicates,itis possible toadda file to the argumentlist twice:argded.Thisis like using:argadd and then:edit (withthe small exception that:edit does not change theargument list, so the argumentlist pointer isn'tchanged).Spaces in filenames have to be escaped with "\".[count]is used like with:argadd.If the current file cannot beabandoned{name}s willstill be added to the argument list, but won't beedited. No check for duplicatesis done.Also see++opt and+cmd.:[count]arga[dd]{name} ..:arga:argaddE479:[count]arga[dd]E1156Add the{name}s to the argument list. When{name}isomitted add the current buffer name to the argumentlist.If[count]is omitted, the{name}s are added justafter the current entry in the argument list.Otherwise they are added after the[count]'th file.If the argumentlistis "abc", and "b"is thecurrent argument, then these commands result in:commandnew argument list:argaddxa [b]xc:0argaddxxa [b]c:1argaddxax [b]c:$argaddxa [b]cxAnd after the last one::+2argaddya [b]cxyThereis no check for duplicates,itis possible toadda file to the argumentlist twice. You can use:argdedupe to fixit afterwards::argadd *.txt | argdedupeThe currently edited fileis not changed.Note: you can also use this method::args ## xThis will add the "x" item and sort the new list.:argded[upe]:argded:argdedupeRemove duplicate filenames from the argument list.If your current fileisa duplicate, your current filewill change to the original file index.:argd[elete]{pattern} ..:argd:argdeleteE480E610Delete files from the argumentlist that match the{pattern}s.{pattern}is used likea file pattern,seefile-pattern. "%" can be used to delete thecurrent entry.This command keeps the currently edited file, alsowhen it's deleted from the argument list.Example::argdel *.obj:[range]argd[elete]Delete the[range] files from the argument list.Example::10,$argdelDeletes arguments 10 and further, keeping 1-9.:$argdDeletes just the last one.:argd:.argdDeletes the current argument.:%argdRemoves all the files from the arglist.When the last number in the rangeis too high, up tothe last argumentis deleted.:argu:argument:[count]argu[ment][count][++opt][+cmd]Edit file[count] in the argument list. When[count]is omitted the current entryis used. This failswhen changes have been made and Vim does not want toabandon the current buffer.Also see++opt and+cmd.:[count]argu[ment]![count][++opt][+cmd]Edit file[count] in the argument list,discard anychanges to the current buffer. When[count]isomitted the current entryis used.Also see++opt and+cmd.:[count]n[ext][++opt][+cmd]:n:ne:nextE165E163Edit[count] next file. This fails when changes havebeen made and Vim does not want toabandon thecurrent buffer. Also see++opt and+cmd.:[count]n[ext]![++opt][+cmd]Edit[count] next file,discard any changes to thebuffer. Also see++opt and+cmd.:n[ext][++opt][+cmd]{arglist}:next_fSameas:args_f.:n[ext]![++opt][+cmd]{arglist}Sameas:args_f!.:[count]N[ext][count][++opt][+cmd]:Next:NE164Edit[count] previous file in argument list. Thisfails when changes have been made and Vim does notwant toabandon the current buffer.Also see++opt and+cmd.:[count]N[ext]![count][++opt][+cmd]Edit[count] previous file in argument list. Discardany changes to the buffer. Also see++opt and+cmd.:[count]prev[ious][count][++opt][+cmd]:prev:previousSameas :Next. Also see++opt and+cmd.:rew:rewind:rew[ind][++opt][+cmd]Start editing the first file in the argument list.This fails when changes have been made and Vim doesnot want toabandon the current buffer.Also see++opt and+cmd.:rew[ind]![++opt][+cmd]Start editing the first file in the argument list.Discard any changes to the buffer. Also see++optand+cmd.:fir:first:fir[st][!][++opt][+cmd]Other name for ":rewind".:la:last:la[st][++opt][+cmd]Start editing the last file in the argument list.This fails when changes have been made and Vim doesnot want toabandon the current buffer.Also see++opt and+cmd.:la[st]![++opt][+cmd]Start editing the last file in the argument list.Discard any changes to the buffer. Also see++optand+cmd.:wn:wnext:[count]wn[ext][++opt]Write current file and start editing the[count]next file. Also see++opt and+cmd.:[count]wn[ext][++opt]{file}Write current file to{file} and start editing the[count] next file, unless{file} already exists andthe'writeany' optionis off. Also see++opt and+cmd.:[count]wn[ext]![++opt]{file}Write current file to{file} and start editing the[count] next file. Also see++opt and+cmd.:[count]wN[ext][!][++opt][file]:wN:wNext:[count]wp[revious][!][++opt][file]:wp:wpreviousSameas :wnext, butgo to previous file instead ofnext.The[count] in the commands above defaults to one. For some commandsitispossible to use two counts. The last one (rightmost one)is used.If no[+cmd] argumentis present, the cursoris positionedat the last knowncursor position for the file. If'startofline'is set, the cursor will bepositionedat the first non-blank in the line, otherwise the last know columnis used. If thereis no last known cursor position the cursor will be in thefirst line (the last line inEx mode).{arglist}Thewildcards in the argumentlist are expanded and the file names are sorted.Thus you can use the command "vim *.c" to edit all theC files. From withinVim the command ":n *.c" does the same.Whitespaceis used to separate file names. Putabackslash beforeaspace ortab to includeit ina file name. E.g., to edit the single file "foobar"::next foo\ barOnUnix anda few other systems you can also use backticks, for example::next `find . -name \\*.c -print`The backslashes before thestar are required to prevent "*.c" to be expandedby the shell before executing the find program.arglist-positionWhen thereis an argumentlist you can see which file you are editing in thetitle of thewindow (if thereis one and'title'is on) and with the filemessage you get with the "CTRL-G" command. You will see something like(file 4 of 11)If'shortmess' contains 'f'it will be(4 of 11)If you are not really editing the fileat the current position in the argumentlistit will be(file (4) of 11)This means that you are position 4 in the argument list, but not editing thefourth file in the argument list. This happens when youdo ":e file".LOCAL ARGUMENT LIST:arglocal:argl[ocal]Makea local copy of the global argument list.Doesn't start editing another file.:argl[ocal][!][++opt][+cmd]{arglist}Definea new argument list, whichis local to thecurrent window. Works like:args_f otherwise.:argglobal:argg[lobal]Use the global argumentlist for the current window.Doesn't start editing another file.:argg[lobal][!][++opt][+cmd]{arglist}Use the global argumentlist for the current window.Definea new global argumentlist like:args_f.Allwindows using the global argumentlist will seethis new list.There can be several argument lists. They can be shared between windows.When they are shared,changing the argumentlist in onewindow will alsochangeit in the other window.Whenawindowis split the newwindow inherits the argumentlist from thecurrent window. The twowindows then share this list, until one of them uses:arglocal or:argglobal to use another argument list.USING THE ARGUMENT LIST:argdo:[range]argdo[!]{cmd}Execute{cmd} for each file in the argumentlist orif[range]is specified only for arguments in thatrange. It works like doing this::rewind:{cmd}:next:{cmd}etc.When the current file can't beabandoned and the [!]is not present, the command fails.When an erroris detected on one file, further filesin the argumentlist will not be visited.The last file in the argumentlist (or where an erroroccurred) becomes the current file.{cmd} can contain'|' to concatenate several commands.{cmd}must not change the argument list.Note: While this commandis executing, theSyntaxautocommand eventis disabled by addingit to'eventignore'. This considerably speeds up editingeach file.Also see:windo,:tabdo,:bufdo,:cdo,:ldo,:cfdo and:lfdoExample::args *.c:argdo set ff=unix | updateThis sets the'fileformat' option to "unix" and writes the file ifitis nowchanged. Thisis done for all *.c files.Example::args *.[ch]:argdo %s/\<my_foo\>/My_Foo/ge | updateThis changes theword "my_foo" to "My_Foo" in all *.c and *.h files. The "e"flagis used for the ":substitute" command to avoid an error for files where"my_foo" isn't used. ":update" writes the file only if changes were made.==============================================================================4. Writingwritingsave-fileNote: When the'write' optionis off, you are not able to write any file.:w:writeE502E503E504E505E512E514E667E949:w[rite][++opt]Write the whole buffer to the current file. Thisisthe normal way to save changes toa file. It failswhen the'readonly' optionis set or when thereisanother reason why the file can't be written.For++opt see++opt, but only ++bin, ++nobin,++ffand++enc are effective.:w[rite]![++opt]Like ":write", but forcefully write when'readonly'isset or thereis another reason whywriting wasrefused.Note: This may change the permission and ownership ofthe file and break (symbolic) links. Add the 'W' flagto'cpoptions' to avoid this.:[range]w[rite][!][++opt]Write the specified lines to the current file. Thisis unusual, because the file will not contain alllines in the buffer.:w_f:write_f:[range]w[rite][++opt]{file}Write the specified lines to{file}, unlessitalready exists and the'writeany' optionis off.:w!:[range]w[rite]![++opt]{file}Write the specified lines to{file}. Overwrite anexisting file.:w_a:write_aE494:[range]w[rite][!][++opt]>>Append the specified lines to the current file.:[range]w[rite][!][++opt]>>{file}Append the specified lines to{file}. '!' forces thewrite even if file does not exist.:w_c:write_c:[range]w[rite][++opt] !{cmd}Execute{cmd} with[range] linesas standard input(note thespace in front of the '!').{cmd}isexecuted like with ":!{cmd}", any '!'is replaced withthe previous command:!.The default[range] for the ":w" commandis the whole buffer (1,$). The'[and'] marks will be set to the[range] being used for the write command.If you write the whole buffer,itis no longer considered changed. When youwriteit toa different file with ":w somefile"it depends on the "+" flag in'cpoptions'. When included, the write command will reset the'modified' flag,even though the buffer itself may still be different from its file.Ifa file nameis given with ":w"it becomes the alternate file. This can beused, for example, when the write fails and you want to try again later with":w#". This can be switched off by removing the 'A' flag from the'cpoptions' option.Note that the'fsync' option matters here. If it's setit may make writesslower (but safer).:sav:saveas:sav[eas][!][++opt]{file}Save the current buffer under the name{file} and setthe filename of the current buffer to{file}. Theprevious nameis used for the alternate file name.The [!]is needed to overwrite an existing file.When'filetype'is emptyfiletype detectionis donewith the new name, before the fileis written.When the write was successful'readonly'is reset.:up:update:[range]up[date][!][++opt] [>>][file]Like ":write", but only write when the buffer has beenmodified.WRITING WITH MULTIPLE BUFFERSbuffer-write:wa:wall:wa[ll]Write all changed buffers. Buffers withouta filename cause an error message. Buffers which arereadonly are not written.:wa[ll]!Write all changed buffers, even the ones that arereadonly. Buffers withouta file name are notwritten and cause an error message.Vim will warn you if you try to overwritea file that has been changedelsewhere. Seetimestamp.backupE207E506E507E508E509E510If you write to an existing file (butdo not append) while the'backup','writebackup' or'patchmode' optionis on,abackup of the original fileismade. The fileis either copied or renamed (see'backupcopy'). After thefile has been successfully written and when the'writebackup' optionis on andthe'backup' optionis off, thebackup fileis deleted. When the'patchmode'optionis on thebackup file may be renamed.backup-table'backup' 'writebackup'action off offnobackup made off onbackup current file, deleted afterwards (default) on offdelete old backup,backup current file on ondelete old backup,backup current fileWhen the'backupskip'pattern matches with the name of the file whichiswritten, nobackup fileis made. The values of'backup' and'writebackup' areignored then.When the'backup' optionis on, an oldbackup file (with the same nameas thenewbackup file) will be deleted. If'backup'is not set, but'writebackup'is set, an existingbackup file will not be deleted. Thebackup file thatismade while the fileis being written will havea different name.On some filesystems it's possible that ina crash you lose both thebackup andthe newly written file (it might be there but contain bogus data). In thatcase try recovery, because the swap fileis synced to disk and might still bethere.:recoverThe directories given with the'backupdir' option are used toput thebackupfile in. (default: same directoryas the written file).Whether thebackupisa new file, whichisa copy of the original file, or theoriginal file renamed depends on the'backupcopy' option. See there for anexplanation of when the copyis made and when the fileis renamed.If the creation ofabackup file fails, the writeis not done. If you wantto write anyway adda '!' to the command.file-watcherWhen you notice issues with programs, that act upon whena bufferis written(like inotify, entr or fswatch) or when external applications execute Vim toedit the file (like git) and those programsdo not seem to notice that theoriginal file has been changed, you may want to consider switching the'backupcopy' option value to "yes". This makes sure, Vim writes to the samefile, that those watcher programs expect, without creatinga new file (whichprevents them from detecting that the file has changed). See alsocrontabwrite-permissionsWhenwritinga new file the permissions are read-write. Forunix the maskis0o666 with additionally umask applied. Whenwritinga file that was read Vimwill preserve the permissions, but clear the s-bit.write-readonlyWhen the'cpoptions' option contains 'W', Vim will refuse to overwriteareadonly file. When 'W'is not present, ":w!" will overwritea readonly file,if the system allowsit (the directorymust be writable).write-failIf thewriting of the new file fails, you have to be careful not to loseyour changes AND the original file. If thereis nobackup file andwritingthe new file failed, you have already lost the original file! DON'T EXIT VIMUNTIL YOU WRITE OUT THE FILE! Ifabackup was made,itisput back in placeof the original file (if possible). If you exit Vim, and lose the changesyou made, the original file will mostly still be there. If putting back theoriginal file fails, there will be an error message telling you that youlost the original file.DOS-format-writeIf the'fileformat'is "dos",<CR><NL>is used for<EOL>. Thisis defaultfor Win32. On other systems the message "[dos format]"is shown to remind youthat an unusual<EOL> was used.Unix-format-writeIf the'fileformat'is "unix",<NL>is used for<EOL>. OnWin32 the message"[unix format]"is shown.Mac-format-writeIf the'fileformat'is "mac",<CR>is used for<EOL>. On non-Mac systems themessage "[mac format]"is shown.See alsofile-formats and the'fileformat' and'fileformats' options.ACLACL stands for Access Control List. Itis an advanced way tocontrol accessrights fora file. Itis used on newMS-Windows andUnix systems, but onlywhen the filesystem supports it. Vim attempts to preserve theACL info whenwritinga file. Thebackup filewill get theACL info of the original file. TheACL infois also used to check ifa fileis read-only (when opening thefile).xattrE1506E1508E1509xattr stands for Extended Attributes. Itis an advanced way to save metadataalongside the file in the filesystem. It depends on the actual filesystembeing used and Vim supportsit only ona Linux system. Vim attempts to preserve the extended attribute info whenwritinga file.Thebackup file will get the extended attribute of the original file.read-only-shareWhenMS-Windows sharesa drive on thenetworkit can be markedas read-only.This means that even if the file read-only attributeis absent, and theACLsettings on NTnetwork shared drives allowwriting to the file, you can stillnot write to the file. Vim onWin32 platforms will detect read-onlynetworkdrives and willmark the fileas read-only. You will not be able to overrideit with:write.write-deviceWhen the file nameis actuallya device name, Vim will not makeabackup (thatwould be impossible). You need to use "!", since the device already exists.Example for Unix::w! /dev/lpt0and for MS-Windows::w! lpt0ForUnixa deviceis detected when the name doesn't refer toa normal file ora directory.A fifo or named pipe also looks likea device to Vim.ForMS-Windows the deviceis detected by its name:AUXCONCLOCK$NULPRNCOMnn=1,2,3... etcLPTnn=1,2,3... etcThe names can be in upper- or lowercase.==============================================================================5. Writing and quittingwrite-quit:q:quit:q[uit]Quit the current window. Quit Vim if thisis the lastedit-window. This fails when changes have been madeand Vim refuses toabandon the current buffer, andwhen the last file in the argumentlist has not beenedited.If there are othertab pages and quitting the lastwindow in the currenttab page the currenttab pageisclosedtab-page.Triggers theQuitPreautocommand event.SeeCTRL-W_q for quitting another window.:conf[irm] q[uit]Quit, but give prompt when changes have been made, orthe last file in the argumentlist has not beenedited. See:confirm and'confirm'.:q[uit]!Quit without writing, also when the current buffer haschanges. The bufferis unloaded, also whenit has'hidden' set.If thisis the lastwindow and thereisa modifiedhidden buffer, the current bufferis abandoned and thefirst changed hidden buffer becomes the currentbuffer.Use ":qall!" to exit always.:cq[uit]Quit always, without writing, and return an errorcode. See:cq. Used for Manx's QuickFix mode (seequickfix).:wq:wq[++opt]Write the current file and close the window. If thiswas the lastedit-window Vim quits.Writing fails when the fileis read-only or the bufferdoes not havea name. Quitting fails when the lastfile in the argumentlist has not been edited.:wq![++opt]Write the current file and close the window. If thiswas the lastedit-window Vim quits. Writing failswhen the current buffer does not havea name.:wq[++opt]{file}Write to{file} and close the window. If this was thelastedit-window Vim quits. Quitting fails when thelast file in the argumentlist has not been edited.:wq![++opt]{file}Write to{file} and close the current window. QuitVim if this was the lastedit-window.:[range]wq[!][++opt][file]Sameas above, but only write the lines in[range].:x:xit:[range]x[it][!][++opt][file]Like ":wq", but write only when changes have beenmade.When'hidden'is set and there are more windows, thecurrent buffer becomes hidden, afterwriting the file.This commandis not supported inVim9 script,becauseitis too easily confused witha variablename.:exi:exit:[range]exi[t][!][++opt][file]Sameas :xit.ZZZZWrite current file, if modified, and close the currentwindow (sameas ":x").If there are severalwindows for the current file,only the currentwindowis closed.ZQZQQuit without checking for changes (sameas ":q!").MULTIPLE WINDOWS AND BUFFERSwindow-exit:qa:qall:qa[ll]Exit Vim, unless there are somebuffers which have beenchanged. (Use ":bmod" togo to the next modified buffer).When'autowriteall'is set all changedbuffers will bewritten, like:wqall.:conf[irm] qa[ll]Exit Vim. Bring upa prompt when somebuffers have beenchanged. See:confirm.:qa[ll]!Exit Vim. Any changes tobuffers are lost.Also see:cquit,it does the same but exits witha non-zerovalue.:quita:quitall:quita[ll][!]Sameas ":qall".:wqa[ll][++opt]:wqa:wqall:xa:xall:xa[ll]Write all changedbuffers and exit Vim. If there arebufferswithouta file name, which are readonly or which cannot bewritten for another reason, Vim will not quit.:conf[irm] wqa[ll][++opt]:conf[irm] xa[ll]Write all changedbuffers and exit Vim. Bring upa promptwhen somebuffers are readonly or cannot be written foranother reason. See:confirm.:wqa[ll]![++opt]:xa[ll]!Write all changed buffers, even the ones that are readonly,and exit Vim. If there arebuffers withouta file name orwhich cannot be written for another reason, or thereisaterminal witha running job, Vim will not quit.==============================================================================6. Dialogsedit-dialogs:confirm:conf:conf[irm]{command}Execute{command}, and useadialog when anoperation has to be confirmed. Can be used on the:q,:qa and:w commands (the latter to overridea read-only setting), and any other command that canfail in sucha way, suchas:only,:buffer,:bdelete, etc.Examples: :confirm w fooWill ask for confirmation when "foo" already exists. :confirm qWill ask for confirmation when there are changes. :confirm qaIf any modified, unsavedbuffers exist, you will be prompted to saveorabandon each one. There are also choices to "save all" or "abandonall".If you want to always use ":confirm", set the'confirm' option.:browse:broE338:bro[wse]{command}Opena file selectiondialog for an argument to{command}. At present this works for:e,:w,:wall,:wq,:wqall,:x,:xall,:exit,:view,:sview,:r,:saveas,:sp,:mkexrc,:mkvimrc,:mksession,:mkview,:split,:vsplit,:tabe,:tabnew,:cfile,:cgetfile,:caddfile,:lfile,:lgetfile,:laddfile,:diffsplit,:diffpatch,:open,:pedit,:redir,:source,:update,:visual,:vsplit,and:qall if'confirm'is set.{only in Win32, Motif,GTK andMac GUI, inconsole `browse edit` works if theFileExplorerautocommand group exists}When ":browse"is not possible you get an errormessage. If the+browse featureis missing or the{command} doesn't support browsing, the{command}isexecuted withouta dialog.":browse set" works like:options.See also:oldfiles for ":browse oldfiles".Thesyntaxis best shown via some examples::browse e $vim/fooOpen the browser in the $vim/foo directory, and edit thefile chosen.:browse eOpen the browser in the directory specified with'browsedir',and edit the file chosen.:browse wOpen the browser in the directory of the current buffer,with the current buffer filenameas default, and save thebuffer under the filename chosen.:browse w C:/barOpen the browser in the C:/bar directory, with the currentbuffer filenameas default, and save the buffer under thefilename chosen.Also see the'browsedir' option.For versions of Vim where browsingis not supported, the commandis executedunmodified.browsefilterForMS-Windows and GTK, you can modify the filters that are used in the browsedialog. By setting the g:browsefilter or b:browsefilter variables, you canchange the filters globally or locally to the buffer. The variableis set toastring in the format "{filter label}\t{pattern};{pattern}\n" where {filterlabel}is the text that appears in the "Files of Type" comboBox, and{pattern}is thepattern which filters the filenames. Several patterns can be given,separated by ';'.ForMotif the same formatis used, but only the very firstpatternis actuallyused (Motif only offers one pattern, but you can edit it).For example, to have only Vim files in the dialog, you could use the followingcommand: let g:browsefilter = "Vim scripts\t*.vim\nVim Startup Files\t*vimrc\n"You can override thefilter setting ona per-buffer basis by setting theb:browsefilter variable. You would most likely set b:browsefilter inafiletype plugin, so that the browsedialog would contain entries related tothe type of file you are currently editing. Disadvantage: This makesitdifficult to start editinga file ofa different type. To overcome this, youmay want to add "All Files(*.*)\t*\n"as the finalfilter on Windows or "AllFiles(*)\t*\n" on other platforms, so that the user can still access anydesired file.To avoid settingbrowsefilter when Vim does not actually support it, you canuse has("browsefilter"):if has("browsefilter") let g:browsefilter = "whatever"endif==============================================================================7. The current directorycurrent-directoryYou can use the:cd,:tcd and:lcd commands to change to anotherdirectory, so you will not have to type that directory name in front of thefile names. It also makesa difference for executing external commands, e.g.":!ls".Changing directory fails when the current bufferis modified, the '.' flagispresent in'cpoptions' and "!"is not used in the command.:cdE747E472:cd[!]On non-Unix systems when'cdhome'is off: Print thecurrent directory name.Otherwise: Change the current directory to thehomedirectory. Clear any window-local directory.Use:pwd to print the current directory on allsystems.:cd[!]{path}Change the current directory to{path}.If{path}is relative,itis searched for in thedirectories listed in'cdpath'.Clear any window-local directory.Does not change the meaning of an already opened file,because its full path nameis remembered. Files fromthearglist may change though!OnMS-Windows this also changes the active drive.To change to the directory of the current file::cd %:h:cd-E186:cd[!]-Change to the previous current directory (before theprevious ":cd{path}" command).:chd:chdir:chd[ir][!][path]Sameas:cd.:tc:tcd:tc[d][!]{path}Like:cd, but only set the directory for the currenttab. The currentwindow will also use this directory.The current directoryis not changed forwindows inother tabs and forwindows in the currenttab thathave their own window-local directory.:tcd-:tc[d][!]-Change to the previous current directory, before thelast ":tcd{path}" command.:tch:tchdir:tch[dir][!]Sameas:tcd.:lc:lcd:lc[d][!]{path}Like:cd, but only set the current directory whenthe cursoris in the current window. The currentdirectory for otherwindowsis not changed, switchingto anotherwindow will stop using{path}.:lcd-:lcd[!]-Change to the previous current directory, before thelast ":lcd{path}" command.:lch:lchdir:lch[dir][!]Sameas:lcd.:pw:pwdE187:pw[d]Print the current directory name.Also seegetcwd().:pwd-verboseWhen'verbose'is non-zero,:pwd will also displaywhat scope the current directory was set. Example:" Set by :cd:verbose pwd[global] /path/to/current" Set by :lcd:verbose pwd[window] /path/to/current" Set by :tcd:verbose pwd[tabpage] /path/to/currentSo longas no:lcd or:tcd command has been used, allwindows share thesame current directory. Usinga command to jump to anotherwindow doesn'tchange anything for the current directory.Whena:lcd command has been used fora window, the specified directorybecomes the current directory for that window. Windows where the:lcdcommand has not been used stick to the global or tab-local current directory.When jumping to anotherwindow the current directoryis changed to the lastspecified local current directory. If none was specified, the global ortab-local current directoryis used. When creatinga newwindowit inheritsthe local directory of the current window.Whena:tcd command has been used foratab page, the specified directorybecomes the current directory for the currenttab page and the current window.The current directory of othertab pagesis not affected. When jumping toanothertab page, the current directoryis changed to the last specified localdirectory for thattab page. If the currenttab has no local current directorythe global current directoryis used.Whena:cd commandis used, the currentwindow andtab page will lose thelocal current directory and will use the global current directory from now on.After using:cd the full path name will be used for reading andwritingfiles. On some networked file systems this may cause problems. The result ofusing the full path nameis that the file names currently in use will remainreferring to the same file. Example: If you havea file a:test andadirectory a:vim the commands ":e test" ":cd vim" ":w" will overwrite the filea:test and not write a:vim/test. But if youdo ":w test" the file a:vim/testwill be written, because you gavea new file name and did not refer toafilename before the ":cd".==============================================================================8. Editing binary filesedit-binaryAlthough Vim was made to edit text files,itis possible to edit binaryfiles. The-b Vim argument (b for binary) makes Vimdo file I/O in binarymode, and sets someoptions for editing binary files ('binary' on,'textwidth'to 0,'modeline' off,'expandtab' off). Setting the'binary' option has thesame effect. Don't forget todo this before reading the file.There area few things to remember when editing binary files:- When editing executable files the number of bytesmust not change. Use only the "R" or "r" command to change text. Do not delete characters with "x" or by backspacing.- Set the'textwidth' option to 0. Otherwise lines will unexpectedly be split in two.- When there are not many<EOL>s, the lines will become very long. If you want to edita line that does not fit on the screen reset the'wrap' option. Horizontalscrollingis used then. Ifa line becomes too long (more than about 32767 bytes on the Amiga, much more on 32-bit and 64-bit systems, seelimits) you cannot edit that line. The line will be split when reading the file. Itis also possible that you get an "out of memory" error when reading the file.- Make sure the'binary' optionis set BEFORE loading the file. Otherwise both<CR><NL> and<NL> are considered toenda line and when the fileis written the<NL> will be replaced with<CR><NL>.-<Nul> characters are shown on the screenas ^@. You can enter them with "CTRL-VCTRL-@" or "CTRL-V 000"- Toinserta<NL> character in the file splita line. Whenwriting the buffer toa filea<NL> will be written for the<EOL>.- Vim normally appends an<EOL>at theend of the file if thereis none. Setting the'binary' option prevents this. If you want to add the final<EOL>, set the'endofline' option. You can also read the value of this option to see if there was an<EOL> for the last line (you cannot see this in the text).==============================================================================9. EncryptionencryptionVimis able to write files encrypted, and read them back. The encrypted textcannot be read without the right key.{only available when compiled with the |+cryptv| feature}E833The text in the swap file and theundo fileis also encrypted.E843However, thisis done block-by-block and may reduce the time needed to crackapassword. You can disable the swap file, but thena crash will cause you tolose your work. Theundo file can be disabled without too much disadvantage.:set noundofile:noswapfile edit secretsNote: The text in memoryis not encrypted.A system administrator may be ableto see your text while you are editing it. When filtering text with":!filter" or using ":w !command" the textis also not encrypted, this mayrevealit to others. The'viminfo' fileis not encrypted.You coulddo this to edit very secret text::set noundofile viminfo=:noswapfile edit secrets.txtKeep in mind that withouta swap file you risk losing your work in the eventofa crash ora power failure.WARNING: If you makea typo when entering the key and then write the file andexit, the text will be lost!The normal way to work with encryption,is to use the ":X" command, which willask you to entera key.A following write command will use that key toencrypt the file. If you later edit the same file, Vim will ask you to entera key. If you type the same keyas that was used for writing, the text willbe readable again. If you usea wrong key,it will bea mess.:X:XPrompt for anencryption key. The typingis done without showing theactual text, so that someone lookingat the display won't see it.The typed keyis stored in the'key' option, whichis used to encryptthe file whenitis written.The file will remain unchanged until you write it.Note that commandssuchas:xit andZZ will NOT write the file unless there are otherchanges.See also-x.The value of the'key'optionsis used when textis written. When the optionis not empty, the written file will be encrypted, using the valueas theencryption key.A magic numberis prepended, so that Vim can recognize thatthe fileis encrypted.To disable the encryption, reset the'key' option to an empty value::set key=You can use the'cryptmethod' option to select the type of encryption, use oneof these::setlocal cm=zip " weak method, backwards compatible:setlocal cm=blowfish " method with flaws, do not use:setlocal cm=blowfish2 " medium strong method:setlocal cm=xchacha20v2 " medium strong method using libsodiumDo this beforewriting the file. When reading an encrypted fileit will beset automatically to themethod used when that file was written. You canchange'cryptmethod' beforewriting that file to change the method.To set the default method, used for new files, use this in yourvimrcfile:set cm=blowfish2Using "blowfish2"is highly recommended. Only use anothermethod if youmust use an olderVim version that does not support it.The message given for reading andwritinga file will show "[crypted]" whenusing zip, "[blowfish]" when using blowfish, etc.Whenwriting anundo file, the same key andmethod will be used for the textin theundo file.persistent-undo.To test forblowfish support you can use these conditions:has('crypt-blowfish')has('crypt-blowfish2')This works since Vim 7.4.1099 whileblowfish support was added earlier.Thus the condition failing doesn't meanblowfishis not supported. You cantest forblowfish with:v:version >= 703And forblowfish2 with:v:version > 704 || (v:version == 704 && has('patch401'))If you are sure Vim includes patch 7.4.237a simpler check is:has('patch-7.4.401')E817E818E819E820Whenencryption does not work properly, you would be able to write your texttoa file and never be able to readit back. Thereforea testis performed tocheck if theencryption worksas expected. If you get one of theseerrorsdon't write the file encrypted! You need to rebuild the Vim binary to fixthis.E831 Thisis an internal error, "cannot happen". If you can reproduce it,please report to the developers.When readinga file that has been encrypted and the'key' optionis not empty,it will be used for decryption. If the valueis empty, you will be promptedto enter the key. If you don't entera key, or you enter the wrong key, thefileis edited without being decrypted. Thereis no warning about using thewrong key (this makes brute force methods to find the key more difficult).If want to start readinga file that usesa different key, set the'key'option to an empty string, so that Vim will prompt fora new one. Don't usethe ":set" command to enter the value, other people can read the command overyour shoulder.Since the value of the'key' optionis supposed to bea secret, its value cannever be viewed. You should not set this option inavimrc file.An encrypted file can be recognized by the "file" command, if you add theselines to "/etc/magic", "/usr/share/misc/magic" or wherever your system has the"magic" file: 0stringVimCrypt~Vim encrypted file >9string01- "zip" cryptmethod >9string02- "blowfish" cryptmethod >9string03- "blowfish2" cryptmethodNotes:- Encryptionis not possible when doing conversion with'charconvert'.- Text you copy or delete goes to the numbered registers. Theregisters can be saved in the .viminfo file, where they could be read. Change your'viminfo' option to be safe.- Someone can type commands in Vim when you walk away fora moment, he should not be able to get the key.- If you makea typing mistake when entering the key, you might not be able to get your text back!- If you type the key witha ":set key=value" command,it can be kept in the history, showing the'key' value inaviminfo file.- Thereis never 100% safety. Theencryption in Vim has not been tested for robustness.- The algorithm used for'cryptmethod' "zip"is breakable.A 4 character key in about one hour,a 6 character key in one day (ona Pentium 133 PC). This requires that you know some text thatmust appear in the file. An expert can breakit for any key. When the text has been decrypted, this also means that the key can be revealed, and other files encrypted with the same key can be decrypted.- Pkzip uses the sameencryptionas'cryptmethod' "zip", and US Govt has no objection to its export. Pkzip's public file APPNOTE.TXT describes this algorithm in detail.- The implementation of'cryptmethod' "blowfish" hasa flaw. Itis possible to crack the first 64 bytes ofa file and in some circumstances more of the file. Use ofitis not recommended, but it's still the strongestmethod supported by Vim 7.3 and 7.4. The "zip"methodis even weaker.- Vim originates from the Netherlands. Thatis where the sources come from. Thus theencryption codeis not exported from the USA.==============================================================================10. TimestampstimestamptimestampsVim remembers the modification timestamp, mode and size ofa file when youbegin editing it. Thisis used to avoid that you have two different versionsof the same file (without you knowing this).Aftera shell commandis run(:!cmdsuspend:read!K) timestamps,file modes and file sizes are compared for allbuffers ina window. Vim willrun any associatedFileChangedShellautocommands or displaya warning forany files that have changed. In theGUI this happens when Vim regains inputfocus.E321E462If you want to automaticallyreloada file whenit has been changed outside ofVim, set the'autoread' option. This doesn't workat the moment you write thefile though, only when the file wasn't changed inside of Vim.ignore-timestampIf youdo not want to be asked or automaticallyreload the file, you can usethis:set buftype=nofileOr, whenstartinggvim froma shell:gvim file.log -c "set buftype=nofile"Note that ifaFileChangedShellautocommandis defined you will not getawarning message or prompt. Theautocommandis expected to handle this.Thereis no warning fora directory (e.g., withnetrw-browse). But youdoget warned if you started editinga new file andit was createdasa directorylater.When Vim notices thetimestamp ofa file has changed, and the fileis beingedited ina buffer but has not changed, Vim checks if the contents of the fileis equal. Thisis done by reading the file again (intoa hidden buffer, whichis immediately deleted again) and comparing the text. If the textis equal,you will get no warning.If you don't get warned often enough you can use the following command.:checkt:checktime:checkt[ime]Check if anybuffers were changed outside of Vim.This checks and warns you if you wouldend up with twoversions ofa file.If thisis called from an autocommand,a ":global"command oris not typed the actual checkis postponeduntila moment the side effects (reloading the file)would be harmless.Each loaded bufferis checked for its associated filebeing changed. If the file was changed Vim will takeaction. If there are no changes in the buffer and'autoread'is set, the bufferis reloaded. Otherwise,you are offered the choice of reloading the file. Ifthe file was deleted you get an error message.If the file previously didn't exist you geta warningifit exists now.Oncea file has been checked thetimestampis reset,you will not be warned again.Syntax highlighting, marks,diff status,'fileencoding','fileformat' and'binary'optionsare not changed. Seev:fcs_choice toreload thesetoo (for example, ifa codeformatting tools haschanged the file).:[N]checkt[ime]{filename}:[N]checkt[ime] [N]Check thetimestamp ofa specific buffer. The buffermay be specified by name, number or witha pattern.E813E814Vim willreload the buffer if you chose to. Ifawindowis visible thatcontains this buffer, the reloading will happen in the context of this window.Otherwisea specialwindowis used, so that mostautocommands will work. Youcan't close this window.A few other restrictions apply. Bestis to makesure nothing happens outside of the current buffer. E.g., settingwindow-localoptions mayend up in the wrong window. Splitting the window,doing something there and closingit should be OK (if there are no sideeffects from other autocommands). Closing unrelatedwindows andbuffers willget you into trouble.Beforewritinga file thetimestampis checked. Ifit has changed, Vim willask if you really want to overwrite the file:WARNING: The file has been changed since reading it!!!Do you really want to write toit (y/n)?If you hit 'y' Vim will continuewriting the file. If you hit 'n' the writeisaborted. If you used ":wq" or "ZZ" Vim will not exit, you will get anotherchance to write the file.The message would normally mean that somebody has written to the file afterthe edit session started. This could be another person, in whichcase youprobably want to check if your changes to the file and the changes from theother person should be merged. Write the file under another name and check fordifferences (the "diff" program can be used for this).Itis also possible that you modified the file yourself, from another editsession or with another command (e.g.,afilter command). Then you will knowwhich version of the file you want to keep.The accuracy of the time check depends on the filesystem. OnUnixitisusually sub-second. With old file systems and onMS-Windowsitis normally onesecond. Usehas('nanotime') to check if sub-second time stamp checks areavailable.Thereis one situation where you get the message while thereis nothing wrong:OnaWin32 system on the day daylight saving time starts. Thereis somethingin theWin32 libraries that confuses Vim about the hour time difference. Theproblem goes away the next day.==============================================================================11. File Searchingfile-searchingThe file searchingis currently used for the'path','cdpath' and'tags'options, forfinddir() andfindfile(). Other commands usewildcardswhichis slightly different.There are three different types of searching:1) Downward search:starstar Downward search uses thewildcards'*','**' and possibly others supported by your operating system.'*' and'**' are handled inside Vim, so they work on all operating systems.Note that "**" only actsasa specialwildcard whenitisat the start ofa name. The usage of'*'is quite simple: It matches0 or more characters. Ina searchpattern this would be ".*".Note that the "."is not used for file searching.'**'is more sophisticated:- It ONLY matches directories.- It matches up to 30 directories deep by default, so you can useit tosearch an entire directory tree- The maximum number of levels matched can be given by appendinga numberto'**'.Thus '/usr/**2' can match:/usr/usr/include/usr/include/sys/usr/include/g++/usr/lib/usr/lib/X11....It does NOT match '/usr/include/g++/std'as this would be threelevels.The allowed number rangeis0 ('**0'is removed) to 100If the given numberis smaller than0it defaults to 30, if it'sbigger than 100 then 100is used. The system also hasa limit on thepath length, usually 256 or 1024 bytes.-'**' can only beat theend of the path or be followed bya pathseparator or bya number anda path separator. You can combine'*' and'**' in any order:/usr/**/sys/*/usr/*tory/sys/**/usr/**2/sys/*2) Upward search: Here you can givea directory and then search the directory tree upward fora file. You could give stop-directories to limit the upward search. The stop-directories are appended to the path (for the'path' option) or to the filename (for the'tags' option) witha ';'. If you want several stop-directories separate them with ';'. If you want no stop-directory("search upward till the root directory") just use ';'./usr/include/sys;/usr will search in: /usr/include/sys /usr/include /usr If you usea relative path the upward searchis started in Vim's current directory or in the directory of the current file (if the relative path starts with './' and 'd'is not included in'cpoptions'). If Vim's current pathis /u/user_x/work/release and youdo:set path=include;/u/user_x and then search fora file withgf the fileis searched in:/u/user_x/work/release/include/u/user_x/work/include/u/user_x/includeNote: If your'path' setting includesa non-existing directory, Vim will skip the non-existing directory, and also does not search in the parent of the non-existing directory if upwards searchingis used.3) Combined up/downward search: If Vim's current pathis /u/user_x/work/release and youdoset path=**;/u/user_x and then search fora file withgf the fileis searched in:/u/user_x/work/release/**/u/user_x/work/**/u/user_x/** BE CAREFUL! This might consumea lot of time,as the search of '/u/user_x/**' includes '/u/user_x/work/**' and '/u/user_x/work/release/**'. So '/u/user_x/work/release/**'is searched three times and '/u/user_x/work/**'is searched twice. In the above example you might want to set path to::set path=**,/u/user_x/** This searches:/u/user_x/work/release/**/u/user_x/** This searches the same directories, but ina different order.Note that completion for ":find", ":sfind", and ":tabfind" commandsdo not currently work with'path' items that containa URL or use the doublestar with depth limiter (/usr/**2) or upward search (;) notations. vim:tw=78:ts=8:noet:ft=help:norl: