Function: recover-file

recover-file is an interactive and byte-compiled function defined in files.el.gz.

Signature

(recover-file FILE)

Documentation

Visit file FILE, but get contents from its last auto-save file.

View in manual

Probably introduced at or before Emacs version 17.

Key Bindings

Source Code

;; Defined in /usr/src/emacs/lisp/files.el.gz
(defun recover-file (file)
  "Visit file FILE, but get contents from its last auto-save file."
  ;; Actually putting the file name in the minibuffer should be used
  ;; only rarely.
  ;; Not just because users often use the default.
  (interactive "FRecover file: ")
  (setq file (expand-file-name file))
  (if (auto-save-file-name-p (file-name-nondirectory file))
      (user-error "%s is an auto-save file" (abbreviate-file-name file)))
  (let ((file-name (let ((buffer-file-name file))
		     (make-auto-save-file-name))))
    (cond ((and (file-exists-p file)
                (not (file-exists-p file-name)))
           (error "Auto save file %s does not exist"
                  (abbreviate-file-name file-name)))
          ((if (file-exists-p file)
	       (not (file-newer-than-file-p file-name file))
	     (not (file-exists-p file-name)))
	   (user-error "Auto-save file %s not current"
                       (abbreviate-file-name file-name)))
	  ((with-temp-buffer-window
	    "*Directory*" nil
	    #'(lambda (window _value)
		(with-selected-window window
		  (unwind-protect
		      (yes-or-no-p (format "Recover auto save file %s? " file-name))
		    (when (window-live-p window)
		      (quit-restore-window window 'kill)))))
	    (with-current-buffer standard-output
	      (let ((switches dired-listing-switches))
		(if (file-symlink-p file)
		    (setq switches (concat switches " -L")))
		;; Use insert-directory-safely, not insert-directory,
		;; because these files might not exist.  In particular,
		;; FILE might not exist if the auto-save file was for
		;; a buffer that didn't visit a file, such as "*mail*".
		;; The code in v20.x called `ls' directly, so we need
		;; to emulate what `ls' did in that case.
		(insert-directory-safely file switches)
		(insert-directory-safely file-name switches))))
	   (switch-to-buffer (find-file-noselect file t))
	   (let ((inhibit-read-only t)
		 ;; Keep the current buffer-file-coding-system.
		 (coding-system buffer-file-coding-system)
		 ;; Auto-saved file should be read with special coding.
		 (coding-system-for-read 'auto-save-coding))
	     (erase-buffer)
	     (insert-file-contents file-name nil)
	     (set-buffer-file-coding-system coding-system)
             (set-buffer-auto-saved))
	   (after-find-file nil nil t))
	  (t (user-error "Recover-file canceled")))))