Wednesday, October 16, 2019

Meta-Programming In Emacs Using Defadvice


Meta-Programming In Emacs Using defadvice

1 Introduction

This blog article Meta Programming In Python reminded me to write up
the equivalent for Emacs Lisp.
Decorators in Python enable you to modify the vehavior of existing
functions without changing the original function; Advice in Lisp
which traces back to the 80's enables similar functionality —
incidentally, Advice was the inspiration behind Aspect Oriented
Programming in Java.


2 Advice And Emacs Lisp

Advice came to Emacs lisp in the summer of 1994, when module
advice.el shipped as part of Emacs 19.23. A few weeks later, a
colleague at work (Win Treese) wrote up a simple example that added
a before advice to the vc-checkin functions of the time to create
an RCS subdirectory if one did not exist. This was such a neat
trick that all of us in our Lab adopted it — and having random
RCS*,v* files lying around in the working directory became history.


3 Emacspeak And Advice — Fall 1994

And then I decided to make Emacs speak to me.
Module advice.el provided the ability to add before, after, or
around advice. In brief, Emacspeak used these three classes of
advice as follows:


  1. Speak line moved to after next-line and previous-line — add
    an after advice that called function emacspeak-speak-line.
  2. Speak character being deleted — Add a before advice that
    speaks the character under point before it is deleted.
  3. Get various types of completion spoken — Add an around advice
    that remembers the current context, calls the original function
    being adviced, and finally speak the current context that now
    reflects the completion.

The rest of the story was written up a few years ago as Emacspeak At
Twenty
. Fast-forwarding 25 years, present versions of Emacs still
include module advice.el as well as an arguably simplified front-end
implemented by module nadvice.el that enables the definition of
custom functions that are then attached to existing code via advice.


4 References

  1. Emacspeak At Twenty, Looking Back, Looking Forward.
  2. emacspeak: The Complete Audio Desktop. Chapter from the book
    entitled Beautiful Code, OReilly.