169

I usually work on files which are updated in the file system via version control. What's a quick way to reload a file without having to C-x C-f the file again and getting asked if I want to reload it?

Drew
  • 75,699
  • 9
  • 109
  • 225
Fernando Briano
  • 1,915
  • 2
  • 14
  • 13

10 Answers10

188

M-x revert-buffer will do exactly what you want. It will still ask for confirmation.

Another option (my favorite) is the below function:

;; Source: https://www.emacswiki.org/emacs/misc-cmds.el
(defun revert-buffer-no-confirm ()
    "Revert buffer without confirmation."
    (interactive)
    (revert-buffer :ignore-auto :noconfirm))
Kaushal Modi
  • 25,203
  • 3
  • 74
  • 179
  • 13
    You might have cited the library that that code is from: [`misc-cmds.el`](http://www.emacswiki.org/emacs-en/download/misc-cmds.el). Not that it is complicated, but when you copy something *exactly* it is common courtesy to point to the source. – Drew Sep 24 '14 at 15:11
  • 6
    Apologies! I, myself, wasn't sure where I got that snippet from. I should have at least googled the function name and try to find its source so that I can credit it here. **Update** I have noted down the sources for everything I copied; just wasn't sure about this one: https://github.com/kaushalmodi/.emacs.d/blob/master/setup-files/setup-windows-buffers.el – Kaushal Modi Sep 24 '14 at 15:12
  • 6
    I wouldn't recommend this function. It's too dangerous to use accidentally on a modified file. – Gilles 'SO- stop being evil' Sep 27 '14 at 00:13
  • 2
    @Gilles I agree, with great power comes great responsibility. I wouldn't bind that to an easy to access binding. – Kaushal Modi Sep 27 '14 at 00:44
  • 1
    @Gilles: MS Windows users are used to using `F5` to revert buffers, pages, whatever, everywhere. I bind this command to `F5`, and I use it all the time. Do you unbind `g` in Dired because `revert-buffer` is dangerous? One person's danger is another person's convenience - your car and bicycle are dangerous too. – Drew Sep 28 '14 at 03:43
  • 11
    My variant of this will prompt for confirmation only if the buffer is modified, using `(revert-buffer t (not (buffer-modified-p)) t)`. – glucas Jul 10 '15 at 15:23
  • 1
    You can also use "C-x C-v" shortcut – Reza Feb 01 '19 at 08:55
  • 1
    `(global-set-key (kbd "") 'revert-buffer-no-confirm)` – ceving Sep 01 '20 at 15:52
  • Can I run it automatically on the background if a change is triggered – alper Nov 18 '20 at 15:33
  • @glucas I have tried to replace the last line in this answer by your code, but Emacs 27.1 gives me an error. Do you know why? – user90726 Aug 04 '21 at 15:11
80

There is also auto-revert-mode which does it automatically and gives you feedback.

From the doc string:

auto-revert-mode is an interactive autoloaded compiled Lisp function
in `autorevert.el'.

(auto-revert-mode &optional ARG)

Toggle reverting buffer when the file changes (Auto Revert mode).
With a prefix argument ARG, enable Auto Revert mode if ARG is
positive, and disable it otherwise.  If called from Lisp, enable
the mode if ARG is omitted or nil.

Auto Revert mode is a minor mode that affects only the current
buffer.  When enabled, it reverts the buffer when the file on
disk changes.

Use `global-auto-revert-mode' to automatically revert all buffers.
Use `auto-revert-tail-mode' if you know that the file will only grow
without being changed in the part that is already in the buffer.
thermans
  • 901
  • 7
  • 7
  • How can I enable `auto-revert-tail-mode` doing : `(setq auto-revert-tail-mode 1)`? – alper Oct 01 '21 at 15:19
  • The thing with this mode is that I can start typing before it notices the change, or not? – x-yuri Dec 17 '21 at 20:33
  • 2
    It is possible to start typing before `emacs` reverts a buffer, but it will not let you do it right away. It will ask you: "... is changed on disk; really edit the buffer (y, n, r or C-h)". – x-yuri Feb 15 '22 at 17:39
72

Another option, which I use, is find-alternate-file bound to C-x C-v. This opens a file reusing your current buffer.

By default, it points to the file you're currently on, so you can just type C-x C-v RET to reload your file. It won't prompt unless your buffer has unsaved data.

Some non-text modes like image-mode (used for rendering pictures, pdfs, svgs...etc) and dired have revert-buffer bound to g for faster access.

Tikhon Jelvis
  • 6,152
  • 2
  • 27
  • 40
13

Emacs calls this reverting.

You can revert the current file with M-x revert-buffer. This prompts for confirmation whether the file has been modified or not, except for files that match patterns listed in the variable revert-without-query (see the manual for details). Another occasional annoyance of revert-buffer is that it resets the file mode to the default.

I use the following function to revert a bunch of files, given by name. If a file isn't opened in some buffer, it is ignored.

(defun revert-files (&rest files)
  "Reload all specified files from disk.
Only files that are currently visited in some buffer are reverted.
Do not ask confirmation unless the buffer is modified."
  (save-excursion
    (let ((revert-without-query '("")))
      (dolist (file-name files)
        (message "Considering whether to revert file %s" file-name)
        (let ((buf (find-buffer-visiting file-name)))
          (when buf
            (message "Reverting file in buffer %s" (buffer-name buf))
            (set-buffer buf)
        (revert-buffer t nil t)))))))

A typical use case for this function is after updating files from version control. Use emacsclient to call revert-files on all the files that have been updated, or (this is easier, and only slightly slower) on all the files concerned by the update. I call the following shell script, passing it the files as arguments:

#! /bin/sh
# Similar to gnuclient, but call `revert-files' on the files.
files=

## Find a way to convert a path to absolute. Bizarre OSes such as Windows
## require special cases. We also try to detect non-filenames such as URIs.
case `uname -s` in
  CYGWIN*)
    absolute_path () {
      cygpath -a -w -- "$1"
    };;
  *)
    wd="`pwd -P 2>/dev/null || pwd`"
    absolute_path () {
      case "$1" in
        /*) printf '%s' "$1";; # ordinary absolute path
        *:/*)
          if expr "z$1" : 'z[0-9A-Z_a-z][-.0-9@A-Z_a-z]*:/.*'; then
            printf '%s' "$1" # URI or machine:/some/path
          else
            printf '%s' "$wd/$1" # default to a relative path
          fi;;
        *) printf '%s' "$wd/$1";; # default to a relative path
      esac
    };;
esac

for x; do
  files="$files \"`absolute_path "$x" | sed 's/[\\\\\\\"]/\\\\&/g'`\""
done
exec emacsclient -e "(revert-files$files)"

Usage example:

svn update
find -name .svn -prune -o -type f -exec emacsclient-revert {} +
11

revert-buffer is there. But I like to have some feedback.

I have the following in my .emacs.

(global-set-key (kbd "C-c r") (lambda ()
                                (interactive)
                                (revert-buffer t t t)
                                (message "buffer is reverted")))
kindahero
  • 528
  • 4
  • 11
10

you can also enable global-auto-revert-mode as shown below

(global-auto-revert-mode 1)

this is helpful when you do a lot of checks of your js files with auto-fix mode enabled, like in jssc.

DmitrySemenov
  • 271
  • 3
  • 9
9

You can use find-alternate-file, which is bound to C-x C-v by default, and just simply type RET at the prompt to reload the file.

7

For spacemacs users: SPC b R (spacemacs/safe-revert-buffer).

For skipping confirmation, other answers already cover that, though I agree with others that it's probably not a good idea to bind that to a key.

Croad Langshan
  • 3,192
  • 14
  • 42
5

Magit manages file reversions for you automatically, thus solving your core problem. You also benefit from its other features.

Here are the docs for tweaking the settings you're interested in:

If you stick with Magit, also be sure to enable all 3 global WIP modes (Work In Progress) to avoid losing work.

You can thus perform version-control actions inside Emacs with Magit and avoid your original problem altogether.

x-yuri
  • 281
  • 1
  • 8
webappzero
  • 151
  • 1
  • 3
  • 1
    Please let me know if this is helpful. – webappzero Aug 14 '17 at 23:33
  • This answer should have more upvotes! In case not clear: the WIP modes may be good (I don't use them currently), but they're not strictly necessary in order for it to solves the revert problem for you. – Croad Langshan Nov 13 '18 at 21:35
  • It is possible to start typing before `emacs` reverts a buffer, but it will not let you do it right away. It will ask you: "... is changed on disk; really edit the buffer (y, n, r or C-h)". – x-yuri Feb 15 '22 at 17:38
2

It seems there is a built-in function named revert-buffer-quick which does the trick (source). It checks if you have unsaved modification on the buffer, if there is any, it asks for confirmation, otherwise it will revert (i.e. reload) the file. The default keybinding in vanilla emacs is C-x x g which is long, so I have bound it to F5 as well:

(global-set-key (kbd "<f5>") 'revert-buffer-quick)