Opening a header file in Emacs

I use the following function from the "find-file-hook" in order to choose between using objc-mode, c++-mode and c-mode when opening a ".h" file:

  1.  
  2. (defun bh-choose-header-mode ()
  3. (interactive)
  4. (if (string-equal (substring (buffer-file-name) -2) ".h")
  5. (progn
  6. ;; OK, we got a .h file, if a .m file exists we'll assume it's
  7. ; an objective c file. Otherwise, we'll look for a .cpp file.
  8. (let ((dot-m-file (concat (substring (buffer-file-name) 0 -1) "m"))
  9. (dot-cpp-file (concat (substring (buffer-file-name) 0 -1) "cpp")))
  10. (if (file-exists-p dot-m-file)
  11. (progn
  12. (objc-mode)
  13. )
  14. (if (file-exists-p dot-cpp-file)
  15. (c++-mode)
  16. )
  17. )
  18. )
  19. )
  20. )
  21. )
  22.  
  23. (add-hook 'find-file-hook 'bh-choose-header-mode)
  24.  

One thought on “Opening a header file in Emacs

  1. Joonhwan

    I have an idea that can improve your ones.

    please refer following snippet

    ;; *.h objc file criteria
    ;; – if there are a pair of *.h/*.m
    ;; – if the directory contains xcodeproj
    ;; – if the directory contains xib
    (defun my/h-file-looks-like-objc()
    ;; (message (concat “file path : ” (buffer-file-name)))
    (let* ((file-path (buffer-file-name))
    (file-ext (or (and (stringp file-path) (downcase (file-name-extension file-path)))
    “”))
    )
    (and (string= file-ext “h”)
    (or (file-exists-p (concat (file-name-sans-extension file-path) “.m”))
    (directory-files (file-name-directory file-path) t (regexp-opt ‘(“\.xib” “\.xcodeproj”)))))
    )
    )
    (add-to-list ‘magic-mode-alist ‘(my/h-file-looks-like-objc . objc-mode))
    (add-to-list ‘auto-mode-alist ‘(“\\.\\(m\\)?$” . objc-mode) nil)

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>