6

I use an Emacs mode to annotate some of my files (the actual mode is not important). It's supplied as a library and comes with compiled lisp code (of course). I want to modify its behavior by overriding a single function in it. Just for my local Emacs session. For now, I just copy-paste the function from the library's source file, modify it a bit, then hit eval-last-sexp. So far, so good. However, I get inconsistent results: I'm not sure how Emacs handles functions coming from .elc files mixed with functions coming from source. Sometimes I see my own version of the function running, sometimes the original version. Very confusing (and annoying).

Any ideas how can I consistently replace a lisp function in an Emacs library without modifying the library's source files which are read-only?

Drew
  • 29,895
  • 7
  • 74
  • 104
Lajos Nagy
  • 9,075
  • 11
  • 44
  • 55

2 Answers2

6

Something like this should do the trick:

(advice-add 'name-of-func-to-override :override
            (lambda () (message "does this instead now")))

Replace name-of-func-to-override with the function name and the lambda with your version.

I suggest looking at the add-function (and advice-add) docs as :override may not actually be what you want.

Stefan
  • 27,908
  • 4
  • 53
  • 82
Jack
  • 20,735
  • 11
  • 48
  • 48
  • 1
    Important to mention that 'add-function' and the others were added only in Emacs 24.4 (I need to update my Emacs). – Lajos Nagy Jul 22 '16 at 18:15
2

The most likely explanation for your problem is that you sometimes (copy and) eval-last-sexp before the other library is loaded: the last one wins!

Using advice-add as suggested by @Jack is a good solution, because that override can be applied before the function is defined and it will survive the function's normal definition.

This said, in many cases you don't need to override any function. Maybe all it takes is to define your own function with your own name and then change the keymap so that it runs your function instead of the one from the library.

Stefan
  • 27,908
  • 4
  • 53
  • 82