Emacs: Automatically rename buffer with region

For some workflows that include keeping an eye on many open buffers, it is sometimes useful to rename buffers. This is where inbuilt function rename-buffer comes in, by default bound to C-x x r.

The vanilla rename-buffer function requires manual typing in minibuffer. If the renaming involves a string that is present in the buffer text, the process can be sped up.

The following code gives the buffer a new name based on the selection in the buffer text:

  (defun autorename-buffer ()
"Give the current buffer a new name based on the selected string."
    (let ((string
           (buffer-substring-no-properties (region-beginning) (region-end))))
      (rename-buffer string t)))

The following code has the same effect, except it also adds asterisks around the buffer name:

  (defun autorename-buffer-1 ()
"Give the current buffer a new name based on the selected string,
with asterisks."
    (let ((string (progn
        (copy-region-as-kill (region-beginning) (region-end))
        (with-temp-buffer (insert (current-kill 0))
             (goto-char (point-min))
             (insert "*")
             (goto-char (point-max))
             (insert "*")
      (rename-buffer string t)
;; Clean up kill ring
(when kill-ring (setq kill-ring (cdr kill-ring)))))

Lastly another piece of code to name the buffer back to its original filename. If the buffer has no associated file, there will be an error message:

(defun autorename-buffer-2 ()
  "Rename the buffer (back) to the filename associated with it.
If the buffer is not associated with a file, it is an error."
  (if (eq buffer-file-name nil)
      (error "No file associated with the buffer.")
    (rename-buffer (file-name-nondirectory (buffer-file-name)) t)))

Leave a Reply

Your email address will not be published. Required fields are marked *