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:

(defun bh-choose-header-mode ()
  (interactive)
  (if (string-equal (substring (buffer-file-name) -2) ".h")
      (progn
        ;; OK, we got a .h file, if a .m file exists we'll assume it's
        ; an objective c file. Otherwise, we'll look for a .cpp file.
        (let ((dot-m-file (concat (substring (buffer-file-name) 0 -1) "m"))
              (dot-cpp-file (concat (substring (buffer-file-name) 0 -1) "cpp")))
          (if (file-exists-p dot-m-file)
              (progn
                (objc-mode)
                )
            (if (file-exists-p dot-cpp-file)
                (c++-mode)
              )
            )
          )
        )
    )
  )

(add-hook 'find-file-hook 'bh-choose-header-mode)

One Reply to “Opening a header file in Emacs”

  1. 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)

Leave a Reply