5

How can I define an Elisp function such that it is available only under a specific mode?

(FWIW, at the moment, the mode I want to restrict a function to is comint.)

1 Answer 1

12

You can't. But you can do either of the following:

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

  2. If it is a command, you can ensure that it is not bound to a key in some modes, or in all modes except some modes.

Well, there is a way to make a function or variable essentially invisible in a given context, and that is to put its symbol in a different obarray from the default obarray. You can think of an obarray as a kind of a namespace.

If you are a relative novice then I wouldn't recommend this, but if this is really what you need then go for it. If you want an example of such use, you can take a look at library synonyms.el (description).

4
  • This is a great answer. I wish I could give it some extra points or something...
    – kjo
    Feb 6, 2016 at 16:50
  • @kjo Note that while you can test the mode in the function, you should not: a function that makes sense in comint mode surely makes sense in derived modes as well. If the function has a requirement such as needing a process associated with the buffer, test for that (if you need to — in many cases you don't need to test anything, you can just assume things are set up properly and let an exception be thrown if they aren't). Feb 6, 2016 at 19:15
  • @Gilles: I think you're advocating to go with EAFP rather than LBYL. I used to agree with this preference, but over the years I've seen EAFP fail in truly spectacular, catastrophic ways, so I've gradually returned to LBYL, to the point that it has become almost reflexive for me. Now I will adopt EAFP only as an exception, if the case for it over LBYL is extremely strong.
    – kjo
    Feb 6, 2016 at 20:16
  • For anyone else who is reading kjo's comment and doesn't know the acronyms, I'll save you a Google search: EAFP is "Easier to ask for forgiveness than permission" and LBYL is "Look before you leap". Mar 13, 2016 at 23:12

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.