1

Suppose I want to code something like this

case mode in
   lisp-mode)
       do-something
       ;;
   shell-mode)
       do-other
       ;;
   latex-mode)
       do-different
       ;;
esac

What would be the best way to do this in lisp? Especially, how to find out, which mode is in use?

1 Answer 1

9

See major-mode variable to find out major mode:

Symbol for current buffer’s major mode.

See cond function to do something depending on mode:

Try each clause until one succeeds.

Each clause looks like (CONDITION BODY...). CONDITION is evaluated and, if the value is non-nil, this clause succeeds: then the expressions in BODY are evaluated and the last one’s value is the value of the cond-form. If a clause has one element, as in (CONDITION), then the cond-form returns CONDITION’s value, if that is non-nil. If no clause succeeds, cond returns nil.

E.g.

(cond
 ((eq major-mode 'lisp-interaction-mode) (message "lisp interaction mode"))
 ((eq major-mode 'text-mode) (message "text mode")))

Also see derived-mode-p function:

(derived-mode-p &rest MODES)

Non-nil if the current major mode is derived from one of MODES.

1
  • 2
    This could also use pcase to remove the repeated eq major-mode; e.g., (pcase major-mode ('lisp-interaction-mode (message...
    – zck
    Dec 27, 2019 at 16:30

Your Answer

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

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