tags:

views:

513

answers:

2

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?

+4  A: 

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.

Pierre
I guess Emacs will warn about the "eval" each time, but nice idea!
ShreevatsaR
Yes, right it warns about "eval" each time. You could then set the variable "enable-local-variable" to t if it bothers you. It is not safe though...
Pierre
+2  A: 

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))  
  )
Mike K
This should complete the solution definitely. Nice !
Pierre