The operating system stores data permanently in named files, so most of the text you edit with Emacs comes from a file and is ultimately stored in a file.
To edit a file, you must tell Emacs to read the file and prepare a buffer containing a copy of the file’s text. This is called visiting the file. Editing commands apply directly to text in the buffer; that is, to the copy inside Emacs. Your changes appear in the file itself only when you save the buffer back into the file.
In addition to visiting and saving files, Emacs can delete, copy, rename, and append to files, keep multiple versions of them, and operate on file directories.
Many Emacs commands that operate on a file require you to specify the file name, using the minibuffer (see Minibuffers for File Names).
While in the minibuffer, you can use the usual completion and
history commands (see The Minibuffer). Note that file name completion
ignores file names whose extensions appear in the variable
completion-ignored-extensions (see Completion Options).
Note also that most commands use permissive completion with
confirmation for reading file names: you are allowed to submit a
nonexistent file name, but if you type RET immediately after
completing up to a nonexistent file name, Emacs prints
‘[Confirm]’ and you must type a second RET to confirm.
See Completion Exit, for details.
Minibuffer history commands offer some special features for reading file names, see Minibuffer History.
Each buffer has a default directory, stored in the
buffer-local variable default-directory. Whenever Emacs reads
a file name using the minibuffer, it usually inserts the default
directory into the minibuffer as the initial contents. You can
inhibit this insertion by changing the variable
insert-default-directory to nil (see Minibuffers for File Names). Regardless, Emacs always assumes that any relative file name
is relative to the default directory, e.g., entering a file name
without a directory specifies a file in the default directory.
When you visit a file, Emacs sets default-directory in the
visiting buffer to the directory of its file. When you create a new
buffer that is not visiting a file, via a command like C-x b,
its default directory is usually copied from the buffer that was
current at the time (see Creating and Selecting Buffers). You can use the command
M-x pwd to see the value of default-directory in the
current buffer. The command M-x cd prompts for a directory’s
name, and sets the buffer’s default-directory to that directory
(doing this does not change the buffer’s file name, if any).
As an example, when you visit the file /u/rms/gnu/gnu.tasks, the default directory is set to /u/rms/gnu/. If you invoke a command that reads a file name, entering just ‘foo’ in the minibuffer, with a directory omitted, specifies the file /u/rms/gnu/foo; entering ‘../.login’ specifies /u/rms/.login; and entering ‘new/foo’ specifies /u/rms/gnu/new/foo.
When typing a file name into the minibuffer, you can make use of a couple of shortcuts: a double slash ignores everything before the second slash in the pair, and ‘~/’ is your home directory. See Minibuffers for File Names.
The character ‘$’ is used to
substitute an environment variable into a file name. The name of the
environment variable consists of all the alphanumeric characters after
the ‘$’; alternatively, it can be enclosed in braces after the
‘$’. For example, if you have used the shell command
export FOO=rms/hacks to set up an environment variable named
FOO, then both /u/$FOO/test.c and
/u/${FOO}/test.c are abbreviations for
/u/rms/hacks/test.c. If the environment variable is not
defined, no substitution occurs, so that the character ‘$’ stands
for itself. Note that environment variables set outside Emacs affect
Emacs only if they are applied before Emacs is started.
To access a file with ‘$’ in its name, if the ‘$’ causes expansion, type ‘$$’. This pair is converted to a single ‘$’ at the same time that variable substitution is performed for a single ‘$’. Alternatively, quote the whole file name with ‘/:’ (see Quoted File Names). File names which begin with a literal ‘~’ should be quoted with ‘/:./’.
You can include non-ASCII characters in file names. See Coding Systems for File Names.
Visit a file (find-file).
Visit a file for viewing, without allowing changes to it
(find-file-read-only).
Visit a different file instead of the one visited last
(find-alternate-file).
Visit a file, in another window (find-file-other-window). Don’t
alter what is displayed in the selected window.
Visit a file, in a new frame (find-file-other-frame). Don’t
alter what is displayed in the selected frame.
Visit a file with no conversion of the contents.
Visiting a file means reading its contents into an Emacs buffer so you can edit them. Emacs makes a new buffer for each file that you visit.
To visit a file, type C-x C-f (find-file) and use the
minibuffer to enter the name of the desired file. While in the
minibuffer, you can abort the command by typing C-g. See File Names, for details about entering file names into minibuffers.
If the specified file exists but the system does not allow you to read it, an error message is displayed in the echo area (on GNU and Unix systems you might be able to visit such a file using the ‘su’ or ‘sudo’ methods; see Remote Files). Otherwise, you can tell that C-x C-f has completed successfully by the appearance of new text on the screen, and by the buffer name shown in the mode line (see The Mode Line). Emacs normally constructs the buffer name from the file name, omitting the directory name. For example, a file named /usr/rms/emacs.tex is visited in a buffer named ‘emacs.tex’. If there is already a buffer with that name, Emacs constructs a unique name; the normal method is to add a suffix based on the directory name (e.g., ‘<rms>’, ‘<tmp>’, and so on), but you can select other methods. See Making Buffer Names Unique.
To create a new file, just visit it using the same command, C-x C-f. Emacs displays ‘(New file)’ in the echo area, but in other respects behaves as if you had visited an existing empty file.
After visiting a file, the changes you make with editing commands are made in the Emacs buffer. They do not take effect in the visited file, until you save the buffer (see Saving Files). If a buffer contains changes that have not been saved, we say the buffer is modified. This implies that some changes will be lost if the buffer is not saved. The mode line displays two stars near the left margin to indicate that the buffer is modified.
If you visit a file that is already in Emacs, C-x C-f switches to the existing buffer instead of making another copy. Before doing so, it checks whether the file has changed since you last visited or saved it. If the file has changed, Emacs offers to reread it.
If you try to visit a file larger than
large-file-warning-threshold (the default is 10000000, which is
about 10 megabytes), Emacs asks you for confirmation first. You can
answer y to proceed with visiting the file or l to visit
the file literally (see below). Visiting large files literally speeds
up navigation and editing of such files, because various
potentially-expensive features are turned off. Note, however, that
Emacs cannot visit files that are larger than the maximum Emacs buffer
size, which is limited by the amount of memory Emacs can allocate and
by the integers that Emacs can represent (see Using Multiple Buffers). If you
try, Emacs displays an error message saying that the maximum buffer
size has been exceeded.
If you try to visit a file whose major mode (see Major Modes)
uses the tree-sitter parsing library, Emacs will display a warning if
the file’s size in bytes is larger than the value of the variable
treesit-max-buffer-size. The default value is 40 megabytes for
64-bit Emacs and 15 megabytes for 32-bit Emacs. This avoids the
danger of having Emacs run out of memory by preventing the activation
of major modes based on tree-sitter in such large buffers, because a
typical tree-sitter parser needs about 10 times as much memory as the
text it parses.
If the file name you specify contains shell-style wildcard
characters, Emacs visits all the files that match it. (On
case-insensitive filesystems, Emacs matches the wildcards disregarding
the letter case.) Wildcards include ‘?’, ‘*’, and
‘[…]’ sequences. To enter the wild card ‘?’ in a file
name in the minibuffer, you need to type C-q ?. See Quoted File Names, for information on how to visit a file whose name
actually contains wildcard characters. You can disable the wildcard
feature by customizing find-file-wildcards.
If you’re asking to visit a file that’s already visited in a buffer,
but the file has changed externally, Emacs normally asks you whether
you want to re-read the file from disk. But if you set
query-about-changed-file to nil, Emacs won’t query you,
but will instead just display the buffer’s contents before the
changes, and show an echo-area message telling you how to revert the
buffer from the file.
If you visit the wrong file unintentionally by typing its name
incorrectly, type C-x C-v (find-alternate-file) to visit
the file you really wanted. C-x C-v is similar to C-x
C-f, but it kills the current buffer (after first offering to save it
if it is modified). When C-x C-v reads the file name to visit,
it inserts the entire default file name in the buffer, with point just
after the directory part; this is convenient if you made a slight
error in typing the name.
If you visit a file that is actually a directory, Emacs invokes
Dired, the Emacs directory browser. See Dired, the Directory Editor. You can disable
this behavior by setting the variable find-file-run-dired to
nil; in that case, it is an error to try to visit a directory.
Files which are actually collections of other files, or file archives, are visited in special modes which invoke a Dired-like environment to allow operations on archive members. See File Archives, for more about these features.
If you visit a file that the operating system won’t let you modify,
or that is marked read-only, Emacs makes the buffer read-only too, so
that you won’t go ahead and make changes that you’ll have trouble
saving afterward. You can make the buffer writable with C-x C-q
(read-only-mode). See Miscellaneous Buffer Operations.
If you want to visit a file as read-only in order to protect
yourself from entering changes accidentally, visit it with the command
C-x C-r (find-file-read-only) instead of C-x C-f.
C-x 4 f (find-file-other-window) is like C-x C-f
except that the buffer containing the specified file is selected in another
window. The window that was selected before C-x 4 f continues to
show the same buffer it was already showing. If this command is used when
only one window is being displayed, that window is split in two
(see How display-buffer works), with one window showing the same buffer as
before, and the other one showing the newly requested file.
See Multiple Windows.
C-x 5 f (find-file-other-frame) is similar, but opens a
new frame, or selects any existing frame showing the specified file.
See Frames and Graphical Displays.
On graphical displays, there are two additional methods for visiting files. Firstly, when Emacs is built with a suitable GUI toolkit, commands invoked with the mouse (by clicking on the menu bar or tool bar) use the toolkit’s standard file selection dialog instead of prompting for the file name in the minibuffer. On GNU/Linux and Unix platforms, Emacs does this when built with GTK+, LessTif, and Motif toolkits; on MS-Windows and Mac, the GUI version does that by default. For information on how to customize this, see Using Dialog Boxes.
Secondly, Emacs supports drag and drop: dropping a file into an ordinary Emacs window visits the file using that window. As an exception, dropping a file into a window displaying a Dired buffer moves or copies the file into the displayed directory. For details, see Drag and Drop, and Other Dired Features.
On text-mode terminals and on graphical displays when Emacs was built without a GUI toolkit, you can visit files via the menu-bar ‘File’ menu, which has the ‘Visit New File’ and the ‘Open File’ items.
Each time you visit a file, Emacs automatically scans its contents to detect what character encoding and end-of-line convention it uses, and converts these to Emacs’s internal encoding and end-of-line convention within the buffer. When you save the buffer, Emacs performs the inverse conversion, writing the file to disk with its original encoding and end-of-line convention. See Coding Systems.
If you wish to edit a file as a sequence of ASCII
characters with no special encoding or conversion, use the M-x
find-file-literally command. This visits a file, like C-x C-f,
but does not do format conversion (see Format
Conversion in the Emacs Lisp Reference Manual), character code
conversion (see Coding Systems), or automatic uncompression
(see Accessing Compressed Files), and does not add a final newline because
of require-final-newline (see Customizing Saving of Files). If you have
already visited the same file in the usual (non-literal) manner, this
command asks you whether to visit it literally instead.
Files are sometimes (loosely) tied to other files, and you could call
these files sibling files. For instance, when editing C files,
if you have a file called ‘"foo.c"’, you often also have a file
called ‘"foo.h"’, and that could be its sibling file. Or you may
have different versions of a file, for instance
‘"src/emacs/emacs-27/lisp/allout.el"’ and
‘"src/emacs/emacs-28/lisp/allout.el"’ might be considered
siblings. Emacs provides the find-sibling-file command to jump
between sibling files, but it’s impossible to guess at which files a
user might want to be considered siblings, so Emacs lets you configure
this freely by altering the find-sibling-rules user option.
This is a list of match/expansion elements.
For instance, to do the ‘".c"’ to ‘".h"’ mapping, you could say:
(setq find-sibling-rules
'(("\\([^/]+\\)\\.c\\'" "\\1.h")))
(ff-find-related-file offers similar functionality especially
geared towards C files, see Other Commands for C Mode.)
Or, if you want to consider all files under ‘"src/emacs/DIR/file-name"’ to be siblings of other dirs, you could say:
(setq find-sibling-rules
'(("src/emacs/[^/]+/\\(.*\\)\\'" "src/emacs/.*/\\1")))
As you can see, this is a list of (MATCH EXPANSION...) elements. The match is a regular
expression that matches the visited file name, and each
expansion may refer to match groups by using ‘\\1’ and so
on. The resulting expansion string is then applied to the file system
to see if any files match this expansion (interpreted as a regexp).
Two special hook variables allow extensions to modify the operation
of visiting files. Visiting a file that does not exist runs the
functions in find-file-not-found-functions; this variable holds
a list of functions, which are called one by one (with no arguments)
until one of them returns non-nil. This is not a normal hook,
and the name ends in ‘-functions’ rather than ‘-hook’ to
indicate that fact.
Successful visiting of any file, whether existing or not, calls the
functions in find-file-hook, with no arguments. This variable
is a normal hook. In the case of a nonexistent file, the
find-file-not-found-functions are run first. See Hooks.
There are several ways to specify automatically the major mode for editing the file (see Choosing File Modes), and to specify local variables defined for that file (see Local Variables in Files).
Saving a buffer in Emacs means writing its contents back into the file that was visited in the buffer.
These are the commands that relate to saving and writing files.
Save the current buffer to its file (save-buffer).
Save any or all buffers to their files (save-some-buffers).
Forget that the current buffer has been changed (not-modified).
With prefix argument (C-u), mark the current buffer as changed.
Save the current buffer with a specified file name (write-file).
Change the file name under which the current buffer will be saved.
The same as M-x set-visited-file-name, but also rename the file the buffer is visiting (if any).
When you wish to save the file and make your changes permanent, type
C-x C-s (save-buffer). After saving is finished, C-x C-s
displays a message like this:
Wrote /u/rms/gnu/gnu.tasks
If the current buffer is not modified (no changes have been made in it since the buffer was created or last saved), saving is not really done, because it would have no effect. Instead, C-x C-s displays a message like this in the echo area:
(No changes need to be saved)
With a prefix argument, C-u C-x C-s, Emacs also marks the buffer to be backed up when the next save is done. See Backup Files.
The command C-x s (save-some-buffers) offers to save any
or all modified buffers. It asks you what to do with each buffer. The
possible responses are analogous to those of query-replace:
Save this buffer and ask about the rest of the buffers.
Don’t save this buffer, but ask about the rest of the buffers.
Save this buffer and all the rest with no more questions.
Terminate save-some-buffers without any more saving.
Save this buffer, then exit save-some-buffers without even asking
about other buffers.
Don’t save this buffer, and also mark it as unmodified.
This is like the not-modified command (see Commands for Saving Files).
View the buffer that you are currently being asked about. When you exit
View mode, you get back to save-some-buffers, which asks the
question again.
Exit save-some-buffers and visit the buffer that you are
currently being asked about.
Diff the buffer against its corresponding file, so you can see what
changes you would be saving. This calls the command
diff-buffer-with-file (see Comparing Files).
Display a help message about these options.
You can customize the value of
save-some-buffers-default-predicate to control which buffers
Emacs will ask about.
C-x C-c, the key sequence to exit Emacs, invokes
save-some-buffers and therefore asks the same questions.
If you have changed a buffer but do not wish to save the changes,
you should take some action to prevent it. Otherwise, each time you
use C-x s or C-x C-c, you are liable to save this buffer
by mistake. One thing you can do is type M-~
(not-modified), which clears out the indication that the buffer
is modified. If you do this, none of the save commands will believe
that the buffer needs to be saved. (‘~’ is often used as a
mathematical symbol for “not”; thus M-~ is “not”, metafied.)
Alternatively, you can cancel all the changes made since the file was
visited or saved, by reading the text from the file again. This is
called reverting. See Reverting a Buffer. (You could also undo all
the changes by repeating the undo command C-x u until you have
undone all the changes; but reverting is easier.)
M-x set-visited-file-name alters the name of the file that the
current buffer is visiting. It reads the new file name using the
minibuffer. Then it marks the buffer as visiting that file name, and
changes the buffer name correspondingly. set-visited-file-name
does not save the buffer in the newly visited file; it just alters the
records inside Emacs in case you do save later. It also marks the
buffer as modified so that C-x C-s in that buffer
will save.
If you wish to mark the buffer as visiting a different file and save
it right away, use C-x C-w (write-file). This is
equivalent to set-visited-file-name followed by C-x C-s,
except that C-x C-w asks for confirmation if the file exists.
C-x C-s used on a buffer that is not visiting a file has the
same effect as C-x C-w; that is, it reads a file name, marks the
buffer as visiting that file, and saves it there. The default file
name in a buffer that is not visiting a file is made by combining the
buffer name with the buffer’s default directory (see File Names).
If the new file name implies a major mode, then C-x C-w switches
to that major mode, in most cases. The command
set-visited-file-name also does this. See Choosing File Modes.
If you wish to save the current buffer to a different file without
visiting that file, use mark-whole-buffer (C-x h), then
M-x write-region (see Miscellaneous File Operations).
If Emacs is about to save a file and sees that the date of the latest version on disk does not match what Emacs last read or wrote, Emacs notifies you of this fact, because it probably indicates a problem caused by simultaneous editing and requires your immediate attention. See Simultaneous Editing.
On most operating systems, rewriting a file automatically destroys all record of what the file used to contain. Thus, saving a file from Emacs throws away the old contents of the file—or it would, except that Emacs carefully copies the old contents to another file, called the backup file, before actually saving.
Emacs makes a backup for a file only the first time the file is saved from the buffer that visits it. No matter how many times you subsequently save the file, its backup remains unchanged. However, if you kill the buffer and then visit the file again, a new backup file will be made.
For most files, the variable make-backup-files determines
whether to make backup files. On most operating systems, its default
value is t, so that Emacs does write backup files.
For files managed by a version control system (see Version Control), the variable vc-make-backup-files determines whether
to make backup files. By default it is nil, since backup files
are redundant when you store all the previous versions in a version
control system.
See General Options.
At your option, Emacs can keep either a single backup for each file, or make a series of numbered backup files for each file that you edit. See Single or Numbered Backups.
The default value of the backup-enable-predicate variable
prevents backup files being written for files in the directories used
for temporary files, specified by temporary-file-directory or
small-temporary-file-directory.
You can explicitly tell Emacs to make another backup file from a buffer, even though that buffer has been saved before. If you save the buffer with C-u C-x C-s, the version thus saved will be made into a backup file if you save the buffer again. C-u C-u C-x C-s saves the buffer, but first makes the previous file contents into a new backup file. C-u C-u C-u C-x C-s does both things: it makes a backup from the previous contents, and arranges to make another from the newly saved contents if you save again.
You can customize the variable backup-directory-alist to
specify that files matching certain patterns should be backed up in
specific directories. A typical use is to add an element ("."
. dir) to make all backups in the directory with absolute name
dir. Emacs modifies the backup file names to avoid clashes
between files with the same names originating in different
directories. Alternatively, adding, ("." . ".~") would make
backups in the invisible subdirectory .~ of the original file’s
directory. Emacs creates the directory, if necessary, to make the
backup.
When Emacs makes a backup file, its name is normally constructed by appending ‘~’ to the file name being edited; thus, the backup file for eval.c would be eval.c~.
If access control stops Emacs from writing backup files under the usual names, it writes the backup file as ~/.emacs.d/%backup%~. Only one such file can exist, so only the most recently made such backup is available.
Emacs can also make numbered backup files. Numbered backup file names contain ‘.~’, the number, and another ‘~’ after the original file name. Thus, the backup files of eval.c would be called eval.c.~1~, eval.c.~2~, and so on, all the way through names like eval.c.~259~ and beyond.
The variable version-control determines whether to make
single backup files or multiple numbered backup files. Its possible
values are:
nilMake numbered backups for files that have numbered backups already. Otherwise, make single backups. This is the default.
tMake numbered backups.
neverNever make numbered backups; always make single backups.
The usual way to set this variable is globally, through your init file
or the customization buffer. However, you can set
version-control locally in an individual buffer to control the
making of backups for that buffer’s file (see Local Variables). Some
modes, such as Rmail mode, set this variable. You can also have Emacs
set version-control locally whenever you visit a given file
(see Local Variables in Files).
If you set the environment variable VERSION_CONTROL, to tell
various GNU utilities what to do with backup files, Emacs also obeys the
environment variable by setting the Lisp variable version-control
accordingly at startup. If the environment variable’s value is ‘t’
or ‘numbered’, then version-control becomes t; if the
value is ‘nil’ or ‘existing’, then version-control
becomes nil; if it is ‘never’ or ‘simple’, then
version-control becomes never.
If you set the variable make-backup-file-name-function to
a suitable Lisp function, you can override the usual way Emacs
constructs backup file names.
To prevent excessive consumption of disk space, Emacs can delete numbered backup versions automatically. Generally Emacs keeps the first few backups and the latest few backups, deleting any in between. This happens every time a new backup is made.
The two variables kept-old-versions and
kept-new-versions control this deletion. Their values are,
respectively, the number of oldest (lowest-numbered) backups to keep
and the number of newest (highest-numbered) ones to keep, each time a
new backup is made. The backups in the middle (excluding those oldest
and newest) are the excess middle versions—those backups are
deleted. These variables’ values are used when it is time to delete
excess versions, just after a new backup version is made; the newly
made backup is included in the count in kept-new-versions. By
default, both variables are 2.
If delete-old-versions is t, Emacs deletes the excess
backup files silently. If it is nil, the default, Emacs asks
you whether it should delete the excess backup versions. If it has
any other value, then Emacs never automatically deletes backups.
Dired’s . (Period) command can also be used to delete old versions. See Flagging Many Files at Once.
Backup files can be made by copying the old file or by renaming it. This makes a difference when the old file has multiple names (hard links). If the old file is renamed into the backup file, then the alternate names become names for the backup file. If the old file is copied instead, then the alternate names remain names for the file that you are editing, and the contents accessed by those names will be the new contents.
The method of making a backup file may also affect the file’s owner and group. If copying is used, these do not change. If renaming is used, you become the file’s owner, and the file’s group becomes the default (different operating systems have different defaults for the group).
The choice of renaming or copying is made as follows:
backup-by-copying is non-nil (the
default is nil), use copying.
backup-by-copying-when-linked is
non-nil (the default is nil), and the file has multiple
names, use copying.
backup-by-copying-when-mismatch is
non-nil (the default is t), and renaming would change
the file’s owner or group, use copying.
If you change backup-by-copying-when-mismatch to nil,
Emacs checks the numeric user-id of the file’s owner and the numeric
group-id of the file’s group. If either is
no greater than backup-by-copying-when-privileged-mismatch, then it
behaves as though backup-by-copying-when-mismatch is
non-nil anyway.
When a file is managed with a version control system (see Version Control), Emacs does not normally make backups in the usual way for that file. But committing (a.k.a. checking in, see Concepts of Version Control) new versions of files is similar in some ways to making backups. One unfortunate similarity is that these operations typically break hard links, disconnecting the file name you visited from any alternate names for the same file. This has nothing to do with Emacs—the version control system does it.
Some file storage services support file versioning: they
record history of previous versions of files, and allow reverting to
those previous versions. If you want to be able to do that with files
hosted by those services when editing them with Emacs, customize
backup-by-copying to a non-nil value.
Copying the old file for backup is also useful when editing precious
files, because it makes sure the old file keeps its name if something
fails between the backup and the saving of your edits. Alternatively,
you can customize file-precious-flag to a non-nil value,
which implies backups by copying and also protects against I/O errors
while saving your edits.
If the value of the variable require-final-newline is
t, saving or writing a file silently puts a newline at the end
if there isn’t already one there. If the value is visit, Emacs
adds a newline at the end of any file that doesn’t have one, just
after it visits the file. (This marks the buffer as modified, and you
can undo it.) If the value is visit-save, Emacs adds such
newlines both on visiting and on saving. If the value is nil,
Emacs leaves the end of the file unchanged; any other non-nil
value means Emacs asks you whether to add a newline. The default is
nil.
Some major modes are designed for specific kinds of files that are
always supposed to end in newlines. Such major modes set the variable
require-final-newline to the value of
mode-require-final-newline, which defaults to t. By
setting the latter variable, you can control how these modes handle
final newlines.
If this option is non-nil and you’re visiting a file via a
symbolic link, Emacs will break the symbolic link upon saving the
buffer, and will write the buffer to a file with the same name as the
symbolic link, if the value of file-precious-flag is
non-nil (see file-precious-flag in The
Emacs Lisp Reference Manual). If you want Emacs to save the buffer
to the file the symbolic link points to (thereby preserving the link)
in these cases, customize the variable
file-preserve-symlinks-on-save to t.
Normally, when a program writes a file, the operating system briefly caches the file’s data in main memory before committing the data to secondary storage. Although this can greatly improve performance, it risks data loss if the system loses power before committing the cache, and on some platforms other processes might not immediately notice the file’s change.
To lessen this risk, Emacs can invoke the fsync system call
after saving a file. Using fsync does not eliminate the risk
of data loss or slow notification, partly because many systems do not support
fsync properly, and partly because Emacs’s file-saving
procedure typically relies also on directory updates that might not
survive a crash even if fsync works properly.
The write-region-inhibit-fsync variable controls whether
Emacs invokes fsync after saving a file. The variable’s
default value is t.
Emacs never uses fsync when writing auto-save files, as these
files might lose data anyway.
Simultaneous editing occurs when two users visit the same file, both make changes, and then both save them. If nobody is informed that this is happening, whichever user saves first would later find that their changes were lost.
On some systems, Emacs notices immediately when the second user starts to change the file, and issues an immediate warning. On all systems, Emacs checks when you save the file, and warns if you are about to overwrite another user’s changes. You can prevent loss of the other user’s work by taking the proper corrective action instead of saving the file.
When you make the first modification in an Emacs buffer that is visiting a file, Emacs records that the file is locked by you. (It does this by creating a specially-named symbolic link9 with special contents in the same directory. See (elisp)File Locks, for more details.) Emacs removes the lock when you save the changes. The idea is that the file is locked whenever an Emacs buffer visiting it has unsaved changes.
You can prevent the creation of lock files by setting the variable
create-lockfiles to nil. Caution: by
doing so you will lose the benefits that this feature provides. You
can also control where lock files are written by using the
lock-file-name-transforms variable.
If you begin to modify the buffer while the visited file is locked by
someone else, this constitutes a collision. When Emacs detects a
collision, it asks you what to do, by calling the Lisp function
ask-user-about-lock. You can redefine this function for the sake
of customization. The standard definition of this function asks you a
question and accepts three possible answers:
Steal the lock. Whoever was already changing the file loses the lock, and you gain the lock.
Proceed. Go ahead and edit the file despite its being locked by someone else.
Quit. This causes an error (file-locked), and the buffer
contents remain unchanged—the modification you were trying to make
does not actually take place.
If Emacs or the operating system crashes, this may leave behind lock files which are stale, so you may occasionally get warnings about spurious collisions. When you determine that the collision is spurious, just use p to tell Emacs to go ahead anyway.
Note that locking works on the basis of a file name; if a file has multiple names, Emacs does not prevent two users from editing it simultaneously under different names.
A lock file cannot be written in some circumstances, e.g., if Emacs lacks the system permissions or cannot create lock files for some other reason. In these cases, Emacs can still detect the collision when you try to save a file, by checking the file’s last-modification date. If the file has changed since the last time Emacs visited or saved it, that implies that changes have been made in some other way, and will be lost if Emacs proceeds with saving. Emacs then displays a warning message and asks for confirmation before saving; answer yes to save, and no or C-g cancel the save.
If you are notified that simultaneous editing has already taken place, one way to compare the buffer to its file is the M-x diff-buffer-with-file command. See Comparing Files.
You can prevent the creation of remote lock files by setting the
variable remote-file-name-inhibit-locks to t.
The minor mode lock-file-mode, called interactively, toggles
the local value of create-lockfiles in the current buffer.
You can arrange to keep identical shadow copies of certain files in more than one place—possibly on different machines. To do this, first you must set up a shadow file group, which is a set of identically-named files shared between a list of sites. The file group is permanent and applies to further Emacs sessions as well as the current one. Once the group is set up, every time you exit Emacs, it will copy the file you edited to the other files in its group. You can also do the copying without exiting Emacs, by typing M-x shadow-copy-files.
A shadow cluster is a group of hosts that share directories, so that copying to or from one of them is sufficient to update the file on all of them. Each shadow cluster has a name, and specifies the network address of a primary host (the one we copy files to), and a regular expression that matches the host names of all the other hosts in the cluster. You can define a shadow cluster with M-x shadow-define-cluster.
Set up file shadowing.
Declare a single file to be shared between sites.
Make all files that match each of a group of files be shared between hosts.
Define a shadow file cluster name.
Copy all pending shadow files.
Cancel the instruction to shadow some files.
To set up a shadow file group, use M-x shadow-define-literal-group or M-x shadow-define-regexp-group. See their documentation strings for further information.
Before copying a file to its shadows, Emacs asks for confirmation. You can answer “no” to bypass copying of this file, this time. If you want to cancel the shadowing permanently for a certain file, use M-x shadow-cancel to eliminate or change the shadow file group.
File Shadowing is not available on MS Windows.
Having a time stamp in the text of a file ensures that the time the file was written will be preserved even if the file is copied or transformed in a way that loses the file system’s modification time. A time stamp may also be called a date stamp or a last modified time. You can arrange to have a time stamp in a file update automatically each time you save the file.
There are two steps to setting up automatic time stamping. First, the file needs a time stamp template. By default, the template occurs somewhere in the first eight lines and looks like this:
Time-stamp: <>
or (your choice) like this:
Time-stamp: " "
With that template in place, you can update the current buffer’s time stamp once immediately with the command M-x time-stamp. The Emacs editor will check for a template; if a template is found, Emacs will write the current date, time, author, and/or other info between the angle brackets or quotes. After the first time stamp, the line might look like this:
Time-stamp: <1993-07-06 11:05:14 terryg>
Second, configure your Emacs to run time-stamp whenever it saves a
file, by adding time-stamp
to before-save-hook (see Hooks).
There are two ways to do this step: you can
before-save-hook, or
(add-hook 'before-save-hook 'time-stamp)
Now every time you save a file, Emacs will look for a time stamp.
If the buffer has no template, time-stamp does nothing;
any file that does have a time stamp will have it kept up to date
automatically.
To customize the time stamp in a particular file, set the
variable time-stamp-pattern in that file’s local variables
list (see Specifying File Variables).
You can change what pattern time-stamp will match against to
identify a template and where in the file to look for the pattern using
time-stamp-pattern; for details, see the variable’s built-in
documentation (with C-h v, see Help by Command or Variable Name).
As a simple example, suppose you want a manuscript to say the year and city of publication. You would like the year updated as you make revisions. You could have this line near the top of a file:
publishing_year_and_city = "Published nnnn in Boston, Mass.";
and the following comment at the end of the same file to tell
time-stamp how to identify and update that custom template:
// Local variables: // time-stamp-pattern: "Published %Y in Boston" // End:
This pattern says that the text before the start of the time stamp is
“Published ”, and the text after the end is “ in Boston”.
If time-stamp finds both the start and the end in one of the
first eight lines,
what is between will be updated as specified by the format, %Y in
this example. Since %Y requests the year, the result might look
like this:
publishing_year_and_city = "Published 2025 in Boston, Mass.";
By specifying a format of %Y, we get exactly the year
substituted; other parts of the default format (day, time and
author) are not part of this example pattern and so do not appear in the
result.
After changing the value of time-stamp-pattern
(or any file-local variable),
type M-x normal-mode so that Emacs notices.
Here is another example, with the time stamp inserted into
the last paragraph of an HTML document.
Since this template is at the end of the document, not in the first
eight lines, time-stamp-pattern starts with -10/ to tell
time-stamp to look at the last 10 lines.
The %% asks for the default format
(specified by time-stamp-format).
...
<p>Last modified: </p>
</body>
</html>
<!--
Local variables:
time-stamp-pattern: "-10/Last modified: %%</p>$"
End:
-->
By default the time stamp is
formatted according to your locale setting (see Environment Variables) and
time zone (see Time of Day in The Emacs Lisp Reference
Manual).
Set time-stamp-time-zone to override the time zone used.
See the built-in documentation for the variable time-stamp-format
for specifics on formatting and other variables that affect it.
If you are working on a file with multiple authors, and you cannot
be sure the other authors have enabled time-stamping globally in
their Emacs initialization files, you can force it to be enabled for a
particular file by adding time-stamp to that buffer’s
before-save-hook in that file’s local variables list.
To extend one of the previous examples:
// Local variables: // eval: (add-hook 'before-save-hook 'time-stamp nil t) // time-stamp-pattern: "Published %Y in Boston" // End:
Although this example shows them both set together,
you can use eval without also setting time-stamp-pattern
if you like the default pattern.
The extra arguments to add-hook used here, nil and t,
are necessary to have the added hook affect only this buffer.
If you have made extensive changes to a file-visiting buffer and then change your mind, you can revert the changes and go back to the saved version of the file. To do this, type C-x x g. Since reverting unintentionally could lose a lot of work, Emacs asks for confirmation first if the buffer is modified.
The revert-buffer command tries to position point in such a
way that, if the file was edited only slightly, you will be at
approximately the same part of the text as before. But if you have
made major changes, point may end up in a totally different location.
Reverting marks the buffer as not modified. However, it adds the reverted changes as a single modification to the buffer’s undo history (see Undo). Thus, after reverting, you can type C-/ or its aliases to bring the reverted changes back, if you happen to change your mind.
To revert a buffer more conservatively, you can use the command
revert-buffer-with-fine-grain. This command acts like
revert-buffer, but it tries to be as non-destructive as
possible, making an effort to preserve all markers, properties and
overlays in the buffer. Since reverting this way can be very slow
when you have made a large number of changes, you can modify the
variable revert-buffer-with-fine-grain-max-seconds to
specify a maximum amount of seconds that replacing the buffer
contents this way should take. Note that it is not ensured that the
whole execution of revert-buffer-with-fine-grain won’t take
longer than this.
Some kinds of buffers that are not associated with files, such as
Dired buffers, can also be reverted. For them, reverting means
recalculating their contents. Buffers created explicitly with
C-x b cannot be reverted; revert-buffer reports an error
if you try.
When you edit a file that changes automatically and frequently—for
example, a log of output from a process that continues to run—it may
be useful for Emacs to revert the file without querying you. To
request this behavior, set the variable revert-without-query to
a list of regular expressions. When a file name matches one of these
regular expressions, find-file and revert-buffer will
revert it automatically if it has changed—provided the buffer itself
is not modified. (If you have edited the text, it would be wrong to
discard your changes.)
The C-x x g keystroke is bound to the
revert-buffer-quick command. This is like the
revert-buffer command, but prompts less. Unlike
revert-buffer, it will not prompt if the current buffer visits
a file, and the buffer is not modified. It also respects the
revert-buffer-quick-short-answers user option. If this option
is non-nil, use a shorter y/n query instead of a longer
yes/no query.
You can also tell Emacs to revert buffers automatically when their visited files change on disk; see Auto Revert: Keeping buffers automatically up-to-date.
Note that reverting a buffer turns on the major mode appropriate for
visiting the buffer’s file, as described in Choosing File Modes. Thus,
the major mode actually turned on as result of reverting a buffer
depends on mode remapping, and could be different from the original mode
if you customized major-mode-remap-alist in-between.
The C-x x @ keystroke is bound to the
tramp-revert-buffer-with-sudo command. This visits the file
again, but with superuser, or root, permissions. If called with a
C-u prefix argument, it prompts for another Tramp method to use
other than the default, sudo. See Tramp in The Tramp Manual.
A buffer can get out of sync with respect to its visited file on disk if that file is changed by another program. To keep it up to date, you can enable Auto Revert mode by typing M-x auto-revert-mode. This automatically reverts the buffer when its visited file changes on disk. To do the same for all file buffers, type M-x global-auto-revert-mode to enable Global Auto Revert mode.
Auto Revert will not revert a buffer if it has unsaved changes, or if its file on disk is deleted or renamed.
One use of Auto Revert mode is to “tail” a file such as a system
log, so that changes made to that file by other programs are
continuously displayed. To do this, just move the point to the end of
the buffer, and it will stay there as the file contents change.
However, if you are sure that the file will only change by growing at
the end, use Auto Revert Tail mode instead
(auto-revert-tail-mode). It is more efficient for this.
Auto Revert Tail mode also works for remote files.
When a buffer is auto-reverted, a message is generated. This can be
suppressed by setting auto-revert-verbose to nil.
The Auto Revert modes do not check or revert remote files, because
that is usually too slow. This behavior can be changed by setting the
variable auto-revert-remote-files to non-nil.
By default, Auto Revert mode works using file notifications,
whereby changes in the filesystem are reported to Emacs by the OS.
You can disable use of file notifications by customizing the variable
auto-revert-use-notify to a nil value, then Emacs will
check for file changes by polling every five seconds. You can change
the polling interval through the variable auto-revert-interval.
Not all systems support file notifications; where they are not
supported, auto-revert-use-notify will be nil by
default.
By default, Auto Revert mode will poll files for changes
periodically even when file notifications are used. Polling is
unnecessary in many cases, and turning it off may save power by
relying on notifications only. To do so, set the variable
auto-revert-avoid-polling to non-nil. However,
notification is ineffective on certain file systems; mainly network
file system on Unix-like machines, where files can be altered from
other machines. For such file systems, polling may be necessary.
To force polling when
auto-revert-avoid-polling is non-nil, set
auto-revert-notify-exclude-dir-regexp to match files that
should be excluded from using notification.
In Dired buffers (see Dired, the Directory Editor), Auto Revert mode refreshes the buffer when a file is created or deleted in the buffer’s directory.
See Undoing Version Control Actions, for commands to revert to earlier versions of files under version control. See Version Control and the Mode Line, for Auto Revert peculiarities when visiting files under version control.
Global Auto Revert Mode normally only reverts file buffers. There are
two ways to auto-revert certain non-file buffers: by enabling Auto
Revert Mode in those buffers (using M-x auto-revert-mode); and
by setting global-auto-revert-non-file-buffers to a
non-nil value. The latter enables Auto Reverting for all types
of buffers for which it is implemented (listed in the menu below).
Like file buffers, non-file buffers should normally not revert while you are working on them, or while they contain information that might get lost after reverting. Therefore, they do not revert if they are modified. This can get tricky, because deciding when a non-file buffer should be marked modified is usually more difficult than for file buffers.
Another tricky detail is that, for efficiency reasons, Auto Revert often does not try to detect all possible changes in the buffer, only changes that are major or easy to detect. Hence, enabling auto-reverting for a non-file buffer does not always guarantee that all information in the buffer is up-to-date, and does not necessarily make manual reverts useless.
At the other extreme, certain buffers automatically revert every
auto-revert-interval seconds. (This currently only applies to
the Buffer Menu.) In this case, Auto Revert does not print any
messages while reverting, even when auto-revert-verbose is
non-nil.
Some non-file buffers can be updated reliably by file notification on
their default directory; Dired buffers is an example. The major mode
can indicate this by setting buffer-auto-revert-by-notification
to a non-nil value in that buffer, allowing Auto Revert to
avoid periodic polling. Such notification does not include changes to
files in that directory, only to the directory itself.
The details depend on the particular types of buffers and are explained in the corresponding sections.
If auto-reverting of non-file buffers is enabled, the Buffer Menu
(see Operating on Several Buffers)
automatically reverts every
auto-revert-interval seconds, whether there is a need for it or
not. (It would probably take longer to check whether there is a need
than to actually revert.)
If the Buffer Menu inappropriately gets marked modified, just revert it manually using g and auto-reverting will resume. However, if you marked certain buffers to get deleted or to be displayed, you have to be careful, because reverting erases all marks. The fact that adding marks sets the buffer’s modified flag prevents Auto Revert from automatically erasing the marks.
Dired buffers only auto-revert when the file list of the buffer’s main directory changes (e.g., when a new file is added or deleted). They do not auto-revert when information about a particular file changes (e.g., when the size changes) or when inserted subdirectories change. To be sure that all listed information is up to date, you have to manually revert using g, even if auto-reverting is enabled in the Dired buffer. Sometimes, you might get the impression that modifying or saving files listed in the main directory actually does cause auto-reverting. This is because making changes to a file, or saving it, very often causes changes in the directory itself; for instance, through backup files or auto-save files. However, this is not guaranteed.
If the Dired buffer is marked modified and there are no changes you want to protect, then most of the time you can make auto-reverting resume by manually reverting the buffer using g. There is one exception. If you flag or mark files, you can safely revert the buffer. This will not erase the flags or marks (unless the marked file has been deleted, of course). However, the buffer will stay modified, even after reverting, and auto-reverting will not resume. This is because, if you flag or mark files, you may be working on the buffer and you might not want the buffer to change without warning. If you want auto-reverting to resume in the presence of marks and flags, mark the buffer non-modified using M-~. However, adding, deleting or changing marks or flags will mark it modified again.
Remote Dired buffers are currently not auto-reverted. Neither are Dired buffers for which you used shell wildcards or file arguments to list only some of the files. *Find* and *Locate* buffers do not auto-revert either.
Note that auto-reverting Dired buffers may not work satisfactorily on some systems.
From time to time, Emacs automatically saves each visited file in a separate file, without altering the file you actually use. This is called auto-saving. It prevents you from losing more than a limited amount of work if the system crashes.
When Emacs determines that it is time for auto-saving, it considers
each buffer, and each is auto-saved if auto-saving is enabled for it
and it has been changed since the last time it was auto-saved. When
the auto-save-no-message variable is set to nil (the
default), the message ‘Auto-saving...’ is displayed in the echo
area during auto-saving, if any files are actually auto-saved; to
disable these messages, customize the variable to a non-nil
value. Errors occurring during auto-saving are caught so that they do
not interfere with the execution of commands you have been typing.
Auto-saving does not normally save in the files that you visited, because it can be very undesirable to save a change that you did not want to make permanent. Instead, auto-saving is done in a different file called the auto-save file, and the visited file is changed only when you request saving explicitly (such as with C-x C-s).
Normally, the auto-save file name is made by appending ‘#’ to the
front and rear of the visited file name. Thus, a buffer visiting file
foo.c is auto-saved in a file #foo.c#. Most buffers that
are not visiting files are auto-saved only if you request it explicitly;
when they are auto-saved, the auto-save file name is made by appending
‘#’ to the front and rear of buffer name, then
adding digits and letters at the end for uniqueness. For
example, the *mail* buffer in which you compose messages to be
sent might be auto-saved in a file named #*mail*#704juu. Auto-save file
names are made this way unless you reprogram parts of Emacs to do
something different (the functions make-auto-save-file-name and
auto-save-file-name-p). The file name to be used for auto-saving
in a buffer is calculated when auto-saving is turned on in that buffer.
The variable auto-save-file-name-transforms allows a degree
of control over the auto-save file name. It lets you specify a series
of regular expressions and replacements to transform the auto save
file name. The default value puts the auto-save files for remote
files (see Remote Files) into the temporary file directory on the
local machine.
When you delete a substantial part of the text in a large buffer, auto save turns off temporarily in that buffer. This is because if you deleted the text unintentionally, you might find the auto-save file more useful if it contains the deleted text. To reenable auto-saving after this happens, save the buffer with C-x C-s, or use C-u 1 M-x auto-save-mode.
If you want auto-saving to be done in the visited file rather than
in a separate auto-save file, enable the global minor mode
auto-save-visited-mode. In this mode, auto-saving is identical
to explicit saving. Note that this mode is orthogonal to the
auto-save mode described above; you can enable both at the same
time. However, if auto-save mode is active in some buffer and
the obsolete auto-save-visited-file-name variable is set to a
non-nil value, that buffer won’t be affected by
auto-save-visited-mode.
You can use the variable auto-save-visited-interval to
customize the interval between auto-save operations in
auto-save-visited-mode; by default it’s five seconds.
auto-save-interval and auto-save-timeout have no effect
on auto-save-visited-mode. See Controlling Auto-Saving, for
details on these variables.
A buffer’s auto-save file is deleted when you save the buffer in its
visited file. (You can inhibit this by setting the variable
delete-auto-save-files to nil.) Changing the visited
file name with C-x C-w or set-visited-file-name renames
any auto-save file to go with the new visited name.
Killing a buffer, by default, doesn’t remove the buffer’s auto-save
file. If kill-buffer-delete-auto-save-files is non-nil,
killing a buffer that has an auto-save file will make Emacs prompt the
user for whether the auto-save file should be deleted. (This is
inhibited if delete-auto-save-files is nil.)
Each time you visit a file, auto-saving is turned on for that file’s
buffer if the variable auto-save-default is non-nil (but
not in batch mode; see Initial Options). The default for this
variable is t, so auto-saving is the usual practice for
file-visiting buffers. To toggle auto-saving in the current buffer,
type M-x auto-save-mode. Auto Save mode acts as a buffer-local
minor mode (see Minor Modes).
Emacs auto-saves periodically based on how many characters you have
typed since the last auto-save. The variable
auto-save-interval specifies how many characters there are
between auto-saves. By default, it is 300. Emacs doesn’t accept
values that are too small: if you customize auto-save-interval
to a value less than 20, Emacs will behave as if the value is 20.
Auto-saving also takes place when you stop typing for a while. By
default, it does this after 30 seconds of idleness (at this time,
Emacs may also perform garbage collection; see Garbage
Collection in The Emacs Lisp Reference Manual). To change
this interval, customize the variable auto-save-timeout. The
actual time period is longer if the current buffer is long; this is a
heuristic which aims to keep out of your way when you are editing long
buffers, in which auto-save takes an appreciable amount of time.
Auto-saving during idle periods accomplishes two things: first, it
makes sure all your work is saved if you go away from the terminal for
a while; second, it may avoid some auto-saving while you are actually
typing.
When auto-save-visited-mode is enabled, Emacs will auto-save
file-visiting buffers after five seconds of idle time. You can
customize the variable auto-save-visited-interval to change the
idle time interval.
Emacs also does auto-saving whenever it gets a fatal error. This includes killing the Emacs job with a shell command such as ‘kill %emacs’, or disconnecting a phone line or network connection.
You can perform an auto-save explicitly with the command M-x do-auto-save.
You can use the contents of an auto-save file to recover from a loss of data with the command M-x recover-file RET file RET. This visits file and then (after your confirmation) restores the contents from its auto-save file #file#. You can then save with C-x C-s to put the recovered text into file itself. For example, to recover file foo.c from its auto-save file #foo.c#, do:
M-x recover-file RET foo.c RET yes RET C-x C-s
Before asking for confirmation, M-x recover-file displays a directory listing describing the specified file and the auto-save file, so you can compare their sizes and dates. If the auto-save file is older, M-x recover-file does not offer to read it.
When M-x recover-file asks for confirmation, if you answer with diff or =, it shows the diffs between file and its auto-save file #file# and reprompts you for confirmation.
If Emacs or the computer crashes, you can recover all the files you were editing from their auto save files with the command M-x recover-session. This first shows you a list of recorded interrupted sessions. Move point to the one you choose, and type C-c C-c.
Then recover-session asks about each of the files that were
being edited during that session, asking whether to recover that file.
If you answer y, it calls recover-file, which works in its
normal fashion. It shows the dates of the original file and its
auto-save file, and asks once again whether to recover that file.
When recover-session is done, the files you’ve chosen to
recover are present in Emacs buffers. You should then save them. Only
this—saving them—updates the files themselves.
Emacs records information about interrupted sessions in files named
.saves-pid-hostname~ in the directory
~/.emacs.d/auto-save-list/. This directory is determined by
the variable auto-save-list-file-prefix. If you set
auto-save-list-file-prefix to nil, sessions are not
recorded for recovery.
Symbolic links and hard links both make it possible for several file names to refer to the same file. Hard links are alternate names that refer directly to the file; all the names are equally valid, and no one of them is preferred. By contrast, a symbolic link is a kind of defined alias: when foo is a symbolic link to bar, you can use either name to refer to the file, but bar is the real name, while foo is just an alias. More complex cases occur when symbolic links point to directories.
Normally, if you visit a file which Emacs is already visiting under
a different name, Emacs displays a message in the echo area and uses
the existing buffer visiting that file. This can happen on systems
that support hard or symbolic links, or if you use a long file name on
a system that truncates long file names, or on a case-insensitive file
system. You can suppress the message by setting the variable
find-file-suppress-same-file-warnings to a non-nil
value. You can disable this feature entirely by setting the variable
find-file-existing-other-name to nil: then if you visit
the same file under two different names, you get a separate buffer for
each file name.
If the variable find-file-visit-truename is non-nil,
then the file name recorded for a buffer is the file’s truename
(made by replacing all symbolic links with their target names), rather
than the name you specify. Setting find-file-visit-truename also
implies the effect of find-file-existing-other-name.
Sometimes, a directory is ordinarily accessed through a symbolic
link, and you may want Emacs to preferentially show its linked
name. To do this, customize directory-abbrev-alist. Each
element in this list should have the form (from
. to), which means to replace from with to whenever
from appears in a directory name. The from string is a
regular expression (see Syntax of Regular Expressions). It is matched against directory
names anchored at the first character, and should start with ‘\`’
(to support directory names with embedded newlines, which would defeat
‘^’). The to string should be an ordinary absolute
directory name pointing to the same directory. Do not use ‘~’ to
stand for a home directory in the to string; Emacs performs
these substitutions separately. Here’s an example, from a system on
which /home/fsf is normally accessed through a symbolic link
named /fsf:
(("\\`/home/fsf" . "/fsf"))
The file system groups files into directories. A directory listing is a list of all the files in a directory. Emacs provides commands to create and delete directories, and to make directory listings in brief format (file names only) and verbose format (sizes, dates, and other attributes included). Emacs also includes a directory browser feature called Dired, which you can invoke with C-x d; see Dired, the Directory Editor.
Display a brief directory listing (list-directory).
Display a verbose directory listing.
Create a new directory named dirname.
Delete the directory named dirname. If it isn’t empty, you will be asked whether you want to delete it recursively.
The command to display a directory listing is C-x C-d
(list-directory). It reads using the minibuffer a file name
which is either a directory to be listed or a wildcard-containing
pattern for the files to be listed. For example,
C-x C-d /u2/emacs/etc RET
lists all the files in directory /u2/emacs/etc. Here is an example of specifying a file name pattern:
C-x C-d /u2/emacs/src/*.c RET
Normally, C-x C-d displays a brief directory listing containing just file names. A numeric argument (regardless of value) tells it to make a verbose listing including sizes, dates, and owners (like ‘ls -l’).
The text of a directory listing is mostly obtained by running
ls in an inferior process. Two Emacs variables control the
switches passed to ls: list-directory-brief-switches is
a string giving the switches to use in brief listings ("-CF" by
default), and list-directory-verbose-switches is a string
giving the switches to use in a verbose listing ("-l" by
default).
In verbose directory listings, Emacs adds information about the amount of free space on the disk that contains the directory.
The command M-x delete-directory prompts for a directory’s name
using the minibuffer, and deletes the directory if it is empty. If
the directory is not empty, you will be asked whether you want to
delete it recursively. On systems that have a “Trash” (or “Recycle
Bin”) feature, you can make this command move the specified directory
to the Trash instead of deleting it outright, by changing the variable
delete-by-moving-to-trash to t. See Miscellaneous File Operations,
for more information about using the Trash.
The command M-x diff prompts for two file names, using the
minibuffer, and displays the differences between the two files in a
buffer named *diff*. This works by running the diff
program, using options taken from the variable diff-switches.
The value of diff-switches should be a string; the default is
"-u" to specify a unified context diff.
See Diff in Comparing and Merging Files, for more
information about the diff program.
The output of the diff command is shown using a major mode
called Diff mode. See Diff Mode.
A (much more sophisticated) alternative is M-x ediff (see Ediff in The Ediff Manual).
The command M-x diff-backup compares a specified file with its
most recent backup. If you specify the name of a backup file,
diff-backup compares it with the source file that it is a
backup of. In all other respects, this behaves like M-x diff.
The command M-x diff-buffer-with-file compares a specified buffer with its corresponding file. This shows you what changes you would make to the file if you save the buffer.
The command M-x diff-buffers compares the contents of two specified buffers.
The command M-x compare-windows compares the text in the current window with that in the window that was the selected window before you selected the current one. (For more information about windows in Emacs, see Multiple Windows.) Comparison starts at point in each window, after pushing each initial point value on the mark ring (see The Mark Ring) in its respective buffer. Then it moves point forward in each window, one character at a time, until it reaches characters that don’t match. Then the command exits.
If point in the two windows is followed by non-matching text when the command starts, M-x compare-windows tries heuristically to advance up to matching text in the two windows, and then exits. So if you use M-x compare-windows repeatedly (see Repeating a Command), each time it either skips one matching range or finds the start of another.
With a numeric argument, compare-windows ignores changes in
whitespace. If the variable compare-ignore-case is
non-nil, the comparison ignores differences in case as well.
If the variable compare-ignore-whitespace is non-nil,
compare-windows by default ignores changes in whitespace, but a
prefix argument turns that off for that single invocation of the
command.
You can use M-x smerge-mode to turn on Smerge mode, a minor
mode for editing output from the diff3 program. This is
typically the result of a failed merge from a version control system
update outside VC, due to conflicting changes to a file. Smerge
mode provides commands to resolve conflicts by selecting specific
changes.
See Merging Files with Emerge, for the Emerge facility, which provides a powerful interface for merging files.
Diff mode is a major mode used for the output of M-x diff and
other similar commands. This kind of output is called a patch,
because it can be passed to the patch command to
automatically apply the specified changes. To select Diff mode
manually, type M-x diff-mode.
The changes specified in a patch are grouped into hunks, which are contiguous chunks of text that contain one or more changed lines. Hunks usually also include unchanged lines to provide context for the changes. Each hunk is preceded by a hunk header, which specifies the old and new line numbers where the hunk’s changes occur. Diff mode highlights each hunk header, to distinguish it from the actual contents of the hunk.
The first hunk in a patch is preceded by a file header, which shows the names of the new and the old versions of the file, and their time stamps. If a patch shows changes for more than one file, each file has such a header before the first hunk of that file’s changes.
You can edit a Diff mode buffer like any other buffer. (If it is
read-only, you need to make it writable first; see Miscellaneous Buffer Operations.)
Whenever you edit a hunk, Diff mode attempts to automatically correct
the line numbers in the hunk headers, to ensure that the patch remains
correct, and could still be applied by patch. To disable
automatic line number correction, change the variable
diff-update-on-the-fly to nil.
Diff mode arranges for hunks to be treated as compiler error messages by M-g M-n and other commands that handle error messages (see Compilation Mode). Thus, you can use the compilation-mode commands to visit the corresponding source locations.
In addition, Diff mode provides the following commands to navigate, manipulate and apply parts of patches:
Move to the next hunk-start (diff-hunk-next). With prefix
argument n, move forward to the nth next hunk.
By default, Diff mode automatically refines hunks as Emacs
displays them, highlighting their changes with better granularity.
Alternatively, if you set diff-refine to the symbol
navigation, Diff mode only refines the hunk you move to with this
command or with diff-hunk-prev. Finally, you can set
diff-refine to nil and manually refine hunks using
C-c C-b (diff-refine-hunk), described below.
By default, refining a hunk in any way displays a shadow cursor at
one of the two edges of the refined region, to better show where the
refined region starts or ends. This can be controlled by customizing
the variable smerge-refine-shadow-cursor.
Move to the previous hunk-start (diff-hunk-prev). With prefix
argument n, move back to the nth previous hunk. Like
M-n, this command refines the hunk you move to if you set
diff-refine to the symbol navigation.
Move to the next file-start, in a multi-file patch
(diff-file-next). With prefix argument n, move forward
to the start of the nth next file.
Move to the previous file-start, in a multi-file patch
(diff-file-prev). With prefix argument n, move back to
the start of the nth previous file.
Kill the hunk at point (diff-hunk-kill). If the region is
active, kills all hunks the region overlaps.
In a multi-file patch, kill the current file part.
(diff-file-kill).
Apply this hunk to its target file (diff-apply-hunk). With a
prefix argument of C-u, revert this hunk, i.e. apply the
reverse of the hunk, which changes the “new” version into the “old”
version. If diff-jump-to-old-file is non-nil, apply the
hunk to the “old” version of the file instead.
diff-apply-hunk prompts you to confirm deleting files and
applying hunks to backup files, and it offers to reverse-apply hunks
that are already applied. If the region is active, however, it applies
all hunks that the region overlaps without doing any prompting. In this
mode, it simply fails if any hunks do not apply cleanly, and does not
confirm deletions or applying hunks to backup files.
Revert this hunk, and then remove the hunk from the diffs
(diff-revert-and-kill-hunk). Save the buffer visiting the target
file. When the region is active, the command reverse-applies and kills
hunks that the region overlaps.
This command is useful in buffers generated by C-x v = and C-x v D (see Examining And Comparing Old Revisions). These buffers present you with a view of the changes you’ve made, and you can use this command to undo changes you didn’t intend to do, or no longer want.
This is a destructive operation, so by default, this command asks you to
confirm you really want to revert and kill the hunks. You can customize
diff-ask-before-revert-and-kill-hunk to control that.
Apply all the hunks in the buffer (diff-apply-buffer). If the
region is active, apply all hunks that the region overlaps; otherwise,
apply all hunks. With a prefix argument, reverse-apply the hunks.
If the diffs were applied successfully, save the changed buffers.
Delete hunks other than the current one. If the region is active, this command deletes the hunks the region overlaps; otherwise it deletes all hunks other than the current hunk. This command does not work in a narrowed buffer because deleting hunks safely requires access to the parts of the buffer where the hunks’ file names are specified.
Highlight the changes of the hunk at point with a finer granularity
(diff-refine-hunk). This allows you to see exactly which parts
of each changed line were actually changed. Refining a hunk by default
shows a “shadow cursor” at one of the two edges of the refined region.
By default, Diff mode refines hunks as Emacs displays them, so you may
find this command useful if you customize diff-refine to a
non-default value.
Go to the source file and line corresponding to this hunk
(diff-goto-source). By default, this jumps to the “new”
version of the file, the one shown first on the file header.
With a prefix argument, jump to the “old” version instead. If
diff-jump-to-old-file is non-nil, this command by
default jumps to the “old” file, and the meaning of the prefix
argument is reversed. If the prefix argument is a number greater than
8 (e.g., if you type C-u C-u C-c C-c), then this command also
sets diff-jump-to-old-file for the next invocation.
If the source file is under version control (see Version Control),
this jumps to the work file by default. With a prefix argument, jump
to the “old” revision of the file (see Examining And Comparing Old Revisions), when
point is on the old line, or otherwise jump to the “new” revision.
Start an Ediff session with the patch (diff-ediff-patch).
See Ediff in The Ediff Manual.
Restrict the view to the current hunk (diff-restrict-view).
See Narrowing. With a prefix argument, restrict the
view to the current file of a multiple-file patch. To widen again,
use C-x n w (widen).
Reverse the direction of comparison for the entire buffer
(diff-reverse-direction). With a prefix argument, reverse the
direction only inside the current region (see The Mark and the Region). Reversing
the direction means changing the hunks and the file-start headers to
produce a patch that would change the “new” version into the “old”
one.
Split the hunk at point (diff-split-hunk) into two separate
hunks. This inserts a hunk header and modifies the header of the
current hunk. This command is useful for manually editing patches,
and only works with the unified diff format produced by the
-u or --unified options to the diff
program. If you need to split a hunk in the context diff format
produced by the -c or --context options to
diff, first convert the buffer to the unified diff format
with C-c C-u.
Convert the entire buffer to the context diff format
(diff-unified->context). With a prefix argument, convert only
the hunks within the region.
Convert the entire buffer to unified diff format
(diff-context->unified). With a prefix argument, convert
unified format to context format. When the mark is active, convert
only the hunks within the region.
Re-generate the current hunk (diff-refresh-hunk).
Re-generate the current hunk, disregarding changes in whitespace.
With a non-nil prefix arg, re-generate all the hunks
(diff-ignore-whitespace-hunk). This calls diff-command
with diff-ignore-whitespace-switches, which defaults to
‘-b’, meaning ignore changes in whitespace only.
Generate a ChangeLog entry, like C-x 4 a does (see Change Logs), for each one of the hunks
(diff-add-change-log-entries-other-window). This creates a
skeleton of the log of changes that you can later fill with the actual
descriptions of the changes. C-x 4 a itself in Diff mode
operates on behalf of the current hunk’s file, but gets the function
name from the patch itself. This is useful for making log entries for
functions that are deleted by the patch.
Patches sometimes include trailing whitespace on modified lines, as an unintentional and undesired change. There are two ways to deal with this problem. Firstly, if you enable Whitespace mode in a Diff buffer (see Useless Whitespace), it automatically highlights trailing whitespace in modified lines. Secondly, you can use the command M-x diff-delete-trailing-whitespace, which searches for trailing whitespace in the lines modified by the patch, and removes that whitespace in both the patch and the patched source file(s). This command does not save the modifications that it makes, so you can decide whether to save the changes (the list of modified files is displayed in the echo area). With a prefix argument, it tries to modify the original (“old”) source files rather than the patched (“new”) source files.
If diff-font-lock-syntax is non-nil, fragments of
source in hunks are highlighted according to the appropriate major
mode.
Emacs has several commands for copying, naming, and renaming files. All of them read two file names, old (or target) and new, using the minibuffer, and then copy or adjust a file’s name accordingly; they do not accept wildcard file names.
In all these commands, if the argument new is just a directory name (see Directory Names in the Emacs Lisp Reference Manual), the real new name is in that directory, with the same non-directory component as old. For example, the command M-x rename-file RET ~/foo RET /tmp/ RET renames ~/foo to /tmp/foo. On GNU and other POSIX-like systems, directory names end in ‘/’.
All these commands ask for confirmation when the new file name already exists.
M-x copy-file copies the contents of the file old to the file new.
M-x copy-directory copies directories, similar to the
cp -r shell command. If new is a directory name, it
creates a copy of the old directory and puts it in new.
Otherwise it copies all the contents of old into a new directory
named new. If copy-directory-create-symlink is
non-nil and old is a symbolic link, this command will
copy the symbolic link. If nil, this command will follow the
link and copy the contents instead. (This is the default.)
M-x rename-file renames file old as new. If the file name new already exists, you must confirm with yes or renaming is not done; this is because renaming causes the old meaning of the name new to be lost. If old and new are on different file systems, the file old is copied and deleted.
If a file is under version control (see Version Control), you should rename it using C-x v R instead of M-x rename-file. See Deleting and Renaming Version-Controlled Files.
M-x add-name-to-file adds an additional name to an existing file without removing the old name. The new name is created as a hard link to the existing file. The new name must belong on the same file system that the file is on. On MS-Windows, this command works only if the file resides in an NTFS file system. On MS-DOS, and some remote system types, it works by copying the file.
M-x make-symbolic-link creates a symbolic link named new, which points at target. The effect is that future attempts to open file new will refer to whatever file is named target at the time the opening is done, or will get an error if the name target is nonexistent at that time. This command does not expand the argument target, so that it allows you to specify a relative name as the target of the link. However, this command does expand leading ‘~’ in target so that you can easily specify home directories, and strips leading ‘/:’ so that you can specify relative names beginning with literal ‘~’ or ‘/:’. See Quoted File Names. On MS-Windows, this command works only on MS Windows Vista and later. When new is remote, it works depending on the system type.
Emacs has commands for performing many other operations on files. All operate on one file; they do not accept wildcard file names.
M-x delete-file prompts for a file and deletes it. If you are
deleting many files in one directory, it may be more convenient to use
Dired rather than delete-file. See Deleting Files with Dired.
M-x move-file-to-trash moves a file into the system Trash (or Recycle Bin). This is a facility available on most operating systems; files that are moved into the Trash can be brought back later if you change your mind. (The way to restore trashed files is system-dependent.)
By default, Emacs deletion commands do not use the Trash. To
use the Trash (when it is available) for common deletion commands,
change the variable delete-by-moving-to-trash to t.
This affects the commands M-x delete-file and M-x
delete-directory (see File Directories), as well as the deletion
commands in Dired (see Deleting Files with Dired). Supplying a prefix
argument to M-x delete-file or M-x delete-directory makes
them delete outright, instead of using the Trash, regardless of
delete-by-moving-to-trash.
If you have delete-by-moving-to-trash set, and you want to
delete files manually in Emacs from the Trash directory, using
commands like D (dired-do-delete) doesn’t work well in
the Trash directory (it’ll just give the file a new name, but won’t
delete anything). If you want to be able to do this, you should
create a .dir-locals.el file containing something like the
following in the Trash directory:
((dired-mode . ((delete-by-moving-to-trash . nil))))
Note, however, if you use the system “empty trash” command, it’s
liable to also delete this .dir-locals.el file, so this should
only be done if you delete files from the Trash directory manually.
If the variable remote-file-name-inhibit-delete-by-moving-to-trash
is non-nil, remote files are never moved to the Trash. They
are deleted instead.
If a file is under version control (see Version Control), you should delete it using M-x vc-delete-file instead of M-x delete-file. See Deleting and Renaming Version-Controlled Files.
M-x insert-file (also C-x i) inserts a copy of the contents of the specified file into the current buffer at point, leaving point unchanged before the contents. The position after the inserted contents is added to the mark ring, without activating the mark (see The Mark Ring).
M-x insert-file-literally is like M-x insert-file, except the file is inserted literally: it is treated as a sequence of ASCII characters with no special encoding or conversion, similar to the M-x find-file-literally command (see Visiting Files).
M-x write-region is the inverse of M-x insert-file; it
copies the contents of the region into the specified file. M-x
append-to-file adds the text of the region to the end of the
specified file. See Accumulating Text. The variable
write-region-inhibit-fsync applies to these commands, as well
as saving files; see Customizing Saving of Files.
M-x set-file-modes reads a file name followed by a file
mode, and applies that file mode to the specified file. File modes,
also called file permissions, determine whether a file can be
read, written to, or executed, and by whom. This command reads file
modes using the same symbolic or octal format accepted by the
chmod command; for instance, ‘u+x’ means to add
execution permission for the user who owns the file. It has no effect
on operating systems that do not support file modes. chmod is a
convenience alias for this function.
Emacs automatically uncompresses compressed files when you visit
them, and automatically recompresses them if you alter them and save
them. Emacs recognizes compressed files by their file names. File
names ending in ‘.gz’ indicate a file compressed with
gzip. Other endings indicate other compression programs.
Automatic uncompression and compression apply to all the operations in which Emacs uses the contents of a file. This includes visiting it, saving it, inserting its contents into a buffer, loading it, and byte compiling it.
To disable this feature, type the command M-x
auto-compression-mode. You can disable it permanently by
customizing the variable auto-compression-mode.
A file whose name ends in ‘.tar’ is normally an archive
made by the tar program. Emacs views these files in a special
mode called Tar mode which provides a Dired-like list of the contents
(see Dired, the Directory Editor). You can move around through the list just as you
would in Dired, and visit the subfiles contained in the archive.
However, not all Dired commands are available in Tar mode.
If Auto Compression mode is enabled (see Accessing Compressed Files), then
Tar mode is used also for compressed archives—files with extensions
‘.tgz’, .tar.Z and .tar.gz.
The keys e, f and RET all extract a component file into its own buffer. You can edit it there, and if you save the buffer, the edited version will replace the version in the Tar buffer. Clicking with the mouse on the file name in the Tar buffer does likewise. v extracts a file into a buffer in View mode (see View Mode). o extracts the file and displays it in another window, so you could edit the file and operate on the archive simultaneously.
The I key adds a new (regular) file to the archive. The file is initially empty, but can readily be edited using the commands above. The command inserts the new file before the current one, so that using it on the topmost line of the Tar buffer makes the new file the first one in the archive, and using it at the end of the buffer makes it the last one.
d marks a file for deletion when you later use x, and u unmarks a file, as in Dired. C copies a file from the archive to disk and R renames a file within the archive. g reverts the buffer from the archive on disk. The keys M, G, and O change the file’s permission bits, group, and owner, respectively.
Saving the Tar buffer writes a new version of the archive to disk with the changes you made to the components.
You don’t need the tar program to use Tar mode—Emacs reads
the archives directly. However, accessing compressed archives
requires the appropriate uncompression program.
A separate but similar Archive mode is used for arc,
jar, lzh, zip, rar, 7z, and
zoo archives, as well as exe files that are
self-extracting executables.
The key bindings of Archive mode are similar to those in Tar mode, with the addition of the m key which marks a file for subsequent operations, and M-DEL which unmarks all the marked files. Also, the a key toggles the display of detailed file information, for those archive types where it won’t fit in a single line. Operations such as renaming a subfile, or changing its mode or owner, are supported only for some of the archive formats.
Unlike Tar mode, Archive mode runs the archiving programs to unpack and repack archives. However, you don’t need these programs to look at the archive table of contents, only to extract or manipulate the subfiles in the archive. Details of the program names and their options can be set in the ‘Archive’ Customize group (see Customization Groups).
You can refer to files on other machines using a special file name syntax:
/method:host:filename /method:user@host:filename /method:user@host#port:filename
To carry out this request, Emacs uses a remote-login program such as
ssh.
You must always specify in the file name which method to use—for
example, /ssh:user@host:filename uses
ssh. When you specify the pseudo method ‘-’ in the
file name, Emacs chooses the method as follows:
tramp-default-method is set to ‘ftp’,
Emacs uses FTP.
ssh-agent is running, Emacs uses scp.
ssh.
You can entirely turn off the remote file name feature by running M-x inhibit-remote-files. You can turn off the feature in individual cases by quoting the file name with ‘/:’ (see Quoted File Names).
Remote file access through FTP is handled by the Ange-FTP package, which is documented in the following. Remote file access through the other methods is handled by the Tramp package, which has its own manual. See The Tramp Manual in The Tramp Manual.
When the Ange-FTP package is used, Emacs logs in through FTP using
the name user, if that is specified in the remote file name. If
user is unspecified, Emacs logs in using your user name on the
local system; but if you set the variable ange-ftp-default-user
to a string, that string is used instead. When logging in, Emacs may
also ask for a password.
For performance reasons, Emacs does not make backup files for files
accessed via FTP by default. To make it do so, change the variable
ange-ftp-make-backup-files to a non-nil value.
By default, auto-save files for remote files are made in the
temporary file directory on the local machine, as specified by the
variable auto-save-file-name-transforms. See Auto-Save Files.
To visit files accessible by anonymous FTP, you use special user
names ‘anonymous’ or ‘ftp’. Passwords for these user names
are handled specially. The variable
ange-ftp-generate-anonymous-password controls what happens: if
the value of this variable is a string, then that string is used as
the password; if non-nil (the default), then the value of
user-mail-address is used; if nil, then Emacs prompts
you for a password as usual (see Entering passwords).
Sometimes you may be unable to access files on a remote machine
because a firewall in between blocks the connection for security
reasons. If you can log in on a gateway machine from which the
target files are accessible, and whose FTP server supports
gatewaying features, you can still use remote file names; all you have
to do is specify the name of the gateway machine by setting the
variable ange-ftp-gateway-host, and set
ange-ftp-smart-gateway to t. Otherwise you may be able
to make remote file names work, but the procedure is complex. You can
read the instructions by typing M-x finder-commentary RET
ange-ftp RET.
You can quote an absolute file name to prevent special characters and syntax in it from having their special effects. The way to do this is to add ‘/:’ at the beginning.
For example, you can quote a local file name which appears remote, to prevent it from being treated as a remote file name. Thus, if you have a directory named /foo: and a file named bar in it, you can refer to that file in Emacs as ‘/:/foo:/bar’.
If you want to quote only special characters in the local part of a remote file name, you can quote just the local part. ‘/ssh:baz:/:/foo:/bar’ refers to the file bar of directory /foo: on the host baz.
‘/:’ can also prevent ‘~’ from being treated as a special character for a user’s home directory. For example, /:/tmp/~hack refers to a file whose name is ~hack in directory /tmp. If ‘~’ is at the beginning of the file name, it must be quoted with ‘/:./’, like in ‘/:./~foo/bar’.
Quoting with ‘/:’ is also a way to enter in the minibuffer a file name that contains ‘$’. In order for this to work, the ‘/:’ must be at the beginning of the minibuffer contents. (You can also double each ‘$’; see File Names with $.)
You can also quote wildcard characters with ‘/:’, for visiting. For example, /:/tmp/foo*bar visits the file /tmp/foo*bar.
Another method of getting the same result is to enter /tmp/foo[*]bar, which is a wildcard specification that matches only /tmp/foo*bar. However, in many cases there is no need to quote the wildcard characters because even unquoted they give the right result. For example, if the only file name in /tmp that starts with ‘foo’ and ends with ‘bar’ is foo*bar, then specifying /tmp/foo*bar will visit only /tmp/foo*bar.
You can use the file name cache to make it easy to locate a
file by name, without having to remember exactly where it is located.
When typing a file name in the minibuffer, C-TAB
(file-cache-minibuffer-complete) completes it using the file
name cache. If you repeat C-TAB, that cycles through the
possible completions of what you had originally typed. (However, note
that the C-TAB character cannot be typed on most text
terminals.)
The file name cache does not fill up automatically. Instead, you load file names into the cache using these commands:
Add each file name in directory to the file name cache.
Add each file name in directory and all of its nested subdirectories to the file name cache.
Add each file name in directory and all of its nested
subdirectories to the file name cache, using locate to find
them all.
Add each file name in each directory listed in variable to the
file name cache. variable should be a Lisp variable whose value
is a list of directories, like load-path.
Clear the cache; that is, remove all file names from it.
The file name cache is not persistent: it is kept and maintained
only for the duration of the Emacs session. You can view the contents
of the cache with the file-cache-display command.
In this section, we introduce some convenient facilities for finding recently-opened files, reading file names from a buffer.
If you enable Recentf mode, with M-x recentf-mode, Emacs
maintains a list of recently opened files. To open a file from this
list, use the M-x recentf-open command. When this mode is
enabled, the ‘File’ menu will include a submenu that you can use
to visit one of these files. M-x recentf-save-list saves the
current recentf-list to a file, and M-x recentf-edit-list
edits it.
If you use remote files, you might also consider customizing
remote-file-name-access-timeout, which is the number of
seconds after which the check whether a remote file shall be used
in Recentf is stopped. This prevents Emacs being blocked.
The M-x ffap command generalizes find-file with more
powerful heuristic defaults (see Finding Files and URLs at Point), often based on the text at
point. Partial Completion mode offers other features extending
find-file, which can be used with ffap.
See Completion Options.
Visiting image files automatically selects Image mode. In this
major mode, you can type C-c C-c (image-toggle-display)
to toggle between displaying the file as an image in the Emacs buffer,
and displaying its underlying text (or raw byte) representation.
Additionally you can type C-c C-x (image-toggle-hex-display)
to toggle between displaying the file as an image in the Emacs buffer,
and displaying it in hex representation. Displaying the file as an
image works only if Emacs is compiled with support for displaying
such images.
If the displayed image is wider or taller than the window in which it
is displayed, the usual point motion keys (C-f, C-p, and
so forth) cause different parts of the image to be displayed.
However, by default images are resized automatically to fit the
window, so this is only necessary if you customize the default
behavior by using the options image-auto-resize and
image-auto-resize-on-window-resize.
To resize the image manually you can use the command
image-transform-fit-to-window bound to s w that fits the
image to both the window height and width. To scale the image to a
percentage of its original size, use the command
image-transform-set-percent bound to s p. To scale the
image specifying a scale factor, use the command
image-transform-set-scale bound to s s. To reset all
transformations to the initial state, use
image-transform-reset-to-initial bound to s 0, or
image-transform-reset-to-original bound to s o.
You can press n (image-next-file) and p
(image-previous-file) to visit the next image file and the
previous image file in the same directory, respectively. These
commands will consult the “parent” dired buffer to determine what
the next/previous image file is. These commands also work when
opening a file from archive files (like zip or tar files), and will
then instead consult the archive mode buffer. If neither an archive
nor a dired “parent” buffer can be found, a dired buffer is opened.
When looking through images, it’s sometimes convenient to be able to
mark the files for later processing (for instance, if you want to
select a group of images to copy somewhere else). The m
(image-mode-mark-file) command will mark the current file in
any Dired buffer(s) that display the current file’s directory. If no
such buffer is open, the directory is opened in a new buffer. To
unmark files, use the u (image-mode-unmark-file) command.
Finally, if you just want to copy the current buffers file name to the
kill ring, you can use the w
(image-mode-copy-file-name-as-kill) command.
If the image can be animated, the command RET
(image-toggle-animation) starts or stops the animation.
Animation plays once, unless the option image-animate-loop is
non-nil. With f (image-next-frame) and b
(image-previous-frame) you can step through the individual
frames. Both commands accept a numeric prefix to step through several
frames at once. You can go to a specific frame with F
(image-goto-frame). Frames are indexed from 1. Typing a
+ (image-increase-speed) increases the speed of the animation,
a - (image-decrease-speed) decreases it, and a r
(image-reverse-speed) reverses it. The command a 0
(image-reset-speed) resets the speed to the original value.
In addition to the above key bindings, which are specific to Image mode, images shown in any Emacs buffer have special key bindings when point is at or inside the image:
Increase the image size (image-increase-size) by 20%. Prefix
numeric argument controls the increment; the value of n means to
multiply the size by the factor of 1 + n / 10, so
C-u 5 i + means to increase the size by 50%.
Decrease the image size (image-decrease-size) by 20%. Prefix
numeric argument controls the decrement; the value of n means to
multiply the size by the factor of 1 - n / 10, so
C-u 3 i - means to decrease the size by 30%.
Rotate the image by 90 degrees clockwise (image-rotate).
With the prefix argument, rotate by 90 degrees counter-clockwise instead.
Note that this command is not available for sliced images.
Flip the image horizontally (image-flip-horizontally). This
presents the image as if reflected in a vertical mirror.
Note that this command is not available for sliced images.
Flip the image vertically (image-flip-vertically). This
presents the image as if reflected in a horizontal mirror.
Note that this command is not available for sliced images.
Save the image to a file (image-save). This command prompts
you for the name of the file to save the image.
Crop the image (image-crop). This command is available only if
your system has an external program installed that can be used for
cropping and cutting of images; the user option
image-crop-crop-command determines what program to use, and
defaults to the ImageMagick’s convert program. The command
displays the image with a rectangular frame superimposed on it, and
lets you use the mouse to move and resize the frame. Type m to
cause mouse movements to move the frame instead of resizing it; type
s to move a square frame instead. When you are satisfied with
the position and size of the cropping frame, type RET to
actually crop the part under the frame; or type q to exit
without cropping. You can then save the cropped image using i o or M-x image-save.
Cut a rectangle from the image (image-cut). This works the
same as image-crop (and also requires an external program,
defined by the variable image-crop-cut-command, to perform the
image cut), but instead of cropping the image, it removes the part
inside the frame and fills that part with the color specified by
image-cut-color. With prefix argument, the command prompts for
the color to use.
The size and rotation commands are “repeating”, which means that you can continue adjusting the image without using the i prefix.
If Emacs was compiled with support for the ImageMagick library, it
can use ImageMagick to render a wide variety of images. The variable
imagemagick-enabled-types lists the image types that Emacs may
render using ImageMagick; each element in the list should be an
internal ImageMagick name for an image type, as a symbol or an
equivalent string (e.g., BMP for .bmp images). To
enable ImageMagick for all possible image types, change
imagemagick-enabled-types to t. The variable
imagemagick-types-inhibit lists the image types which should
never be rendered using ImageMagick, regardless of the value of
imagemagick-enabled-types (the default list includes types like
C and HTML, which ImageMagick can render as an image
but Emacs should not). To disable ImageMagick entirely, change
imagemagick-types-inhibit to t.
If Emacs doesn’t have native support for the image format in
question, and image-use-external-converter is non-nil,
Emacs will try to determine whether there are external utilities that
can be used to transform the image in question to PNG before
displaying. GraphicsMagick, ImageMagick and ffmpeg are
currently supported for image conversions.
In addition, you may wish to add special handlers for certain image
formats. These can be added with the
image-converter-add-handler function. For instance, to allow
viewing Krita files as simple images, you could say something like:
(image-converter-add-handler
"kra"
(lambda (file data-p)
(if data-p
(error "Can't decode non-files")
(call-process "unzip" nil t nil
"-qq" "-c" "-x" file "mergedimage.png"))))
The function takes two parameters, where the first is a file name
suffix, and the second is a function to do the “conversion”. This
function takes two parameters, where the first is the file name or a
string with the data, and the second says whether the first parameter
is data or not, and should output an image in
image-convert-to-format format in the current buffer.
The Image-Dired package can also be used to view images as thumbnails. See Viewing Image Thumbnails in Dired.
If you regularly edit a certain group of files, you can define them
as a fileset. This lets you perform certain operations, such as
visiting, query-replace, and shell commands on all the files at
once. To make use of filesets, you must first add the expression
(filesets-init) to your init file (see The Emacs Initialization File). This
adds a ‘Filesets’ sub-menu to the menu bar’s ‘File’ menu.
The simplest way to define a fileset is by adding files to it one at a time. To add a file to fileset name, visit the file and type M-x filesets-add-buffer RET name RET. If there is no fileset name, this creates a new one, which initially contains only the current file. The command M-x filesets-remove-buffer removes the current file from a fileset.
You can also edit the list of filesets directly, with M-x filesets-edit (or by choosing ‘Edit Filesets’ from the ‘Filesets’ menu). The editing is performed in a Customize buffer (see Easy Customization Interface). Normally, a fileset is a simple list of files, but you can also define a fileset as a regular expression matching file names. Some examples of these more complicated filesets are shown in the Customize buffer. Remember to select ‘Save for future sessions’ if you want to use the same filesets in future Emacs sessions.
You can use the command M-x filesets-open to visit all the
files in a fileset, and M-x filesets-close to close them. Use
M-x filesets-run-cmd to run a command (such as
multi-isearch-files or grep) on all the files in
a fileset. These commands, which are specified in
filesets-commands, are also available from the ‘Filesets’
menu, where each existing fileset is represented by a submenu.
See Version Control, for a different concept of filesets: groups of files bundled together for version control operations. Filesets of that type are unnamed, and do not persist across Emacs sessions.