Function: rename-visited-file

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

Signature

(rename-visited-file NEW-LOCATION)

Documentation

Rename the file visited by the current buffer to NEW-LOCATION.

This command also sets the visited file name. If the buffer isn't visiting any file, that's all it does.

Interactively, this prompts for NEW-LOCATION.

Probably introduced at or before Emacs version 29.1.

Key Bindings

Source Code

;; Defined in /usr/src/emacs/lisp/files.el.gz
(defun rename-visited-file (new-location)
  "Rename the file visited by the current buffer to NEW-LOCATION.
This command also sets the visited file name.  If the buffer
isn't visiting any file, that's all it does.

Interactively, this prompts for NEW-LOCATION."
  (interactive
   (list (if buffer-file-name
             (read-file-name "Rename visited file to: ")
           (read-file-name "Set visited file name: "
                           default-directory
                           (expand-file-name
                            (file-name-nondirectory (buffer-name))
                            default-directory)))))
  ;; If the user has given a directory name, the file should be moved
  ;; there (under the same file name).
  (when (file-directory-p new-location)
    (unless buffer-file-name
      (user-error "Can't rename buffer to a directory file name"))
    (setq new-location (expand-file-name
                        (file-name-nondirectory buffer-file-name)
                        new-location)))
  (when (and buffer-file-name
             (file-exists-p buffer-file-name))
    (rename-file buffer-file-name new-location))
  (set-visited-file-name new-location nil t))