Emacs dummy headers mode without Objective C
Choosing between C mode and C++ mode in emacs for header files can be a
bit of a chore if both types of header files have a .h extension. As
usual, a package for solving this problem already exists:
dummy-h-mode. One of
the heuristics that it uses is to search for an implementation file and
then to check the extension of that implementation file for a hint on
the mode. This heuristic works very well, but with a minor annoyance
that it tries to handle Objective C headers as well. In my use case, I
sometimes have purely template-based C++ code and a test implementation
in Matlab or octave:
mycode.h mycode.m
dummy-h-mode unfortunately parses the Matlab/octave file as an
Objective C file. Since I do not use Objective C, I used a quick and
dirty hack to avoid it:
(defun ravi/do-not-allow-objc (mode-val) (if (eq mode-val 'objc-mode) nil mode-val)) (mapc (lambda (x) (advice-add x :filter-return #'ravi/do-not-allow-objc)) '(dummy-h-mode-get-major-mode-by-source-file ;dummy-h-mode-get-major-mode-by-keywords dummy-h-mode-get-major-mode-by-files-directory))
We could simply avoid checking for .m files, but that would involve
intrusive changes to dummy-h-mode. Instead, in the code above, we look
at the result of obtaining the major mode by one of the file-based
methods (checking the implementation, or checking the number of files),
and set it to nil if the result is Objective C. When one method
returns nil, dummy-h-mode goes on to the next heuristic. In my case,
looking at keywords is almost always sufficient since most of my C++
code is in some namespace which clearly indicates the correct mode.