Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override a single function in an Emacs library

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?

like image 631
Lajos Nagy Avatar asked Jul 21 '16 17:07

Lajos Nagy


2 Answers

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.

like image 154
Jack Avatar answered Oct 20 '22 11:10

Jack


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.

like image 28
Stefan Avatar answered Oct 20 '22 11:10

Stefan