tags:

views:

156

answers:

4

What lines should I add to my _emacs (on Windows) file to have it open .h files in C++ mode? The default is C mode.

Thanks,

kris

+4  A: 

Try this:

(add-to-list 'auto-mode-alist '("\\.h\\'" . c++-mode))

Whenever you open .h files, C++-mode will be used.

It worked. Thanks a lot.
kujawk
This would be when you 'Accept' this answer as The Answer.
phils
+2  A: 

I could swear I saw this question answered appropriately already? Weird.

You want this:

(add-to-list 'auto-mode-alist '("\\.h\\'" . c++-mode))
phils
You did... the author deleted it.
Paul Nathan
+2  A: 

If you don't want this to apply to every .h file, you can add the following to the bottom of your C++ header files.

// Local Variables:
// mode: c++
// End:

This will work for any emacs variables that you want to set on a per file basis. Emacs ignores the leading characters, so use whatever comment variable is appropriate for the file type.

KeithB
Thanks, didn't realize you could do this with emacs.
kujawk
+3  A: 

Since I use both C and C++ regularly, I wrote this function to try and "guess" whether a .h file is meant to be C or C++

;; function decides whether .h file is C or C++ header, sets C++ by
;; default because there's more chance of there being a .h without a
;; .cc than a .h without a .c (ie. for C++ template files)
(defun c-c++-header ()
  "sets either c-mode or c++-mode, whichever is appropriate for
header"
  (interactive)
  (let ((c-file (concat (substring (buffer-file-name) 0 -1) "c")))
    (if (file-exists-p c-file)
        (c-mode)
      (c++-mode))))
(add-to-list 'auto-mode-alist '("\\.h\\'" . c-c++-header))

And if that doesn't work I set a key to toggle between C and C++ modes

;; and if that doesn't work, a function to toggle between c-mode and
;; c++-mode
(defun c-c++-toggle ()
  "toggles between c-mode and c++-mode"
  (interactive)
  (cond ((string= major-mode "c-mode")
         (c++-mode))
        ((string= major-mode "c++-mode")
         (c-mode))))

It's not perfect, there might be a better heuristic for deciding whether a header is C or C++ but it works for me.

Borbus
A better solution might be to encode the mode in the file (see my answer), and then define keys for adding the appropriate lines to the file. The only drawback is that people who don't use emacs will see this as well, but since its at the bottom of the file it shouldn't be much of an issue.
KeithB
That's fine for your own projects but my solution is mainly for dealing with other people's projects. You could `cat` your local variables on to the end of the headers in a 3rd party project but this is way too much effort IMO.
Borbus