19.4 Reverting a 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.