I want my emacs buffer to have a different name than the file name. Rather than setting this manually every time, I want to have this happen automatically based on the file contents, something like:
// Local Variables:
// buffer-name: MyName
// End:
But this doesn't work because buffer-name is a function, not a variable. How can I do this?
To change the read-only status of a buffer, use C-x C-q (toggle read-only-mode ). To change file permissions, you can run dired on the file's directory ( C-x d ), search for the file by C-s and use M to change its mode.
If you want to create a buffer that contains a file, simply type C-x C-f to find the file. Emacs automatically creates a second buffer and moves you there. If you already have a copy of the file in a buffer, C-x C-f just moves you to the existing buffer.
A buffer visiting a write-protected file is normally read-only. Here, the purpose is to inform the user that editing the buffer with the aim of saving it in the file may be futile or undesirable. The user who wants to change the buffer text despite this can do so after clearing the read-only flag with C-x C-q .
When Emacs has multiple windows, each window has a chosen buffer which is displayed there, but at any time only one of the windows is selected and its chosen buffer is the selected buffer. Each window's mode line displays the name of the buffer that the window is displaying (see section Multiple Windows).
You could say:
// Local Variables:
// eval: (rename-buffer "my-buffer-name-here")
// end:
It is a trick though.
You could otherwise program a find-file-hook
hook in your .emacs
which rename the buffer to a specific local variable contents. Something like:
(defvar pdp-buffer-name nil)
(defun pdp-rename-buffer-if-necessary ()
"Rename the current buffer according to the value of variable"
(interactive)
(if (and pdp-buffer-name (stringp pdp-buffer-name))
(rename-buffer pdp-buffer-name)))
(add-hook 'find-file-hook 'pdp-rename-buffer-if-necessary)
Then in your specific file you have
// Local Variables:
// pdp-buffer-name: "pierre"
// end:
With more brain power you could have a nicer solution.
Note that there could already exist an extension for your need. Look in the Emacs wiki.
Thanks Pierre. Your pdp-buffer-name elisp example worked very well.
I made one enhancement because I noticed emacs was treating the local variable as "unsafe" i.e., always prompting to ask if the value should be applied. Since I want this to work with many different values without cluttering up my .emacs with a list of "safe" values, I added a piece of advice. With the nomenclature of the previous example, it looks like this:
;; allow all values for "pdp-buffer-name"
(defadvice safe-local-variable-p (after allow-pdp-buffer-name (sym val) activate)
(if (eq sym 'pdp-buffer-name)
(setq ad-return-value t))
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With