Figured out an advice-based way using ideas that came from @Drew's comments and @glucas's answer which I'll record here in case they're useful for anyone.
The short version: use after
advice to query whether the buffer has an associated file name, set one temporarily if it doesn't, and then let the rest of the set-auto-mode
machinery take care of the details. After a bit of testing (not extensive), it seems to be working just fine.
For ido-switch-buffer
and vanilla switch-to-buffer
, the two bits of advice would be:
(defadvice ido-switch-buffer (after set-mode activate)
(unless buffer-file-name
(let ((buffer-file-name (buffer-name)))
(set-auto-mode t))))
(defadvice switch-to-buffer (after set-mode activate)
(unless buffer-file-name
(let ((buffer-file-name (buffer-name)))
(set-auto-mode t))))
I find this option helpful on top of the find-file
point that @Drew raised because my fingers can get ahead of my brain: muscle memory will often get me into switch-to-buffer territory before it fully occurs to me that find-file
would do what I need. Now, both options are available.
UPDATE: small but potentially-irritating bug in the above code: it will re-run the mode hook on the buffer each time you switch to it. The following gives it an actual filename off of the /tmp
directory and avoids that problem:
(defadvice ido-switch-buffer (after set-mode activate)
(unless buffer-file-name
(setq buffer-file-name (concat "/tmp/" (buffer-name)))
(set-auto-mode t)))