Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
up vote 8 down vote accepted

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

share|improve this answer
    
This is a great answer. I wish I could give it some extra points or something... – kjo Feb 6 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). – Gilles Feb 6 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 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". – Aaron Harris Mar 13 at 23:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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