The accepted answer to this question says:

When the function is invoked, it can test the current mode and do something appropriate. For example, for some modes, or all modes except some modes, it can be a no-op or it can raise an error.

How can this be done?

  • The answer showing derived-mode-p is the correct answer in most circumstances. You would only test major-mode directly in cases where you explicitly wished to exclude derived modes.
    – phils
    Sep 27, 2022 at 0:44

2 Answers 2


Inspect the value of the variable major-mode. From the docs:

Symbol for current buffer’s major mode. The default value (normally ‘fundamental-mode’) affects new buffers. A value of nil means to use the current buffer’s major mode, provided it is not marked as "special".


(defun example ()
  (cond ((eq major-mode 'foo-mode) (foo))
        ((eq major-mode 'bar-mode) (bar))))

  • Could you give an example of a function that executes a function foo if the major is foo-mode and executes bar if in bar-mode?
    – M0M0
    Nov 26, 2021 at 20:57
  • Edited to give such an example Nov 26, 2021 at 21:20

Fran's answer is perfectly acceptable but it may be worth bringing up a point made by Bozhidar Batsov, on Emacs Redux:

[...] You’re doing an exact match for a particular mode, but major modes can be inherited by other modes. Consider clojure-mode - it’s the parent of modes like clojurescript-mode and clojurec-mode, and it inherits from prog-mode.

Enter derived-mode-p:

;; Assuming the current major mode is clojurescript-mode

(derived-mode-p 'clojurescript-mode)
;; => t

(derived-mode-p 'clojure-mode)
;; => t

(derived-mode-p 'prog-mode)
;; => t

From https://www.gnu.org/software/emacs/manual/html_node/elisp/Derived-Modes.html:

Function: derived-mode-p &rest modes

This function returns non-nil if the current major mode is derived from any of the major modes given by the symbols modes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.