How to set an Emacs buffer name with a file local variable


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?

Best Solution

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"
  (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.